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
JavaScript
mit
cd5f54429efbf31bb9548ae7c8a895c2d1d8cd0c
0
junwatu/blogel,junwatu/blogel,junwatu/blogel
/* @flow */ 'use strict' import moment from 'moment' import type { Post, PostCreated } from '../core/types.js' import { compile } from '../core/compile' import { Logger } from '../logger' import { savePost, getAllPost, getPostById, updateThePost } from '../db.js' const app = require('../../package.json') const striptags = require('striptags') export default class Api { constructor () {} info (req: any, res: any) { res.json({ api: app.version, description: app.description }) } savePostAPI (req: any, res: any) { let now = new Date() let doc: Post = { title: req.body.post.title.value, content: req.body.post.content.value, postCreated : now.toString(), postPublished: '', lastUpdated: now.toString(), status: req.body.post.status, author: '', tags: ['hello', 'world'] } savePost(doc).then((result) => { compile(doc).then((status) => { let jsonOut = { post: status, id: result.generated_keys } res.json(jsonOut) }, (err) => res.json({ error: err })) }, (err) => res.json({ error: err })) } updatePostAPI (req: any, res: any) { let now = new Date() let doc: Post = { title: req.body.post.title.value, content: req.body.post.content.value, postCreated : now.toString(), postPublished: '', lastUpdated: now.toString(), status: req.body.post.status, author: '', tags: ['hello', 'world'], generated_keys: req.params.id } updateThePost(doc).then((result) => res.json(result)) } listPostsAPI (req: any, res: any) { getAllPost().then((result) => { res.json(result) }, (err) => console.log(err)) } listDraftPostsAPI (req: any, res: any) { res.json({ process: 'list draft posts' }) } listPublishedPostsAPI (req: any, res: any) { res.json({ process: 'list published posts' }) } getPostAPI (req: any, res: any) { let postId = req.params.id getPostById(postId).then((result) => { res.json({ post: result }) }) } deletePostAPI (req: any, res: any) { res.json({ process: 'delete post' }) } }
server/routes/api.js
/* @flow */ 'use strict' import moment from 'moment' import type { Post, PostCreated } from '../core/types.js' import { compile } from '../core/compile' import { Logger } from '../logger' import { savePost, getAllPost, getPostById, updateThePost } from '../db.js' const app = require('../../package.json') const striptags = require('striptags') export default class Api { constructor () {} info (req: any, res: any) { res.json({ api: app.version, description: app.description }) } savePostAPI (req: any, res: any) { let now = new Date() let doc: Post = { title: req.body.post.title.value, content: req.body.post.content.value, postCreated : now.toString(), postPublished: '', lastUpdated: now.toString(), status: req.body.post.status, author: '', tags: ['hello', 'world'] } savePost(doc).then((result) => { compile(doc).then((status) => { let jsonOut = { post: status, id: result.generated_keys } res.json(jsonOut) }, (err) => res.json({ error: err })) }, (err) => res.json({ error: err })) } updatePostAPI (req: any, res: any) { let now = new Date() let doc: Post = { title: req.body.post.title.value, content: req.body.post.content.value, postCreated : now.toString(), postPublished: '', lastUpdated: now.toString(), status: req.body.post.status, author: '', tags: ['hello', 'world'], generated_keys: req.params.id } updateThePost(doc).then((result) => res.json(result)) } }
Move API to api.js
server/routes/api.js
Move API to api.js
<ide><path>erver/routes/api.js <ide> updateThePost(doc).then((result) => res.json(result)) <ide> } <ide> <del> <add> listPostsAPI (req: any, res: any) { <add> getAllPost().then((result) => { <add> res.json(result) <add> }, (err) => console.log(err)) <add> } <add> <add> listDraftPostsAPI (req: any, res: any) { <add> res.json({ <add> process: 'list draft posts' <add> }) <add> } <add> <add> listPublishedPostsAPI (req: any, res: any) { <add> res.json({ <add> process: 'list published posts' <add> }) <add> } <add> <add> getPostAPI (req: any, res: any) { <add> let postId = req.params.id <add> getPostById(postId).then((result) => { <add> res.json({ post: result }) <add> }) <add> } <add> <add> deletePostAPI (req: any, res: any) { <add> res.json({ <add> process: 'delete post' <add> }) <add> } <ide> }
Java
epl-1.0
253d342eb02c5f87bf16fe3a0a40d3e5eed82c3d
0
codenvy/plugin-datasource,codenvy/plugin-datasource
/* * CODENVY CONFIDENTIAL * __________________ * * [2013] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.ide.ext.datasource.client.sqllauncher; import java.util.Collection; import com.codenvy.ide.api.editor.EditorPartPresenter; import com.codenvy.ide.api.notification.Notification; import com.codenvy.ide.api.notification.Notification.Type; import com.codenvy.ide.api.notification.NotificationManager; import com.codenvy.ide.api.preferences.PreferencesManager; import com.codenvy.ide.api.ui.workspace.AbstractPartPresenter; import com.codenvy.ide.ext.datasource.client.DatasourceClientService; import com.codenvy.ide.ext.datasource.client.DatasourceManager; import com.codenvy.ide.ext.datasource.client.events.DatasourceCreatedEvent; import com.codenvy.ide.ext.datasource.client.events.DatasourceCreatedHandler; import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider; import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO; import com.codenvy.ide.resources.marshal.StringUnmarshaller; import com.codenvy.ide.rest.AsyncRequestCallback; import com.codenvy.ide.util.loging.Log; import com.google.gwt.http.client.RequestException; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.TextArea; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; public class SqlRequestLauncherPresenter extends AbstractPartPresenter implements SqlRequestLauncherView.ActionDelegate, DatasourceCreatedHandler { /** Preference property name for default result limit. */ private static final String PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT = "SqlEditor_default_request_limit"; /** Default value for request limit (when no pref is set). */ private static final int DEFAULT_REQUEST_LIMIT = 20; /** The matching view. */ private final SqlRequestLauncherView view; /** The i18n-able constants. */ private final SqlRequestLauncherConstants constants; private String selectedDatasourceId = null; private int resultLimit = DEFAULT_REQUEST_LIMIT; private EditorPartPresenter editor; private DatasourceClientService datasourceClientService; private NotificationManager notificationManager; private DatasourceManager datasourceManager; private TextArea editorArea; private TextArea resultArea; @Inject public SqlRequestLauncherPresenter(final SqlRequestLauncherView view, final SqlRequestLauncherConstants constants, final PreferencesManager preferencesManager, final SqlEditorProvider sqlEditorProvider, final DatasourceClientService service, final NotificationManager notificationManager, final DatasourceManager datasourceManager, final EventBus eventBus) { this.view = view; this.view.setDelegate(this); this.constants = constants; this.editor = sqlEditorProvider.getEditor(); this.datasourceClientService = service; this.notificationManager = notificationManager; this.datasourceManager = datasourceManager; final String prefRequestLimit = preferencesManager.getValue(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT); if (prefRequestLimit != null) { try { int prefValue = Integer.valueOf(prefRequestLimit); if (prefValue > 0) { this.resultLimit = prefValue; } else { Log.warn(SqlRequestLauncherPresenter.class, "negative value stored in preference " + PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT); } } catch (final NumberFormatException e) { StringBuilder sb = new StringBuilder("Preference stored in ") .append(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT) .append(" is not an integer (") .append(resultLimit) .append(")."); Log.warn(SqlRequestLauncherPresenter.class, sb.toString()); } } // push the request limit value to the view this.view.setResultLimit(this.resultLimit); // register for datasource creation events eventBus.addHandler(DatasourceCreatedEvent.getType(), this); // temporary editorArea = new TextArea(); editorArea.getElement().getStyle().clearBackgroundColor(); resultArea = new TextArea(); resultArea.getElement().getStyle().clearBackgroundColor(); resultArea.setReadOnly(true); } private void setupDatasourceComponent() { Collection<String> datasourceIds = this.datasourceManager.getNames(); this.view.setDatasourceList(datasourceIds); } @Override public String getTitle() { return this.constants.sqlEditorWindowTitle(); } @Override public ImageResource getTitleImage() { return null; } @Override public String getTitleToolTip() { return null; } @Override public void go(final AcceptsOneWidget container) { container.setWidget(view); // editor.go(this.view.getEditorZone()); this.view.getEditorZone().setWidget(editorArea); this.view.getResultZone().setWidget(resultArea); setupDatasourceComponent(); } @Override public boolean onClose() { return this.editor.onClose(); } @Override public void onOpen() { this.editor.onOpen(); } @Override public void datasourceChanged(final String newDataSourceId) { this.selectedDatasourceId = newDataSourceId; } @Override public void resultLimitChanged(final int newResultLimit) { if (newResultLimit > 0) { this.resultLimit = newResultLimit; } else { this.view.setResultLimit(this.resultLimit); } } @Override public void executeRequested(final String request) { if (this.selectedDatasourceId == null) { Window.alert("No datasource selected"); } DatabaseConfigurationDTO databaseConf = this.datasourceManager.getByName(this.selectedDatasourceId); String rawSql = this.editor.getEditorInput().getFile().getContent(); if (rawSql != null) { rawSql = rawSql.trim(); if (!"".equals(rawSql)) { try { datasourceClientService.executeSqlRequest(databaseConf, this.resultLimit, rawSql, new AsyncRequestCallback<String>(new StringUnmarshaller()) { @Override protected void onSuccess(final String result) { // TODO Auto-generated method stub } @Override protected void onFailure(final Throwable exception) { // TODO Auto-generated method stub } }); } catch (final RequestException e) { Log.error(SqlRequestLauncherPresenter.class, "Exception on SQL request execution : " + e.getMessage()); notificationManager.showNotification(new Notification("Failed execution of SQL request", Type.ERROR)); } } } Window.alert("No SQL request"); } @Override public void onDatasourceCreated(DatasourceCreatedEvent event) { this.setupDatasourceComponent(); } @Override public void minimize() { // nothing to do } }
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherPresenter.java
/* * CODENVY CONFIDENTIAL * __________________ * * [2013] - [2014] Codenvy, S.A. * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Codenvy S.A. and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Codenvy S.A. * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Codenvy S.A.. */ package com.codenvy.ide.ext.datasource.client.sqllauncher; import java.util.Collection; import com.codenvy.ide.api.editor.EditorPartPresenter; import com.codenvy.ide.api.notification.Notification; import com.codenvy.ide.api.notification.Notification.Type; import com.codenvy.ide.api.notification.NotificationManager; import com.codenvy.ide.api.preferences.PreferencesManager; import com.codenvy.ide.api.ui.workspace.AbstractPartPresenter; import com.codenvy.ide.ext.datasource.client.DatasourceClientService; import com.codenvy.ide.ext.datasource.client.DatasourceManager; import com.codenvy.ide.ext.datasource.client.events.DatasourceCreatedEvent; import com.codenvy.ide.ext.datasource.client.events.DatasourceCreatedHandler; import com.codenvy.ide.ext.datasource.client.sqleditor.SqlEditorProvider; import com.codenvy.ide.ext.datasource.shared.DatabaseConfigurationDTO; import com.codenvy.ide.resources.marshal.StringUnmarshaller; import com.codenvy.ide.rest.AsyncRequestCallback; import com.codenvy.ide.util.loging.Log; import com.google.gwt.http.client.RequestException; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.ui.AcceptsOneWidget; import com.google.gwt.user.client.ui.TextArea; import com.google.inject.Inject; import com.google.web.bindery.event.shared.EventBus; public class SqlRequestLauncherPresenter extends AbstractPartPresenter implements SqlRequestLauncherView.ActionDelegate, DatasourceCreatedHandler { /** Preference property name for default result limit. */ private static final String PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT = "SqlEditor_default_request_limit"; /** Default value for request limit (when no pref is set). */ private static final int DEFAULT_REQUEST_LIMIT = 20; /** The matching view. */ private final SqlRequestLauncherView view; /** The i18n-able constants. */ private final SqlRequestLauncherConstants constants; private String selectedDatasourceId = null; private int resultLimit = DEFAULT_REQUEST_LIMIT; private EditorPartPresenter editor; private DatasourceClientService datasourceClientService; private NotificationManager notificationManager; private DatasourceManager datasourceManager; private TextArea editorArea; @Inject public SqlRequestLauncherPresenter(final SqlRequestLauncherView view, final SqlRequestLauncherConstants constants, final PreferencesManager preferencesManager, final SqlEditorProvider sqlEditorProvider, final DatasourceClientService service, final NotificationManager notificationManager, final DatasourceManager datasourceManager, final EventBus eventBus) { this.view = view; this.view.setDelegate(this); this.constants = constants; this.editor = sqlEditorProvider.getEditor(); this.datasourceClientService = service; this.notificationManager = notificationManager; this.datasourceManager = datasourceManager; final String prefRequestLimit = preferencesManager.getValue(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT); if (prefRequestLimit != null) { try { int prefValue = Integer.valueOf(prefRequestLimit); if (prefValue > 0) { this.resultLimit = prefValue; } else { Log.warn(SqlRequestLauncherPresenter.class, "negative value stored in preference " + PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT); } } catch (final NumberFormatException e) { StringBuilder sb = new StringBuilder("Preference stored in ") .append(PREFERENCE_KEY_DEFAULT_REQUEST_LIMIT) .append(" is not an integer (") .append(resultLimit) .append(")."); Log.warn(SqlRequestLauncherPresenter.class, sb.toString()); } } // push the request limit value to the view this.view.setResultLimit(this.resultLimit); // register for datasource creation events eventBus.addHandler(DatasourceCreatedEvent.getType(), this); // temporary editorArea = new TextArea(); editorArea.getElement().getStyle().clearBackgroundColor(); } private void setupDatasourceComponent() { Collection<String> datasourceIds = this.datasourceManager.getNames(); this.view.setDatasourceList(datasourceIds); } @Override public String getTitle() { return this.constants.sqlEditorWindowTitle(); } @Override public ImageResource getTitleImage() { return null; } @Override public String getTitleToolTip() { return null; } @Override public void go(final AcceptsOneWidget container) { container.setWidget(view); // editor.go(this.view.getEditorZone()); this.view.getEditorZone().setWidget(editorArea); setupDatasourceComponent(); } @Override public boolean onClose() { return this.editor.onClose(); } @Override public void onOpen() { this.editor.onOpen(); } @Override public void datasourceChanged(final String newDataSourceId) { this.selectedDatasourceId = newDataSourceId; } @Override public void resultLimitChanged(final int newResultLimit) { if (newResultLimit > 0) { this.resultLimit = newResultLimit; } else { this.view.setResultLimit(this.resultLimit); } } @Override public void executeRequested(final String request) { if (this.selectedDatasourceId == null) { Window.alert("No datasource selected"); } DatabaseConfigurationDTO databaseConf = this.datasourceManager.getByName(this.selectedDatasourceId); String rawSql = this.editor.getEditorInput().getFile().getContent(); if (rawSql != null) { rawSql = rawSql.trim(); if (!"".equals(rawSql)) { try { datasourceClientService.executeSqlRequest(databaseConf, this.resultLimit, rawSql, new AsyncRequestCallback<String>(new StringUnmarshaller()) { @Override protected void onSuccess(final String result) { // TODO Auto-generated method stub } @Override protected void onFailure(final Throwable exception) { // TODO Auto-generated method stub } }); } catch (final RequestException e) { Log.error(SqlRequestLauncherPresenter.class, "Exception on SQL request execution : " + e.getMessage()); notificationManager.showNotification(new Notification("Failed execution of SQL request", Type.ERROR)); } } } Window.alert("No SQL request"); } @Override public void onDatasourceCreated(DatasourceCreatedEvent event) { this.setupDatasourceComponent(); } @Override public void minimize() { // nothing to do } }
Add textarea for the result zone
codenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherPresenter.java
Add textarea for the result zone
<ide><path>odenvy-ext-datasource-core/src/main/java/com/codenvy/ide/ext/datasource/client/sqllauncher/SqlRequestLauncherPresenter.java <ide> private DatasourceManager datasourceManager; <ide> <ide> private TextArea editorArea; <add> private TextArea resultArea; <ide> <ide> @Inject <ide> public SqlRequestLauncherPresenter(final SqlRequestLauncherView view, <ide> // temporary <ide> editorArea = new TextArea(); <ide> editorArea.getElement().getStyle().clearBackgroundColor(); <add> resultArea = new TextArea(); <add> resultArea.getElement().getStyle().clearBackgroundColor(); <add> resultArea.setReadOnly(true); <ide> } <ide> <ide> private void setupDatasourceComponent() { <ide> container.setWidget(view); <ide> // editor.go(this.view.getEditorZone()); <ide> this.view.getEditorZone().setWidget(editorArea); <add> this.view.getResultZone().setWidget(resultArea); <ide> <ide> <ide> setupDatasourceComponent();
Java
epl-1.0
db392fbfcbc7def861ca7851971e19311fefe4b3
0
MarcojAdaro/Concu2015,MarcojAdaro/Concu2015
package Modelo; /** * Clase principal del programa * @author Adaro, Barreda, Vogelghj * */ public class Main { /** * @param args */ public static void main(String[] args){ Monitor m = new Monitor(); /* int[] recorrido_v1 = {1, 8, 5, 0, 0}; int[] recorrido_v2 = {1, 9, 10, 5, 0}; int[] recorrido_v3 = {1, 9, 11, 12, 5}; int[] recorrido_v4 = {7, 3, 5, 0, 0}; int[] recorrido_v5 = {7, 4, 8, 5, 0}; int[] recorrido_v6 = {7, 4, 9, 10, 5}; int[] recorrido_v7 = {6, 12, 5, 0, 0}; int[] recorrido_v8 = {6, 13, 3, 5, 0}; int[] recorrido_v9 = {6, 13, 4, 8, 5}; int[] recorrido_v10 = {2, 10, 5, 0, 0}; int[] recorrido_v11 = {2, 11, 12, 5, 0}; int[] recorrido_v12 = {2, 11, 13, 3, 5}; */ // Creamos los autos que ingresan en los caminos posibles: //INGRESAN POR E2 /* Vehiculos v1 = new Vehiculos("Vehiculo_1", m,recorrido_v1); Vehiculos v2 = new Vehiculos("Vehiculo_2", m, recorrido_v2); */ //Vehiculos v3 = new Vehiculos("Vehiculo_3", m, recorrido_v3); //INGRESAN POR E4 /* Vehiculos v7 = new Vehiculos("Vehiculo_7", m, recorrido_v4); Vehiculos v8 = new Vehiculos("Vehiculo_8", m, recorrido_v5); */ //Vehiculos v9 = new Vehiculos("Vehiculo_9", m, recorrido_v6); //INGRESAN POR E6 /* Vehiculos v10 = new Vehiculos("Vehiculo_10", m, recorrido_v7); Vehiculos v11 = new Vehiculos("Vehiculo_11", m, recorrido_v8); */ //Vehiculos v12 = new Vehiculos("Vehiculo_12", m, recorrido_v9); //INGRESAN POR E8 /* Vehiculos v4 = new Vehiculos("Vehiculo_4", m, recorrido_v10); Vehiculos v5 = new Vehiculos("Vehiculo_5", m, recorrido_v11); */ //Vehiculos v6 = new Vehiculos("Vehiculo_6", m, recorrido_v12); /* v1.start(); v2.start();*/ //v3.start(); /* v4.start(); v5.start();*/ //v6.start(); /* v7.start(); v8.start();*/ //v9.start(); /* v10.start(); v11.start();*/ //v12.start(); } }
FINAL/src/Modelo/Main.java
package Modelo; import java.io.FileNotFoundException; import java.io.IOException; /** * Clase principal del programa * @author Adaro, Barreda, Vogel * */ public class Main { /** * * @param args */ public static void main(String[] args){ Monitor m = new Monitor(); /* int[] recorrido_v1 = {1, 8, 5, 0, 0}; int[] recorrido_v2 = {1, 9, 10, 5, 0}; int[] recorrido_v3 = {1, 9, 11, 12, 5}; int[] recorrido_v4 = {7, 3, 5, 0, 0}; int[] recorrido_v5 = {7, 4, 8, 5, 0}; int[] recorrido_v6 = {7, 4, 9, 10, 5}; int[] recorrido_v7 = {6, 12, 5, 0, 0}; int[] recorrido_v8 = {6, 13, 3, 5, 0}; int[] recorrido_v9 = {6, 13, 4, 8, 5}; int[] recorrido_v10 = {2, 10, 5, 0, 0}; int[] recorrido_v11 = {2, 11, 12, 5, 0}; int[] recorrido_v12 = {2, 11, 13, 3, 5}; */ // Creamos los autos que ingresan en los caminos posibles: //INGRESAN POR E2 /* Vehiculos v1 = new Vehiculos("Vehiculo_1", m,recorrido_v1); Vehiculos v2 = new Vehiculos("Vehiculo_2", m, recorrido_v2); */ //Vehiculos v3 = new Vehiculos("Vehiculo_3", m, recorrido_v3); //INGRESAN POR E4 /* Vehiculos v7 = new Vehiculos("Vehiculo_7", m, recorrido_v4); Vehiculos v8 = new Vehiculos("Vehiculo_8", m, recorrido_v5); */ //Vehiculos v9 = new Vehiculos("Vehiculo_9", m, recorrido_v6); //INGRESAN POR E6 /* Vehiculos v10 = new Vehiculos("Vehiculo_10", m, recorrido_v7); Vehiculos v11 = new Vehiculos("Vehiculo_11", m, recorrido_v8); */ //Vehiculos v12 = new Vehiculos("Vehiculo_12", m, recorrido_v9); //INGRESAN POR E8 /* Vehiculos v4 = new Vehiculos("Vehiculo_4", m, recorrido_v10); Vehiculos v5 = new Vehiculos("Vehiculo_5", m, recorrido_v11); */ //Vehiculos v6 = new Vehiculos("Vehiculo_6", m, recorrido_v12); /* v1.start(); v2.start();*/ //v3.start(); /* v4.start(); v5.start();*/ //v6.start(); /* v7.start(); v8.start();*/ //v9.start(); /* v10.start(); v11.start();*/ //v12.start(); } }
gfjgfhgf
FINAL/src/Modelo/Main.java
gfjgfhgf
<ide><path>INAL/src/Modelo/Main.java <ide> package Modelo; <ide> <del>import java.io.FileNotFoundException; <del>import java.io.IOException; <ide> <ide> /** <ide> * Clase principal del programa <del> * @author Adaro, Barreda, Vogel <add> * @author Adaro, Barreda, Vogelghj <ide> * <ide> */ <ide> public class Main { <ide> <ide> /** <del> * <ide> * @param args <ide> */ <ide> public static void main(String[] args){
Java
mit
9731dc1e8ea7a44d904b6d147d63befa236fc78b
0
orionlee/aBrightnessQS,orionlee/aBrightnessQS
package net.oldev.aBrightnessQS; import android.content.DialogInterface; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.text.InputType; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private BrightnessSettingsModel mModel; private BrightnessManager mBrightnessManager; private BrightnessManager.BrightnessContentObserver mBrightnessContentObserver; private void dbgMsg(String msg) { android.widget.Toast.makeText(getApplicationContext(), msg, android.widget.Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Now setup the UI setContentView(R.layout.activity_main); // init member variables mModel = new BrightnessSettingsModel(this); mBrightnessManager = new BrightnessManager(this); mBrightnessContentObserver = mBrightnessManager.new BrightnessContentObserver(new Handler(), new BrightnessManager.ChangeListener() { @Override public void onChange(int newBrightnessPct) { PLog.d("mBrightnessContentObserver.onChange(): " + newBrightnessPct); doShowCurBrightnessPct(newBrightnessPct); } }); // Useful for issues below final TextView brightnessPctsOutput = (TextView)findViewById(R.id.brightnessPctsOutput); // Connect brightnessPctsOutput UI to the model BrightnessSettingsModel.ChangeListener changeListener = new BrightnessSettingsModel.ChangeListener() { @Override public void onChange(String settings) { brightnessPctsOutput.setText(settings); } }; mModel.setOnChangeListener(changeListener); // Hook a dialog to change brightness levels final View brightnessPctsSection = findViewById(R.id.brightnessPctsSection); brightnessPctsSection.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final CharSequence brightnessPctsStr = brightnessPctsOutput.getText(); new BrightnessPctsDialogBuilder().show(brightnessPctsStr); } }); // // Non-UI related // // see BrightnessTileUpdateService for the service's starting points BrightnessTileUpdateService.start(this); } private void doShowCurBrightnessPct(int curBrightnessPct) { final TextView curBrightnessPctOutput = (TextView)findViewById(R.id.curBrightnessPctOutput); final String curBrightnessPctStr = ( curBrightnessPct != BrightnessManager.BRIGHTNESS_AUTO ? curBrightnessPct + "%" : getResources().getString(R.string.brightness_auto_label) ); curBrightnessPctOutput.setText(curBrightnessPctStr); } @Override protected void onResume() { super.onResume(); // UI to show current brightness percentage // It's updated upon re-entering the screen // final int curBrightnessPct = mBrightnessManager.getPct(); doShowCurBrightnessPct(curBrightnessPct); // Use case: After the activity is run, when changes brightness on quick settings // and comes back here, the UI will not updated by onResume() // Using this change listener to compensate for it. mBrightnessManager.registerOnChange(mBrightnessContentObserver); } @Override protected void onPause() { super.onPause(); // Activity no longer visible: no need to listen to brightness change anymore. mBrightnessManager.unregisterOnChange(mBrightnessContentObserver); } // Encapsulates the logic of the dialog UI and actions // It is primarily stateless, except it needs parent's mModel and Context private class BrightnessPctsDialogBuilder { public void show(CharSequence curValue) { show(curValue, null); } public void show(CharSequence curValue, CharSequence errMsg) { //@see https://stackoverflow.com/questions/10903754/input-text-dialog-android android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(MainActivity.this, R.style.AppTheme_Dialog_Alert); builder.setTitle(getTextOfViewById(R.id.brightnessPctsLabel)); builder.setMessage(getTextOfViewById(R.id.brightnessPctsLabelDesc)); final EditText editText = new EditText(MainActivity.this); editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //@see https://developer.android.com/training/keyboard-input/style.html#Action //@see https://stackoverflow.com/a/5941620 editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setId(R.id.brightnessPctsInput); // for androidTest // TODO: style EditText to be consistent with the colors of the app builder.setView(editText); editText.setText(curValue); if (errMsg != null && errMsg.length() > 0) { editText.setError(errMsg); } builder.setPositiveButton(R.string.ok_btn_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { updateModelSettingsWithEditText(editText); } }); builder.setNegativeButton(R.string.cancel_btn_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Nothing to do } }); final android.app.Dialog dialog = builder.show(); // set it here as it requires a reference to dialog editText.setOnEditorActionListener(new android.widget.TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { updateModelSettingsWithEditText(editText); dialog.dismiss(); handled = true; } return handled; } }); } private void updateModelSettingsWithEditText(final EditText editText) { String newVal = editText.getText().toString(); try { MainActivity.this.mModel.setSettings(newVal); } catch (IllegalArgumentException iae) { show(newVal, iae.getMessage()); } } private CharSequence getTextOfViewById(int id) { final TextView tView = (TextView)MainActivity.this.findViewById(id); return tView.getText(); } } }
app/src/main/java/net/oldev/aBrightnessQS/MainActivity.java
package net.oldev.aBrightnessQS; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.DialogInterface; import android.os.Handler; import android.view.View; import android.widget.TextView; import android.widget.EditText; import android.text.InputType; import android.view.inputmethod.EditorInfo; import android.view.KeyEvent; public class MainActivity extends AppCompatActivity { private BrightnessSettingsModel mModel; private BrightnessManager mBrightnessManager; private BrightnessManager.BrightnessContentObserver mBrightnessContentObserver; private void dbgMsg(String msg) { android.widget.Toast.makeText(getApplicationContext(), msg, android.widget.Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Now setup the UI setContentView(R.layout.activity_main); // init member variables mModel = new BrightnessSettingsModel(this); mBrightnessManager = new BrightnessManager(this); mBrightnessContentObserver = mBrightnessManager.new BrightnessContentObserver(new Handler(), new BrightnessManager.ChangeListener() { @Override public void onChange(int newBrightnessPct) { PLog.d("mBrightnessContentObserver.onChange(): " + newBrightnessPct); doShowCurBrightnessPct(newBrightnessPct); } }); // Useful for issues below final TextView brightnessPctsOutput = (TextView)findViewById(R.id.brightnessPctsOutput); // Connect brightnessPctsOutput UI to the model BrightnessSettingsModel.ChangeListener changeListener = new BrightnessSettingsModel.ChangeListener() { @Override public void onChange(String settings) { brightnessPctsOutput.setText(settings); } }; mModel.setOnChangeListener(changeListener); // Hook a dialog to change brightness levels final View brightnessPctsSection = findViewById(R.id.brightnessPctsSection); brightnessPctsSection.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { final CharSequence brightnessPctsStr = brightnessPctsOutput.getText(); showBrightnessPctsDialog(brightnessPctsStr); } }); // // Non-UI related // // see BrightnessTileUpdateService for the service's starting points BrightnessTileUpdateService.start(this); } private void doShowCurBrightnessPct(int curBrightnessPct) { final TextView curBrightnessPctOutput = (TextView)findViewById(R.id.curBrightnessPctOutput); final String curBrightnessPctStr = ( curBrightnessPct != BrightnessManager.BRIGHTNESS_AUTO ? curBrightnessPct + "%" : getResources().getString(R.string.brightness_auto_label) ); curBrightnessPctOutput.setText(curBrightnessPctStr); } @Override protected void onResume() { super.onResume(); // UI to show current brightness percentage // It's updated upon re-entering the screen // final int curBrightnessPct = mBrightnessManager.getPct(); doShowCurBrightnessPct(curBrightnessPct); // Use case: After the activity is run, when changes brightness on quick settings // and comes back here, the UI will not updated by onResume() // Using this change listener to compensate for it. mBrightnessManager.registerOnChange(mBrightnessContentObserver); } @Override protected void onPause() { super.onPause(); // Activity no longer visible: no need to listen to brightness change anymore. mBrightnessManager.unregisterOnChange(mBrightnessContentObserver); } private CharSequence getTextOfViewById(int id) { final TextView tView = (TextView)findViewById(id); return tView.getText(); } private void showBrightnessPctsDialog(CharSequence curValue) { showBrightnessPctsDialog(curValue, null); } private void showBrightnessPctsDialog(CharSequence curValue, CharSequence errMsg) { //@see https://stackoverflow.com/questions/10903754/input-text-dialog-android android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this, R.style.AppTheme_Dialog_Alert); builder.setTitle(getTextOfViewById(R.id.brightnessPctsLabel)); builder.setMessage(getTextOfViewById(R.id.brightnessPctsLabelDesc)); final EditText editText = new EditText(this); editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //@see https://developer.android.com/training/keyboard-input/style.html#Action //@see https://stackoverflow.com/a/5941620 editText.setImeOptions(EditorInfo.IME_ACTION_DONE); editText.setId(R.id.brightnessPctsInput); // for androidTest // TODO: style EditText to be consistent with the colors of the app builder.setView(editText); editText.setText(curValue); final TextView errMsgText = new TextView(this); if (errMsg != null && errMsg.length() > 0) { editText.setError(errMsg); } builder.setPositiveButton(R.string.ok_btn_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { updateModelSettingsWithEditText(editText); } }); builder.setNegativeButton(R.string.cancel_btn_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { // Nothing to do } }); final android.app.Dialog dialog = builder.show(); // set it here as it requires a reference to dialog editText.setOnEditorActionListener(new android.widget.TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { boolean handled = false; if (actionId == EditorInfo.IME_ACTION_DONE) { updateModelSettingsWithEditText(editText); dialog.dismiss(); handled = true; } return handled; } }); } private void updateModelSettingsWithEditText(final EditText editText) { String newVal = editText.getText().toString(); try { mModel.setSettings(newVal); } catch (IllegalArgumentException iae) { showBrightnessPctsDialog(newVal, iae.getMessage()); } } }
Settings UI refactor: encapsulate dialog implementation into an inner class
app/src/main/java/net/oldev/aBrightnessQS/MainActivity.java
Settings UI refactor: encapsulate dialog implementation into an inner class
<ide><path>pp/src/main/java/net/oldev/aBrightnessQS/MainActivity.java <ide> package net.oldev.aBrightnessQS; <ide> <add>import android.content.DialogInterface; <add>import android.os.Bundle; <add>import android.os.Handler; <ide> import android.support.v7.app.AppCompatActivity; <del>import android.os.Bundle; <del>import android.content.DialogInterface; <del>import android.os.Handler; <add>import android.text.InputType; <add>import android.view.KeyEvent; <ide> import android.view.View; <add>import android.view.inputmethod.EditorInfo; <add>import android.widget.EditText; <ide> import android.widget.TextView; <del>import android.widget.EditText; <del> <del>import android.text.InputType; <del>import android.view.inputmethod.EditorInfo; <del>import android.view.KeyEvent; <ide> <ide> public class MainActivity extends AppCompatActivity { <ide> <ide> brightnessPctsSection.setOnClickListener(new View.OnClickListener() { <ide> public void onClick(View v) { <ide> final CharSequence brightnessPctsStr = brightnessPctsOutput.getText(); <del> showBrightnessPctsDialog(brightnessPctsStr); <add> new BrightnessPctsDialogBuilder().show(brightnessPctsStr); <ide> } <ide> }); <ide> <ide> // Activity no longer visible: no need to listen to brightness change anymore. <ide> mBrightnessManager.unregisterOnChange(mBrightnessContentObserver); <ide> } <del> private CharSequence getTextOfViewById(int id) { <del> final TextView tView = (TextView)findViewById(id); <del> return tView.getText(); <del> } <ide> <del> private void showBrightnessPctsDialog(CharSequence curValue) { <del> showBrightnessPctsDialog(curValue, null); <del> } <del> <del> private void showBrightnessPctsDialog(CharSequence curValue, CharSequence errMsg) { <del> //@see https://stackoverflow.com/questions/10903754/input-text-dialog-android <del> <del> android.support.v7.app.AlertDialog.Builder builder = <del> new android.support.v7.app.AlertDialog.Builder(this, R.style.AppTheme_Dialog_Alert); <del> <del> builder.setTitle(getTextOfViewById(R.id.brightnessPctsLabel)); <del> builder.setMessage(getTextOfViewById(R.id.brightnessPctsLabelDesc)); <del> <del> final EditText editText = new EditText(this); <del> editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); <del> //@see https://developer.android.com/training/keyboard-input/style.html#Action <del> //@see https://stackoverflow.com/a/5941620 <del> editText.setImeOptions(EditorInfo.IME_ACTION_DONE); <del> editText.setId(R.id.brightnessPctsInput); // for androidTest <del> // TODO: style EditText to be consistent with the colors of the app <del> <del> builder.setView(editText); <del> <del> editText.setText(curValue); <del> final TextView errMsgText = new TextView(this); <del> if (errMsg != null && errMsg.length() > 0) { <del> editText.setError(errMsg); <add> // Encapsulates the logic of the dialog UI and actions <add> // It is primarily stateless, except it needs parent's mModel and Context <add> private class BrightnessPctsDialogBuilder { <add> public void show(CharSequence curValue) { <add> show(curValue, null); <ide> } <ide> <del> builder.setPositiveButton(R.string.ok_btn_label, new DialogInterface.OnClickListener() { <del> public void onClick(DialogInterface dialog, int whichButton) { <del> updateModelSettingsWithEditText(editText); <add> public void show(CharSequence curValue, CharSequence errMsg) { <add> //@see https://stackoverflow.com/questions/10903754/input-text-dialog-android <add> <add> android.support.v7.app.AlertDialog.Builder builder = <add> new android.support.v7.app.AlertDialog.Builder(MainActivity.this, R.style.AppTheme_Dialog_Alert); <add> <add> builder.setTitle(getTextOfViewById(R.id.brightnessPctsLabel)); <add> builder.setMessage(getTextOfViewById(R.id.brightnessPctsLabelDesc)); <add> <add> final EditText editText = new EditText(MainActivity.this); <add> editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); <add> //@see https://developer.android.com/training/keyboard-input/style.html#Action <add> //@see https://stackoverflow.com/a/5941620 <add> editText.setImeOptions(EditorInfo.IME_ACTION_DONE); <add> editText.setId(R.id.brightnessPctsInput); // for androidTest <add> // TODO: style EditText to be consistent with the colors of the app <add> <add> builder.setView(editText); <add> <add> editText.setText(curValue); <add> if (errMsg != null && errMsg.length() > 0) { <add> editText.setError(errMsg); <ide> } <del> }); <del> <del> builder.setNegativeButton(R.string.cancel_btn_label, new DialogInterface.OnClickListener() { <del> public void onClick(DialogInterface dialog, int whichButton) { <del> // Nothing to do <add> <add> builder.setPositiveButton(R.string.ok_btn_label, new DialogInterface.OnClickListener() { <add> public void onClick(DialogInterface dialog, int whichButton) { <add> updateModelSettingsWithEditText(editText); <add> } <add> }); <add> <add> builder.setNegativeButton(R.string.cancel_btn_label, new DialogInterface.OnClickListener() { <add> public void onClick(DialogInterface dialog, int whichButton) { <add> // Nothing to do <add> } <add> }); <add> <add> final android.app.Dialog dialog = builder.show(); <add> <add> // set it here as it requires a reference to dialog <add> editText.setOnEditorActionListener(new android.widget.TextView.OnEditorActionListener() { <add> @Override <add> public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { <add> boolean handled = false; <add> if (actionId == EditorInfo.IME_ACTION_DONE) { <add> updateModelSettingsWithEditText(editText); <add> dialog.dismiss(); <add> handled = true; <add> } <add> return handled; <add> } <add> }); <add> <add> } <add> private void updateModelSettingsWithEditText(final EditText editText) { <add> String newVal = editText.getText().toString(); <add> try { <add> MainActivity.this.mModel.setSettings(newVal); <add> } catch (IllegalArgumentException iae) { <add> show(newVal, iae.getMessage()); <ide> } <del> }); <add> } <ide> <del> final android.app.Dialog dialog = builder.show(); <del> <del> // set it here as it requires a reference to dialog <del> editText.setOnEditorActionListener(new android.widget.TextView.OnEditorActionListener() { <del> @Override <del> public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { <del> boolean handled = false; <del> if (actionId == EditorInfo.IME_ACTION_DONE) { <del> updateModelSettingsWithEditText(editText); <del> dialog.dismiss(); <del> handled = true; <del> } <del> return handled; <del> } <del> }); <del> <del> } <del> <del> private void updateModelSettingsWithEditText(final EditText editText) { <del> String newVal = editText.getText().toString(); <del> try { <del> mModel.setSettings(newVal); <del> } catch (IllegalArgumentException iae) { <del> showBrightnessPctsDialog(newVal, iae.getMessage()); <add> private CharSequence getTextOfViewById(int id) { <add> final TextView tView = (TextView)MainActivity.this.findViewById(id); <add> return tView.getText(); <ide> } <ide> } <ide> }
Java
apache-2.0
c78ba5c24ebef5c39edab49cdb5c4100ace72b35
0
hoge1e3/soyText,hoge1e3/soyText
/* * 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 jp.tonyu.soytext2.servlet; import jp.tonyu.js.Wrappable; import jp.tonyu.soytext2.auth.AuthenticatorList; import jp.tonyu.util.Context; public class Auth implements Wrappable { private String user; private final AuthenticatorList a; public static final Context<Auth> cur=new Context<Auth>(); public Auth(AuthenticatorList a) { super(); this.a = a; } public boolean login(String user, Object credential) { //AuthenticatorList a=authenticator(); if (a!=null && a.check(user, credential+"")) { this.user=user; return true; } return false; } public String user() { String user=(this.user==null?"nobody":this.user); // currentSession().userName(); return user; } public boolean isRoot() { return a.isRootUser(user()); } }
src/jp/tonyu/soytext2/servlet/Auth.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 jp.tonyu.soytext2.servlet; import jp.tonyu.js.Wrappable; import jp.tonyu.soytext2.auth.AuthenticatorList; import jp.tonyu.util.Context; public class Auth implements Wrappable { private String user; private final AuthenticatorList a; public static final Context<Auth> cur=new Context<Auth>(); public Auth(AuthenticatorList a) { super(); this.a = a; } public boolean login(String user, Object credential) { //AuthenticatorList a=authenticator(); if (a!=null && a.check(user, credential+"")) { this.user=user; return true; } return false; } public String user() { String user=(this.user==null?"nobody":this.user); // currentSession().userName(); return user; } }
Auth.isRoot
src/jp/tonyu/soytext2/servlet/Auth.java
Auth.isRoot
<ide><path>rc/jp/tonyu/soytext2/servlet/Auth.java <ide> String user=(this.user==null?"nobody":this.user); // currentSession().userName(); <ide> return user; <ide> } <add> public boolean isRoot() { <add> return a.isRootUser(user()); <add> } <ide> }
Java
apache-2.0
67d3e7ef3ea9c3c48e294d074121529523f8f3cb
0
WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules,WNPRC-EHR-Services/wnprc-modules
/* * Copyright (c) 2020 LabKey Corporation * * 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.labkey.test.tests.wnprc_purchasing; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.labkey.remoteapi.CommandException; import org.labkey.remoteapi.Connection; import org.labkey.remoteapi.query.InsertRowsCommand; import org.labkey.remoteapi.query.SaveRowsResponse; import org.labkey.remoteapi.query.TruncateTableCommand; import org.labkey.test.BaseWebDriverTest; import org.labkey.test.Locator; import org.labkey.test.Pages.CreateRequestPage; import org.labkey.test.TestFileUtils; import org.labkey.test.TestTimeoutException; import org.labkey.test.categories.EHR; import org.labkey.test.categories.WNPRC_EHR; import org.labkey.test.componenes.CreateVendorDialog; import org.labkey.test.components.dumbster.EmailRecordTable; import org.labkey.test.components.html.SiteNavBar; import org.labkey.test.util.APIUserHelper; import org.labkey.test.util.AbstractUserHelper; import org.labkey.test.util.ApiPermissionsHelper; import org.labkey.test.util.DataRegionTable; import org.labkey.test.util.Maps; import org.labkey.test.util.PortalHelper; import org.labkey.test.util.PostgresOnlyTest; import org.labkey.test.util.SchemaHelper; import org.labkey.test.util.UIPermissionsHelper; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.labkey.test.WebTestHelper.buildRelativeUrl; import static org.labkey.test.WebTestHelper.getRemoteApiConnection; @Category({EHR.class, WNPRC_EHR.class}) @BaseWebDriverTest.ClassTimeout(minutes = 5) public class WNPRC_PurchasingTest extends BaseWebDriverTest implements PostgresOnlyTest { //folders private static final String PURCHASING_FOLDER = "WNPRC Purchasing"; private static final String BILLING_FOLDER = "WNPRC Billing"; //user groups private static final String PURCHASE_REQUESTER_GROUP = "Purchase Requesters"; private static final String PURCHASE_RECEIVER_GROUP = "Purchase Receivers"; private static final String PURCHASE_ADMIN_GROUP = "Purchase Admins"; //users private static final String REQUESTER_USER_1 = "[email protected]"; private static final String REQUESTER_USER_2 = "[email protected]"; private static final String RECEIVER_USER = "[email protected]"; private static final String requester1Name = "purchaserequester1"; private static final String requester2Name = "purchaserequester2"; private static final String ADMIN_USER = "[email protected]"; private static final String PURCHASE_DIRECTOR_USER = "[email protected]"; //other properties //sample data private final File ALIASES_TSV = TestFileUtils.getSampleData("wnprc_purchasing/aliases.tsv"); private final File SHIPPING_INFO_TSV = TestFileUtils.getSampleData("wnprc_purchasing/shippingInfo.tsv"); private final File VENDOR_TSV = TestFileUtils.getSampleData("wnprc_purchasing/vendor.tsv"); //account info private final String ACCT_100 = "acct100"; private final String ACCT_101 = "acct101"; private final String OTHER_ACCT_FIELD_NAME = "otherAcctAndInves"; //helpers public AbstractUserHelper _userHelper = new APIUserHelper(this); ApiPermissionsHelper _apiPermissionsHelper = new ApiPermissionsHelper(this); File pdfFile = new File(TestFileUtils.getSampleData("fileTypes"), "pdf_sample.pdf"); DateTimeFormatter _dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime today = LocalDateTime.now(); private int _adminUserId; private int _requesterUserId1; private int _requesterUserId2; private int _receiverUserId; private int _directorUserId; private int _adminGroupId; private int _receiverGroupId; private int _requesterGroupId; private SchemaHelper _schemaHelper = new SchemaHelper(this); private UIPermissionsHelper _permissionsHelper = new UIPermissionsHelper(this); @BeforeClass public static void setupProject() throws IOException, CommandException { WNPRC_PurchasingTest init = (WNPRC_PurchasingTest) getCurrentTest(); init.doSetup(); } @Override protected void doCleanup(boolean afterTest) throws TestTimeoutException { _containerHelper.deleteProject(getProjectName(), afterTest); _containerHelper.deleteProject(BILLING_FOLDER, afterTest); } private void doSetup() throws IOException, CommandException { goToHome(); log("Create 'WNPRC Billing' folder"); _containerHelper.createProject(BILLING_FOLDER, PURCHASING_FOLDER); _containerHelper.enableModules(Arrays.asList("EHR_Billing", "Dumbster")); log("Populate ehr_billing.aliases"); goToProjectHome(BILLING_FOLDER); addExtensibleColumn("groupName"); uploadData(ALIASES_TSV, "ehr_billing", "aliases", BILLING_FOLDER); goToHome(); log("Create a 'WNPRC Purchasing' folder"); _containerHelper.createProject(getProjectName(), PURCHASING_FOLDER); log("Add WNPRC Purchasing Landing page webpart"); new SiteNavBar(getDriver()).enterPageAdminMode(); (new PortalHelper(this)).addWebPart("WNPRC Purchasing Landing Page"); new SiteNavBar(getDriver()).exitPageAdminMode(); goToProjectHome(); log("Upload purchasing data"); uploadPurchasingData(); log("Create ehrBillingLinked schema"); _schemaHelper.createLinkedSchema(getProjectName(), "ehr_billingLinked", BILLING_FOLDER, "ehr_billingLinked", null, null, null); log("Create users and groups"); createUsersAndGroups(); log("Add groups to purchasing folder"); addUsersToPurchasingFolder(); log("Create user-account associations"); createUserAccountAssociations(); goToHome(); } private void addExtensibleColumn(String extensibleCol) { goToSchemaBrowser(); selectQuery("ehr_billing", "aliases"); clickAndWait(Locator.linkWithText("create definition"), 5000); Locator.XPathLocator manuallyDefineFieldsLoc = Locator.tagWithClass("div", "domain-form-manual-btn"); click(manuallyDefineFieldsLoc); setFormElement(Locator.inputByNameContaining("domainpropertiesrow-name"), extensibleCol); clickButton("Save"); } private void createUsersAndGroups() { log("Create a purchasing admin user"); _adminUserId = _userHelper.createUser(ADMIN_USER).getUserId().intValue(); log("Create a purchasing requester users"); _requesterUserId1 = _userHelper.createUser(REQUESTER_USER_1).getUserId().intValue(); _requesterUserId2 = _userHelper.createUser(REQUESTER_USER_2).getUserId().intValue(); log("Create a purchasing receiver user"); _receiverUserId = _userHelper.createUser(RECEIVER_USER).getUserId().intValue(); log("Create a purchasing director user"); _directorUserId = _userHelper.createUser(PURCHASE_DIRECTOR_USER).getUserId().intValue(); log("Create a purchasing groups"); _adminGroupId = _permissionsHelper.createPermissionsGroup(PURCHASE_ADMIN_GROUP); _receiverGroupId = _permissionsHelper.createPermissionsGroup(PURCHASE_RECEIVER_GROUP); _requesterGroupId = _permissionsHelper.createPermissionsGroup(PURCHASE_REQUESTER_GROUP); } private void addUsersToPurchasingFolder() { goToProjectHome(); log("Add users to " + PURCHASE_ADMIN_GROUP); _permissionsHelper.addUserToProjGroup(getCurrentUserName(), getProjectName(), PURCHASE_ADMIN_GROUP); _permissionsHelper.addUserToProjGroup(ADMIN_USER, getProjectName(), PURCHASE_ADMIN_GROUP); _permissionsHelper.addUserToProjGroup(PURCHASE_DIRECTOR_USER, getProjectName(), PURCHASE_ADMIN_GROUP); log("Add users to " + PURCHASE_RECEIVER_GROUP); _permissionsHelper.addUserToProjGroup(RECEIVER_USER, getProjectName(), PURCHASE_RECEIVER_GROUP); log("Add users to " + PURCHASE_REQUESTER_GROUP); _permissionsHelper.addUserToProjGroup(REQUESTER_USER_1, getProjectName(), PURCHASE_REQUESTER_GROUP); _permissionsHelper.addUserToProjGroup(REQUESTER_USER_2, getProjectName(), PURCHASE_REQUESTER_GROUP); _permissionsHelper.setPermissions(PURCHASE_ADMIN_GROUP, "Project Administrator"); _permissionsHelper.setPermissions(PURCHASE_REQUESTER_GROUP, "Submitter"); _permissionsHelper.setPermissions(PURCHASE_REQUESTER_GROUP, "Reader"); _permissionsHelper.setPermissions(PURCHASE_RECEIVER_GROUP, "Editor"); _permissionsHelper.setUserPermissions(PURCHASE_DIRECTOR_USER, "WNPRC Purchasing Director"); } private void goToPurchaseAdminPage() { beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "purchaseAdmin")); } private void goToRequesterPage() { beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "requester")); } private void goToReceiverPage() { beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "purchaseReceiver")); } private void createUserAccountAssociations() throws IOException, CommandException { List<Map<String, Object>> userAcctAssocRows = new ArrayList<>(); Map<String, Object> userAcctRow = new HashMap<>(); userAcctRow.put("userId", _requesterGroupId); userAcctRow.put("account", ACCT_100); userAcctAssocRows.add(userAcctRow); userAcctRow = new HashMap<>(); userAcctRow.put("userId", _requesterGroupId); userAcctRow.put("account", ACCT_101); userAcctAssocRows.add(userAcctRow); userAcctRow = new HashMap<>(); userAcctRow.put("userId", _adminGroupId); userAcctRow.put("accessToAllAccounts", true); userAcctAssocRows.add(userAcctRow); int rowsInserted = insertData(getRemoteApiConnection(true), "ehr_purchasing", "userAccountAssociations", userAcctAssocRows, getProjectName()).size(); assertEquals("Incorrect number of rows created", 3, rowsInserted); } private void uploadPurchasingData() throws IOException, CommandException { uploadData(SHIPPING_INFO_TSV, "ehr_purchasing", "shippingInfo", getProjectName()); uploadData(VENDOR_TSV, "ehr_purchasing", "vendor", getProjectName()); } private void uploadData(File tsvFile, String schemaName, String tableName, String projectName) throws IOException, CommandException { Connection connection = getRemoteApiConnection(true); List<Map<String, Object>> tsv = loadTsv(tsvFile); insertData(connection, schemaName, tableName, tsv, projectName); } private List<Map<String, Object>> insertData(Connection connection, String schemaName, String queryName, List<Map<String, Object>> rows, String projectName) throws IOException, CommandException { log("Loading data in: " + schemaName + "." + queryName); InsertRowsCommand command = new InsertRowsCommand(schemaName, queryName); command.setRows(rows); SaveRowsResponse response = command.execute(connection, projectName); return response.getRows(); } @Before public void preTest() throws IOException, CommandException { goToProjectHome(); clearAllRequest(); } @Test public void testCreateRequestAndEmailNotification() throws IOException, CommandException { log("Delete emails from dumbster"); enableEmailRecorder(); goToRequesterPage(); impersonate(REQUESTER_USER_1); waitAndClickAndWait(Locator.linkWithText("Create Request")); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); log("Verifying the validation for mandatory fields"); requestPage.submitForReviewExpectingError(); checker().verifyEquals("Invalid error message", "Unable to submit request, missing required fields.", requestPage.getAlertMessage()); log("Creating a request order"); requestPage.setAccountsToCharge("acct100 - Assay Services") .setVendor("Real Santa Claus") .setBusinessPurpose("Holiday Party") .setSpecialInstructions("Ho Ho Ho") .setShippingDestination("456 Thompson lane (Math bldg)") .setDeliveryAttentionTo("Mrs Claus") .setItemDesc("Pen") .setUnitInput("CS") .setUnitCost("10") .setQuantity("25") .submitForReview(); log("Verifying the request created"); waitForElement(Locator.tagWithAttribute("h3", "title", "Purchase Requests")); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); assertEquals("Invalid number of requests ", 1, table.getDataRowCount()); assertEquals("Invalid request status ", "Review Pending", table.getDataAsText(0, "requestStatus")); String requestId = table.getDataAsText(0, "rowId"); stopImpersonating(); goToModule("Dumbster"); log("Verify email sent to purchase admins for orders < $5000"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "A new purchase request for $250.00 is submitted"; List<String> sortedExpected = Arrays.asList("[email protected]"); sortedExpected.sort(String.CASE_INSENSITIVE_ORDER); List<String> sortedActual = mailTable.getColumnDataAsText("To"); sortedActual.sort(String.CASE_INSENSITIVE_ORDER); checker().verifyEquals("Incorrect To for the emails sent", sortedExpected, sortedActual); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("A new purchasing request # " + requestId + " by " + requester1Name + " was submitted on " + _dateTimeFormatter.format(today) + " for the total of $250.00.")); } @Test public void testOtherVendorRequest() throws IOException, CommandException { goToRequesterPage(); impersonate(REQUESTER_USER_1); clickButton("Create Request"); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setVendor("Other"); log("Creating the New vendor"); CreateVendorDialog vendorDialog = new CreateVendorDialog(getDriver()); vendorDialog.setVendorName("Test1") .setStreetAddress("123 Will street") .setCity("New York City") .setState("New York") .setCountry("USA") .setZipCode("98989") .save(); log("Edit the vendor information"); clickButton("Edit other vendor", 0); vendorDialog = new CreateVendorDialog(getDriver()); vendorDialog.setNotes("Edited vendor") .save(); requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge("acct101 - Business Office") .setBusinessPurpose("New vendor") .setSpecialInstructions("Welcome Party") .setShippingDestination("89 meow ave (Chemistry Bldg)") .setDeliveryAttentionTo("Newcomer") .setItemDesc("Pencil") .setUnitInput("PK") .setUnitCost("1000") .setQuantity("25000") .submitForReview(); log("Verifying the request created"); waitForElement(Locator.tagWithAttribute("h3", "title", "Purchase Requests")); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); checker().verifyEquals("Invalid number of requests ", 1, table.getDataRowCount()); checker().verifyEquals("Invalid request status ", "Review Pending", table.getDataAsText(0, "requestStatus")); checker().verifyEquals("Invalid Vendor ", "Test1", table.getDataAsText(0, "vendor")); checker().screenShotIfNewError("other_vendor_request"); stopImpersonating(); } @Test public void testPurchaseAdminWorkflow() throws IOException, CommandException { File jpgFile = new File(TestFileUtils.getSampleData("fileTypes"), "jpg_sample.jpg"); log("-----Create request as lab end user-----"); log("Impersonate as " + REQUESTER_USER_1); impersonate(REQUESTER_USER_1); log("Create new Request - START"); goToRequesterPage(); clickButton("Create Request"); final CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge("acct100 - Assay Services") .setVendor("Real Santa Claus") .setBusinessPurpose("Holiday Party") .setSpecialInstructions("Ho Ho Ho") .setShippingDestination("456 Thompson lane (Math bldg)") .setDeliveryAttentionTo("Mrs Claus") .setItemDesc("Pen") .setUnitInput("CS") .setUnitCost("10") .setQuantity("25"); log("Upload an attachment"); requestPage.addAttachment(jpgFile) .submitForReview(); log("Verify " + REQUESTER_USER_1 + " can view the request submitted"); waitForElement(Locator.tagWithAttribute("h3", "title", "Purchase Requests")); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); String requestID = table.getDataAsText(0, "rowId"); checker().verifyEquals("Invalid number of requests ", 1, table.getDataRowCount()); checker().verifyEquals("Invalid request status ", "Review Pending", table.getDataAsText(0, "requestStatus")); checker().verifyEquals("Invalid requester", requester1Name, table.getDataAsText(0, "requester")); checker().screenShotIfNewError("requester_view_submitted"); stopImpersonating(); log("-----Update request as Purchasing Admin-----"); goToPurchaseAdminPage(); log("Impersonate as " + ADMIN_USER); impersonate(ADMIN_USER); clickAndWait(Locator.linkContainingText("All Open Requests")); DataRegionTable requestsQueryForAdmins = new DataRegionTable("query", getDriver()); requestsQueryForAdmins.setFilter("requestNum", "Equals", requestID); assertEquals("Admin is not seeing the request " + requestID, 1, requestsQueryForAdmins.getDataRowCount()); clickAndWait(Locator.linkWithText(requestID)); final CreateRequestPage requestPage2 = new CreateRequestPage(getDriver()); waitFor(() -> !requestPage2.getAccountsToCharge().equals("Select"), "Form didn't load existing values", 5_000); checker().verifyEquals("Invalid value for Accounts to charge ", "acct100 - Assay Services", requestPage2.getAccountsToCharge()); checker().verifyEquals("Invalid value for Vendor ", "Real Santa Claus", requestPage2.getVendor()); checker().verifyEquals("Invalid value for BusinessPurpose ", "Holiday Party", requestPage2.getBusinessPurpose()); checker().verifyEquals("Invalid value for Special Instructions ", "Ho Ho Ho", requestPage2.getSpecialInstructions()); checker().verifyEquals("Invalid value for Shipping Destination", "456 Thompson lane (Math bldg)", requestPage2.getShippingDestination()); checker().verifyEquals("Invalid value for Delivery Attention to ", "Mrs Claus", requestPage2.getDeliveryAttentionTo()); checker().verifyEquals("Invalid value for Line Item ", "Pen", requestPage2.getItemDesc()); checker().verifyEquals("Invalid value for Unit Input ", "CS", requestPage2.getUnitInput()); checker().verifyEquals("Invalid value for Unit cost ", "10", requestPage2.getUnitCost()); checker().verifyEquals("Invalid value for Quantity ", "25", requestPage2.getQuantity()); checker().screenShotIfNewError("admin_view_submitted"); log("Upload another attachment"); requestPage2.addAttachment(pdfFile); log("Verify Status in 'Purchase Admin' panel is 'Review Pending'"); checker().verifyEquals("Invalid Assigned to value ", "Select", requestPage2.getAssignedTo()); checker().verifyEquals("Invalid Program value", "4", requestPage2.getProgram()); checker().verifyEquals("Invalid status ", "Review Pending", requestPage2.getStatus()); checker().screenShotIfNewError("status_review_pending"); requestPage2.setStatus("Request Approved") .setConfirmationNo("12345") .submit(); stopImpersonating(false); beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "requestEntry", Maps.of("requestRowId", requestID))); log("Impersonate as " + REQUESTER_USER_2); impersonate(REQUESTER_USER_2); assertTextPresent("You do not have sufficient permissions to update this request."); stopImpersonating(); } @Test public void testReferenceTables() { goToProjectHome(); clickAndWait(Locator.linkWithText("Purchasing Admin")); log("Checking if the link is present on the Purchasing Admin page"); checker().verifyTrue("Vendors reference is not present", isElementPresent(Locator.linkWithText("Vendors"))); checker().verifyTrue("User Account Associations reference is not present", isElementPresent(Locator.linkWithText("User Account Associations"))); checker().verifyTrue("Shipping Info reference is not present", isElementPresent(Locator.linkWithText("Shipping Info"))); checker().verifyTrue("Item Units reference is not present", isElementPresent(Locator.linkWithText("Item Units"))); checker().verifyTrue("Line Items reference is not present", isElementPresent(Locator.linkWithText("Line Items"))); log("Verifying if link navigates to correct query"); checker().verifyEquals("Incorrect link for Vendors", "Vendor", getQueryName("Vendors")); checker().verifyEquals("Incorrect link for User Account Associations", "User Account Associations", getQueryName("User Account Associations")); checker().verifyEquals("Incorrect link for Shipping Info", "Shipping Info", getQueryName("Shipping Info")); checker().verifyEquals("Incorrect link for Item Units", "Item Units", getQueryName("Item Units")); checker().verifyEquals("Incorrect link for Line Items", "Line Items", getQueryName("Line Items")); } @Test public void testAdminPage() throws IOException, CommandException { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime date = LocalDateTime.now(); log("Verifying requester does not access to admin web part"); goToProjectHome(); impersonate(REQUESTER_USER_1); goToPurchaseAdminPage(); checker().verifyTrue(REQUESTER_USER_1 + "user should not permission for admin page", isElementPresent(Locator.tagWithClass("div", "labkey-error-subheading") .withText("User does not have permission to perform this operation."))); checker().screenShotIfNewError("requester_view_restricted"); goBack(); log("Creating request as " + REQUESTER_USER_1); goToRequesterPage(); waitAndClickAndWait(Locator.linkWithText("Create Request")); Map<String, String> requesterRequest = new HashMap<>(); requesterRequest.put("Account to charge", "acct100 - Assay Services"); requesterRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); requesterRequest.put("Vendor", "Dunder Mifflin"); requesterRequest.put("Delivery attention to", "testing the workflow"); requesterRequest.put("Business purpose", "regression test"); requesterRequest.put("Item description", "Item1"); requesterRequest.put("Unit", "Term"); requesterRequest.put("Unit Cost", "10"); requesterRequest.put("Quantity", "6"); String requestId1 = createRequest(requesterRequest, null); stopImpersonating(); log("Creating request as " + ADMIN_USER); impersonate(ADMIN_USER); goToPurchaseAdminPage(); Map<String, String> adminRequest = new HashMap<>(); adminRequest.put("Account to charge", "acct101 - Business Office"); adminRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); adminRequest.put("Vendor", "Real Santa Claus"); adminRequest.put("Delivery attention to", "testing the workflow - Admin"); adminRequest.put("Business purpose", "regression test -Admin request"); adminRequest.put("Item description", "Item1"); adminRequest.put("Unit", "Term"); adminRequest.put("Unit Cost", "20"); adminRequest.put("Quantity", "3"); clickAndWait(Locator.linkWithText("Enter Request")); String requestId2 = createRequest(requesterRequest, null); log("Verifying all open requests"); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Open Requests")); DataRegionTable table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Incorrect request Id's", Arrays.asList(requestId1, requestId2), table.getColumnDataAsText("requestNum")); checker().verifyEquals("Incorrect requester's", Arrays.asList("purchaserequester1", "purchaseadmin"), table.getColumnDataAsText("requester")); checker().screenShotIfNewError("all_open_requests"); log("Changing the assignment of the request"); clickAndWait(Locator.linkWithText(requestId1)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAssignedTo("purchaseadmin") .setPurchaseOptions("Direct Payment") .setStatus("Request Approved") .setOrderDate(dtf.format(date)) .setCardPostDate(dtf.format(date)) .submit(); goToPurchaseAdminPage(); waitAndClickAndWait(Locator.linkWithText("My Open Requests")); table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Incorrect request in my open request", requestId1, table.getDataAsText(0, "requestNum")); checker().verifyEquals("Incorrect status", "Request Approved", table.getDataAsText(0, "requestStatus")); checker().screenShotIfNewError("my_open_requests"); log("Completing the order"); goToPurchaseAdminPage(); waitAndClickAndWait(Locator.linkWithText("All Open Requests")); clickAndWait(Locator.linkWithText(requestId2)); requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Order Complete").submit(); clickAndWait(Locator.linkWithText("Completed Requests")); table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Incorrect request in my open request", requestId2, table.getDataAsText(0, "requestNum")); checker().verifyEquals("Incorrect status", "Order Complete", table.getDataAsText(0, "requestStatus")); checker().screenShotIfNewError("completed_requests"); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Open Requests")); table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Completed order should not be present", Arrays.asList(requestId1), table.getColumnDataAsText("requestNum")); checker().screenShotIfNewError("requests_after_completing"); stopImpersonating(); log("Verifying the P-Card view"); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("P-Card View")); table = new DataRegionTable("query", getDriver()); assertEquals("Incorrect number of rows in P-Card view", 2, table.getDataRowCount()); } @Test public void testReceiverActions() { goToProjectHome(); impersonate(REQUESTER_USER_1); goToRequesterPage(); log("Creating the first request as" + REQUESTER_USER_1); waitAndClickAndWait(Locator.linkWithText("Create Request")); Map<String, String> requestInputs = new HashMap<>(); requestInputs.put("Account to charge", "acct101 - Business Office"); requestInputs.put("Shipping destination", "456 Thompson lane (Math bldg)"); requestInputs.put("Vendor", "Dunder Mifflin"); requestInputs.put("Delivery attention to", "testing the workflow - receiver"); requestInputs.put("Business purpose", "regression test -receiver request"); requestInputs.put("Item description", "Item1"); requestInputs.put("Unit", "Term"); requestInputs.put("Unit Cost", "20"); requestInputs.put("Quantity", "3"); String requestId1 = createRequest(requestInputs, null); log("Creating the second request as" + REQUESTER_USER_1); requestInputs = new HashMap<>(); requestInputs.put("Account to charge", "acct100 - Assay Services"); requestInputs.put("Shipping destination", "456 Thompson lane (Math bldg)"); requestInputs.put("Vendor", "Real Santa Claus"); requestInputs.put("Delivery attention to", "testing the workflow - receiver"); requestInputs.put("Business purpose", "regression test -receiver request"); requestInputs.put("Item description", "Item2"); requestInputs.put("Unit", "CS"); requestInputs.put("Unit Cost", "20"); requestInputs.put("Quantity", "300"); clickAndWait(Locator.linkWithText("Create Request")); String requestId2 = createRequest(requestInputs, null); stopImpersonating(); log("Updating the request by " + ADMIN_USER); goToPurchaseAdminPage(); impersonate(ADMIN_USER); clickAndWait(Locator.linkWithText("All Open Requests")); clickAndWait(Locator.linkWithText(requestId1)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setQuantityReceived("4"); requestPage.setStatus("Order Placed"); requestPage.submit(); waitAndClickAndWait(Locator.linkWithText("All Open Requests")); clickAndWait(Locator.linkWithText(requestId2)); requestPage = new CreateRequestPage(getDriver()); requestPage.setQuantityReceived("40"); requestPage.setStatus("Order Placed"); requestPage.submit(); stopImpersonating(); log("Testing as receiver"); impersonate(RECEIVER_USER); goToPurchaseAdminPage(); Assert.assertTrue("Receiver should not have permission to access admin page", isElementPresent(Locator.tagWithClass("div", "labkey-error-subheading") .withText("User does not have permission to perform this operation."))); goToReceiverPage(); waitAndClickAndWait(Locator.linkWithText(requestId2)); requestPage = new CreateRequestPage(getDriver()); requestPage.addAttachment(pdfFile); requestPage.setQuantityReceived("300"); requestPage.submit(); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); assertEquals("The line item table should be empty", 0, table.getDataRowCount()); stopImpersonating(); goToPurchaseAdminPage(); waitAndClickAndWait(Locator.linkWithText("All Requests")); table = new DataRegionTable("query", getDriver()); table.setFilter("requestNum", "Equals One Of (example usage: a;b;c)", requestId1 + ";" + requestId2); assertEquals("Incorrect order status", Arrays.asList("Order Received", "Order Received"), table.getColumnDataAsText("requestStatus")); } @Test public void testEmailNotificationApprovalWorkflow() { log("Delete all the emails from dumbster"); enableEmailRecorder(); goToProjectHome(PURCHASING_FOLDER); impersonate(REQUESTER_USER_2); goToRequesterPage(); Map<String, String> emailApprovalRequest = new HashMap<>(); emailApprovalRequest.put("Account to charge", "acct100 - Assay Services"); emailApprovalRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); emailApprovalRequest.put("Vendor", "Stuff, Inc"); emailApprovalRequest.put("Delivery attention to", "Testing the email notification approval workflow"); emailApprovalRequest.put("Business purpose", "BP"); emailApprovalRequest.put("Item description", "Item1"); emailApprovalRequest.put("Unit", "Term"); emailApprovalRequest.put("Unit Cost", "500"); emailApprovalRequest.put("Quantity", "10"); waitAndClickAndWait(Locator.linkWithText("Create Request")); String requestId = createRequest(emailApprovalRequest, null); stopImpersonating(); log("Verifying create request emails for request total of $5000"); goToModule("Dumbster"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "A new purchase request for $5,000.00 is submitted"; checker().verifyEquals("Incorrect To for the emails sent", Arrays.asList("[email protected]", "[email protected]"), mailTable.getColumnDataAsText("To")); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("A new purchasing request # " + requestId + " by " + requester2Name + " was submitted on " + _dateTimeFormatter.format(today) + " for the total of $5,000.00.")); checker().screenShotIfNewError("request_submitted_email"); log("Delete emails from dumbster"); enableEmailRecorder(); goToPurchaseAdminPage(); impersonate(PURCHASE_DIRECTOR_USER); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Request Approved").submit(); stopImpersonating(); goToModule("Dumbster"); mailTable = new EmailRecordTable(this); subject = "Purchase request # " + requestId + " status update"; checker().verifyEquals("Incorrect To for the emails sent after approval", Arrays.asList(getCurrentUser(), ADMIN_USER), mailTable.getColumnDataAsText("To")); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " for the total of $5,000.00 has been approved by the purchasing director.")); checker().screenShotIfNewError("request_approved_email"); } @Test public void testEmailNotificationRejectWorkflow() { String rejectReasonMsg = "Rejected due to budgetary constraints, please contact your PI for more details."; goToProjectHome(PURCHASING_FOLDER); impersonate(REQUESTER_USER_1); goToRequesterPage(); Map<String, String> emailApprovalRequest = new HashMap<>(); emailApprovalRequest.put("Account to charge", "acct100 - Assay Services"); emailApprovalRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); emailApprovalRequest.put("Vendor", "Stuff, Inc"); emailApprovalRequest.put("Delivery attention to", "Testing the email notification approval workflow"); emailApprovalRequest.put("Business purpose", "BP"); emailApprovalRequest.put("Item description", "Item1"); emailApprovalRequest.put("Unit", "Term"); emailApprovalRequest.put("Unit Cost", "500"); emailApprovalRequest.put("Quantity", "20"); waitAndClickAndWait(Locator.linkWithText("Create Request")); String requestId = createRequest(emailApprovalRequest, null); stopImpersonating(); log("Delete the emails in the dumbster"); enableEmailRecorder(); log("Purchase Director : Rejecting the request >= $5000"); goToPurchaseAdminPage(); impersonate(PURCHASE_DIRECTOR_USER); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Request Rejected"); requestPage.setRejectReason(rejectReasonMsg); requestPage.submit(); stopImpersonating(); goToModule("Dumbster"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "Purchase request # " + requestId + " status update"; checker().verifyEquals("Incorrect To for the emails sent after rejection", Arrays.asList(getCurrentUser(), ADMIN_USER), mailTable.getColumnDataAsText("To")); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " for the total of $10,000.00 has been rejected by the purchasing director.")); checker().verifyTrue("Reason for rejection not found in the email body", mailTable.getMessage(subject).getBody().contains(rejectReasonMsg)); checker().screenShotIfNewError("request_rejection_email"); } @Test public void testEmailCustomizationLineItemUpdate() { log("Updating the settings for custom message"); goToAdminConsole().clickEmailCustomization(); selectOptionByText(Locator.css("select[id='templateClass']"), "WNPRC Purchasing - Line item update notification"); setFormElement(Locator.name("emailSubject"), "Custom subject # ^requestNum^ for line item update"); clickButton("Save"); goToRequesterPage(); impersonate(REQUESTER_USER_1); goToRequesterPage(); Map<String, String> emailApprovalRequest = new HashMap<>(); emailApprovalRequest.put("Account to charge", "acct100 - Assay Services"); emailApprovalRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); emailApprovalRequest.put("Vendor", "Stuff, Inc"); emailApprovalRequest.put("Delivery attention to", "Testing the email notification approval workflow"); emailApprovalRequest.put("Business purpose", "BP"); emailApprovalRequest.put("Item description", "Item1"); emailApprovalRequest.put("Unit", "Term"); emailApprovalRequest.put("Unit Cost", "500"); emailApprovalRequest.put("Quantity", "20"); waitAndClickAndWait(Locator.linkWithText("Create Request")); String requestId = createRequest(emailApprovalRequest, null); stopImpersonating(); log("Deleting the emails from dumbster"); enableEmailRecorder(); log("Updating the request status and line item to trigger email notif"); impersonate(ADMIN_USER); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Order Placed"); requestPage.setQuantity("15").submit(); stopImpersonating(); goToModule("Dumbster"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "Custom subject # " + requestId + " for line item update"; checker().verifyEquals("Incorrect To for the emails sent for line item update", Arrays.asList(REQUESTER_USER_1, REQUESTER_USER_1), mailTable.getColumnDataAsText("To")); mailTable.clickSubject(subject); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Your purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " has been updated.")); subject = "Purchase request # " + requestId + " status update"; mailTable.clickSubject(subject); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " for the total of $7,500.00 has been ordered by the purchasing department.")); checker().screenShotIfNewError("custom_request_email"); log("Delete emails from dumbster"); enableEmailRecorder(); log("Verify quantity received email notif"); goToReceiverPage(); impersonate(RECEIVER_USER); clickAndWait(Locator.linkWithText(requestId)); requestPage = new CreateRequestPage(getDriver()); requestPage.setQuantityReceived("15").submit(); stopImpersonating(); goToModule("Dumbster"); mailTable = new EmailRecordTable(this); subject = "Custom subject # " + requestId + " for line item update"; checker().verifyEquals("Incorrect To for the emails sent for line item update", Arrays.asList(REQUESTER_USER_1), mailTable.getColumnDataAsText("To")); mailTable.clickSubject(subject); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("All line items are received.")); checker().screenShotIfNewError("custom_request_email"); } @Test public void testReorderRequest() { File jpgFile = new File(TestFileUtils.getSampleData("fileTypes"), "jpg_sample.jpg"); goToProjectHome(); impersonate(REQUESTER_USER_1); goToRequesterPage(); log("Creating the first request as" + REQUESTER_USER_1); waitAndClickAndWait(Locator.linkWithText("Create Request")); Map<String, String> requestInputs = new HashMap<>(); requestInputs.put("Account to charge", "acct101 - Business Office"); requestInputs.put("Shipping destination", "456 Thompson lane (Math bldg)"); requestInputs.put("Vendor", "Dunder Mifflin"); requestInputs.put("Delivery attention to", "testing the reorder"); requestInputs.put("Business purpose", "regression test -reorder"); requestInputs.put("Item description", "Item1"); requestInputs.put("Unit", "Term"); requestInputs.put("Unit Cost", "20"); requestInputs.put("Quantity", "3"); String requestId = createRequest(requestInputs, null); log("Verifying reorder by link"); clickAndWait(Locator.linkWithText("Reorder")); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge("acct100 - Assay Services"); requestPage.addAttachment(jpgFile); requestPage.submitForReview(); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); assertEquals("No new request created for reorder link", 2, table.getDataRowCount()); stopImpersonating(); log("verifying reorder by button"); impersonate(ADMIN_USER); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); requestPage = new CreateRequestPage(getDriver()); requestPage.reorderButton(); requestPage.setAccountsToCharge("acct100 - Assay Services"); requestPage.addAttachment(jpgFile); requestPage.submitForReview(); table = new DataRegionTable("query", getDriver()); clickAndWait(Locator.linkWithText("All Requests")); assertEquals("No new request created from reorder button", 3, table.getDataRowCount()); } private String getQueryName(String linkName) { clickAndWait(Locator.linkWithText(linkName)); String retVal = Locator.tag("h3").findElement(getDriver()).getText(); goBack(); return retVal; } private String createRequest(Map<String, String> request, @Nullable File fileName) { CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge(request.get("Account to charge")) .setVendor(request.get("Vendor")) .setBusinessPurpose(request.get("Business purpose")) .setShippingDestination(request.get("Shipping destination")) .setDeliveryAttentionTo(request.get("Delivery attention to")) .setItemDesc(request.get("Item description")) .setUnitInput(request.get("Unit")) .setUnitCost(request.get("Unit Cost")) .setQuantity(request.get("Quantity")); if (request.containsKey("Special instructions")) requestPage.setSpecialInstructions(request.get("Special instructions")); if (fileName != null) requestPage.addAttachment(fileName); requestPage.submitForReview(); if (getCurrentUser().equals("[email protected]")) { clickAndWait(Locator.linkWithText("All Open Requests")); DataRegionTable table = new DataRegionTable("query", getDriver()); table.setFilter("requester", "Equals", "purchaseadmin"); return table.getDataAsText(0, "requestNum"); } else { DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); return table.getDataAsText(table.getDataRowCount() - 1, "rowId"); } } private void clearAllRequest() throws IOException, CommandException { Connection cn = createDefaultConnection(); new TruncateTableCommand("ehr_purchasing", "lineItems").execute(cn, getProjectName()); new TruncateTableCommand("ehr_purchasing", "purchasingRequests").execute(cn, getProjectName()); } @Override protected BrowserType bestBrowser() { return BrowserType.CHROME; } @Override protected String getProjectName() { return PURCHASING_FOLDER; } @Override public List<String> getAssociatedModules() { return Collections.singletonList("WNPRC_Purchasing"); } }
WNPRC_Purchasing/test/src/org/labkey/test/tests/wnprc_purchasing/WNPRC_PurchasingTest.java
/* * Copyright (c) 2020 LabKey Corporation * * 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.labkey.test.tests.wnprc_purchasing; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.labkey.remoteapi.CommandException; import org.labkey.remoteapi.Connection; import org.labkey.remoteapi.query.InsertRowsCommand; import org.labkey.remoteapi.query.SaveRowsResponse; import org.labkey.remoteapi.query.TruncateTableCommand; import org.labkey.test.BaseWebDriverTest; import org.labkey.test.Locator; import org.labkey.test.Pages.CreateRequestPage; import org.labkey.test.TestFileUtils; import org.labkey.test.TestTimeoutException; import org.labkey.test.categories.EHR; import org.labkey.test.categories.WNPRC_EHR; import org.labkey.test.componenes.CreateVendorDialog; import org.labkey.test.components.dumbster.EmailRecordTable; import org.labkey.test.components.html.SiteNavBar; import org.labkey.test.util.APIUserHelper; import org.labkey.test.util.AbstractUserHelper; import org.labkey.test.util.ApiPermissionsHelper; import org.labkey.test.util.DataRegionTable; import org.labkey.test.util.Maps; import org.labkey.test.util.PortalHelper; import org.labkey.test.util.PostgresOnlyTest; import org.labkey.test.util.SchemaHelper; import org.labkey.test.util.UIPermissionsHelper; import java.io.File; import java.io.IOException; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.labkey.test.WebTestHelper.buildRelativeUrl; import static org.labkey.test.WebTestHelper.getRemoteApiConnection; @Category({EHR.class, WNPRC_EHR.class}) @BaseWebDriverTest.ClassTimeout(minutes = 5) public class WNPRC_PurchasingTest extends BaseWebDriverTest implements PostgresOnlyTest { //folders private static final String PURCHASING_FOLDER = "WNPRC Purchasing"; private static final String BILLING_FOLDER = "WNPRC Billing"; //user groups private static final String PURCHASE_REQUESTER_GROUP = "Purchase Requesters"; private static final String PURCHASE_RECEIVER_GROUP = "Purchase Receivers"; private static final String PURCHASE_ADMIN_GROUP = "Purchase Admins"; //users private static final String REQUESTER_USER_1 = "[email protected]"; private static final String REQUESTER_USER_2 = "[email protected]"; private static final String RECEIVER_USER = "[email protected]"; private static final String requester1Name = "purchaserequester1"; private static final String requester2Name = "purchaserequester2"; private static final String ADMIN_USER = "[email protected]"; private static final String PURCHASE_DIRECTOR_USER = "[email protected]"; //other properties //sample data private final File ALIASES_TSV = TestFileUtils.getSampleData("wnprc_purchasing/aliases.tsv"); private final File SHIPPING_INFO_TSV = TestFileUtils.getSampleData("wnprc_purchasing/shippingInfo.tsv"); private final File VENDOR_TSV = TestFileUtils.getSampleData("wnprc_purchasing/vendor.tsv"); //account info private final String ACCT_100 = "acct100"; private final String ACCT_101 = "acct101"; private final String OTHER_ACCT_FIELD_NAME = "otherAcctAndInves"; //helpers public AbstractUserHelper _userHelper = new APIUserHelper(this); ApiPermissionsHelper _apiPermissionsHelper = new ApiPermissionsHelper(this); File pdfFile = new File(TestFileUtils.getSampleData("fileTypes"), "pdf_sample.pdf"); DateTimeFormatter _dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime today = LocalDateTime.now(); private int _adminUserId; private int _requesterUserId1; private int _requesterUserId2; private int _receiverUserId; private int _directorUserId; private int _adminGroupId; private int _receiverGroupId; private int _requesterGroupId; private SchemaHelper _schemaHelper = new SchemaHelper(this); private UIPermissionsHelper _permissionsHelper = new UIPermissionsHelper(this); @BeforeClass public static void setupProject() throws IOException, CommandException { WNPRC_PurchasingTest init = (WNPRC_PurchasingTest) getCurrentTest(); init.doSetup(); } @Override protected void doCleanup(boolean afterTest) throws TestTimeoutException { _containerHelper.deleteProject(getProjectName(), afterTest); _containerHelper.deleteProject(BILLING_FOLDER, afterTest); } private void doSetup() throws IOException, CommandException { goToHome(); log("Create 'WNPRC Billing' folder"); _containerHelper.createProject(BILLING_FOLDER, PURCHASING_FOLDER); _containerHelper.enableModules(Arrays.asList("EHR_Billing", "Dumbster")); log("Populate ehr_billing.aliases"); goToProjectHome(BILLING_FOLDER); addExtensibleColumn("groupName"); uploadData(ALIASES_TSV, "ehr_billing", "aliases", BILLING_FOLDER); goToHome(); log("Create a 'WNPRC Purchasing' folder"); _containerHelper.createProject(getProjectName(), PURCHASING_FOLDER); log("Add WNPRC Purchasing Landing page webpart"); new SiteNavBar(getDriver()).enterPageAdminMode(); (new PortalHelper(this)).addWebPart("WNPRC Purchasing Landing Page"); new SiteNavBar(getDriver()).exitPageAdminMode(); goToProjectHome(); log("Upload purchasing data"); uploadPurchasingData(); log("Create ehrBillingLinked schema"); _schemaHelper.createLinkedSchema(getProjectName(), "ehr_billingLinked", BILLING_FOLDER, "ehr_billingLinked", null, null, null); log("Create users and groups"); createUsersAndGroups(); log("Add groups to purchasing folder"); addUsersToPurchasingFolder(); log("Create user-account associations"); createUserAccountAssociations(); goToHome(); } private void addExtensibleColumn(String extensibleCol) { goToSchemaBrowser(); selectQuery("ehr_billing", "aliases"); clickAndWait(Locator.linkWithText("create definition"), 5000); Locator.XPathLocator manuallyDefineFieldsLoc = Locator.tagWithClass("div", "domain-form-manual-btn"); click(manuallyDefineFieldsLoc); setFormElement(Locator.inputByNameContaining("domainpropertiesrow-name"), extensibleCol); clickButton("Save"); } private void createUsersAndGroups() { log("Create a purchasing admin user"); _adminUserId = _userHelper.createUser(ADMIN_USER).getUserId().intValue(); log("Create a purchasing requester users"); _requesterUserId1 = _userHelper.createUser(REQUESTER_USER_1).getUserId().intValue(); _requesterUserId2 = _userHelper.createUser(REQUESTER_USER_2).getUserId().intValue(); log("Create a purchasing receiver user"); _receiverUserId = _userHelper.createUser(RECEIVER_USER).getUserId().intValue(); log("Create a purchasing director user"); _directorUserId = _userHelper.createUser(PURCHASE_DIRECTOR_USER).getUserId().intValue(); log("Create a purchasing groups"); _adminGroupId = _permissionsHelper.createPermissionsGroup(PURCHASE_ADMIN_GROUP); _receiverGroupId = _permissionsHelper.createPermissionsGroup(PURCHASE_RECEIVER_GROUP); _requesterGroupId = _permissionsHelper.createPermissionsGroup(PURCHASE_REQUESTER_GROUP); } private void addUsersToPurchasingFolder() { goToProjectHome(); log("Add users to " + PURCHASE_ADMIN_GROUP); _permissionsHelper.addUserToProjGroup(getCurrentUserName(), getProjectName(), PURCHASE_ADMIN_GROUP); _permissionsHelper.addUserToProjGroup(ADMIN_USER, getProjectName(), PURCHASE_ADMIN_GROUP); _permissionsHelper.addUserToProjGroup(PURCHASE_DIRECTOR_USER, getProjectName(), PURCHASE_ADMIN_GROUP); log("Add users to " + PURCHASE_RECEIVER_GROUP); _permissionsHelper.addUserToProjGroup(RECEIVER_USER, getProjectName(), PURCHASE_RECEIVER_GROUP); log("Add users to " + PURCHASE_REQUESTER_GROUP); _permissionsHelper.addUserToProjGroup(REQUESTER_USER_1, getProjectName(), PURCHASE_REQUESTER_GROUP); _permissionsHelper.addUserToProjGroup(REQUESTER_USER_2, getProjectName(), PURCHASE_REQUESTER_GROUP); _permissionsHelper.setPermissions(PURCHASE_ADMIN_GROUP, "Project Administrator"); _permissionsHelper.setPermissions(PURCHASE_REQUESTER_GROUP, "Submitter"); _permissionsHelper.setPermissions(PURCHASE_REQUESTER_GROUP, "Reader"); _permissionsHelper.setPermissions(PURCHASE_RECEIVER_GROUP, "Editor"); _permissionsHelper.setUserPermissions(PURCHASE_DIRECTOR_USER, "WNPRC Purchasing Director"); } private void goToPurchaseAdminPage() { beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "purchaseAdmin")); } private void goToRequesterPage() { beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "requester")); } private void goToReceiverPage() { beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "purchaseReceiver")); } private void createUserAccountAssociations() throws IOException, CommandException { List<Map<String, Object>> userAcctAssocRows = new ArrayList<>(); Map<String, Object> userAcctRow = new HashMap<>(); userAcctRow.put("userId", _requesterGroupId); userAcctRow.put("account", ACCT_100); userAcctAssocRows.add(userAcctRow); userAcctRow = new HashMap<>(); userAcctRow.put("userId", _requesterGroupId); userAcctRow.put("account", ACCT_101); userAcctAssocRows.add(userAcctRow); userAcctRow = new HashMap<>(); userAcctRow.put("userId", _adminGroupId); userAcctRow.put("accessToAllAccounts", true); userAcctAssocRows.add(userAcctRow); int rowsInserted = insertData(getRemoteApiConnection(true), "ehr_purchasing", "userAccountAssociations", userAcctAssocRows, getProjectName()).size(); assertEquals("Incorrect number of rows created", 3, rowsInserted); } private void uploadPurchasingData() throws IOException, CommandException { uploadData(SHIPPING_INFO_TSV, "ehr_purchasing", "shippingInfo", getProjectName()); uploadData(VENDOR_TSV, "ehr_purchasing", "vendor", getProjectName()); } private void uploadData(File tsvFile, String schemaName, String tableName, String projectName) throws IOException, CommandException { Connection connection = getRemoteApiConnection(true); List<Map<String, Object>> tsv = loadTsv(tsvFile); insertData(connection, schemaName, tableName, tsv, projectName); } private List<Map<String, Object>> insertData(Connection connection, String schemaName, String queryName, List<Map<String, Object>> rows, String projectName) throws IOException, CommandException { log("Loading data in: " + schemaName + "." + queryName); InsertRowsCommand command = new InsertRowsCommand(schemaName, queryName); command.setRows(rows); SaveRowsResponse response = command.execute(connection, projectName); return response.getRows(); } @Before public void preTest() throws IOException, CommandException { goToProjectHome(); clearAllRequest(); } @Test public void testCreateRequestAndEmailNotification() throws IOException, CommandException { log("Delete emails from dumbster"); enableEmailRecorder(); goToRequesterPage(); impersonate(REQUESTER_USER_1); clickButton("Create Request"); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); log("Verifying the validation for mandatory fields"); requestPage.submitForReviewExpectingError(); checker().verifyEquals("Invalid error message", "Unable to submit request, missing required fields.", requestPage.getAlertMessage()); log("Creating a request order"); requestPage.setAccountsToCharge("acct100 - Assay Services") .setVendor("Real Santa Claus") .setBusinessPurpose("Holiday Party") .setSpecialInstructions("Ho Ho Ho") .setShippingDestination("456 Thompson lane (Math bldg)") .setDeliveryAttentionTo("Mrs Claus") .setItemDesc("Pen") .setUnitInput("CS") .setUnitCost("10") .setQuantity("25") .submitForReview(); log("Verifying the request created"); waitForElement(Locator.tagWithAttribute("h3", "title", "Purchase Requests")); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); assertEquals("Invalid number of requests ", 1, table.getDataRowCount()); assertEquals("Invalid request status ", "Review Pending", table.getDataAsText(0, "requestStatus")); String requestId = table.getDataAsText(0, "rowId"); stopImpersonating(); goToModule("Dumbster"); log("Verify email sent to purchase admins for orders < $5000"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "A new purchase request for $250.00 is submitted"; List<String> sortedExpected = Arrays.asList("[email protected]"); sortedExpected.sort(String.CASE_INSENSITIVE_ORDER); List<String> sortedActual = mailTable.getColumnDataAsText("To"); sortedActual.sort(String.CASE_INSENSITIVE_ORDER); checker().verifyEquals("Incorrect To for the emails sent", sortedExpected, sortedActual); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("A new purchasing request # " + requestId + " by " + requester1Name + " was submitted on " + _dateTimeFormatter.format(today) + " for the total of $250.00.")); } @Test public void testOtherVendorRequest() throws IOException, CommandException { goToRequesterPage(); impersonate(REQUESTER_USER_1); clickButton("Create Request"); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setVendor("Other"); log("Creating the New vendor"); CreateVendorDialog vendorDialog = new CreateVendorDialog(getDriver()); vendorDialog.setVendorName("Test1") .setStreetAddress("123 Will street") .setCity("New York City") .setState("New York") .setCountry("USA") .setZipCode("98989") .save(); log("Edit the vendor information"); clickButton("Edit other vendor", 0); vendorDialog = new CreateVendorDialog(getDriver()); vendorDialog.setNotes("Edited vendor") .save(); requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge("acct101 - Business Office") .setBusinessPurpose("New vendor") .setSpecialInstructions("Welcome Party") .setShippingDestination("89 meow ave (Chemistry Bldg)") .setDeliveryAttentionTo("Newcomer") .setItemDesc("Pencil") .setUnitInput("PK") .setUnitCost("1000") .setQuantity("25000") .submitForReview(); log("Verifying the request created"); waitForElement(Locator.tagWithAttribute("h3", "title", "Purchase Requests")); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); checker().verifyEquals("Invalid number of requests ", 1, table.getDataRowCount()); checker().verifyEquals("Invalid request status ", "Review Pending", table.getDataAsText(0, "requestStatus")); checker().verifyEquals("Invalid Vendor ", "Test1", table.getDataAsText(0, "vendor")); checker().screenShotIfNewError("other_vendor_request"); stopImpersonating(); } @Test public void testPurchaseAdminWorkflow() throws IOException, CommandException { File jpgFile = new File(TestFileUtils.getSampleData("fileTypes"), "jpg_sample.jpg"); log("-----Create request as lab end user-----"); log("Impersonate as " + REQUESTER_USER_1); impersonate(REQUESTER_USER_1); log("Create new Request - START"); goToRequesterPage(); clickButton("Create Request"); final CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge("acct100 - Assay Services") .setVendor("Real Santa Claus") .setBusinessPurpose("Holiday Party") .setSpecialInstructions("Ho Ho Ho") .setShippingDestination("456 Thompson lane (Math bldg)") .setDeliveryAttentionTo("Mrs Claus") .setItemDesc("Pen") .setUnitInput("CS") .setUnitCost("10") .setQuantity("25"); log("Upload an attachment"); requestPage.addAttachment(jpgFile) .submitForReview(); log("Verify " + REQUESTER_USER_1 + " can view the request submitted"); waitForElement(Locator.tagWithAttribute("h3", "title", "Purchase Requests")); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); String requestID = table.getDataAsText(0, "rowId"); checker().verifyEquals("Invalid number of requests ", 1, table.getDataRowCount()); checker().verifyEquals("Invalid request status ", "Review Pending", table.getDataAsText(0, "requestStatus")); checker().verifyEquals("Invalid requester", requester1Name, table.getDataAsText(0, "requester")); checker().screenShotIfNewError("requester_view_submitted"); stopImpersonating(); log("-----Update request as Purchasing Admin-----"); goToPurchaseAdminPage(); log("Impersonate as " + ADMIN_USER); impersonate(ADMIN_USER); clickAndWait(Locator.linkContainingText("All Open Requests")); DataRegionTable requestsQueryForAdmins = new DataRegionTable("query", getDriver()); requestsQueryForAdmins.setFilter("requestNum", "Equals", requestID); assertEquals("Admin is not seeing the request " + requestID, 1, requestsQueryForAdmins.getDataRowCount()); clickAndWait(Locator.linkWithText(requestID)); final CreateRequestPage requestPage2 = new CreateRequestPage(getDriver()); waitFor(() -> !requestPage2.getAccountsToCharge().equals("Select"), "Form didn't load existing values", 5_000); checker().verifyEquals("Invalid value for Accounts to charge ", "acct100 - Assay Services", requestPage2.getAccountsToCharge()); checker().verifyEquals("Invalid value for Vendor ", "Real Santa Claus", requestPage2.getVendor()); checker().verifyEquals("Invalid value for BusinessPurpose ", "Holiday Party", requestPage2.getBusinessPurpose()); checker().verifyEquals("Invalid value for Special Instructions ", "Ho Ho Ho", requestPage2.getSpecialInstructions()); checker().verifyEquals("Invalid value for Shipping Destination", "456 Thompson lane (Math bldg)", requestPage2.getShippingDestination()); checker().verifyEquals("Invalid value for Delivery Attention to ", "Mrs Claus", requestPage2.getDeliveryAttentionTo()); checker().verifyEquals("Invalid value for Line Item ", "Pen", requestPage2.getItemDesc()); checker().verifyEquals("Invalid value for Unit Input ", "CS", requestPage2.getUnitInput()); checker().verifyEquals("Invalid value for Unit cost ", "10", requestPage2.getUnitCost()); checker().verifyEquals("Invalid value for Quantity ", "25", requestPage2.getQuantity()); checker().screenShotIfNewError("admin_view_submitted"); log("Upload another attachment"); requestPage2.addAttachment(pdfFile); log("Verify Status in 'Purchase Admin' panel is 'Review Pending'"); checker().verifyEquals("Invalid Assigned to value ", "Select", requestPage2.getAssignedTo()); checker().verifyEquals("Invalid Program value", "4", requestPage2.getProgram()); checker().verifyEquals("Invalid status ", "Review Pending", requestPage2.getStatus()); checker().screenShotIfNewError("status_review_pending"); requestPage2.setStatus("Request Approved") .setConfirmationNo("12345") .submit(); stopImpersonating(false); beginAt(buildRelativeUrl("WNPRC_Purchasing", getProjectName(), "requestEntry", Maps.of("requestRowId", requestID))); log("Impersonate as " + REQUESTER_USER_2); impersonate(REQUESTER_USER_2); assertTextPresent("You do not have sufficient permissions to update this request."); stopImpersonating(); } @Test public void testReferenceTables() { goToProjectHome(); clickAndWait(Locator.linkWithText("Purchasing Admin")); log("Checking if the link is present on the Purchasing Admin page"); checker().verifyTrue("Vendors reference is not present", isElementPresent(Locator.linkWithText("Vendors"))); checker().verifyTrue("User Account Associations reference is not present", isElementPresent(Locator.linkWithText("User Account Associations"))); checker().verifyTrue("Shipping Info reference is not present", isElementPresent(Locator.linkWithText("Shipping Info"))); checker().verifyTrue("Item Units reference is not present", isElementPresent(Locator.linkWithText("Item Units"))); checker().verifyTrue("Line Items reference is not present", isElementPresent(Locator.linkWithText("Line Items"))); log("Verifying if link navigates to correct query"); checker().verifyEquals("Incorrect link for Vendors", "Vendor", getQueryName("Vendors")); checker().verifyEquals("Incorrect link for User Account Associations", "User Account Associations", getQueryName("User Account Associations")); checker().verifyEquals("Incorrect link for Shipping Info", "Shipping Info", getQueryName("Shipping Info")); checker().verifyEquals("Incorrect link for Item Units", "Item Units", getQueryName("Item Units")); checker().verifyEquals("Incorrect link for Line Items", "Line Items", getQueryName("Line Items")); } @Test public void testAdminPage() throws IOException, CommandException { DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd"); LocalDateTime date = LocalDateTime.now(); log("Verifying requester does not access to admin web part"); goToProjectHome(); impersonate(REQUESTER_USER_1); goToPurchaseAdminPage(); checker().verifyTrue(REQUESTER_USER_1 + "user should not permission for admin page", isElementPresent(Locator.tagWithClass("div", "labkey-error-subheading") .withText("User does not have permission to perform this operation."))); checker().screenShotIfNewError("requester_view_restricted"); goBack(); log("Creating request as " + REQUESTER_USER_1); goToRequesterPage(); clickAndWait(Locator.linkWithText("Create Request")); Map<String, String> requesterRequest = new HashMap<>(); requesterRequest.put("Account to charge", "acct100 - Assay Services"); requesterRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); requesterRequest.put("Vendor", "Dunder Mifflin"); requesterRequest.put("Delivery attention to", "testing the workflow"); requesterRequest.put("Business purpose", "regression test"); requesterRequest.put("Item description", "Item1"); requesterRequest.put("Unit", "Term"); requesterRequest.put("Unit Cost", "10"); requesterRequest.put("Quantity", "6"); String requestId1 = createRequest(requesterRequest, null); stopImpersonating(); log("Creating request as " + ADMIN_USER); impersonate(ADMIN_USER); goToPurchaseAdminPage(); Map<String, String> adminRequest = new HashMap<>(); adminRequest.put("Account to charge", "acct101 - Business Office"); adminRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); adminRequest.put("Vendor", "Real Santa Claus"); adminRequest.put("Delivery attention to", "testing the workflow - Admin"); adminRequest.put("Business purpose", "regression test -Admin request"); adminRequest.put("Item description", "Item1"); adminRequest.put("Unit", "Term"); adminRequest.put("Unit Cost", "20"); adminRequest.put("Quantity", "3"); clickAndWait(Locator.linkWithText("Enter Request")); String requestId2 = createRequest(requesterRequest, null); log("Verifying all open requests"); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Open Requests")); DataRegionTable table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Incorrect request Id's", Arrays.asList(requestId1, requestId2), table.getColumnDataAsText("requestNum")); checker().verifyEquals("Incorrect requester's", Arrays.asList("purchaserequester1", "purchaseadmin"), table.getColumnDataAsText("requester")); checker().screenShotIfNewError("all_open_requests"); log("Changing the assignment of the request"); clickAndWait(Locator.linkWithText(requestId1)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAssignedTo("purchaseadmin") .setPurchaseOptions("Direct Payment") .setStatus("Request Approved") .setOrderDate(dtf.format(date)) .setCardPostDate(dtf.format(date)) .submit(); goToPurchaseAdminPage(); waitAndClickAndWait(Locator.linkWithText("My Open Requests")); table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Incorrect request in my open request", requestId1, table.getDataAsText(0, "requestNum")); checker().verifyEquals("Incorrect status", "Request Approved", table.getDataAsText(0, "requestStatus")); checker().screenShotIfNewError("my_open_requests"); log("Completing the order"); goToPurchaseAdminPage(); waitAndClickAndWait(Locator.linkWithText("All Open Requests")); clickAndWait(Locator.linkWithText(requestId2)); requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Order Complete").submit(); clickAndWait(Locator.linkWithText("Completed Requests")); table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Incorrect request in my open request", requestId2, table.getDataAsText(0, "requestNum")); checker().verifyEquals("Incorrect status", "Order Complete", table.getDataAsText(0, "requestStatus")); checker().screenShotIfNewError("completed_requests"); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Open Requests")); table = new DataRegionTable("query", getDriver()); checker().verifyEquals("Completed order should not be present", Arrays.asList(requestId1), table.getColumnDataAsText("requestNum")); checker().screenShotIfNewError("requests_after_completing"); stopImpersonating(); log("Verifying the P-Card view"); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("P-Card View")); table = new DataRegionTable("query", getDriver()); assertEquals("Incorrect number of rows in P-Card view", 2, table.getDataRowCount()); } @Test public void testReceiverActions() { goToProjectHome(); impersonate(REQUESTER_USER_1); goToRequesterPage(); log("Creating the first request as" + REQUESTER_USER_1); waitAndClickAndWait(Locator.linkWithText("Create Request")); Map<String, String> requestInputs = new HashMap<>(); requestInputs.put("Account to charge", "acct101 - Business Office"); requestInputs.put("Shipping destination", "456 Thompson lane (Math bldg)"); requestInputs.put("Vendor", "Dunder Mifflin"); requestInputs.put("Delivery attention to", "testing the workflow - receiver"); requestInputs.put("Business purpose", "regression test -receiver request"); requestInputs.put("Item description", "Item1"); requestInputs.put("Unit", "Term"); requestInputs.put("Unit Cost", "20"); requestInputs.put("Quantity", "3"); String requestId1 = createRequest(requestInputs, null); log("Creating the second request as" + REQUESTER_USER_1); requestInputs = new HashMap<>(); requestInputs.put("Account to charge", "acct100 - Assay Services"); requestInputs.put("Shipping destination", "456 Thompson lane (Math bldg)"); requestInputs.put("Vendor", "Real Santa Claus"); requestInputs.put("Delivery attention to", "testing the workflow - receiver"); requestInputs.put("Business purpose", "regression test -receiver request"); requestInputs.put("Item description", "Item2"); requestInputs.put("Unit", "CS"); requestInputs.put("Unit Cost", "20"); requestInputs.put("Quantity", "300"); clickAndWait(Locator.linkWithText("Create Request")); String requestId2 = createRequest(requestInputs, null); stopImpersonating(); log("Updating the request by " + ADMIN_USER); goToPurchaseAdminPage(); impersonate(ADMIN_USER); clickAndWait(Locator.linkWithText("All Open Requests")); clickAndWait(Locator.linkWithText(requestId1)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setQuantityReceived("4"); requestPage.setStatus("Order Placed"); requestPage.submit(); waitAndClickAndWait(Locator.linkWithText("All Open Requests")); clickAndWait(Locator.linkWithText(requestId2)); requestPage = new CreateRequestPage(getDriver()); requestPage.setQuantityReceived("40"); requestPage.setStatus("Order Placed"); requestPage.submit(); stopImpersonating(); log("Testing as receiver"); impersonate(RECEIVER_USER); goToPurchaseAdminPage(); Assert.assertTrue("Receiver should not have permission to access admin page", isElementPresent(Locator.tagWithClass("div", "labkey-error-subheading") .withText("User does not have permission to perform this operation."))); goToReceiverPage(); waitAndClickAndWait(Locator.linkWithText(requestId2)); requestPage = new CreateRequestPage(getDriver()); requestPage.addAttachment(pdfFile); requestPage.setQuantityReceived("300"); requestPage.submit(); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); assertEquals("The line item table should be empty", 0, table.getDataRowCount()); stopImpersonating(); goToPurchaseAdminPage(); waitAndClickAndWait(Locator.linkWithText("All Requests")); table = new DataRegionTable("query", getDriver()); table.setFilter("requestNum", "Equals One Of (example usage: a;b;c)", requestId1 + ";" + requestId2); assertEquals("Incorrect order status", Arrays.asList("Order Received", "Order Received"), table.getColumnDataAsText("requestStatus")); } @Test public void testEmailNotificationApprovalWorkflow() { log("Delete all the emails from dumbster"); enableEmailRecorder(); goToProjectHome(PURCHASING_FOLDER); impersonate(REQUESTER_USER_2); goToRequesterPage(); Map<String, String> emailApprovalRequest = new HashMap<>(); emailApprovalRequest.put("Account to charge", "acct100 - Assay Services"); emailApprovalRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); emailApprovalRequest.put("Vendor", "Stuff, Inc"); emailApprovalRequest.put("Delivery attention to", "Testing the email notification approval workflow"); emailApprovalRequest.put("Business purpose", "BP"); emailApprovalRequest.put("Item description", "Item1"); emailApprovalRequest.put("Unit", "Term"); emailApprovalRequest.put("Unit Cost", "500"); emailApprovalRequest.put("Quantity", "10"); waitAndClickAndWait(Locator.linkWithText("Create Request")); String requestId = createRequest(emailApprovalRequest, null); stopImpersonating(); log("Verifying create request emails for request total of $5000"); goToModule("Dumbster"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "A new purchase request for $5,000.00 is submitted"; checker().verifyEquals("Incorrect To for the emails sent", Arrays.asList("[email protected]", "[email protected]"), mailTable.getColumnDataAsText("To")); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("A new purchasing request # " + requestId + " by " + requester2Name + " was submitted on " + _dateTimeFormatter.format(today) + " for the total of $5,000.00.")); checker().screenShotIfNewError("request_submitted_email"); log("Delete emails from dumbster"); enableEmailRecorder(); goToPurchaseAdminPage(); impersonate(PURCHASE_DIRECTOR_USER); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Request Approved").submit(); stopImpersonating(); goToModule("Dumbster"); mailTable = new EmailRecordTable(this); subject = "Purchase request # " + requestId + " status update"; checker().verifyEquals("Incorrect To for the emails sent after approval", Arrays.asList(getCurrentUser(), ADMIN_USER), mailTable.getColumnDataAsText("To")); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " for the total of $5,000.00 has been approved by the purchasing director.")); checker().screenShotIfNewError("request_approved_email"); } @Test public void testEmailNotificationRejectWorkflow() { String rejectReasonMsg = "Rejected due to budgetary constraints, please contact your PI for more details."; goToProjectHome(PURCHASING_FOLDER); impersonate(REQUESTER_USER_1); goToRequesterPage(); Map<String, String> emailApprovalRequest = new HashMap<>(); emailApprovalRequest.put("Account to charge", "acct100 - Assay Services"); emailApprovalRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); emailApprovalRequest.put("Vendor", "Stuff, Inc"); emailApprovalRequest.put("Delivery attention to", "Testing the email notification approval workflow"); emailApprovalRequest.put("Business purpose", "BP"); emailApprovalRequest.put("Item description", "Item1"); emailApprovalRequest.put("Unit", "Term"); emailApprovalRequest.put("Unit Cost", "500"); emailApprovalRequest.put("Quantity", "20"); waitAndClickAndWait(Locator.linkWithText("Create Request")); String requestId = createRequest(emailApprovalRequest, null); stopImpersonating(); log("Delete the emails in the dumbster"); enableEmailRecorder(); log("Purchase Director : Rejecting the request >= $5000"); goToPurchaseAdminPage(); impersonate(PURCHASE_DIRECTOR_USER); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Request Rejected"); requestPage.setRejectReason(rejectReasonMsg); requestPage.submit(); stopImpersonating(); goToModule("Dumbster"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "Purchase request # " + requestId + " status update"; checker().verifyEquals("Incorrect To for the emails sent after rejection", Arrays.asList(getCurrentUser(), ADMIN_USER), mailTable.getColumnDataAsText("To")); mailTable.clickSubjectAtIndex(subject, 0); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " for the total of $10,000.00 has been rejected by the purchasing director.")); checker().verifyTrue("Reason for rejection not found in the email body", mailTable.getMessage(subject).getBody().contains(rejectReasonMsg)); checker().screenShotIfNewError("request_rejection_email"); } @Test public void testEmailCustomizationLineItemUpdate() { log("Updating the settings for custom message"); goToAdminConsole().clickEmailCustomization(); selectOptionByText(Locator.css("select[id='templateClass']"), "WNPRC Purchasing - Line item update notification"); setFormElement(Locator.name("emailSubject"), "Custom subject # ^requestNum^ for line item update"); clickButton("Save"); goToRequesterPage(); impersonate(REQUESTER_USER_1); goToRequesterPage(); Map<String, String> emailApprovalRequest = new HashMap<>(); emailApprovalRequest.put("Account to charge", "acct100 - Assay Services"); emailApprovalRequest.put("Shipping destination", "456 Thompson lane (Math bldg)"); emailApprovalRequest.put("Vendor", "Stuff, Inc"); emailApprovalRequest.put("Delivery attention to", "Testing the email notification approval workflow"); emailApprovalRequest.put("Business purpose", "BP"); emailApprovalRequest.put("Item description", "Item1"); emailApprovalRequest.put("Unit", "Term"); emailApprovalRequest.put("Unit Cost", "500"); emailApprovalRequest.put("Quantity", "20"); waitAndClickAndWait(Locator.linkWithText("Create Request")); String requestId = createRequest(emailApprovalRequest, null); stopImpersonating(); log("Deleting the emails from dumbster"); enableEmailRecorder(); log("Updating the request status and line item to trigger email notif"); impersonate(ADMIN_USER); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setStatus("Order Placed"); requestPage.setQuantity("15").submit(); stopImpersonating(); goToModule("Dumbster"); EmailRecordTable mailTable = new EmailRecordTable(this); String subject = "Custom subject # " + requestId + " for line item update"; checker().verifyEquals("Incorrect To for the emails sent for line item update", Arrays.asList(REQUESTER_USER_1, REQUESTER_USER_1), mailTable.getColumnDataAsText("To")); mailTable.clickSubject(subject); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Your purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " has been updated.")); subject = "Purchase request # " + requestId + " status update"; mailTable.clickSubject(subject); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("Purchase request # " + requestId + " from vendor Stuff, Inc submitted on " + _dateTimeFormatter.format(today) + " for the total of $7,500.00 has been ordered by the purchasing department.")); checker().screenShotIfNewError("custom_request_email"); log("Delete emails from dumbster"); enableEmailRecorder(); log("Verify quantity received email notif"); goToReceiverPage(); impersonate(RECEIVER_USER); clickAndWait(Locator.linkWithText(requestId)); requestPage = new CreateRequestPage(getDriver()); requestPage.setQuantityReceived("15").submit(); stopImpersonating(); goToModule("Dumbster"); mailTable = new EmailRecordTable(this); subject = "Custom subject # " + requestId + " for line item update"; checker().verifyEquals("Incorrect To for the emails sent for line item update", Arrays.asList(REQUESTER_USER_1), mailTable.getColumnDataAsText("To")); mailTable.clickSubject(subject); log("Email body " + mailTable.getMessage(subject).getBody()); checker().verifyTrue("Incorrect email body", mailTable.getMessage(subject).getBody().contains("All line items are received.")); checker().screenShotIfNewError("custom_request_email"); } @Test public void testReorderRequest() { File jpgFile = new File(TestFileUtils.getSampleData("fileTypes"), "jpg_sample.jpg"); goToProjectHome(); impersonate(REQUESTER_USER_1); goToRequesterPage(); log("Creating the first request as" + REQUESTER_USER_1); waitAndClickAndWait(Locator.linkWithText("Create Request")); Map<String, String> requestInputs = new HashMap<>(); requestInputs.put("Account to charge", "acct101 - Business Office"); requestInputs.put("Shipping destination", "456 Thompson lane (Math bldg)"); requestInputs.put("Vendor", "Dunder Mifflin"); requestInputs.put("Delivery attention to", "testing the reorder"); requestInputs.put("Business purpose", "regression test -reorder"); requestInputs.put("Item description", "Item1"); requestInputs.put("Unit", "Term"); requestInputs.put("Unit Cost", "20"); requestInputs.put("Quantity", "3"); String requestId = createRequest(requestInputs, null); log("Verifying reorder by link"); clickAndWait(Locator.linkWithText("Reorder")); CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge("acct100 - Assay Services"); requestPage.addAttachment(jpgFile); requestPage.submitForReview(); DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); assertEquals("No new request created for reorder link", 2, table.getDataRowCount()); stopImpersonating(); log("verifying reorder by button"); impersonate(ADMIN_USER); goToPurchaseAdminPage(); clickAndWait(Locator.linkWithText("All Requests")); clickAndWait(Locator.linkWithText(requestId)); requestPage = new CreateRequestPage(getDriver()); requestPage.reorderButton(); requestPage.setAccountsToCharge("acct100 - Assay Services"); requestPage.addAttachment(jpgFile); requestPage.submitForReview(); table = new DataRegionTable("query", getDriver()); clickAndWait(Locator.linkWithText("All Requests")); assertEquals("No new request created from reorder button", 3, table.getDataRowCount()); } private String getQueryName(String linkName) { clickAndWait(Locator.linkWithText(linkName)); String retVal = Locator.tag("h3").findElement(getDriver()).getText(); goBack(); return retVal; } private String createRequest(Map<String, String> request, @Nullable File fileName) { CreateRequestPage requestPage = new CreateRequestPage(getDriver()); requestPage.setAccountsToCharge(request.get("Account to charge")) .setVendor(request.get("Vendor")) .setBusinessPurpose(request.get("Business purpose")) .setShippingDestination(request.get("Shipping destination")) .setDeliveryAttentionTo(request.get("Delivery attention to")) .setItemDesc(request.get("Item description")) .setUnitInput(request.get("Unit")) .setUnitCost(request.get("Unit Cost")) .setQuantity(request.get("Quantity")); if (request.containsKey("Special instructions")) requestPage.setSpecialInstructions(request.get("Special instructions")); if (fileName != null) requestPage.addAttachment(fileName); requestPage.submitForReview(); if (getCurrentUser().equals("[email protected]")) { clickAndWait(Locator.linkWithText("All Open Requests")); DataRegionTable table = new DataRegionTable("query", getDriver()); table.setFilter("requester", "Equals", "purchaseadmin"); return table.getDataAsText(0, "requestNum"); } else { DataRegionTable table = DataRegionTable.DataRegion(getDriver()).find(); return table.getDataAsText(table.getDataRowCount() - 1, "rowId"); } } private void clearAllRequest() throws IOException, CommandException { Connection cn = createDefaultConnection(); new TruncateTableCommand("ehr_purchasing", "lineItems").execute(cn, getProjectName()); new TruncateTableCommand("ehr_purchasing", "purchasingRequests").execute(cn, getProjectName()); } @Override protected BrowserType bestBrowser() { return BrowserType.CHROME; } @Override protected String getProjectName() { return PURCHASING_FOLDER; } @Override public List<String> getAssociatedModules() { return Collections.singletonList("WNPRC_Purchasing"); } }
Fixes for test timing issue (#154) * Fix for test timing issues. * Waiting for element before clicking
WNPRC_Purchasing/test/src/org/labkey/test/tests/wnprc_purchasing/WNPRC_PurchasingTest.java
Fixes for test timing issue (#154)
<ide><path>NPRC_Purchasing/test/src/org/labkey/test/tests/wnprc_purchasing/WNPRC_PurchasingTest.java <ide> <ide> goToRequesterPage(); <ide> impersonate(REQUESTER_USER_1); <del> clickButton("Create Request"); <add> waitAndClickAndWait(Locator.linkWithText("Create Request")); <ide> CreateRequestPage requestPage = new CreateRequestPage(getDriver()); <ide> <ide> log("Verifying the validation for mandatory fields"); <ide> <ide> log("Creating request as " + REQUESTER_USER_1); <ide> goToRequesterPage(); <del> clickAndWait(Locator.linkWithText("Create Request")); <add> waitAndClickAndWait(Locator.linkWithText("Create Request")); <ide> Map<String, String> requesterRequest = new HashMap<>(); <ide> requesterRequest.put("Account to charge", "acct100 - Assay Services"); <ide> requesterRequest.put("Shipping destination", "456 Thompson lane (Math bldg)");
Java
apache-2.0
15b312cf975e7a63a4664638b5cc458fa6804842
0
dkcreinoso/jitsi,laborautonomo/jitsi,ibauersachs/jitsi,dkcreinoso/jitsi,bebo/jitsi,laborautonomo/jitsi,ringdna/jitsi,jitsi/jitsi,Metaswitch/jitsi,martin7890/jitsi,marclaporte/jitsi,cobratbq/jitsi,jibaro/jitsi,cobratbq/jitsi,marclaporte/jitsi,iant-gmbh/jitsi,gpolitis/jitsi,mckayclarey/jitsi,459below/jitsi,level7systems/jitsi,procandi/jitsi,marclaporte/jitsi,pplatek/jitsi,HelioGuilherme66/jitsi,mckayclarey/jitsi,jitsi/jitsi,cobratbq/jitsi,damencho/jitsi,dkcreinoso/jitsi,marclaporte/jitsi,jibaro/jitsi,tuijldert/jitsi,ringdna/jitsi,cobratbq/jitsi,459below/jitsi,iant-gmbh/jitsi,tuijldert/jitsi,ringdna/jitsi,bhatvv/jitsi,459below/jitsi,bhatvv/jitsi,pplatek/jitsi,bebo/jitsi,laborautonomo/jitsi,iant-gmbh/jitsi,damencho/jitsi,martin7890/jitsi,HelioGuilherme66/jitsi,pplatek/jitsi,dkcreinoso/jitsi,level7systems/jitsi,martin7890/jitsi,mckayclarey/jitsi,mckayclarey/jitsi,jitsi/jitsi,damencho/jitsi,gpolitis/jitsi,mckayclarey/jitsi,459below/jitsi,jibaro/jitsi,ringdna/jitsi,pplatek/jitsi,procandi/jitsi,jitsi/jitsi,ibauersachs/jitsi,procandi/jitsi,level7systems/jitsi,tuijldert/jitsi,Metaswitch/jitsi,gpolitis/jitsi,ibauersachs/jitsi,tuijldert/jitsi,pplatek/jitsi,bhatvv/jitsi,bebo/jitsi,cobratbq/jitsi,level7systems/jitsi,procandi/jitsi,marclaporte/jitsi,ibauersachs/jitsi,martin7890/jitsi,tuijldert/jitsi,Metaswitch/jitsi,bebo/jitsi,bebo/jitsi,jibaro/jitsi,iant-gmbh/jitsi,HelioGuilherme66/jitsi,Metaswitch/jitsi,gpolitis/jitsi,laborautonomo/jitsi,bhatvv/jitsi,jitsi/jitsi,iant-gmbh/jitsi,damencho/jitsi,bhatvv/jitsi,ibauersachs/jitsi,jibaro/jitsi,HelioGuilherme66/jitsi,HelioGuilherme66/jitsi,laborautonomo/jitsi,damencho/jitsi,gpolitis/jitsi,level7systems/jitsi,ringdna/jitsi,martin7890/jitsi,459below/jitsi,procandi/jitsi,dkcreinoso/jitsi
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.slick.protocol.sip; import junit.framework.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.service.protocol.*; import java.text.ParseException; import net.java.sip.communicator.service.protocol.event.*; import java.util.*; /** * Tests Basic telephony functionality by making one provider call the other. * * @author Emil Ivov */ public class TestOperationSetBasicTelephonySipImpl extends TestCase { private static final Logger logger = Logger.getLogger(TestOperationSetBasicTelephonySipImpl.class); /** * */ private SipSlickFixture fixture = new SipSlickFixture(); /** * Initializes the test with the specified <tt>name</tt>. * * @param name the name of the test to initialize. */ public TestOperationSetBasicTelephonySipImpl(String name) { super(name); } /** * JUnit setup method. * @throws Exception in case anything goes wrong. */ protected void setUp() throws Exception { super.setUp(); fixture.setUp(); } /** * JUnit teardown method. * @throws Exception in case anything goes wrong. */ protected void tearDown() throws Exception { fixture.tearDown(); super.tearDown(); } /** * Creates a call from provider1 to provider2 then cancels it without * waiting for provider1 to answer. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateCancelCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call peers are properly created assertEquals("callAtP1.getCallPeerCount()" , 1, callAtP1.getCallPeerCount()); assertEquals("callAtP2.getCallPeerCount()" , 1, callAtP2.getCallPeerCount()); CallPeer peerAtP1 = (CallPeer)callAtP1.getCallPeers().next(); CallPeer peerAtP2 = (CallPeer)callAtP2.getCallPeers().next(); //now add listeners to the peers and make sure they have entered //the states they were expected to. //check states for call peers at both parties CallPeerStateEventCollector stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.ALERTING_REMOTE_SIDE); CallPeerStateEventCollector stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("peerAtP1.getCall" , peerAtP1.getCall(), callAtP1); assertSame("peerAtP2.getCall" , peerAtP2.getCall(), callAtP2); //make sure that the peers are in the proper state assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.ALERTING_REMOTE_SIDE , peerAtP1.getState()); assertEquals("The peer at provider two was not in the " +"right state." , CallPeerState.INCOMING_CALL , peerAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PEER_INFO")) { //check properties on the remote call peer for the party that //initiated the call. String expectedPeer1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedPeer1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedPeer1Address.indexOf( peerAtP1.getAddress()) != -1 || peerAtP1.getAddress().indexOf( expectedPeer1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedPeer1DisplayName , peerAtP1.getDisplayName()); //check properties on the remote call peer for the party that //receives the call. String expectedPeer2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedPeer2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedPeer2Address.indexOf( peerAtP2.getAddress()) != -1 || peerAtP2.getAddress().indexOf( expectedPeer2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedPeer2DisplayName , peerAtP2.getDisplayName()); } //we'll now try to cancel the call //listeners monitoring state change of the peer stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.DISCONNECTED); stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP1.hangupCallPeer(peerAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the peer is disconnected assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , peerAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the peer is disconnected assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , peerAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2 then rejects the call from the * side of provider2 (provider2 replies with busy-tone). * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateRejectCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call peers are properly created assertEquals("callAtP1.getCallPeerCount()" , 1, callAtP1.getCallPeerCount()); assertEquals("callAtP2.getCallPeerCount()" , 1, callAtP2.getCallPeerCount()); CallPeer peerAtP1 = (CallPeer)callAtP1.getCallPeers().next(); CallPeer peerAtP2 = (CallPeer)callAtP2.getCallPeers().next(); //now add listeners to the peers and make sure they have entered //the states they were expected to. //check states for call peers at both parties CallPeerStateEventCollector stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.ALERTING_REMOTE_SIDE); CallPeerStateEventCollector stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("peerAtP1.getCall" , peerAtP1.getCall(), callAtP1); assertSame("peerAtP2.getCall" , peerAtP2.getCall(), callAtP2); //make sure that the peers are in the proper state assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.ALERTING_REMOTE_SIDE , peerAtP1.getState()); assertEquals("The peer at provider two was not in the " +"right state." , CallPeerState.INCOMING_CALL , peerAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PEER_INFO")) { //check properties on the remote call peer for the party that //initiated the call. String expectedPeer1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedPeer1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedPeer1Address.indexOf( peerAtP1.getAddress()) != -1 || peerAtP1.getAddress().indexOf( expectedPeer1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedPeer1DisplayName , peerAtP1.getDisplayName()); //check properties on the remote call peer for the party that //receives the call. String expectedPeer2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedPeer2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedPeer2Address.indexOf( peerAtP2.getAddress()) != -1 || peerAtP2.getAddress().indexOf( expectedPeer2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedPeer2DisplayName , peerAtP2.getDisplayName()); } //we'll now try to send busy tone. //listeners monitoring state change of the peer CallPeerStateEventCollector busyStateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.BUSY); stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.DISCONNECTED); stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP2.hangupCallPeer(peerAtP2); busyStateCollectorForPp1.waitForEvent(10000); basicTelephonyP1.hangupCallPeer(peerAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the peer is disconnected assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , peerAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the peer is disconnected assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , peerAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2, makes provider2 answer it * and then reject it. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void aTestCreateAnswerHangupCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call peers are properly created assertEquals("callAtP1.getCallpeersCount()" , 1, callAtP1.getCallPeerCount()); assertEquals("callAtP2.getCallpeersCount()" , 1, callAtP2.getCallPeerCount()); CallPeer peerAtP1 = (CallPeer)callAtP1.getCallPeers().next(); CallPeer peerAtP2 = (CallPeer)callAtP2.getCallPeers().next(); //now add listeners to the peers and make sure they have entered //the states they were expected to. //check states for call peers at both parties CallPeerStateEventCollector stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.ALERTING_REMOTE_SIDE); CallPeerStateEventCollector stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("peerAtP1.getCall" , peerAtP1.getCall(), callAtP1); assertSame("peerAtP2.getCall" , peerAtP2.getCall(), callAtP2); //make sure that the peers are in the proper state assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.ALERTING_REMOTE_SIDE , peerAtP1.getState()); assertEquals("The peer at provider two was not in the " +"right state." , CallPeerState.INCOMING_CALL , peerAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PEER_INFO")) { //check properties on the remote call peer for the party that //initiated the call. String expectedPeer1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedPeer1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedPeer1Address.indexOf( peerAtP1.getAddress()) != -1 || peerAtP1.getAddress().indexOf( expectedPeer1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedPeer1DisplayName , peerAtP1.getDisplayName()); //check properties on the remote call peer for the party that //receives the call. String expectedPeer2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedPeer2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedPeer2Address.indexOf( peerAtP2.getAddress()) != -1 || peerAtP2.getAddress().indexOf( expectedPeer2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedPeer2DisplayName , peerAtP2.getDisplayName()); } //add listeners to the peers and make sure enter //a connected state after we answer stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.CONNECTED); stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.CONNECTED); //we will now anser the call and verify that both parties change states //accordingly. basicTelephonyP2.answerCallPeer(peerAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the peers are in the proper state assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.CONNECTED , peerAtP1.getState()); assertEquals("The peer at provider two was not in the " +"right state." , CallPeerState.CONNECTED , peerAtP2.getState()); //make sure that events have been distributed when states were changed. assertEquals("No event was dispatched when a call peer changed " +"its state." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("No event was dispatched when a call peer changed " +"its state." , 1 , stateCollectorForPp2.collectedEvents.size()); //add listeners to the peers and make sure they have entered //the states they are expected to. stateCollectorForPp1 = new CallPeerStateEventCollector( peerAtP1, CallPeerState.DISCONNECTED); stateCollectorForPp2 = new CallPeerStateEventCollector( peerAtP2, CallPeerState.DISCONNECTED); //we will now end the call and verify that both parties change states //accordingly. basicTelephonyP2.hangupCallPeer(peerAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the peers are in the proper state assertEquals("The peer at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , peerAtP1.getState()); assertEquals("The peer at provider two was not in the " +"right state." , CallPeerState.DISCONNECTED , peerAtP2.getState()); //make sure that the corresponding events were delivered. assertEquals("a provider did not distribute an event when a call " +"peer changed states." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("a provider did not distribute an event when a call " +"peer changed states." , 1 , stateCollectorForPp2.collectedEvents.size()); } /** * Allows tests to wait for and collect events issued upon creation and * reception of calls. */ public class CallEventCollector implements CallListener { public ArrayList collectedEvents = new ArrayList(); public OperationSetBasicTelephony listenedOpSet = null; /** * Creates an instance of this call event collector and registers it * with listenedOpSet. * @param listenedOpSet the operation set that we will be scanning for * new calls. */ public CallEventCollector(OperationSetBasicTelephony listenedOpSet) { this.listenedOpSet = listenedOpSet; this.listenedOpSet.addCallListener(this); } /** * Blocks until at least one event is received or until waitFor * miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallEvent"); synchronized(this) { if(collectedEvents.size() > 0){ logger.trace("Event already received. " + collectedEvents); listenedOpSet.removeCallListener(this); return; } try{ wait(waitFor); if(collectedEvents.size() > 0) logger.trace("Received a CallEvent."); else logger.trace("No CallEvent received for "+waitFor+"ms."); listenedOpSet.removeCallListener(this); } catch (InterruptedException ex) { logger.debug( "Interrupted while waiting for a call event", ex); } } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void incomingCallReceived(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void outgoingCallCreated(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void callEnded(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } } /** * Allows tests to wait for and collect events issued upon call peer * status changes. */ public class CallPeerStateEventCollector extends CallPeerAdapter { public ArrayList collectedEvents = new ArrayList(); private CallPeer listenedCallPeer = null; public CallPeerState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>callPeer</tt>. * @param callPeer the CallPeer that we will be listening * to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallPeerStateEventCollector( CallPeer callPeer, CallPeerState awaitedState) { this.listenedCallPeer = callPeer; this.listenedCallPeer.addCallPeerListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void peerStateChanged(CallPeerChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallPeerState)event.getNewValue()) .equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { waitForEvent(waitFor, false); } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. * @param exitIfAlreadyInState specifies whether the method is to return * if the call peer is already in such a state even if no event * has been received for the sate change. */ public void waitForEvent(long waitFor, boolean exitIfAlreadyInState) { logger.trace("Waiting for a CallPeerEvent with newState=" + awaitedState + " for peer " + this.listenedCallPeer); synchronized (this) { if(exitIfAlreadyInState && listenedCallPeer.getState().equals(awaitedState)) { logger.trace("Src peer is already in the awaited " + "state." + collectedEvents); listenedCallPeer.removeCallPeerListener(this); return; } if(collectedEvents.size() > 0) { CallPeerChangeEvent lastEvent = (CallPeerChangeEvent) collectedEvents .get(collectedEvents.size() - 1); if (lastEvent.getNewValue().equals(awaitedState)) { logger.trace("Event already received. " + collectedEvents); listenedCallPeer .removeCallPeerListener(this); return; } } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallParticpantStateEvent."); else logger.trace("No CallParticpantStateEvent received for " + waitFor + "ms."); listenedCallPeer .removeCallPeerListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } /** * Allows tests to wait for and collect events issued upon call state * changes. */ public class CallStateEventCollector extends CallChangeAdapter { public ArrayList collectedEvents = new ArrayList(); private Call listenedCall = null; public CallState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>call</tt>. * @param call the Call that we will be listening to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallStateEventCollector(Call call, CallState awaitedState) { this.listenedCall = call; this.listenedCall.addCallChangeListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void callStateChanged(CallChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallState)event.getNewValue()).equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallParticpantEvent"); synchronized (this) { if (listenedCall.getCallState() == awaitedState) { logger.trace("Event already received. " + collectedEvents); listenedCall.removeCallChangeListener(this); return; } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallChangeEvent."); else logger.trace("No CallChangeEvent received for " + waitFor + "ms."); listenedCall.removeCallChangeListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } }
test/net/java/sip/communicator/slick/protocol/sip/TestOperationSetBasicTelephonySipImpl.java
/* * SIP Communicator, the OpenSource Java VoIP and Instant Messaging client. * * Distributable under LGPL license. * See terms of license at gnu.org. */ package net.java.sip.communicator.slick.protocol.sip; import junit.framework.*; import net.java.sip.communicator.util.*; import net.java.sip.communicator.service.protocol.*; import java.text.ParseException; import net.java.sip.communicator.service.protocol.event.*; import java.util.*; /** * Tests Basic telephony functionality by making one provider call the other. * * @author Emil Ivov */ public class TestOperationSetBasicTelephonySipImpl extends TestCase { private static final Logger logger = Logger.getLogger(TestOperationSetBasicTelephonySipImpl.class); /** * */ private SipSlickFixture fixture = new SipSlickFixture(); /** * Initializes the test with the specified <tt>name</tt>. * * @param name the name of the test to initialize. */ public TestOperationSetBasicTelephonySipImpl(String name) { super(name); } /** * JUnit setup method. * @throws Exception in case anything goes wrong. */ protected void setUp() throws Exception { super.setUp(); fixture.setUp(); } /** * JUnit teardown method. * @throws Exception in case anything goes wrong. */ protected void tearDown() throws Exception { fixture.tearDown(); super.tearDown(); } /** * Creates a call from provider1 to provider2 then cancels it without * waiting for provider1 to answer. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateCancelCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallPeerCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallPeerCount()); CallPeer participantAtP1 = (CallPeer)callAtP1.getCallPeers().next(); CallPeer participantAtP2 = (CallPeer)callAtP2.getCallPeers().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallPeerState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //we'll now try to cancel the call //listeners monitoring state change of the participant stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP1.hangupCallPeer(participantAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , participantAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , participantAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2 then rejects the call from the * side of provider2 (provider2 replies with busy-tone). * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void testCreateRejectCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallPeerCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallPeerCount()); CallPeer participantAtP1 = (CallPeer)callAtP1.getCallPeers().next(); CallPeer participantAtP2 = (CallPeer)callAtP2.getCallPeers().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallPeerState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //we'll now try to send busy tone. //listeners monitoring state change of the participant CallParticipantStateEventCollector busyStateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.BUSY); stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.DISCONNECTED); //listeners waiting for the op set to announce the end of the call call1Listener = new CallEventCollector(basicTelephonyP1); call2Listener = new CallEventCollector(basicTelephonyP2); //listeners monitoring the state of the call CallStateEventCollector call1StateCollector = new CallStateEventCollector(callAtP1, CallState.CALL_ENDED); CallStateEventCollector call2StateCollector = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); //Now make the caller CANCEL the call. basicTelephonyP2.hangupCallPeer(participantAtP2); busyStateCollectorForPp1.waitForEvent(10000); basicTelephonyP1.hangupCallPeer(participantAtP1); //wait for everything to happen call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); call1StateCollector.waitForEvent(10000); call2StateCollector.waitForEvent(10000); //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , participantAtP1.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call1Listener.collectedEvents.size()); CallEvent collectedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //same for provider 2 //make sure that the participant is disconnected assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , participantAtP2.getState()); //make sure the telephony operation set distributed an event for the end //of the call assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , 1 , call2Listener.collectedEvents.size()); collectedEvent = (CallEvent)call2Listener.collectedEvents.get(0); assertEquals("The basic telephony operation set did not distribute " +"an event to notify us that a call has been ended." , CallEvent.CALL_ENDED , collectedEvent.getEventID()); //make sure that the call objects are in an ENDED state. assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP1.getCallState()); assertEquals("A call did not change its state to CallState.CALL_ENDED " +"when it ended." , CallState.CALL_ENDED , callAtP2.getCallState()); } /** * Creates a call from provider1 to provider2, makes provider2 answer it * and then reject it. * * @throws ParseException if we hand a malformed URI to someone * @throws OperationFailedException if something weird happens. */ public void aTestCreateAnswerHangupCall() throws ParseException, OperationFailedException { OperationSetBasicTelephony basicTelephonyP1 = (OperationSetBasicTelephony)fixture.provider1.getOperationSet( OperationSetBasicTelephony.class); OperationSetBasicTelephony basicTelephonyP2 = (OperationSetBasicTelephony)fixture.provider2.getOperationSet( OperationSetBasicTelephony.class); CallEventCollector call1Listener = new CallEventCollector(basicTelephonyP1); CallEventCollector call2Listener = new CallEventCollector(basicTelephonyP2); //Provider1 calls Provider2 String provider2Address = fixture.provider2.getAccountID().getAccountAddress(); Call callAtP1 = basicTelephonyP1.createCall(provider2Address); call1Listener.waitForEvent(10000); call2Listener.waitForEvent(10000); //make sure that both listeners have received their events. assertEquals("The provider that created the call did not dispatch " + "an event that it has done so." , 1, call1Listener.collectedEvents.size()); //call1 listener checks CallEvent callCreatedEvent = (CallEvent)call1Listener.collectedEvents.get(0); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_INITIATED, callCreatedEvent.getEventID()); assertSame("CallEvent.getSource()" , callAtP1, callCreatedEvent.getSource()); //call2 listener checks assertTrue("The callee provider did not receive a call or did " +"not issue an event." , call2Listener.collectedEvents.size() > 0); CallEvent callReceivedEvent = (CallEvent)call2Listener.collectedEvents.get(0); Call callAtP2 = callReceivedEvent.getSourceCall(); assertEquals("CallEvent.getEventID()" ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); assertNotNull("CallEvent.getSource()", callAtP2); //verify that call participants are properly created assertEquals("callAtP1.getCallParticipantsCount()" , 1, callAtP1.getCallPeerCount()); assertEquals("callAtP2.getCallParticipantsCount()" , 1, callAtP2.getCallPeerCount()); CallPeer participantAtP1 = (CallPeer)callAtP1.getCallPeers().next(); CallPeer participantAtP2 = (CallPeer)callAtP2.getCallPeers().next(); //now add listeners to the participants and make sure they have entered //the states they were expected to. //check states for call participants at both parties CallParticipantStateEventCollector stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.ALERTING_REMOTE_SIDE); CallParticipantStateEventCollector stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.INCOMING_CALL); stateCollectorForPp1.waitForEvent(10000, true); stateCollectorForPp2.waitForEvent(10000, true); assertSame("participantAtP1.getCall" , participantAtP1.getCall(), callAtP1); assertSame("participantAtP2.getCall" , participantAtP2.getCall(), callAtP2); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.ALERTING_REMOTE_SIDE , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallPeerState.INCOMING_CALL , participantAtP2.getState()); //test whether caller/callee info is properly distributed in case //the server is said to support it. if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) { //check properties on the remote call participant for the party that //initiated the call. String expectedParticipant1Address = fixture.provider2.getAccountID().getAccountAddress(); String expectedParticipant1DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 2 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant1Address.indexOf( participantAtP1.getAddress()) != -1 || participantAtP1.getAddress().indexOf( expectedParticipant1Address) != -1); assertEquals("Provider 2 did not properly advertise their " + "display name." , expectedParticipant1DisplayName , participantAtP1.getDisplayName()); //check properties on the remote call participant for the party that //receives the call. String expectedParticipant2Address = fixture.provider1.getAccountID().getAccountAddress(); String expectedParticipant2DisplayName = System.getProperty( SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX + ProtocolProviderFactory.DISPLAY_NAME); //do not asser equals here since one of the addresses may contain a //display name or something of the kind assertTrue("Provider 1 did not advertise their " + "accountID.getAccoutAddress() address." , expectedParticipant2Address.indexOf( participantAtP2.getAddress()) != -1 || participantAtP2.getAddress().indexOf( expectedParticipant2Address) != -1); assertEquals("Provider 1 did not properly advertise their " + "display name." , expectedParticipant2DisplayName , participantAtP2.getDisplayName()); } //add listeners to the participants and make sure enter //a connected state after we answer stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.CONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.CONNECTED); //we will now anser the call and verify that both parties change states //accordingly. basicTelephonyP2.answerCallPeer(participantAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.CONNECTED , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallPeerState.CONNECTED , participantAtP2.getState()); //make sure that events have been distributed when states were changed. assertEquals("No event was dispatched when a call participant changed " +"its state." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("No event was dispatched when a call participant changed " +"its state." , 1 , stateCollectorForPp2.collectedEvents.size()); //add listeners to the participants and make sure they have entered //the states they are expected to. stateCollectorForPp1 = new CallParticipantStateEventCollector( participantAtP1, CallPeerState.DISCONNECTED); stateCollectorForPp2 = new CallParticipantStateEventCollector( participantAtP2, CallPeerState.DISCONNECTED); //we will now end the call and verify that both parties change states //accordingly. basicTelephonyP2.hangupCallPeer(participantAtP2); stateCollectorForPp1.waitForEvent(10000); stateCollectorForPp2.waitForEvent(10000); //make sure that the participants are in the proper state assertEquals("The participant at provider one was not in the " +"right state." , CallPeerState.DISCONNECTED , participantAtP1.getState()); assertEquals("The participant at provider two was not in the " +"right state." , CallPeerState.DISCONNECTED , participantAtP2.getState()); //make sure that the corresponding events were delivered. assertEquals("a provider did not distribute an event when a call " +"participant changed states." , 1 , stateCollectorForPp1.collectedEvents.size()); assertEquals("a provider did not distribute an event when a call " +"participant changed states." , 1 , stateCollectorForPp2.collectedEvents.size()); } /** * Allows tests to wait for and collect events issued upon creation and * reception of calls. */ public class CallEventCollector implements CallListener { public ArrayList collectedEvents = new ArrayList(); public OperationSetBasicTelephony listenedOpSet = null; /** * Creates an instance of this call event collector and registers it * with listenedOpSet. * @param listenedOpSet the operation set that we will be scanning for * new calls. */ public CallEventCollector(OperationSetBasicTelephony listenedOpSet) { this.listenedOpSet = listenedOpSet; this.listenedOpSet.addCallListener(this); } /** * Blocks until at least one event is received or until waitFor * miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallEvent"); synchronized(this) { if(collectedEvents.size() > 0){ logger.trace("Event already received. " + collectedEvents); listenedOpSet.removeCallListener(this); return; } try{ wait(waitFor); if(collectedEvents.size() > 0) logger.trace("Received a CallEvent."); else logger.trace("No CallEvent received for "+waitFor+"ms."); listenedOpSet.removeCallListener(this); } catch (InterruptedException ex) { logger.debug( "Interrupted while waiting for a call event", ex); } } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void incomingCallReceived(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void outgoingCallCreated(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } /** * Stores the received event and notifies all waiting on this object * @param event the event containing the source call. */ public void callEnded(CallEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); this.collectedEvents.add(event); notifyAll(); } } } /** * Allows tests to wait for and collect events issued upon call participant * status changes. */ public class CallParticipantStateEventCollector extends CallPeerAdapter { public ArrayList collectedEvents = new ArrayList(); private CallPeer listenedCallParticipant = null; public CallPeerState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>callParticipant</tt>. * @param callParticipant the CallParticipant that we will be listening * to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallParticipantStateEventCollector( CallPeer callParticipant, CallPeerState awaitedState) { this.listenedCallParticipant = callParticipant; this.listenedCallParticipant.addCallPeerListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void peerStateChanged(CallPeerChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallPeerState)event.getNewValue()) .equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { waitForEvent(waitFor, false); } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. * @param exitIfAlreadyInState specifies whether the method is to return * if the call participant is already in such a state even if no event * has been received for the sate change. */ public void waitForEvent(long waitFor, boolean exitIfAlreadyInState) { logger.trace("Waiting for a CallParticipantEvent with newState=" + awaitedState + " for participant " + this.listenedCallParticipant); synchronized (this) { if(exitIfAlreadyInState && listenedCallParticipant.getState().equals(awaitedState)) { logger.trace("Src participant is already in the awaited " + "state." + collectedEvents); listenedCallParticipant.removeCallPeerListener(this); return; } if(collectedEvents.size() > 0) { CallPeerChangeEvent lastEvent = (CallPeerChangeEvent) collectedEvents .get(collectedEvents.size() - 1); if (lastEvent.getNewValue().equals(awaitedState)) { logger.trace("Event already received. " + collectedEvents); listenedCallParticipant .removeCallPeerListener(this); return; } } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallParticpantStateEvent."); else logger.trace("No CallParticpantStateEvent received for " + waitFor + "ms."); listenedCallParticipant .removeCallPeerListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } /** * Allows tests to wait for and collect events issued upon call state * changes. */ public class CallStateEventCollector extends CallChangeAdapter { public ArrayList collectedEvents = new ArrayList(); private Call listenedCall = null; public CallState awaitedState = null; /** * Creates an instance of this collector and adds it as a listener * to <tt>call</tt>. * @param call the Call that we will be listening to. * @param awaitedState the state that we will be waiting for inside * this collector. */ public CallStateEventCollector(Call call, CallState awaitedState) { this.listenedCall = call; this.listenedCall.addCallChangeListener(this); this.awaitedState = awaitedState; } /** * Stores the received event and notifies all waiting on this object * * @param event the event containing the source call. */ public void callStateChanged(CallChangeEvent event) { synchronized(this) { logger.debug( "Collected evt("+collectedEvents.size()+")= "+event); if(((CallState)event.getNewValue()).equals(awaitedState)) { this.collectedEvents.add(event); notifyAll(); } } } /** * Blocks until an event notifying us of the awaited state change is * received or until waitFor miliseconds pass (whichever happens first). * * @param waitFor the number of miliseconds that we should be waiting * for an event before simply bailing out. */ public void waitForEvent(long waitFor) { logger.trace("Waiting for a CallParticpantEvent"); synchronized (this) { if (listenedCall.getCallState() == awaitedState) { logger.trace("Event already received. " + collectedEvents); listenedCall.removeCallChangeListener(this); return; } try { wait(waitFor); if (collectedEvents.size() > 0) logger.trace("Received a CallChangeEvent."); else logger.trace("No CallChangeEvent received for " + waitFor + "ms."); listenedCall.removeCallChangeListener(this); } catch (InterruptedException ex) { logger.debug("Interrupted while waiting for a " + "CallParticpantEvent" , ex); } } } } }
Renames CallParticipant to CallPeer so that it would better reflect our new Call architecture that also includes conferencing and ConferenceMembers
test/net/java/sip/communicator/slick/protocol/sip/TestOperationSetBasicTelephonySipImpl.java
Renames CallParticipant to CallPeer so that it would better reflect our new Call architecture that also includes conferencing and ConferenceMembers
<ide><path>est/net/java/sip/communicator/slick/protocol/sip/TestOperationSetBasicTelephonySipImpl.java <ide> ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); <ide> assertNotNull("CallEvent.getSource()", callAtP2); <ide> <del> //verify that call participants are properly created <del> assertEquals("callAtP1.getCallParticipantsCount()" <add> //verify that call peers are properly created <add> assertEquals("callAtP1.getCallPeerCount()" <ide> , 1, callAtP1.getCallPeerCount()); <del> assertEquals("callAtP2.getCallParticipantsCount()" <add> assertEquals("callAtP2.getCallPeerCount()" <ide> , 1, callAtP2.getCallPeerCount()); <ide> <del> CallPeer participantAtP1 <add> CallPeer peerAtP1 <ide> = (CallPeer)callAtP1.getCallPeers().next(); <del> CallPeer participantAtP2 <add> CallPeer peerAtP2 <ide> = (CallPeer)callAtP2.getCallPeers().next(); <ide> <del> //now add listeners to the participants and make sure they have entered <add> //now add listeners to the peers and make sure they have entered <ide> //the states they were expected to. <del> //check states for call participants at both parties <del> CallParticipantStateEventCollector stateCollectorForPp1 <del> = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.ALERTING_REMOTE_SIDE); <del> CallParticipantStateEventCollector stateCollectorForPp2 <del> = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.INCOMING_CALL); <add> //check states for call peers at both parties <add> CallPeerStateEventCollector stateCollectorForPp1 <add> = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.ALERTING_REMOTE_SIDE); <add> CallPeerStateEventCollector stateCollectorForPp2 <add> = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.INCOMING_CALL); <ide> <ide> stateCollectorForPp1.waitForEvent(10000, true); <ide> stateCollectorForPp2.waitForEvent(10000, true); <ide> <del> assertSame("participantAtP1.getCall" <del> , participantAtP1.getCall(), callAtP1); <del> assertSame("participantAtP2.getCall" <del> , participantAtP2.getCall(), callAtP2); <del> <del> //make sure that the participants are in the proper state <del> assertEquals("The participant at provider one was not in the " <add> assertSame("peerAtP1.getCall" <add> , peerAtP1.getCall(), callAtP1); <add> assertSame("peerAtP2.getCall" <add> , peerAtP2.getCall(), callAtP2); <add> <add> //make sure that the peers are in the proper state <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.ALERTING_REMOTE_SIDE <del> , participantAtP1.getState()); <del> assertEquals("The participant at provider two was not in the " <add> , peerAtP1.getState()); <add> assertEquals("The peer at provider two was not in the " <ide> +"right state." <ide> , CallPeerState.INCOMING_CALL <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> <ide> //test whether caller/callee info is properly distributed in case <ide> //the server is said to support it. <del> if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) <del> { <del> //check properties on the remote call participant for the party that <add> if(Boolean.getBoolean("accounts.sip.PRESERVE_PEER_INFO")) <add> { <add> //check properties on the remote call peer for the party that <ide> //initiated the call. <del> String expectedParticipant1Address <add> String expectedPeer1Address <ide> = fixture.provider2.getAccountID().getAccountAddress(); <del> String expectedParticipant1DisplayName <add> String expectedPeer1DisplayName <ide> = System.getProperty( <ide> SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX <ide> + ProtocolProviderFactory.DISPLAY_NAME); <ide> //display name or something of the kind <ide> assertTrue("Provider 2 did not advertise their " <ide> + "accountID.getAccoutAddress() address." <del> , expectedParticipant1Address.indexOf( <del> participantAtP1.getAddress()) != -1 <del> || participantAtP1.getAddress().indexOf( <del> expectedParticipant1Address) != -1); <add> , expectedPeer1Address.indexOf( <add> peerAtP1.getAddress()) != -1 <add> || peerAtP1.getAddress().indexOf( <add> expectedPeer1Address) != -1); <ide> assertEquals("Provider 2 did not properly advertise their " <ide> + "display name." <del> , expectedParticipant1DisplayName <del> , participantAtP1.getDisplayName()); <del> <del> //check properties on the remote call participant for the party that <add> , expectedPeer1DisplayName <add> , peerAtP1.getDisplayName()); <add> <add> //check properties on the remote call peer for the party that <ide> //receives the call. <del> String expectedParticipant2Address <add> String expectedPeer2Address <ide> = fixture.provider1.getAccountID().getAccountAddress(); <del> String expectedParticipant2DisplayName <add> String expectedPeer2DisplayName <ide> = System.getProperty( <ide> SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX <ide> + ProtocolProviderFactory.DISPLAY_NAME); <ide> //display name or something of the kind <ide> assertTrue("Provider 1 did not advertise their " <ide> + "accountID.getAccoutAddress() address." <del> , expectedParticipant2Address.indexOf( <del> participantAtP2.getAddress()) != -1 <del> || participantAtP2.getAddress().indexOf( <del> expectedParticipant2Address) != -1); <add> , expectedPeer2Address.indexOf( <add> peerAtP2.getAddress()) != -1 <add> || peerAtP2.getAddress().indexOf( <add> expectedPeer2Address) != -1); <ide> assertEquals("Provider 1 did not properly advertise their " <ide> + "display name." <del> , expectedParticipant2DisplayName <del> , participantAtP2.getDisplayName()); <add> , expectedPeer2DisplayName <add> , peerAtP2.getDisplayName()); <ide> } <ide> <ide> //we'll now try to cancel the call <ide> <del> //listeners monitoring state change of the participant <del> stateCollectorForPp1 = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.DISCONNECTED); <del> stateCollectorForPp2 = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.DISCONNECTED); <add> //listeners monitoring state change of the peer <add> stateCollectorForPp1 = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.DISCONNECTED); <add> stateCollectorForPp2 = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.DISCONNECTED); <ide> <ide> //listeners waiting for the op set to announce the end of the call <ide> call1Listener = new CallEventCollector(basicTelephonyP1); <ide> = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); <ide> <ide> //Now make the caller CANCEL the call. <del> basicTelephonyP1.hangupCallPeer(participantAtP1); <add> basicTelephonyP1.hangupCallPeer(peerAtP1); <ide> <ide> //wait for everything to happen <ide> call1Listener.waitForEvent(10000); <ide> call2StateCollector.waitForEvent(10000); <ide> <ide> <del> //make sure that the participant is disconnected <del> assertEquals("The participant at provider one was not in the " <add> //make sure that the peer is disconnected <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.DISCONNECTED <del> , participantAtP1.getState()); <add> , peerAtP1.getState()); <ide> <ide> //make sure the telephony operation set distributed an event for the end <ide> //of the call <ide> <ide> //same for provider 2 <ide> <del> //make sure that the participant is disconnected <del> assertEquals("The participant at provider one was not in the " <add> //make sure that the peer is disconnected <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.DISCONNECTED <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> //make sure the telephony operation set distributed an event for the end <ide> //of the call <ide> ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); <ide> assertNotNull("CallEvent.getSource()", callAtP2); <ide> <del> //verify that call participants are properly created <del> assertEquals("callAtP1.getCallParticipantsCount()" <add> //verify that call peers are properly created <add> assertEquals("callAtP1.getCallPeerCount()" <ide> , 1, callAtP1.getCallPeerCount()); <del> assertEquals("callAtP2.getCallParticipantsCount()" <add> assertEquals("callAtP2.getCallPeerCount()" <ide> , 1, callAtP2.getCallPeerCount()); <ide> <del> CallPeer participantAtP1 <add> CallPeer peerAtP1 <ide> = (CallPeer)callAtP1.getCallPeers().next(); <del> CallPeer participantAtP2 <add> CallPeer peerAtP2 <ide> = (CallPeer)callAtP2.getCallPeers().next(); <ide> <del> //now add listeners to the participants and make sure they have entered <add> //now add listeners to the peers and make sure they have entered <ide> //the states they were expected to. <del> //check states for call participants at both parties <del> CallParticipantStateEventCollector stateCollectorForPp1 <del> = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.ALERTING_REMOTE_SIDE); <del> CallParticipantStateEventCollector stateCollectorForPp2 <del> = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.INCOMING_CALL); <add> //check states for call peers at both parties <add> CallPeerStateEventCollector stateCollectorForPp1 <add> = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.ALERTING_REMOTE_SIDE); <add> CallPeerStateEventCollector stateCollectorForPp2 <add> = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.INCOMING_CALL); <ide> <ide> stateCollectorForPp1.waitForEvent(10000, true); <ide> stateCollectorForPp2.waitForEvent(10000, true); <ide> <del> assertSame("participantAtP1.getCall" <del> , participantAtP1.getCall(), callAtP1); <del> assertSame("participantAtP2.getCall" <del> , participantAtP2.getCall(), callAtP2); <del> <del> //make sure that the participants are in the proper state <del> assertEquals("The participant at provider one was not in the " <add> assertSame("peerAtP1.getCall" <add> , peerAtP1.getCall(), callAtP1); <add> assertSame("peerAtP2.getCall" <add> , peerAtP2.getCall(), callAtP2); <add> <add> //make sure that the peers are in the proper state <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.ALERTING_REMOTE_SIDE <del> , participantAtP1.getState()); <del> assertEquals("The participant at provider two was not in the " <add> , peerAtP1.getState()); <add> assertEquals("The peer at provider two was not in the " <ide> +"right state." <ide> , CallPeerState.INCOMING_CALL <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> <ide> //test whether caller/callee info is properly distributed in case <ide> //the server is said to support it. <del> if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) <del> { <del> //check properties on the remote call participant for the party that <add> if(Boolean.getBoolean("accounts.sip.PRESERVE_PEER_INFO")) <add> { <add> //check properties on the remote call peer for the party that <ide> //initiated the call. <del> String expectedParticipant1Address <add> String expectedPeer1Address <ide> = fixture.provider2.getAccountID().getAccountAddress(); <del> String expectedParticipant1DisplayName <add> String expectedPeer1DisplayName <ide> = System.getProperty( <ide> SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX <ide> + ProtocolProviderFactory.DISPLAY_NAME); <ide> //display name or something of the kind <ide> assertTrue("Provider 2 did not advertise their " <ide> + "accountID.getAccoutAddress() address." <del> , expectedParticipant1Address.indexOf( <del> participantAtP1.getAddress()) != -1 <del> || participantAtP1.getAddress().indexOf( <del> expectedParticipant1Address) != -1); <add> , expectedPeer1Address.indexOf( <add> peerAtP1.getAddress()) != -1 <add> || peerAtP1.getAddress().indexOf( <add> expectedPeer1Address) != -1); <ide> assertEquals("Provider 2 did not properly advertise their " <ide> + "display name." <del> , expectedParticipant1DisplayName <del> , participantAtP1.getDisplayName()); <del> <del> //check properties on the remote call participant for the party that <add> , expectedPeer1DisplayName <add> , peerAtP1.getDisplayName()); <add> <add> //check properties on the remote call peer for the party that <ide> //receives the call. <del> String expectedParticipant2Address <add> String expectedPeer2Address <ide> = fixture.provider1.getAccountID().getAccountAddress(); <del> String expectedParticipant2DisplayName <add> String expectedPeer2DisplayName <ide> = System.getProperty( <ide> SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX <ide> + ProtocolProviderFactory.DISPLAY_NAME); <ide> //display name or something of the kind <ide> assertTrue("Provider 1 did not advertise their " <ide> + "accountID.getAccoutAddress() address." <del> , expectedParticipant2Address.indexOf( <del> participantAtP2.getAddress()) != -1 <del> || participantAtP2.getAddress().indexOf( <del> expectedParticipant2Address) != -1); <add> , expectedPeer2Address.indexOf( <add> peerAtP2.getAddress()) != -1 <add> || peerAtP2.getAddress().indexOf( <add> expectedPeer2Address) != -1); <ide> assertEquals("Provider 1 did not properly advertise their " <ide> + "display name." <del> , expectedParticipant2DisplayName <del> , participantAtP2.getDisplayName()); <add> , expectedPeer2DisplayName <add> , peerAtP2.getDisplayName()); <ide> } <ide> <ide> //we'll now try to send busy tone. <ide> <del> //listeners monitoring state change of the participant <del> CallParticipantStateEventCollector busyStateCollectorForPp1 <del> = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.BUSY); <del> stateCollectorForPp1 = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.DISCONNECTED); <del> stateCollectorForPp2 = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.DISCONNECTED); <add> //listeners monitoring state change of the peer <add> CallPeerStateEventCollector busyStateCollectorForPp1 <add> = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.BUSY); <add> stateCollectorForPp1 = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.DISCONNECTED); <add> stateCollectorForPp2 = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.DISCONNECTED); <ide> <ide> //listeners waiting for the op set to announce the end of the call <ide> call1Listener = new CallEventCollector(basicTelephonyP1); <ide> = new CallStateEventCollector(callAtP2, CallState.CALL_ENDED); <ide> <ide> //Now make the caller CANCEL the call. <del> basicTelephonyP2.hangupCallPeer(participantAtP2); <add> basicTelephonyP2.hangupCallPeer(peerAtP2); <ide> busyStateCollectorForPp1.waitForEvent(10000); <del> basicTelephonyP1.hangupCallPeer(participantAtP1); <add> basicTelephonyP1.hangupCallPeer(peerAtP1); <ide> <ide> //wait for everything to happen <ide> call1Listener.waitForEvent(10000); <ide> call2StateCollector.waitForEvent(10000); <ide> <ide> <del> //make sure that the participant is disconnected <del> assertEquals("The participant at provider one was not in the " <add> //make sure that the peer is disconnected <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.DISCONNECTED <del> , participantAtP1.getState()); <add> , peerAtP1.getState()); <ide> <ide> <ide> <ide> <ide> //same for provider 2 <ide> <del> //make sure that the participant is disconnected <del> assertEquals("The participant at provider one was not in the " <add> //make sure that the peer is disconnected <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.DISCONNECTED <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> //make sure the telephony operation set distributed an event for the end <ide> //of the call <ide> ,CallEvent.CALL_RECEIVED, callReceivedEvent.getEventID()); <ide> assertNotNull("CallEvent.getSource()", callAtP2); <ide> <del> //verify that call participants are properly created <del> assertEquals("callAtP1.getCallParticipantsCount()" <add> //verify that call peers are properly created <add> assertEquals("callAtP1.getCallpeersCount()" <ide> , 1, callAtP1.getCallPeerCount()); <del> assertEquals("callAtP2.getCallParticipantsCount()" <add> assertEquals("callAtP2.getCallpeersCount()" <ide> , 1, callAtP2.getCallPeerCount()); <ide> <del> CallPeer participantAtP1 <add> CallPeer peerAtP1 <ide> = (CallPeer)callAtP1.getCallPeers().next(); <del> CallPeer participantAtP2 <add> CallPeer peerAtP2 <ide> = (CallPeer)callAtP2.getCallPeers().next(); <ide> <del> //now add listeners to the participants and make sure they have entered <add> //now add listeners to the peers and make sure they have entered <ide> //the states they were expected to. <del> //check states for call participants at both parties <del> CallParticipantStateEventCollector stateCollectorForPp1 <del> = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.ALERTING_REMOTE_SIDE); <del> CallParticipantStateEventCollector stateCollectorForPp2 <del> = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.INCOMING_CALL); <add> //check states for call peers at both parties <add> CallPeerStateEventCollector stateCollectorForPp1 <add> = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.ALERTING_REMOTE_SIDE); <add> CallPeerStateEventCollector stateCollectorForPp2 <add> = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.INCOMING_CALL); <ide> <ide> stateCollectorForPp1.waitForEvent(10000, true); <ide> stateCollectorForPp2.waitForEvent(10000, true); <ide> <del> assertSame("participantAtP1.getCall" <del> , participantAtP1.getCall(), callAtP1); <del> assertSame("participantAtP2.getCall" <del> , participantAtP2.getCall(), callAtP2); <del> <del> //make sure that the participants are in the proper state <del> assertEquals("The participant at provider one was not in the " <add> assertSame("peerAtP1.getCall" <add> , peerAtP1.getCall(), callAtP1); <add> assertSame("peerAtP2.getCall" <add> , peerAtP2.getCall(), callAtP2); <add> <add> //make sure that the peers are in the proper state <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.ALERTING_REMOTE_SIDE <del> , participantAtP1.getState()); <del> assertEquals("The participant at provider two was not in the " <add> , peerAtP1.getState()); <add> assertEquals("The peer at provider two was not in the " <ide> +"right state." <ide> , CallPeerState.INCOMING_CALL <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> <ide> //test whether caller/callee info is properly distributed in case <ide> //the server is said to support it. <del> if(Boolean.getBoolean("accounts.sip.PRESERVE_PARTICIPANT_INFO")) <del> { <del> //check properties on the remote call participant for the party that <add> if(Boolean.getBoolean("accounts.sip.PRESERVE_PEER_INFO")) <add> { <add> //check properties on the remote call peer for the party that <ide> //initiated the call. <del> String expectedParticipant1Address <add> String expectedPeer1Address <ide> = fixture.provider2.getAccountID().getAccountAddress(); <del> String expectedParticipant1DisplayName <add> String expectedPeer1DisplayName <ide> = System.getProperty( <ide> SipProtocolProviderServiceLick.ACCOUNT_2_PREFIX <ide> + ProtocolProviderFactory.DISPLAY_NAME); <ide> //display name or something of the kind <ide> assertTrue("Provider 2 did not advertise their " <ide> + "accountID.getAccoutAddress() address." <del> , expectedParticipant1Address.indexOf( <del> participantAtP1.getAddress()) != -1 <del> || participantAtP1.getAddress().indexOf( <del> expectedParticipant1Address) != -1); <add> , expectedPeer1Address.indexOf( <add> peerAtP1.getAddress()) != -1 <add> || peerAtP1.getAddress().indexOf( <add> expectedPeer1Address) != -1); <ide> assertEquals("Provider 2 did not properly advertise their " <ide> + "display name." <del> , expectedParticipant1DisplayName <del> , participantAtP1.getDisplayName()); <del> <del> //check properties on the remote call participant for the party that <add> , expectedPeer1DisplayName <add> , peerAtP1.getDisplayName()); <add> <add> //check properties on the remote call peer for the party that <ide> //receives the call. <del> String expectedParticipant2Address <add> String expectedPeer2Address <ide> = fixture.provider1.getAccountID().getAccountAddress(); <del> String expectedParticipant2DisplayName <add> String expectedPeer2DisplayName <ide> = System.getProperty( <ide> SipProtocolProviderServiceLick.ACCOUNT_1_PREFIX <ide> + ProtocolProviderFactory.DISPLAY_NAME); <ide> //display name or something of the kind <ide> assertTrue("Provider 1 did not advertise their " <ide> + "accountID.getAccoutAddress() address." <del> , expectedParticipant2Address.indexOf( <del> participantAtP2.getAddress()) != -1 <del> || participantAtP2.getAddress().indexOf( <del> expectedParticipant2Address) != -1); <add> , expectedPeer2Address.indexOf( <add> peerAtP2.getAddress()) != -1 <add> || peerAtP2.getAddress().indexOf( <add> expectedPeer2Address) != -1); <ide> assertEquals("Provider 1 did not properly advertise their " <ide> + "display name." <del> , expectedParticipant2DisplayName <del> , participantAtP2.getDisplayName()); <del> } <del> <del> //add listeners to the participants and make sure enter <add> , expectedPeer2DisplayName <add> , peerAtP2.getDisplayName()); <add> } <add> <add> //add listeners to the peers and make sure enter <ide> //a connected state after we answer <ide> stateCollectorForPp1 <del> = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.CONNECTED); <add> = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.CONNECTED); <ide> stateCollectorForPp2 <del> = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.CONNECTED); <add> = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.CONNECTED); <ide> <ide> //we will now anser the call and verify that both parties change states <ide> //accordingly. <del> basicTelephonyP2.answerCallPeer(participantAtP2); <add> basicTelephonyP2.answerCallPeer(peerAtP2); <ide> <ide> stateCollectorForPp1.waitForEvent(10000); <ide> stateCollectorForPp2.waitForEvent(10000); <ide> <del> //make sure that the participants are in the proper state <del> assertEquals("The participant at provider one was not in the " <add> //make sure that the peers are in the proper state <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.CONNECTED <del> , participantAtP1.getState()); <del> assertEquals("The participant at provider two was not in the " <add> , peerAtP1.getState()); <add> assertEquals("The peer at provider two was not in the " <ide> +"right state." <ide> , CallPeerState.CONNECTED <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> //make sure that events have been distributed when states were changed. <del> assertEquals("No event was dispatched when a call participant changed " <add> assertEquals("No event was dispatched when a call peer changed " <ide> +"its state." <ide> , 1 <ide> , stateCollectorForPp1.collectedEvents.size()); <del> assertEquals("No event was dispatched when a call participant changed " <add> assertEquals("No event was dispatched when a call peer changed " <ide> +"its state." <ide> , 1 <ide> , stateCollectorForPp2.collectedEvents.size()); <ide> <del> //add listeners to the participants and make sure they have entered <add> //add listeners to the peers and make sure they have entered <ide> //the states they are expected to. <ide> stateCollectorForPp1 <del> = new CallParticipantStateEventCollector( <del> participantAtP1, CallPeerState.DISCONNECTED); <add> = new CallPeerStateEventCollector( <add> peerAtP1, CallPeerState.DISCONNECTED); <ide> stateCollectorForPp2 <del> = new CallParticipantStateEventCollector( <del> participantAtP2, CallPeerState.DISCONNECTED); <add> = new CallPeerStateEventCollector( <add> peerAtP2, CallPeerState.DISCONNECTED); <ide> <ide> //we will now end the call and verify that both parties change states <ide> //accordingly. <del> basicTelephonyP2.hangupCallPeer(participantAtP2); <add> basicTelephonyP2.hangupCallPeer(peerAtP2); <ide> <ide> stateCollectorForPp1.waitForEvent(10000); <ide> stateCollectorForPp2.waitForEvent(10000); <ide> <del> //make sure that the participants are in the proper state <del> assertEquals("The participant at provider one was not in the " <add> //make sure that the peers are in the proper state <add> assertEquals("The peer at provider one was not in the " <ide> +"right state." <ide> , CallPeerState.DISCONNECTED <del> , participantAtP1.getState()); <del> assertEquals("The participant at provider two was not in the " <add> , peerAtP1.getState()); <add> assertEquals("The peer at provider two was not in the " <ide> +"right state." <ide> , CallPeerState.DISCONNECTED <del> , participantAtP2.getState()); <add> , peerAtP2.getState()); <ide> <ide> //make sure that the corresponding events were delivered. <ide> assertEquals("a provider did not distribute an event when a call " <del> +"participant changed states." <add> +"peer changed states." <ide> , 1 <ide> , stateCollectorForPp1.collectedEvents.size()); <ide> assertEquals("a provider did not distribute an event when a call " <del> +"participant changed states." <add> +"peer changed states." <ide> , 1 <ide> , stateCollectorForPp2.collectedEvents.size()); <ide> <ide> } <ide> <ide> /** <del> * Allows tests to wait for and collect events issued upon call participant <add> * Allows tests to wait for and collect events issued upon call peer <ide> * status changes. <ide> */ <del> public class CallParticipantStateEventCollector <add> public class CallPeerStateEventCollector <ide> extends CallPeerAdapter <ide> { <ide> public ArrayList collectedEvents = new ArrayList(); <del> private CallPeer listenedCallParticipant = null; <add> private CallPeer listenedCallPeer = null; <ide> public CallPeerState awaitedState = null; <ide> <ide> /** <ide> * Creates an instance of this collector and adds it as a listener <del> * to <tt>callParticipant</tt>. <del> * @param callParticipant the CallParticipant that we will be listening <add> * to <tt>callPeer</tt>. <add> * @param callPeer the CallPeer that we will be listening <ide> * to. <ide> * @param awaitedState the state that we will be waiting for inside <ide> * this collector. <ide> */ <del> public CallParticipantStateEventCollector( <del> CallPeer callParticipant, <add> public CallPeerStateEventCollector( <add> CallPeer callPeer, <ide> CallPeerState awaitedState) <ide> { <del> this.listenedCallParticipant = callParticipant; <del> this.listenedCallParticipant.addCallPeerListener(this); <add> this.listenedCallPeer = callPeer; <add> this.listenedCallPeer.addCallPeerListener(this); <ide> this.awaitedState = awaitedState; <ide> } <ide> <ide> * @param waitFor the number of miliseconds that we should be waiting <ide> * for an event before simply bailing out. <ide> * @param exitIfAlreadyInState specifies whether the method is to return <del> * if the call participant is already in such a state even if no event <add> * if the call peer is already in such a state even if no event <ide> * has been received for the sate change. <ide> */ <ide> public void waitForEvent(long waitFor, boolean exitIfAlreadyInState) <ide> { <del> logger.trace("Waiting for a CallParticipantEvent with newState=" <del> + awaitedState + " for participant " <del> + this.listenedCallParticipant); <add> logger.trace("Waiting for a CallPeerEvent with newState=" <add> + awaitedState + " for peer " <add> + this.listenedCallPeer); <ide> synchronized (this) <ide> { <ide> if(exitIfAlreadyInState <del> && listenedCallParticipant.getState().equals(awaitedState)) <add> && listenedCallPeer.getState().equals(awaitedState)) <ide> { <del> logger.trace("Src participant is already in the awaited " <add> logger.trace("Src peer is already in the awaited " <ide> + "state." <ide> + collectedEvents); <del> listenedCallParticipant.removeCallPeerListener(this); <add> listenedCallPeer.removeCallPeerListener(this); <ide> return; <ide> } <ide> if(collectedEvents.size() > 0) <ide> { <ide> logger.trace("Event already received. " + <ide> collectedEvents); <del> listenedCallParticipant <add> listenedCallPeer <ide> .removeCallPeerListener(this); <ide> return; <ide> } <ide> logger.trace("No CallParticpantStateEvent received for " <ide> + waitFor + "ms."); <ide> <del> listenedCallParticipant <add> listenedCallPeer <ide> .removeCallPeerListener(this); <ide> } <ide> catch (InterruptedException ex)
Java
apache-2.0
1dd16354521e40566ddc388609362c6037af80ef
0
signed/intellij-community,mglukhikh/intellij-community,vladmm/intellij-community,semonte/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,amith01994/intellij-community,samthor/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,gnuhub/intellij-community,jagguli/intellij-community,slisson/intellij-community,vladmm/intellij-community,fitermay/intellij-community,kdwink/intellij-community,FHannes/intellij-community,semonte/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,semonte/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,mglukhikh/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,fitermay/intellij-community,MichaelNedzelsky/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,michaelgallacher/intellij-community,xfournet/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,slisson/intellij-community,hurricup/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,holmes/intellij-community,signed/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,diorcety/intellij-community,samthor/intellij-community,supersven/intellij-community,allotria/intellij-community,clumsy/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,retomerz/intellij-community,asedunov/intellij-community,pwoodworth/intellij-community,mglukhikh/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,holmes/intellij-community,blademainer/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ibinti/intellij-community,retomerz/intellij-community,kool79/intellij-community,jagguli/intellij-community,akosyakov/intellij-community,wreckJ/intellij-community,akosyakov/intellij-community,samthor/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,suncycheng/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,apixandru/intellij-community,asedunov/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,signed/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,izonder/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,robovm/robovm-studio,ol-loginov/intellij-community,blademainer/intellij-community,signed/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,jagguli/intellij-community,da1z/intellij-community,slisson/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,clumsy/intellij-community,allotria/intellij-community,petteyg/intellij-community,slisson/intellij-community,petteyg/intellij-community,wreckJ/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,slisson/intellij-community,semonte/intellij-community,signed/intellij-community,da1z/intellij-community,clumsy/intellij-community,ibinti/intellij-community,diorcety/intellij-community,alphafoobar/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,kdwink/intellij-community,akosyakov/intellij-community,supersven/intellij-community,signed/intellij-community,ryano144/intellij-community,apixandru/intellij-community,ryano144/intellij-community,clumsy/intellij-community,apixandru/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,wreckJ/intellij-community,samthor/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,adedayo/intellij-community,apixandru/intellij-community,FHannes/intellij-community,kool79/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,akosyakov/intellij-community,samthor/intellij-community,amith01994/intellij-community,allotria/intellij-community,clumsy/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,lucafavatella/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,gnuhub/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,ftomassetti/intellij-community,vvv1559/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,jagguli/intellij-community,holmes/intellij-community,holmes/intellij-community,orekyuu/intellij-community,Lekanich/intellij-community,caot/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,signed/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,supersven/intellij-community,da1z/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,akosyakov/intellij-community,retomerz/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,asedunov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,ftomassetti/intellij-community,salguarnieri/intellij-community,fengbaicanhe/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,vladmm/intellij-community,semonte/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,caot/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,samthor/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,gnuhub/intellij-community,holmes/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,semonte/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,jagguli/intellij-community,gnuhub/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,holmes/intellij-community,izonder/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,diorcety/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,allotria/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,adedayo/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,amith01994/intellij-community,fitermay/intellij-community,izonder/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,TangHao1987/intellij-community,MER-GROUP/intellij-community,youdonghai/intellij-community,Distrotech/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,amith01994/intellij-community,adedayo/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,ThiagoGarciaAlves/intellij-community,fnouama/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,slisson/intellij-community,ibinti/intellij-community,caot/intellij-community,samthor/intellij-community,signed/intellij-community,samthor/intellij-community,amith01994/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,samthor/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,orekyuu/intellij-community,samthor/intellij-community,retomerz/intellij-community,ryano144/intellij-community,ol-loginov/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,ahb0327/intellij-community,clumsy/intellij-community,allotria/intellij-community,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,slisson/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,vladmm/intellij-community,slisson/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,caot/intellij-community,caot/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,blademainer/intellij-community,TangHao1987/intellij-community,michaelgallacher/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,kdwink/intellij-community,da1z/intellij-community,asedunov/intellij-community,allotria/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,asedunov/intellij-community,amith01994/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,gnuhub/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,vladmm/intellij-community,allotria/intellij-community,asedunov/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,kool79/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,kool79/intellij-community,ibinti/intellij-community,kool79/intellij-community,wreckJ/intellij-community,kool79/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,FHannes/intellij-community,retomerz/intellij-community,da1z/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,akosyakov/intellij-community,suncycheng/intellij-community,samthor/intellij-community,semonte/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,SerCeMan/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,Lekanich/intellij-community,da1z/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,xfournet/intellij-community,ahb0327/intellij-community,kool79/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,slisson/intellij-community,supersven/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,salguarnieri/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,robovm/robovm-studio,asedunov/intellij-community,izonder/intellij-community,Lekanich/intellij-community,apixandru/intellij-community,MichaelNedzelsky/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,fitermay/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,apixandru/intellij-community,kdwink/intellij-community,izonder/intellij-community,vladmm/intellij-community,blademainer/intellij-community,fnouama/intellij-community,FHannes/intellij-community,clumsy/intellij-community,dslomov/intellij-community,youdonghai/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,allotria/intellij-community,jagguli/intellij-community,da1z/intellij-community,MichaelNedzelsky/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,xfournet/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,adedayo/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,fitermay/intellij-community,dslomov/intellij-community,kdwink/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,robovm/robovm-studio,jagguli/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,semonte/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,semonte/intellij-community,robovm/robovm-studio,caot/intellij-community,gnuhub/intellij-community,caot/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,da1z/intellij-community,kdwink/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,tmpgit/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,dslomov/intellij-community,ftomassetti/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,robovm/robovm-studio,mglukhikh/intellij-community,diorcety/intellij-community,robovm/robovm-studio,fnouama/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,petteyg/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,ftomassetti/intellij-community,supersven/intellij-community,robovm/robovm-studio,dslomov/intellij-community,salguarnieri/intellij-community,blademainer/intellij-community,signed/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,kdwink/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,ahb0327/intellij-community,izonder/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,signed/intellij-community,kdwink/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,retomerz/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,samthor/intellij-community,izonder/intellij-community,caot/intellij-community,petteyg/intellij-community,fnouama/intellij-community,FHannes/intellij-community,hurricup/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,holmes/intellij-community,signed/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,caot/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,robovm/robovm-studio,amith01994/intellij-community,ibinti/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,nicolargo/intellij-community,ftomassetti/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,signed/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,slisson/intellij-community,xfournet/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,izonder/intellij-community,izonder/intellij-community,holmes/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,fnouama/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,slisson/intellij-community,holmes/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,kool79/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,kool79/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,holmes/intellij-community,youdonghai/intellij-community,adedayo/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,vladmm/intellij-community,ahb0327/intellij-community,idea4bsd/idea4bsd
/* * 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 org.jetbrains.io; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ActionCallback; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.oio.OioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.oio.OioSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.PooledThreadExecutor; import java.io.IOException; import java.net.SocketAddress; public final class NettyUtil { public static final int DEFAULT_CONNECT_ATTEMPT_COUNT = 8; public static final int MIN_START_TIME = 100; public static void log(Throwable throwable, Logger log) { if (isAsWarning(throwable)) { log.warn(throwable); } else { log.error(throwable); } } public static Channel connectClient(Bootstrap bootstrap, SocketAddress remoteAddress, ActionCallback asyncResult) { return connect(bootstrap, remoteAddress, asyncResult, DEFAULT_CONNECT_ATTEMPT_COUNT); } @Nullable public static Channel connect(Bootstrap bootstrap, SocketAddress remoteAddress, ActionCallback asyncResult, int maxAttemptCount) { int attemptCount = 0; while (true) { try { ChannelFuture future = bootstrap.connect(remoteAddress).await(); if (future.isSuccess()) { return future.channel(); } else if (asyncResult.isRejected()) { return null; } else if (++attemptCount < maxAttemptCount) { //noinspection BusyWait Thread.sleep(attemptCount * 100); } else { asyncResult.reject("cannot connect"); return null; } } catch (Throwable e) { asyncResult.reject(e.getMessage()); return null; } } } private static boolean isAsWarning(Throwable throwable) { String message = throwable.getMessage(); if (message == null) { return false; } return (throwable instanceof IOException && message.equals("An existing connection was forcibly closed by the remote host")) || (throwable instanceof ChannelException && message.startsWith("Failed to bind to: ")); } // applicable only in case of ClientBootstrap&OioClientSocketChannelFactory public static void closeAndReleaseFactory(Channel channel) { EventLoop channelFactory = channel.eventLoop(); try { channel.close().awaitUninterruptibly(); } finally { // in our case it does nothing, we don't use ExecutorService, but we are aware of future changes channelFactory.shutdownGracefully(); } } public static ServerBootstrap nioServerBootstrap(EventLoopGroup eventLoopGroup) { ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup).channel(NioServerSocketChannel.class); bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } public static Bootstrap oioClientBootstrap() { Bootstrap bootstrap = new Bootstrap().group(new OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } @SuppressWarnings("UnusedDeclaration") public static Bootstrap nioClientBootstrap() { Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(NioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } public static void initHttpHandlers(ChannelPipeline pipeline) { pipeline.addLast(new HttpRequestDecoder(), new HttpObjectAggregator(1048576), new HttpResponseEncoder()); } }
platform/platform-impl/src/org/jetbrains/io/NettyUtil.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 org.jetbrains.io; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.ActionCallback; import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.*; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.oio.OioEventLoopGroup; import io.netty.channel.socket.nio.NioServerSocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; import io.netty.channel.socket.oio.OioSocketChannel; import io.netty.handler.codec.http.HttpObjectAggregator; import io.netty.handler.codec.http.HttpRequestDecoder; import io.netty.handler.codec.http.HttpResponseEncoder; import org.jetbrains.annotations.Nullable; import org.jetbrains.ide.PooledThreadExecutor; import java.io.IOException; import java.net.SocketAddress; public final class NettyUtil { public static final int DEFAULT_CONNECT_ATTEMPT_COUNT = 8; public static final int MIN_START_TIME = 100; public static void log(Throwable throwable, Logger log) { if (isAsWarning(throwable)) { log.warn(throwable); } else { log.error(throwable); } } public static Channel connectClient(Bootstrap bootstrap, SocketAddress remoteAddress, ActionCallback asyncResult) { return connect(bootstrap, remoteAddress, asyncResult, DEFAULT_CONNECT_ATTEMPT_COUNT); } @Nullable public static Channel connect(Bootstrap bootstrap, SocketAddress remoteAddress, ActionCallback asyncResult, int maxAttemptCount) { int attemptCount = 0; while (true) { try { ChannelFuture future = bootstrap.connect(remoteAddress).await(); if (future.isSuccess()) { return future.channel(); } else if (asyncResult.isRejected()) { return null; } else if (++attemptCount < maxAttemptCount) { //noinspection BusyWait Thread.sleep(attemptCount * 100); } else { asyncResult.reject("cannot connect"); return null; } } catch (Throwable e) { asyncResult.reject(e.getMessage()); return null; } } } private static boolean isAsWarning(Throwable throwable) { String message = throwable.getMessage(); if (message == null) { return false; } return (throwable instanceof IOException && message.equals("An existing connection was forcibly closed by the remote host")) || (throwable instanceof ChannelException && message.startsWith("Failed to bind to: ")); } // applicable only in case of ClientBootstrap&OioClientSocketChannelFactory public static void closeAndReleaseFactory(Channel channel) { EventLoop channelFactory = channel.eventLoop(); try { channel.close().awaitUninterruptibly(); } finally { // in our case it does nothing, we don't use ExecutorService, but we are aware of future changes channelFactory.shutdownGracefully(); } } public static ServerBootstrap nioServerBootstrap(EventLoopGroup eventLoopGroup) { ServerBootstrap bootstrap = new ServerBootstrap().group(eventLoopGroup).channel(NioServerSocketChannel.class); bootstrap.childOption(ChannelOption.TCP_NODELAY, true).childOption(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } public static Bootstrap oioClientBootstrap() { Bootstrap bootstrap = new Bootstrap().group(new OioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(OioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } public static Bootstrap nioClientBootstrap() { Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(NioSocketChannel.class); bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true); return bootstrap; } public static void initHttpHandlers(ChannelPipeline pipeline) { pipeline.addLast(new HttpRequestDecoder(), new HttpObjectAggregator(1048576), new HttpResponseEncoder()); } }
We must not use variable if it is not yet set — we must set channel in "init" handler, but not in "connected" handler. Issue is actual under windows (I don't know why).
platform/platform-impl/src/org/jetbrains/io/NettyUtil.java
We must not use variable if it is not yet set — we must set channel in "init" handler, but not in "connected" handler. Issue is actual under windows (I don't know why).
<ide><path>latform/platform-impl/src/org/jetbrains/io/NettyUtil.java <ide> return bootstrap; <ide> } <ide> <add> @SuppressWarnings("UnusedDeclaration") <ide> public static Bootstrap nioClientBootstrap() { <ide> Bootstrap bootstrap = new Bootstrap().group(new NioEventLoopGroup(1, PooledThreadExecutor.INSTANCE)).channel(NioSocketChannel.class); <ide> bootstrap.option(ChannelOption.TCP_NODELAY, true).option(ChannelOption.SO_KEEPALIVE, true);
Java
apache-2.0
cd9c91b0830b3b49baa27f5c426ff5fe7b093739
0
dragonsKnight5/aquatic-roster-database-setup-and-configuration
/* * Copyright 2016 james. * * 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 java.sql.*; import javax.swing.JOptionPane; /** * @author james */ public class dbConnection { private Connection conn; private String sql; private PreparedStatement ps1 = null; String table = null; Boolean isConnected = false; public dbConnection () { } public boolean firstConnect(String username, String password, String address) { try { conn = DriverManager.getConnection ("jdbc:mysql://"+address+"/?user="+username+"&password="+password); isConnected = true; } catch (SQLException ex) { System.out.println(ex); System.out.println("username: " + username + " password: " + password + " address: " + address); JOptionPane.showMessageDialog(null, "Connection Failed,\n"); isConnected = false; } return isConnected; } public boolean secondConnect(String username, String password, String address) { try { conn = DriverManager.getConnection("jdbc:mysql://"+address+"/staff?user="+username+"&password="+password); isConnected = true; } catch (SQLException ex) { System.out.println(ex); JOptionPane.showMessageDialog(null, "Connection Failed,\nEither no database is available or login credentials are incorrect"); isConnected = false; } return isConnected; } public Boolean connected() { return isConnected; } public void close() { try { conn.close(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } public boolean createDatabase() { int count = 0; String command = "CREATE DATABASE `staff` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 1) { result = true; } return result; } public boolean createUserTable() { int count = 1; String command = "CREATE TABLE `users` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `username` varchar(65) NOT NULL," + " `first_name` varchar(65) NOT NULL," + " `last_name` varchar(65) NOT NULL," + " `department_1` varchar(25) NOT NULL," + " `department_2` varchar(25) DEFAULT NULL," + " `department_3` varchar(25) DEFAULT NULL," + " `supervisor` tinyint(1) DEFAULT NULL," + " `password` varchar(65) NOT NULL," + " PRIMARY KEY (ID)," + " UNIQUE (username)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n"+ ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createLifeguardTable() { int count = 1; String command = "CREATE TABLE `lifeguard` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `shift_date` date NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `location` varchar(65) NOT NULL," + " `staff1` varchar(65) NOT NULL," + " `onCall` varchar(65) NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createLTSTable() { int count = 1; String command = "CREATE TABLE `LTS_Shift` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `staff` varchar(65) NOT NULL," + " `shift_day` varchar(10) NOT NULL," + " `location` varchar(65) NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `start_date` date NOT NULL," + " `end_date` date NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterLtsTable() { int count = 1; String command = "ALTER TABLE `LTS_Shift`" + " ADD KEY `staff` (`staff`)," + " ADD KEY `staff_2` (`staff`)," + " ADD CONSTRAINT `staffFK` FOREIGN KEY (`staff`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createCoversTable() { int count = 1; String command = "CREATE TABLE `LTS_Covers` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `cover_date` date NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `location` varchar(65) NOT NULL," + " `staff` varchar(65) NOT NULL," + " `cover_for` varchar(65) NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterCoversTable() { int count = 1; String command = "ALTER TABLE `LTS_Covers`" + " ADD KEY `staff` (`staff`)," + " ADD KEY `cover_for` (`cover_for`)," + " ADD CONSTRAINT `cover_foreign_key` FOREIGN KEY (`cover_for`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(command); JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean addUser(String username, String firstName, String lastName, String department1, String department2, String department3, boolean supervisor, String password) { int count = 0; String command = "insert into users (username, first_name, last_name, department_1, department_2, department_3, supervisor, password) values " +"(\"" + username + "\", \"" + firstName + "\", \"" + lastName + "\", \"" + department1 + "\", \"" + department2 + "\", \"" + department3 + "\", " + supervisor + ", \"" + password + "\")"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false; if (count == 1) { result = true; } return result; } public boolean alterLifeguardTable() { int count = 1; String command = "ALTER TABLE `lifeguard`" + " ADD KEY `staff1` (`staff1`)," + " ADD CONSTRAINT `lifeguard_ibfk_1` FOREIGN KEY (`staff1`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createLocationTable() { int count = 1; String command = "CREATE TABLE `location` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `Location` varchar(65) NOT NULL," + " `lifeguard` tinyint(1) DEFAULT NULL," + " `lts` tinyint(1) DEFAULT NULL," + " `gym` tinyint(1) DEFAULT NULL," + " `isc` tinyint(1) DEFAULT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean insertLocationEntry() { int count = 1; String command = "INSERT INTO `location` (`ID`, `Location`, `lifeguard`, `lts`, `gym`) VALUES (1, 'None', 1, 1, 1)"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(ex); JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 1) { result = true; } System.out.println("count: " + count + " result: " + result); return result; } public boolean databaseUser(String databaseUser, String network, String databasePassword) { int count = 1; String command = "create user \'" +databaseUser + "\'@\'" + network + "\' identified by \'" + databasePassword +"\'"; System.out.println(command); try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); System.out.println(ex); } boolean result = false; if (count == 0) { result = true; } System.out.println("count: " + count + " result: " + result); return result; } public boolean databaseGrants(String network, String databaseUser) { int count = 1; String command = "grant select, insert, update, delete, alter on staff.* to \'" + databaseUser + "\'@\'" + network +"\'"; System.out.println(command); try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); System.out.println(ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createIscTable() { int count = 1; String command = "CREATE TABLE `ISC` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `shift_date` date NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `location` varchar(65) NOT NULL," + " `staff1` varchar(65) NOT NULL," + " `staff2` varchar(65) NOT NULL," + " `staff3` varchar(65) NOT NULL," + " `staff4` varchar(65) NOT NULL," + " `onCall` varchar(65) NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterIscTable() { int count = 1; String command = "ALTER TABLE `ISC`" + " ADD KEY `staff1` (`staff1`)," + " ADD KEY `staff2` (`staff2`)," + " ADD KEY `staff3` (`staff3`)," + " ADD KEY `staff4` (`staff4`)," + " ADD CONSTRAINT `staff4FK` FOREIGN KEY (`staff4`) REFERENCES `users` (`username`) ON UPDATE CASCADE," + " ADD CONSTRAINT `staff1FK` FOREIGN KEY (`staff1`) REFERENCES `users` (`username`) ON UPDATE CASCADE," + " ADD CONSTRAINT `staff2FK` FOREIGN KEY (`staff2`) REFERENCES `users` (`username`) ON UPDATE CASCADE," + " ADD CONSTRAINT `staff3FK` FOREIGN KEY (`staff3`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createAvailabilityTable() { int count = 1; String command = "CREATE TABLE `availability` (" + " `ID` int(5) NOT NULL AUTO_INCREMENT," + " `username` varchar(65) NOT NULL," + " `monday` varchar(9) DEFAULT NULL," + " `tuesday` varchar(9) DEFAULT NULL," + " `wednesday` varchar(9) DEFAULT NULL," + " `thursday` varchar(9) DEFAULT NULL," + " `friday` varchar(9) DEFAULT NULL," + " `saturday` varchar(9) DEFAULT NULL," + " `sunday` varchar(9) DEFAULT NULL," + " `department` varchar(9) DEFAULT NULL," + " `location` varchar(65) NOT NULL," + " `weekStarting` date NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command +"\n"+ ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterAvailabilityTable() { int count = 1; String command = "ALTER TABLE `availability`" + "ADD KEY `username` (`username`)," + "ADD CONSTRAINT `usernameFK` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(command); JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } }
src/dbConnection.java
/* * Copyright 2016 james. * * 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 java.sql.*; import javax.swing.JOptionPane; /** * @author james */ public class dbConnection { private Connection conn; private String sql; private PreparedStatement ps1 = null; String table = null; Boolean isConnected = false; public dbConnection () { } public boolean firstConnect(String username, String password, String address) { try { conn = DriverManager.getConnection ("jdbc:mysql://"+address+"/?user="+username+"&password="+password); isConnected = true; } catch (SQLException ex) { System.out.println(ex); System.out.println("username: " + username + " password: " + password + " address: " + address); JOptionPane.showMessageDialog(null, "Connection Failed,\n"); isConnected = false; } return isConnected; } public boolean secondConnect(String username, String password, String address) { try { conn = DriverManager.getConnection("jdbc:mysql://"+address+"/staff?user="+username+"&password="+password); isConnected = true; } catch (SQLException ex) { System.out.println(ex); JOptionPane.showMessageDialog(null, "Connection Failed,\nEither no database is available or login credentials are incorrect"); isConnected = false; } return isConnected; } public Boolean connected() { return isConnected; } public void close() { try { conn.close(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, ex); } } public boolean createDatabase() { int count = 0; String command = "CREATE DATABASE `staff` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 1) { result = true; } return result; } public boolean createUserTable() { int count = 1; String command = "CREATE TABLE `users` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `username` varchar(65) NOT NULL," + " `first_name` varchar(65) NOT NULL," + " `last_name` varchar(65) NOT NULL," + " `department_1` varchar(25) NOT NULL," + " `department_2` varchar(25) DEFAULT NULL," + " `department_3` varchar(25) DEFAULT NULL," + " `supervisor` tinyint(1) DEFAULT NULL," + " `password` varchar(65) NOT NULL," + " PRIMARY KEY (ID)," + " UNIQUE (username)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n"+ ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createLifeguardTable() { int count = 1; String command = "CREATE TABLE `lifeguard` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `shift_date` date NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `location` varchar(65) NOT NULL," + " `staff1` varchar(65) NOT NULL," + " `onCall` varchar(65) NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createLTSTable() { int count = 1; String command = "CREATE TABLE `LTS_Shift` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `staff` varchar(65) NOT NULL," + " `shift_day` varchar(10) NOT NULL," + " `location` varchar(65) NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `start_date` date NOT NULL," + " `end_date` date NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterLtsTable() { int count = 1; String command = "ALTER TABLE `LTS_Shift`" + " ADD KEY `staff` (`staff`)," + " ADD KEY `staff_2` (`staff`)," + " ADD CONSTRAINT `staffFK` FOREIGN KEY (`staff`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createCoversTable() { int count = 1; String command = "CREATE TABLE `LTS_Covers` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `cover_date` date NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `location` varchar(65) NOT NULL," + " `staff` varchar(65) NOT NULL," + " `cover_for` varchar(65) NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterCoversTable() { int count = 1; String command = "ALTER TABLE `LTS_Covers`" + " ADD KEY `staff` (`staff`)," + " ADD KEY `cover_for` (`cover_for`)," + " ADD CONSTRAINT `cover_foreign_key` FOREIGN KEY (`cover_for`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(command); JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean addUser(String username, String firstName, String lastName, String department1, String department2, String department3, boolean supervisor, String password) { int count = 0; String command = "insert into users (username, first_name, last_name, department_1, department_2, department_3, supervisor, password) values " +"(\"" + username + "\", \"" + firstName + "\", \"" + lastName + "\", \"" + department1 + "\", \"" + department2 + "\", \"" + department3 + "\", " + supervisor + ", \"" + password + "\")"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false; if (count == 1) { result = true; } return result; } public boolean alterLifeguardTable() { int count = 1; String command = "ALTER TABLE `lifeguard`" + " ADD KEY `staff1` (`staff1`)," + " ADD CONSTRAINT `lifeguard_ibfk_1` FOREIGN KEY (`staff1`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createLocationTable() { int count = 1; String command = "CREATE TABLE `location` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `Location` varchar(65) NOT NULL," + " `lifeguard` tinyint(1) DEFAULT NULL," + " `lts` tinyint(1) DEFAULT NULL," + " `gym` tinyint(1) DEFAULT NULL," + " `isc` tinyint(1) DEFAULT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean insertLocationEntry() { int count = 1; String command = "INSERT INTO `location` (`ID`, `Location`, `lifeguard`, `lts`, `gym`) VALUES (1, 'None', 1, 1, 1)"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(ex); JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 1) { result = true; } System.out.println("count: " + count + " result: " + result); return result; } public boolean databaseUser(String databaseUser, String network, String databasePassword) { int count = 1; String command = "create user \'" +databaseUser + "\'@\'" + network + "\' identified by \'" + databasePassword +"\'"; System.out.println(command); try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); System.out.println(ex); } boolean result = false; if (count == 0) { result = true; } System.out.println("count: " + count + " result: " + result); return result; } public boolean databaseGrants(String network, String databaseUser) { int count = 1; String command = "grant select, insert, delete, alter on staff.* to \'" + databaseUser + "\'@\'" + network +"\'"; System.out.println(command); try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); System.out.println(ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createIscTable() { int count = 1; String command = "CREATE TABLE `ISC` (" + " `ID` int(4) NOT NULL AUTO_INCREMENT," + " `shift_date` date NOT NULL," + " `start_time` time NOT NULL," + " `end_time` time NOT NULL," + " `location` varchar(65) NOT NULL," + " `staff1` varchar(65) NOT NULL," + " `staff2` varchar(65) NOT NULL," + " `staff3` varchar(65) NOT NULL," + " `staff4` varchar(65) NOT NULL," + " `onCall` varchar(65) NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + "\n" + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterIscTable() { int count = 1; String command = "ALTER TABLE `ISC`" + " ADD KEY `staff1` (`staff1`)," + " ADD KEY `staff2` (`staff2`)," + " ADD KEY `staff3` (`staff3`)," + " ADD KEY `staff4` (`staff4`)," + " ADD CONSTRAINT `staff4FK` FOREIGN KEY (`staff4`) REFERENCES `users` (`username`) ON UPDATE CASCADE," + " ADD CONSTRAINT `staff1FK` FOREIGN KEY (`staff1`) REFERENCES `users` (`username`) ON UPDATE CASCADE," + " ADD CONSTRAINT `staff2FK` FOREIGN KEY (`staff2`) REFERENCES `users` (`username`) ON UPDATE CASCADE," + " ADD CONSTRAINT `staff3FK` FOREIGN KEY (`staff3`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean createAvailabilityTable() { int count = 1; String command = "CREATE TABLE `availability` (" + " `ID` int(5) NOT NULL AUTO_INCREMENT," + " `username` varchar(65) NOT NULL," + " `monday` varchar(9) DEFAULT NULL," + " `tuesday` varchar(9) DEFAULT NULL," + " `wednesday` varchar(9) DEFAULT NULL," + " `thursday` varchar(9) DEFAULT NULL," + " `friday` varchar(9) DEFAULT NULL," + " `saturday` varchar(9) DEFAULT NULL," + " `sunday` varchar(9) DEFAULT NULL," + " `department` varchar(9) DEFAULT NULL," + " `location` varchar(65) NOT NULL," + " `weekStarting` date NOT NULL," + " PRIMARY KEY (ID)" + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { JOptionPane.showMessageDialog(null, command +"\n"+ ex); } boolean result = false ; if (count == 0) { result = true; } return result; } public boolean alterAvailabilityTable() { int count = 1; String command = "ALTER TABLE `availability`" + "ADD KEY `username` (`username`)," + "ADD CONSTRAINT `usernameFK` FOREIGN KEY (`username`) REFERENCES `users` (`username`) ON UPDATE CASCADE"; try { ps1 = conn.prepareStatement(command); count = ps1.executeUpdate(); } catch (SQLException ex) { System.out.println(command); JOptionPane.showMessageDialog(null, command + ex); } boolean result = false ; if (count == 0) { result = true; } return result; } }
progress update
src/dbConnection.java
progress update
<ide><path>rc/dbConnection.java <ide> public boolean databaseGrants(String network, String databaseUser) <ide> { <ide> int count = 1; <del> String command = "grant select, insert, delete, alter on staff.* to \'" + databaseUser + "\'@\'" + network +"\'"; <add> String command = "grant select, insert, update, delete, alter on staff.* to \'" + databaseUser + "\'@\'" + network +"\'"; <ide> System.out.println(command); <ide> try <ide> {
Java
apache-2.0
019ca85701b636513d3830587550982c97c52e8f
0
peacekeeper/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,anastasia-tarasova/indy-sdk,anastasia-tarasova/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,Artemkaaas/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,Artemkaaas/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,srottem/indy-sdk,anastasia-tarasova/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk,srottem/indy-sdk,peacekeeper/indy-sdk,peacekeeper/indy-sdk
package org.hyperledger.indy.sdk.crypto; import org.hyperledger.indy.sdk.IndyIntegrationTest; import org.hyperledger.indy.sdk.IndyIntegrationTestWithSingleWallet; import org.hyperledger.indy.sdk.InvalidStructureException; import org.hyperledger.indy.sdk.did.Did; import org.hyperledger.indy.sdk.did.DidResults; import org.hyperledger.indy.sdk.wallet.WalletItemNotFoundException; import org.junit.Test; import org.json.JSONArray; import java.util.concurrent.ExecutionException; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.*; public class PackUnpackMessageTest extends IndyIntegrationTestWithSingleWallet { @Test public void testPackMessageSuccessfully() throws Exception { String message = "hello world"; JSONArray receieversArray = new JSONArray(); receieversArray.put(IndyIntegrationTest.VERKEY_MY1); receieversArray.put(IndyIntegrationTest.VERKEY_MY2); receieversArray.put(IndyIntegrationTest.VERKEY_TRUSTEE); String myVk = Crypto.createKey(wallet, MY1_IDENTITY_KEY_JSON).get(); byte[] packedMessage = Crypto.packMessage(wallet, receieversArray.toString(), null, message.getBytes()).get(); assertNotNull(packedMessage); } @Test public void testPackMessageSuccessfullyWithOneReceiver() throws Exception { String message = "hello world"; JSONArray receieversArray = new JSONArray(); receieversArray.put(IndyIntegrationTest.VERKEY_MY1); String myVk = Crypto.createKey(wallet, MY1_IDENTITY_KEY_JSON).get(); byte[] packedMessage = Crypto.packMessage(wallet, receieversArray.toString(), null, message.getBytes()).get(); assertNotNull(packedMessage); } @Test(expected = java.util.concurrent.ExecutionException.class) public void testUnpackMessageWithInvalidStructure() throws Exception { String packedMessage = "jibberish"; byte[] unpackedMessage = Crypto.unpackMessage(wallet, packedMessage.getBytes()).get(); // this assert should never trigger since unpackMessage should throw exception assertTrue(false); } @Test public void testUnpackMessageSuccessfully() throws Exception { String message = "hello world"; JSONArray receieversArray = new JSONArray(); receieversArray.put(IndyIntegrationTest.VERKEY_MY1); receieversArray.put(IndyIntegrationTest.VERKEY_MY2); receieversArray.put(IndyIntegrationTest.VERKEY_TRUSTEE); String myVk = Crypto.createKey(wallet, MY1_IDENTITY_KEY_JSON).get(); byte[] packedMessage = Crypto.packMessage(wallet, receieversArray.toString(), null, message.getBytes()).get(); byte[] unpackedMessage = Crypto.unpackMessage(wallet, packedMessage).get(); assertNotNull(unpackedMessage); } }
wrappers/java/src/test/java/org/hyperledger/indy/sdk/crypto/PackUnpackMessageTest.java
package org.hyperledger.indy.sdk.crypto; import org.hyperledger.indy.sdk.IndyIntegrationTest; import org.hyperledger.indy.sdk.IndyIntegrationTestWithSingleWallet; import org.hyperledger.indy.sdk.InvalidStructureException; import org.hyperledger.indy.sdk.did.Did; import org.hyperledger.indy.sdk.did.DidResults; import org.hyperledger.indy.sdk.wallet.WalletItemNotFoundException; import org.junit.Test; import org.json.JSONArray; import java.util.concurrent.ExecutionException; import static org.hamcrest.CoreMatchers.isA; import static org.junit.Assert.*; public class PackUnpackMessageTest extends IndyIntegrationTestWithSingleWallet { @Test public void testPackMessage() throws Exception { String message = "hello world"; JSONArray receieversArray = new JSONArray(); receieversArray.put(IndyIntegrationTest.VERKEY_MY1); receieversArray.put(IndyIntegrationTest.VERKEY_MY2); receieversArray.put(IndyIntegrationTest.VERKEY_TRUSTEE); String myVk = Crypto.createKey(wallet, MY1_IDENTITY_KEY_JSON).get(); byte[] packedMessage = Crypto.packMessage(wallet, receieversArray.toString(), null, message.getBytes()).get(); assertNotNull(packedMessage); } // This test proves the API is hooked up correctly and error result is returned @Test(expected = java.util.concurrent.ExecutionException.class) public void testUnpackMessageWithInvalidStructure() throws Exception { String packedMessage = "jibberish"; byte[] unpackedMessage = Crypto.unpackMessage(wallet, packedMessage.getBytes()).get(); } }
finishes tests Signed-off-by: matt raffel <[email protected]>
wrappers/java/src/test/java/org/hyperledger/indy/sdk/crypto/PackUnpackMessageTest.java
finishes tests
<ide><path>rappers/java/src/test/java/org/hyperledger/indy/sdk/crypto/PackUnpackMessageTest.java <ide> public class PackUnpackMessageTest extends IndyIntegrationTestWithSingleWallet { <ide> <ide> @Test <del> public void testPackMessage() throws Exception { <add> public void testPackMessageSuccessfully() throws Exception { <ide> String message = "hello world"; <ide> <ide> JSONArray receieversArray = new JSONArray(); <ide> assertNotNull(packedMessage); <ide> } <ide> <del> // This test proves the API is hooked up correctly and error result is returned <add> @Test <add> public void testPackMessageSuccessfullyWithOneReceiver() throws Exception { <add> String message = "hello world"; <add> <add> JSONArray receieversArray = new JSONArray(); <add> receieversArray.put(IndyIntegrationTest.VERKEY_MY1); <add> <add> String myVk = Crypto.createKey(wallet, MY1_IDENTITY_KEY_JSON).get(); <add> <add> byte[] packedMessage = Crypto.packMessage(wallet, receieversArray.toString(), null, message.getBytes()).get(); <add> <add> assertNotNull(packedMessage); <add> } <add> <ide> @Test(expected = java.util.concurrent.ExecutionException.class) <ide> public void testUnpackMessageWithInvalidStructure() throws Exception { <ide> <ide> String packedMessage = "jibberish"; <ide> byte[] unpackedMessage = Crypto.unpackMessage(wallet, packedMessage.getBytes()).get(); <ide> <add> // this assert should never trigger since unpackMessage should throw exception <add> assertTrue(false); <add> } <add> <add> @Test <add> public void testUnpackMessageSuccessfully() throws Exception { <add> String message = "hello world"; <add> <add> JSONArray receieversArray = new JSONArray(); <add> receieversArray.put(IndyIntegrationTest.VERKEY_MY1); <add> receieversArray.put(IndyIntegrationTest.VERKEY_MY2); <add> receieversArray.put(IndyIntegrationTest.VERKEY_TRUSTEE); <add> <add> String myVk = Crypto.createKey(wallet, MY1_IDENTITY_KEY_JSON).get(); <add> <add> byte[] packedMessage = Crypto.packMessage(wallet, receieversArray.toString(), null, message.getBytes()).get(); <add> byte[] unpackedMessage = Crypto.unpackMessage(wallet, packedMessage).get(); <add> <add> assertNotNull(unpackedMessage); <ide> } <ide> <ide> }
Java
lgpl-2.1
f4a29a313b81099ff749a95f032cf2ee866a892b
0
sbliven/biojava,sbliven/biojava,sbliven/biojava
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 16.03.2004 * @author Andreas Prlic * * */ package org.biojava.bio.structure.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.Compound; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.PDBStatus; import org.biojava.bio.structure.PDBStatus.Status; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.align.ce.AbstractUserArgumentProcessor; import org.biojava.bio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.bio.structure.io.mmcif.ReducedChemCompProvider; import org.biojava.bio.structure.io.util.FileDownloadUtils; import org.biojava3.core.util.InputStreamProvider; /** * <p> * The wrapper class for parsing a PDB file. * </p> * * * <p> * Several flags can be set for this class * <ul> * * <li> {@link #setAutoFetch(boolean)} - if the PDB file can not be found locally, should it be fetched * from the PDB ftp servers? (default:false)</li> * <li> Other parameters can be set using the {@link #setFileParsingParameters(FileParsingParameters)}</li> * </ul> * </p> * * * *<h2>Example</h2> * <p> * Q: How can I get a Structure object from a PDB file? * </p> * <p> * A: * <pre> public {@link Structure} loadStructure(String pathToPDBFile){ {@link PDBFileReader} pdbreader = new {@link PDBFileReader}(); {@link Structure} structure = null; try{ structure = pdbreader.getStructure(pathToPDBFile); System.out.println(structure); } catch (IOException e) { e.printStackTrace(); } return structure; } </pre> * * Access PDB files from a directory, take care of compressed PDB files * <pre> * public {@link Structure} loadStructureById() { String path = "/path/to/PDB/directory/"; {@link PDBFileReader} pdbreader = new {@link PDBFileReader}(); pdbreader.setPath(path); {@link Structure} structure = null; try { structure = pdbreader.getStructureById("5pti"); } catch (IOException e){ e.printStackTrace(); } return structure; } </pre> * * * @author Andreas Prlic * */ public class PDBFileReader implements StructureIOFile { // a list of big pdb files for testing // "1htq", // "1c2w", // "1ffk", // "1giy", // "1j5a", // "1jj2", // "1jzx", // "1jzy", // "1jzz", // "1k01", // "1k73", // "1k8a", // "1k9m", // "1kc8", // "1kd1", // "1kqs", // "1m1k", // "1m90", // "1mkz", // "1ml5", // "1n8r", public static final String LOAD_CHEM_COMP_PROPERTY = "loadChemCompInfo"; String path; List<String> extensions; boolean autoFetch; private boolean fetchCurrent; private boolean fetchFileEvenIfObsolete; boolean pdbDirectorySplit; private int bioAssemblyId = 0; // number > 0 indicates the id of the biological assembly private boolean bioAssemblyFallback = true; // use regular PDB file as the biological assembly (i.e. for NMR structures) // in case no biological assembly file is available. private boolean loadedBioAssembly = false; public static final String lineSplit = System.getProperty("file.separator"); public static final String DEFAULT_PDB_FILE_SERVER = "ftp.wwpdb.org"; public static final String PDB_FILE_SERVER_PROPERTY = "PDB.FILE.SERVER"; private static final String CURRENT_FILES_PATH = "/pub/pdb/data/structures/divided/pdb/"; private static final String OBSOLETE_FILES_PATH = "/pub/pdb/data/structures/obsolete/pdb/"; private static final String BIO_ASSEMBLY_FILES_PATH = "/pub/pdb/data/biounit/coordinates/divided/"; private static final String LOCAL_BIO_ASSEMBLY_DIRECTORY = "bio_assembly"; FileParsingParameters params ; public static final long lastRemediationDate ; static { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US); long t = 0; try { Date d = formatter.parse("2011/07/12"); t = d.getTime(); } catch (Exception e){ e.printStackTrace(); } lastRemediationDate = t; } public static void main(String[] args){ PDBFileReader pdbreader = new PDBFileReader(); // set the path to cache files String property = "java.io.tmpdir"; String tempdir = System.getProperty(property); // tempdir = "/path/to/local/PDB/installation/"; pdbreader.setPath(tempdir); FileParsingParameters params = new FileParsingParameters(); pdbreader.setFileParsingParameters(params); try{ Structure struc = pdbreader.getStructureById("193D"); System.out.println(struc); List<Compound> compounds = struc.getCompounds(); for (Compound comp : compounds ){ List<Chain> chains = comp.getChains(); System.out.print(">Chains :" ); for (Chain c : chains){ System.out.print(c.getChainID() + " " ); } System.out.println(); if ( chains.size() > 0) { System.out.println(chains.get(0).getAtomSequence()); System.out.println(chains.get(0).getSeqResSequence()); System.out.print(" Atom Ligands: "); for ( Group g: chains.get(0).getAtomLigands()){ System.out.print( g.getPDBName() + " "); } System.out.println(" "); } } /* GroupIterator gi = new GroupIterator(struc); while (gi.hasNext()){ Group g = (Group) gi.next(); Chain c = g.getParent(); if ( g instanceof AminoAcid ){ AminoAcid aa = (AminoAcid)g; Map<String,String> sec = aa.getSecStruc(); //System.out.println(c.getName() + " " + g + " " + sec); ChemComp cc = g.getChemComp(); System.out.println(c.getName() + " " + g.getPDBCode() + " " + g.getPDBName() + " " + cc + " " +sec); } } */ } catch (Exception e) { e.printStackTrace(); } } public PDBFileReader() { extensions = new ArrayList<String>(); extensions.add(".ent"); extensions.add(".pdb"); extensions.add(".ent.gz"); extensions.add(".pdb.gz"); extensions.add(".ent.Z"); extensions.add(".pdb.Z"); autoFetch = false; pdbDirectorySplit = false; params = new FileParsingParameters(); //checkPath(); } /** Check the directory that contains the local cache of PDB and chemical component definiton files. * By default, at startup we fall back to java.io.tmpdir */ private void checkPath(){ if ((path == null) || (path.equals("")) || path.equals("null")) { String syspath = System.getProperty(AbstractUserArgumentProcessor.PDB_DIR); if ((syspath != null) && (! syspath.equals("")) && (! syspath.equals("null"))){ path = syspath; return; } // accessing temp. OS directory: String property = "java.io.tmpdir"; String tempdir = System.getProperty(property); if ( !(tempdir.endsWith(lineSplit) ) ) tempdir = tempdir + lineSplit; // System.err.println("you did not set the path in PDBFileReader, don't know where to write the downloaded file to"); System.err.println("assuming default location is temp directory: " + tempdir); path = tempdir; } } /** directory where to find PDB files */ public void setPath(String p){ System.setProperty(AbstractUserArgumentProcessor.PDB_DIR,p); path = p ; } /** * Returns the path value. * @return a String representing the path value * @see #setPath * */ public String getPath() { return path ; } /** define supported file extensions * compressed extensions .Z,.gz do not need to be specified * they are dealt with automatically. */ public void addExtension(String s){ //System.out.println("add Extension "+s); extensions.add(s); } /** clear the supported file extensions * */ public void clearExtensions(){ extensions.clear(); } /** Flag that defines if the PDB directory is containing all PDB files or is split into sub dirs (like the FTP site). * * @return boolean. default is false (all files in one directory) */ public boolean isPdbDirectorySplit() { return pdbDirectorySplit; } /** Flag that defines if the PDB directory is containing all PDB files or is split into sub dirs (like the FTP site). * * @param pdbDirectorySplit boolean. If set to false all files are in one directory. */ public void setPdbDirectorySplit(boolean pdbDirectorySplit) { this.pdbDirectorySplit = pdbDirectorySplit; } /** * Sets the ID of the biological assembly to be loaded. By default, the bioAssemblyId=0, which corresponds to the * original PDB file. If an ID > 0 is specified, the corresponding biological assembly file will be loaded. Note, the * number of available biological unit files varies. Many entries don't have a biological unit specified (i.e. NMR structures), * many entries have only one biological unit (bioAssemblyId=1), and a few structures have multiple biological assemblies. * * @param bioAssemblyId ID of the biological assembly to be loaded * @author Peter Rose * @since 3.2 */ public void setBioAssemblyId(int bioAssemblyId) { this.bioAssemblyId = bioAssemblyId; } /** * Set bioAssemblyFallback to true, to download the original PDB file in cases that a biological assembly file is not available. * * @param bioAssemblyFallback if true, tries reading original PDB file in case the biological assembly file is not available * @author Peter Rose * @since 3.2 */ public void setBioAssemblyFallback(boolean bioAssemblyFallback) { this.bioAssemblyFallback = bioAssemblyFallback; } /** try to find the file in the filesystem and return a filestream in order to parse it * rules how to find file * - first check: if file is in path specified by PDBpath * - secnd check: if not found check in PDBpath/xy/ where xy is second and third char of PDBcode. * if autoFetch is set it will try to download missing PDB files automatically. */ private InputStream getInputStream(String pdbId) throws IOException { if ( pdbId.length() < 4) throw new IOException("the provided ID does not look like a PDB ID : " + pdbId); checkPath(); InputStream inputStream =null; String pdbFile = getLocalPDBFilePath(pdbId); if ( pdbFile != null) { InputStreamProvider isp = new InputStreamProvider(); try { inputStream = isp.getInputStream(pdbFile); return inputStream; } catch (Exception e){ e.printStackTrace(); // something is wrong with the file! // it probably should be downloaded again... pdbFile = null; } } if ( pdbFile == null ) { if (autoFetch){//from here we try our online search if(fetchCurrent && !fetchFileEvenIfObsolete) { String current = PDBStatus.getCurrent(pdbId); if(current == null) { // either an error or there is not current entry current = pdbId; } return downloadAndGetInputStream(current, CURRENT_FILES_PATH); } else if(fetchFileEvenIfObsolete && PDBStatus.getStatus(pdbId) == Status.OBSOLETE) { return downloadAndGetInputStream(pdbId, OBSOLETE_FILES_PATH); } else { return downloadAndGetInputStream(pdbId, CURRENT_FILES_PATH); } }else { String message = "no structure with PDB code " + pdbId + " found!" ; throw new IOException (message); } } return null ; } /** Returns null if local PDB file does not exist or should be downloaded again... * * @param pdbId * @return */ private String getLocalPDBFilePath(String pdbId) { String pdbFile = null ; File f = null ; // this are the possible PDB file names... String fpath ; String ppath ; if ( pdbDirectorySplit){ // pdb files are split into subdirectories based on their middle position... String middle = pdbId.substring(1,3).toLowerCase(); fpath = path+lineSplit + middle + lineSplit + pdbId; ppath = path +lineSplit + middle + lineSplit + "pdb"+pdbId; } else { fpath = path+lineSplit + pdbId; ppath = path +lineSplit + "pdb"+pdbId; } String[] paths = new String[]{fpath,ppath}; for ( int p=0;p<paths.length;p++ ){ String testpath = paths[p]; //System.out.println(testpath); for (int i=0 ; i<extensions.size();i++){ String ex = (String)extensions.get(i) ; //System.out.println("PDBFileReader testing: "+testpath+ex); f = new File(testpath+ex) ; if ( f.exists()) { pdbFile = testpath+ex ; // we have found the file locally if ( params.isUpdateRemediatedFiles()){ long lastModified = f.lastModified(); if (lastModified < lastRemediationDate) { // the file is too old, replace with newer version System.out.println("replacing file " + pdbFile +" with latest remediated file from PDB."); pdbFile = null; return null; } } return pdbFile; } if ( pdbFile != null) break; } } return null; } /** * Returns an input stream for a biological assembly file based on the passed in pdbId and * the biological assembly id {@link #setBioAssemblyId(int)}. Files are cached in a local directory. * @param pdbId * @return InputStream * @throws IOException * @author Peter Rose * @since 3.2 */ private InputStream getInputStreamBioAssembly(String pdbId) throws IOException { loadedBioAssembly = true; InputStream inputStream = null; if ( pdbId.length() < 4) throw new IOException("the provided ID does not look like a PDB ID : " + pdbId); checkPath(); // make sure path follows unix convention String uPath = FileDownloadUtils.toUnixPath(path); // create local subdirectory for biological assembly files if it doesn't exist String dir = uPath + LOCAL_BIO_ASSEMBLY_DIRECTORY; File tmp = new File(dir); if ( ! tmp.exists()){ tmp.mkdir(); } String fpath ; if (pdbDirectorySplit){ // pdb files are split into subdirectories based on their middle position... String middle = pdbId.substring(1,3).toLowerCase(); fpath = dir + "/" + middle + "/"; } else { fpath = dir + "/"; } String fileName = fpath + getBiologicalAsssemblyFileName(pdbId.toLowerCase(), bioAssemblyId); File f = new File(fileName) ; // check if bio assembly file exists in local cache if ( f.exists()) { InputStreamProvider isp = new InputStreamProvider(); try { inputStream = isp.getInputStream(fileName); return inputStream; } catch (Exception e){ e.printStackTrace(); // something is wrong with the file! // it probably should be downloaded again... } } else if (bioAssemblyFallback) { if (pdbDirectorySplit){ // pdb files are split into subdirectories based on their middle position... String middle = pdbId.substring(1,3).toLowerCase(); fpath = uPath + middle + "/"; } else { fpath = uPath; } fileName = fpath + "pdb" + pdbId + ".ent.gz"; f = new File(fileName); if (f.exists()) { try { InputStreamProvider isp = new InputStreamProvider(); inputStream = isp.getInputStream(fileName); System.out.println("Loaded original PDB file as a fallback." + fileName); loadedBioAssembly = false; return inputStream; } catch (Exception e) { // now try autofetch next } } } if (autoFetch){//from here we try our online search if(fetchCurrent && !fetchFileEvenIfObsolete) { String current = PDBStatus.getCurrent(pdbId); if(current == null) { // either an error or there is not current entry current = pdbId; } inputStream = downloadAndGetInputStreamBioAssembly(current, BIO_ASSEMBLY_FILES_PATH); if (inputStream != null) { return inputStream; } } else if(fetchFileEvenIfObsolete && PDBStatus.getStatus(pdbId) == Status.OBSOLETE) { String message = "No biological assembly with PDB code " + pdbId + " found!" ; throw new IOException (message); } else { inputStream = downloadAndGetInputStreamBioAssembly(pdbId, BIO_ASSEMBLY_FILES_PATH); if (inputStream != null) { return inputStream; } } } // if biological assembly file cannot be found, and bioAssemblyFallBack is true, // get the original PDB file as a fall back (i.e. for NMR structures, where the // PDB file represents the biological assembly). if (bioAssemblyFallback) { inputStream = getInputStream(pdbId); if (inputStream != null) { System.out.println("Biological assembly file for PDB ID: " + pdbId+ " is not available. " + "Loaded original PDB file as a fallback from local cache."); return getInputStream(pdbId); } } return null; } private File downloadPDB(String pdbId, String pathOnServer){ if ((path == null) || (path.equals(""))){ // accessing temp. OS directory: String property = "java.io.tmpdir"; String tempdir = System.getProperty(property); if ( !(tempdir.endsWith(lineSplit) ) ) tempdir = tempdir + lineSplit; System.err.println("you did not set the path in PDBFileReader, don;t know where to write the downloaded file to"); System.err.println("assuming default location is temp directory: " + tempdir); path = tempdir; } File realFile = null; pdbId = pdbId.toLowerCase(); String middle = pdbId.substring(1,3); if ( pdbDirectorySplit) { String dir = path+lineSplit+middle; File directoryCheck = new File (dir); if ( ! directoryCheck.exists()){ directoryCheck.mkdir(); } realFile =new File(dir+lineSplit+"pdb"+ pdbId+".ent.gz"); } else { realFile = new File(path+lineSplit+"pdb"+pdbId+".ent.gz"); } String serverName = System.getProperty(PDB_FILE_SERVER_PROPERTY); if ( serverName == null) serverName = DEFAULT_PDB_FILE_SERVER; String ftp = String.format("ftp://%s%s%s/pdb%s.ent.gz", serverName,pathOnServer,middle, pdbId); //System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); FileDownloadUtils.downloadGzipCompressedFile(url, realFile); } catch (Exception e){ System.err.println("Problem while downloading PDB ID " + pdbId + " from FTP server." ); e.printStackTrace(); return null; } return realFile; } /** * Downloads a biological assembly file. If this file cannot be found, it will download the original * PDB file (i.e. for NMR structures), if bioAssemblyFallback has been set to true; * @param pdbId * @param pathOnServer * @return File of biological assembly * @author Peter Rose * @since 3.2 */ private File downloadPDBBiologicalAssembly(String pdbId, String pathOnServer){ loadedBioAssembly = true; checkPath(); String fileName = getBiologicalAsssemblyFileName(pdbId, bioAssemblyId); pdbId = pdbId.toLowerCase(); String middle = pdbId.substring(1,3); String serverName = System.getProperty(PDB_FILE_SERVER_PROPERTY); if ( serverName == null) serverName = DEFAULT_PDB_FILE_SERVER; String ftp = String.format("ftp://%s%s%s/%s", serverName,pathOnServer,middle,fileName); System.out.println("Fetching " + ftp); URL url = null; try { url = new URL(ftp); } catch (MalformedURLException e1) { System.err.println("Problem while downloading Biological Assembly " + pdbId + " from FTP server." ); e1.printStackTrace(); return null; } // check if the file exists on the FTP site. If biological assembly file does not exist // and the fallback has been set, get the original PDB file instead (i.e. for NMR structures). File f = null; try { f = downloadFileIfAvailable(url, pdbId,fileName); } catch (IOException ioe){ // ignore here because it prob. means the file does not exist... } if ( f == null) { if (bioAssemblyFallback) { System.out.println("Biological unit file for PDB ID: " + pdbId+ " is not available. " + "Downloading original PDB file as a fallback."); loadedBioAssembly = false; String fallBackPDBF = getLocalPDBFilePath(pdbId); if ( fallBackPDBF != null) return new File(fallBackPDBF); return downloadPDB(pdbId, CURRENT_FILES_PATH); } return null; } return f; } private File downloadFileIfAvailable(URL url, String pdbId, String fileName) throws IOException { String middle = pdbId.substring(1,3); String uPath = FileDownloadUtils.toUnixPath(path); File tempFile = null; if (pdbDirectorySplit) { String dir = uPath + LOCAL_BIO_ASSEMBLY_DIRECTORY + "/" + middle; File directoryCheck = new File (dir); if ( ! directoryCheck.exists()){ directoryCheck.mkdir(); } tempFile =new File(dir + "/" + fileName); } else { tempFile = new File(path + LOCAL_BIO_ASSEMBLY_DIRECTORY + "/" + fileName); } return FileDownloadUtils.downloadFileIfAvailable(url, tempFile); } private InputStream downloadAndGetInputStream(String pdbId, String pathOnServer) throws IOException{ File tmp = downloadPDB(pdbId, pathOnServer); if (tmp != null) { InputStreamProvider prov = new InputStreamProvider(); InputStream is = prov.getInputStream(tmp); return is; } else { throw new IOException("could not find PDB " + pdbId + " in file system and also could not download"); } } /** * Downloads biological assembly file to local cache and provides input stream to cached file. * @param pdbId * @param pathOnServer * @return inputStream to cached file * @throws IOException * @author Peter Rose * @since 3.2 */ private InputStream downloadAndGetInputStreamBioAssembly(String pdbId, String pathOnServer) throws IOException{ File tmp = downloadPDBBiologicalAssembly(pdbId, pathOnServer); if (tmp != null) { InputStreamProvider prov = new InputStreamProvider(); InputStream is = prov.getInputStream(tmp); return is; } else { throw new IOException("Could not find Biological Assembly " + pdbId + " in file system and also could not download"); } } /** load a structure from local file system and return a PDBStructure object * @param pdbId a String specifying the id value (PDB code) * @return the Structure object * @throws IOException ... */ public Structure getStructureById(String pdbId)throws IOException { InputStream inStream = null; if (bioAssemblyId == 0) { inStream = getInputStream(pdbId); } else { //System.out.println("loading bioassembly " + bioAssemblyId); inStream = getInputStreamBioAssembly(pdbId); } PDBFileParser pdbpars = new PDBFileParser(); pdbpars.setFileParsingParameters(params); Structure struc = pdbpars.parsePDBFile(inStream) ; struc.setBiologicalAssembly(loadedBioAssembly); return struc ; } /** opens filename, parses it and returns * aStructure object . * @param filename a String * @return the Structure object * @throws IOException ... */ public Structure getStructure(String filename) throws IOException { File f = new File(filename); return getStructure(f); } /** opens filename, parses it and returns a Structure object * * @param filename a File object * @return the Structure object * @throws IOException ... */ public Structure getStructure(File filename) throws IOException { InputStreamProvider isp = new InputStreamProvider(); InputStream inStream = isp.getInputStream(filename); return getStructure(inStream); } private Structure getStructure(InputStream inStream) throws IOException{ PDBFileParser pdbpars = new PDBFileParser(); pdbpars.setFileParsingParameters(params); Structure struc = pdbpars.parsePDBFile(inStream) ; return struc ; } public Structure getStructure(URL u) throws IOException{ InputStreamProvider isp = new InputStreamProvider(); InputStream inStream = isp.getInputStream(u); return getStructure(inStream); } public void setFileParsingParameters(FileParsingParameters params){ this.params= params; if ( ! params.isLoadChemCompInfo()) { ChemCompGroupFactory.setChemCompProvider(new ReducedChemCompProvider()); } } public FileParsingParameters getFileParsingParameters(){ return params; } public boolean isAutoFetch(){ return autoFetch; } public void setAutoFetch(boolean autoFetch){ this.autoFetch = autoFetch; } /** * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @param fetchFileEvenIfObsolete the fetchFileEvenIfObsolete to set */ public void setFetchFileEvenIfObsolete(boolean fetchFileEvenIfObsolete) { this.fetchFileEvenIfObsolete = fetchFileEvenIfObsolete; } /**forces the reader to fetch the file if its status is OBSOLETE. * This feature has a higher priority than {@link #setFetchCurrent(boolean)}. <br> * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @return the fetchFileEvenIfObsolete * @author Amr AL-Hossary * @see #fetchCurrent * @since 3.0.2 */ public boolean isFetchFileEvenIfObsolete() { return fetchFileEvenIfObsolete; } /**if enabled, the reader searches for the newest possible PDB ID, if not present in he local installation. * The {@link #setFetchFileEvenIfObsolete(boolean)} function has a higher priority than this function. <br> * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @param fetchCurrent the fetchCurrent to set * @author Amr AL-Hossary * @see #setFetchFileEvenIfObsolete(boolean) * @since 3.0.2 */ public void setFetchCurrent(boolean fetchNewestCurrent) { this.fetchCurrent = fetchNewestCurrent; } /** * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @return the fetchCurrent */ public boolean isFetchCurrent() { return fetchCurrent; } /** * Returns the file name of a PDB biological unit file based on the pdbId and biologicalAssemblyID. * * @param pdbId the protein data bank ID * @param biologicalAssemblyId the ID of the biological assembly * @return file name of PDB biological assembly file * @author Peter Rose * @since 3.2 */ private String getBiologicalAsssemblyFileName(String pdbId, int biologicalAssemblyId) { return pdbId + ".pdb" + biologicalAssemblyId + ".gz"; } }
biojava3-structure/src/main/java/org/biojava/bio/structure/io/PDBFileReader.java
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * * Created on 16.03.2004 * @author Andreas Prlic * * */ package org.biojava.bio.structure.io; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import org.biojava.bio.structure.Chain; import org.biojava.bio.structure.Compound; import org.biojava.bio.structure.Group; import org.biojava.bio.structure.PDBStatus; import org.biojava.bio.structure.PDBStatus.Status; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.align.ce.AbstractUserArgumentProcessor; import org.biojava.bio.structure.io.mmcif.ChemCompGroupFactory; import org.biojava.bio.structure.io.mmcif.ReducedChemCompProvider; import org.biojava.bio.structure.io.util.FileDownloadUtils; import org.biojava3.core.util.InputStreamProvider; /** * <p> * The wrapper class for parsing a PDB file. * </p> * * * <p> * Several flags can be set for this class * <ul> * * <li> {@link #setAutoFetch(boolean)} - if the PDB file can not be found locally, should it be fetched * from the PDB ftp servers? (default:false)</li> * <li> Other parameters can be set using the {@link #setFileParsingParameters(FileParsingParameters)}</li> * </ul> * </p> * * * *<h2>Example</h2> * <p> * Q: How can I get a Structure object from a PDB file? * </p> * <p> * A: * <pre> public {@link Structure} loadStructure(String pathToPDBFile){ {@link PDBFileReader} pdbreader = new {@link PDBFileReader}(); {@link Structure} structure = null; try{ structure = pdbreader.getStructure(pathToPDBFile); System.out.println(structure); } catch (IOException e) { e.printStackTrace(); } return structure; } </pre> * * Access PDB files from a directory, take care of compressed PDB files * <pre> * public {@link Structure} loadStructureById() { String path = "/path/to/PDB/directory/"; {@link PDBFileReader} pdbreader = new {@link PDBFileReader}(); pdbreader.setPath(path); {@link Structure} structure = null; try { structure = pdbreader.getStructureById("5pti"); } catch (IOException e){ e.printStackTrace(); } return structure; } </pre> * * * @author Andreas Prlic * */ public class PDBFileReader implements StructureIOFile { // a list of big pdb files for testing // "1htq", // "1c2w", // "1ffk", // "1giy", // "1j5a", // "1jj2", // "1jzx", // "1jzy", // "1jzz", // "1k01", // "1k73", // "1k8a", // "1k9m", // "1kc8", // "1kd1", // "1kqs", // "1m1k", // "1m90", // "1mkz", // "1ml5", // "1n8r", public static final String LOAD_CHEM_COMP_PROPERTY = "loadChemCompInfo"; String path; List<String> extensions; boolean autoFetch; private boolean fetchCurrent; private boolean fetchFileEvenIfObsolete; boolean pdbDirectorySplit; private int bioAssemblyId = 0; // number > 0 indicates the id of the biological assembly private boolean bioAssemblyFallback = true; // use regular PDB file as the biological assembly (i.e. for NMR structures) // in case no biological assembly file is available. private boolean loadedBioAssembly = false; public static final String lineSplit = System.getProperty("file.separator"); public static final String DEFAULT_PDB_FILE_SERVER = "ftp.wwpdb.org"; public static final String PDB_FILE_SERVER_PROPERTY = "PDB.FILE.SERVER"; private static final String CURRENT_FILES_PATH = "/pub/pdb/data/structures/divided/pdb/"; private static final String OBSOLETE_FILES_PATH = "/pub/pdb/data/structures/obsolete/pdb/"; private static final String BIO_ASSEMBLY_FILES_PATH = "/pub/pdb/data/biounit/coordinates/divided/"; private static final String LOCAL_BIO_ASSEMBLY_DIRECTORY = "bio_assembly"; FileParsingParameters params ; private static final long lastRemediationDate ; static { SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd", Locale.US); long t = 0; try { Date d = formatter.parse("2011/07/12"); t = d.getTime(); } catch (Exception e){ e.printStackTrace(); } lastRemediationDate = t; } public static void main(String[] args){ PDBFileReader pdbreader = new PDBFileReader(); // set the path to cache files String property = "java.io.tmpdir"; String tempdir = System.getProperty(property); // tempdir = "/path/to/local/PDB/installation/"; pdbreader.setPath(tempdir); FileParsingParameters params = new FileParsingParameters(); pdbreader.setFileParsingParameters(params); try{ Structure struc = pdbreader.getStructureById("193D"); System.out.println(struc); List<Compound> compounds = struc.getCompounds(); for (Compound comp : compounds ){ List<Chain> chains = comp.getChains(); System.out.print(">Chains :" ); for (Chain c : chains){ System.out.print(c.getChainID() + " " ); } System.out.println(); if ( chains.size() > 0) { System.out.println(chains.get(0).getAtomSequence()); System.out.println(chains.get(0).getSeqResSequence()); System.out.print(" Atom Ligands: "); for ( Group g: chains.get(0).getAtomLigands()){ System.out.print( g.getPDBName() + " "); } System.out.println(" "); } } /* GroupIterator gi = new GroupIterator(struc); while (gi.hasNext()){ Group g = (Group) gi.next(); Chain c = g.getParent(); if ( g instanceof AminoAcid ){ AminoAcid aa = (AminoAcid)g; Map<String,String> sec = aa.getSecStruc(); //System.out.println(c.getName() + " " + g + " " + sec); ChemComp cc = g.getChemComp(); System.out.println(c.getName() + " " + g.getPDBCode() + " " + g.getPDBName() + " " + cc + " " +sec); } } */ } catch (Exception e) { e.printStackTrace(); } } public PDBFileReader() { extensions = new ArrayList<String>(); extensions.add(".ent"); extensions.add(".pdb"); extensions.add(".ent.gz"); extensions.add(".pdb.gz"); extensions.add(".ent.Z"); extensions.add(".pdb.Z"); autoFetch = false; pdbDirectorySplit = false; params = new FileParsingParameters(); //checkPath(); } /** Check the directory that contains the local cache of PDB and chemical component definiton files. * By default, at startup we fall back to java.io.tmpdir */ private void checkPath(){ if ((path == null) || (path.equals("")) || path.equals("null")) { String syspath = System.getProperty(AbstractUserArgumentProcessor.PDB_DIR); if ((syspath != null) && (! syspath.equals("")) && (! syspath.equals("null"))){ path = syspath; return; } // accessing temp. OS directory: String property = "java.io.tmpdir"; String tempdir = System.getProperty(property); if ( !(tempdir.endsWith(lineSplit) ) ) tempdir = tempdir + lineSplit; // System.err.println("you did not set the path in PDBFileReader, don't know where to write the downloaded file to"); System.err.println("assuming default location is temp directory: " + tempdir); path = tempdir; } } /** directory where to find PDB files */ public void setPath(String p){ System.setProperty(AbstractUserArgumentProcessor.PDB_DIR,p); path = p ; } /** * Returns the path value. * @return a String representing the path value * @see #setPath * */ public String getPath() { return path ; } /** define supported file extensions * compressed extensions .Z,.gz do not need to be specified * they are dealt with automatically. */ public void addExtension(String s){ //System.out.println("add Extension "+s); extensions.add(s); } /** clear the supported file extensions * */ public void clearExtensions(){ extensions.clear(); } /** Flag that defines if the PDB directory is containing all PDB files or is split into sub dirs (like the FTP site). * * @return boolean. default is false (all files in one directory) */ public boolean isPdbDirectorySplit() { return pdbDirectorySplit; } /** Flag that defines if the PDB directory is containing all PDB files or is split into sub dirs (like the FTP site). * * @param pdbDirectorySplit boolean. If set to false all files are in one directory. */ public void setPdbDirectorySplit(boolean pdbDirectorySplit) { this.pdbDirectorySplit = pdbDirectorySplit; } /** * Sets the ID of the biological assembly to be loaded. By default, the bioAssemblyId=0, which corresponds to the * original PDB file. If an ID > 0 is specified, the corresponding biological assembly file will be loaded. Note, the * number of available biological unit files varies. Many entries don't have a biological unit specified (i.e. NMR structures), * many entries have only one biological unit (bioAssemblyId=1), and a few structures have multiple biological assemblies. * * @param bioAssemblyId ID of the biological assembly to be loaded * @author Peter Rose * @since 3.2 */ public void setBioAssemblyId(int bioAssemblyId) { this.bioAssemblyId = bioAssemblyId; } /** * Set bioAssemblyFallback to true, to download the original PDB file in cases that a biological assembly file is not available. * * @param bioAssemblyFallback if true, tries reading original PDB file in case the biological assembly file is not available * @author Peter Rose * @since 3.2 */ public void setBioAssemblyFallback(boolean bioAssemblyFallback) { this.bioAssemblyFallback = bioAssemblyFallback; } /** try to find the file in the filesystem and return a filestream in order to parse it * rules how to find file * - first check: if file is in path specified by PDBpath * - secnd check: if not found check in PDBpath/xy/ where xy is second and third char of PDBcode. * if autoFetch is set it will try to download missing PDB files automatically. */ private InputStream getInputStream(String pdbId) throws IOException { if ( pdbId.length() < 4) throw new IOException("the provided ID does not look like a PDB ID : " + pdbId); checkPath(); InputStream inputStream =null; String pdbFile = getLocalPDBFilePath(pdbId); if ( pdbFile != null) { InputStreamProvider isp = new InputStreamProvider(); try { inputStream = isp.getInputStream(pdbFile); return inputStream; } catch (Exception e){ e.printStackTrace(); // something is wrong with the file! // it probably should be downloaded again... pdbFile = null; } } if ( pdbFile == null ) { if (autoFetch){//from here we try our online search if(fetchCurrent && !fetchFileEvenIfObsolete) { String current = PDBStatus.getCurrent(pdbId); if(current == null) { // either an error or there is not current entry current = pdbId; } return downloadAndGetInputStream(current, CURRENT_FILES_PATH); } else if(fetchFileEvenIfObsolete && PDBStatus.getStatus(pdbId) == Status.OBSOLETE) { return downloadAndGetInputStream(pdbId, OBSOLETE_FILES_PATH); } else { return downloadAndGetInputStream(pdbId, CURRENT_FILES_PATH); } }else { String message = "no structure with PDB code " + pdbId + " found!" ; throw new IOException (message); } } return null ; } /** Returns null if local PDB file does not exist or should be downloaded again... * * @param pdbId * @return */ private String getLocalPDBFilePath(String pdbId) { String pdbFile = null ; File f = null ; // this are the possible PDB file names... String fpath ; String ppath ; if ( pdbDirectorySplit){ // pdb files are split into subdirectories based on their middle position... String middle = pdbId.substring(1,3).toLowerCase(); fpath = path+lineSplit + middle + lineSplit + pdbId; ppath = path +lineSplit + middle + lineSplit + "pdb"+pdbId; } else { fpath = path+lineSplit + pdbId; ppath = path +lineSplit + "pdb"+pdbId; } String[] paths = new String[]{fpath,ppath}; for ( int p=0;p<paths.length;p++ ){ String testpath = paths[p]; //System.out.println(testpath); for (int i=0 ; i<extensions.size();i++){ String ex = (String)extensions.get(i) ; //System.out.println("PDBFileReader testing: "+testpath+ex); f = new File(testpath+ex) ; if ( f.exists()) { pdbFile = testpath+ex ; // we have found the file locally if ( params.isUpdateRemediatedFiles()){ long lastModified = f.lastModified(); if (lastModified < lastRemediationDate) { // the file is too old, replace with newer version System.out.println("replacing file " + pdbFile +" with latest remediated file from PDB."); pdbFile = null; return null; } } return pdbFile; } if ( pdbFile != null) break; } } return null; } /** * Returns an input stream for a biological assembly file based on the passed in pdbId and * the biological assembly id {@link #setBioAssemblyId(int)}. Files are cached in a local directory. * @param pdbId * @return InputStream * @throws IOException * @author Peter Rose * @since 3.2 */ private InputStream getInputStreamBioAssembly(String pdbId) throws IOException { loadedBioAssembly = true; InputStream inputStream = null; if ( pdbId.length() < 4) throw new IOException("the provided ID does not look like a PDB ID : " + pdbId); checkPath(); // make sure path follows unix convention String uPath = FileDownloadUtils.toUnixPath(path); // create local subdirectory for biological assembly files if it doesn't exist String dir = uPath + LOCAL_BIO_ASSEMBLY_DIRECTORY; File tmp = new File(dir); if ( ! tmp.exists()){ tmp.mkdir(); } String fpath ; if (pdbDirectorySplit){ // pdb files are split into subdirectories based on their middle position... String middle = pdbId.substring(1,3).toLowerCase(); fpath = dir + "/" + middle + "/"; } else { fpath = dir + "/"; } String fileName = fpath + getBiologicalAsssemblyFileName(pdbId.toLowerCase(), bioAssemblyId); File f = new File(fileName) ; // check if bio assembly file exists in local cache if ( f.exists()) { InputStreamProvider isp = new InputStreamProvider(); try { inputStream = isp.getInputStream(fileName); return inputStream; } catch (Exception e){ e.printStackTrace(); // something is wrong with the file! // it probably should be downloaded again... } } else if (bioAssemblyFallback) { if (pdbDirectorySplit){ // pdb files are split into subdirectories based on their middle position... String middle = pdbId.substring(1,3).toLowerCase(); fpath = uPath + middle + "/"; } else { fpath = uPath; } fileName = fpath + "pdb" + pdbId + ".ent.gz"; f = new File(fileName); if (f.exists()) { try { InputStreamProvider isp = new InputStreamProvider(); inputStream = isp.getInputStream(fileName); System.out.println("Loaded original PDB file as a fallback." + fileName); loadedBioAssembly = false; return inputStream; } catch (Exception e) { // now try autofetch next } } } if (autoFetch){//from here we try our online search if(fetchCurrent && !fetchFileEvenIfObsolete) { String current = PDBStatus.getCurrent(pdbId); if(current == null) { // either an error or there is not current entry current = pdbId; } inputStream = downloadAndGetInputStreamBioAssembly(current, BIO_ASSEMBLY_FILES_PATH); if (inputStream != null) { return inputStream; } } else if(fetchFileEvenIfObsolete && PDBStatus.getStatus(pdbId) == Status.OBSOLETE) { String message = "No biological assembly with PDB code " + pdbId + " found!" ; throw new IOException (message); } else { inputStream = downloadAndGetInputStreamBioAssembly(pdbId, BIO_ASSEMBLY_FILES_PATH); if (inputStream != null) { return inputStream; } } } // if biological assembly file cannot be found, and bioAssemblyFallBack is true, // get the original PDB file as a fall back (i.e. for NMR structures, where the // PDB file represents the biological assembly). if (bioAssemblyFallback) { inputStream = getInputStream(pdbId); if (inputStream != null) { System.out.println("Biological assembly file for PDB ID: " + pdbId+ " is not available. " + "Loaded original PDB file as a fallback from local cache."); return getInputStream(pdbId); } } return null; } private File downloadPDB(String pdbId, String pathOnServer){ if ((path == null) || (path.equals(""))){ // accessing temp. OS directory: String property = "java.io.tmpdir"; String tempdir = System.getProperty(property); if ( !(tempdir.endsWith(lineSplit) ) ) tempdir = tempdir + lineSplit; System.err.println("you did not set the path in PDBFileReader, don;t know where to write the downloaded file to"); System.err.println("assuming default location is temp directory: " + tempdir); path = tempdir; } File realFile = null; pdbId = pdbId.toLowerCase(); String middle = pdbId.substring(1,3); if ( pdbDirectorySplit) { String dir = path+lineSplit+middle; File directoryCheck = new File (dir); if ( ! directoryCheck.exists()){ directoryCheck.mkdir(); } realFile =new File(dir+lineSplit+"pdb"+ pdbId+".ent.gz"); } else { realFile = new File(path+lineSplit+"pdb"+pdbId+".ent.gz"); } String serverName = System.getProperty(PDB_FILE_SERVER_PROPERTY); if ( serverName == null) serverName = DEFAULT_PDB_FILE_SERVER; String ftp = String.format("ftp://%s%s%s/pdb%s.ent.gz", serverName,pathOnServer,middle, pdbId); //System.out.println("Fetching " + ftp); try { URL url = new URL(ftp); FileDownloadUtils.downloadGzipCompressedFile(url, realFile); } catch (Exception e){ System.err.println("Problem while downloading PDB ID " + pdbId + " from FTP server." ); e.printStackTrace(); return null; } return realFile; } /** * Downloads a biological assembly file. If this file cannot be found, it will download the original * PDB file (i.e. for NMR structures), if bioAssemblyFallback has been set to true; * @param pdbId * @param pathOnServer * @return File of biological assembly * @author Peter Rose * @since 3.2 */ private File downloadPDBBiologicalAssembly(String pdbId, String pathOnServer){ loadedBioAssembly = true; checkPath(); String fileName = getBiologicalAsssemblyFileName(pdbId, bioAssemblyId); pdbId = pdbId.toLowerCase(); String middle = pdbId.substring(1,3); String serverName = System.getProperty(PDB_FILE_SERVER_PROPERTY); if ( serverName == null) serverName = DEFAULT_PDB_FILE_SERVER; String ftp = String.format("ftp://%s%s%s/%s", serverName,pathOnServer,middle,fileName); System.out.println("Fetching " + ftp); URL url = null; try { url = new URL(ftp); } catch (MalformedURLException e1) { System.err.println("Problem while downloading Biological Assembly " + pdbId + " from FTP server." ); e1.printStackTrace(); return null; } // check if the file exists on the FTP site. If biological assembly file does not exist // and the fallback has been set, get the original PDB file instead (i.e. for NMR structures). File f = null; try { f = downloadFileIfAvailable(url, pdbId,fileName); } catch (IOException ioe){ // ignore here because it prob. means the file does not exist... } if ( f == null) { if (bioAssemblyFallback) { System.out.println("Biological unit file for PDB ID: " + pdbId+ " is not available. " + "Downloading original PDB file as a fallback."); loadedBioAssembly = false; String fallBackPDBF = getLocalPDBFilePath(pdbId); if ( fallBackPDBF != null) return new File(fallBackPDBF); return downloadPDB(pdbId, CURRENT_FILES_PATH); } return null; } return f; } private File downloadFileIfAvailable(URL url, String pdbId, String fileName) throws IOException { String middle = pdbId.substring(1,3); String uPath = FileDownloadUtils.toUnixPath(path); File tempFile = null; if (pdbDirectorySplit) { String dir = uPath + LOCAL_BIO_ASSEMBLY_DIRECTORY + "/" + middle; File directoryCheck = new File (dir); if ( ! directoryCheck.exists()){ directoryCheck.mkdir(); } tempFile =new File(dir + "/" + fileName); } else { tempFile = new File(path + LOCAL_BIO_ASSEMBLY_DIRECTORY + "/" + fileName); } return FileDownloadUtils.downloadFileIfAvailable(url, tempFile); } private InputStream downloadAndGetInputStream(String pdbId, String pathOnServer) throws IOException{ File tmp = downloadPDB(pdbId, pathOnServer); if (tmp != null) { InputStreamProvider prov = new InputStreamProvider(); InputStream is = prov.getInputStream(tmp); return is; } else { throw new IOException("could not find PDB " + pdbId + " in file system and also could not download"); } } /** * Downloads biological assembly file to local cache and provides input stream to cached file. * @param pdbId * @param pathOnServer * @return inputStream to cached file * @throws IOException * @author Peter Rose * @since 3.2 */ private InputStream downloadAndGetInputStreamBioAssembly(String pdbId, String pathOnServer) throws IOException{ File tmp = downloadPDBBiologicalAssembly(pdbId, pathOnServer); if (tmp != null) { InputStreamProvider prov = new InputStreamProvider(); InputStream is = prov.getInputStream(tmp); return is; } else { throw new IOException("Could not find Biological Assembly " + pdbId + " in file system and also could not download"); } } /** load a structure from local file system and return a PDBStructure object * @param pdbId a String specifying the id value (PDB code) * @return the Structure object * @throws IOException ... */ public Structure getStructureById(String pdbId)throws IOException { InputStream inStream = null; if (bioAssemblyId == 0) { inStream = getInputStream(pdbId); } else { inStream = getInputStreamBioAssembly(pdbId); } PDBFileParser pdbpars = new PDBFileParser(); pdbpars.setFileParsingParameters(params); Structure struc = pdbpars.parsePDBFile(inStream) ; struc.setBiologicalAssembly(loadedBioAssembly); return struc ; } /** opens filename, parses it and returns * aStructure object . * @param filename a String * @return the Structure object * @throws IOException ... */ public Structure getStructure(String filename) throws IOException { File f = new File(filename); return getStructure(f); } /** opens filename, parses it and returns a Structure object * * @param filename a File object * @return the Structure object * @throws IOException ... */ public Structure getStructure(File filename) throws IOException { InputStreamProvider isp = new InputStreamProvider(); InputStream inStream = isp.getInputStream(filename); return getStructure(inStream); } private Structure getStructure(InputStream inStream) throws IOException{ PDBFileParser pdbpars = new PDBFileParser(); pdbpars.setFileParsingParameters(params); Structure struc = pdbpars.parsePDBFile(inStream) ; return struc ; } public Structure getStructure(URL u) throws IOException{ InputStreamProvider isp = new InputStreamProvider(); InputStream inStream = isp.getInputStream(u); return getStructure(inStream); } public void setFileParsingParameters(FileParsingParameters params){ this.params= params; if ( ! params.isLoadChemCompInfo()) { ChemCompGroupFactory.setChemCompProvider(new ReducedChemCompProvider()); } } public FileParsingParameters getFileParsingParameters(){ return params; } public boolean isAutoFetch(){ return autoFetch; } public void setAutoFetch(boolean autoFetch){ this.autoFetch = autoFetch; } /** * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @param fetchFileEvenIfObsolete the fetchFileEvenIfObsolete to set */ public void setFetchFileEvenIfObsolete(boolean fetchFileEvenIfObsolete) { this.fetchFileEvenIfObsolete = fetchFileEvenIfObsolete; } /**forces the reader to fetch the file if its status is OBSOLETE. * This feature has a higher priority than {@link #setFetchCurrent(boolean)}. <br> * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @return the fetchFileEvenIfObsolete * @author Amr AL-Hossary * @see #fetchCurrent * @since 3.0.2 */ public boolean isFetchFileEvenIfObsolete() { return fetchFileEvenIfObsolete; } /**if enabled, the reader searches for the newest possible PDB ID, if not present in he local installation. * The {@link #setFetchFileEvenIfObsolete(boolean)} function has a higher priority than this function. <br> * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @param fetchCurrent the fetchCurrent to set * @author Amr AL-Hossary * @see #setFetchFileEvenIfObsolete(boolean) * @since 3.0.2 */ public void setFetchCurrent(boolean fetchNewestCurrent) { this.fetchCurrent = fetchNewestCurrent; } /** * <b>N.B.</b> This feature won't work unless the structure wasn't found & autoFetch is set to <code>true</code>. * @return the fetchCurrent */ public boolean isFetchCurrent() { return fetchCurrent; } /** * Returns the file name of a PDB biological unit file based on the pdbId and biologicalAssemblyID. * * @param pdbId the protein data bank ID * @param biologicalAssemblyId the ID of the biological assembly * @return file name of PDB biological assembly file * @author Peter Rose * @since 3.2 */ private String getBiologicalAsssemblyFileName(String pdbId, int biologicalAssemblyId) { return pdbId + ".pdb" + biologicalAssemblyId + ".gz"; } }
making field public git-svn-id: ed25c26de1c5325e8eb0deed0b990ab8af8a4def@9804 7c6358e6-4a41-0410-a743-a5b2a554c398
biojava3-structure/src/main/java/org/biojava/bio/structure/io/PDBFileReader.java
making field public
<ide><path>iojava3-structure/src/main/java/org/biojava/bio/structure/io/PDBFileReader.java <ide> private static final String LOCAL_BIO_ASSEMBLY_DIRECTORY = "bio_assembly"; <ide> FileParsingParameters params ; <ide> <del> private static final long lastRemediationDate ; <add> public static final long lastRemediationDate ; <ide> <ide> static { <ide> <ide> <ide> String fileName = fpath + getBiologicalAsssemblyFileName(pdbId.toLowerCase(), bioAssemblyId); <ide> File f = new File(fileName) ; <del> <add> <ide> // check if bio assembly file exists in local cache <ide> if ( f.exists()) { <ide> InputStreamProvider isp = new InputStreamProvider(); <ide> if (bioAssemblyId == 0) { <ide> inStream = getInputStream(pdbId); <ide> } else { <add> //System.out.println("loading bioassembly " + bioAssemblyId); <ide> inStream = getInputStreamBioAssembly(pdbId); <ide> } <ide>
Java
mit
9853a694c5befe167d6e482bd05c15c33f2901ef
0
Telerik-Verified-Plugins/PushNotification,Telerik-Verified-Plugins/PushNotification,Telerik-Verified-Plugins/PushNotification,Telerik-Verified-Plugins/PushNotification,Telerik-Verified-Plugins/PushNotification
package com.plugin.gcm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.content.WakefulBroadcastReceiver; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.json.JSONException; import org.json.JSONObject; import java.util.Random; /* * Implementation of GCMBroadcastReceiver that hard-wires the intent service to be * com.plugin.gcm.GcmntentService, instead of your_package.GcmIntentService */ public class CordovaGCMBroadcastReceiver extends WakefulBroadcastReceiver { private static final String TAG = "GcmIntentService"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onHandleIntent - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String messageType = gcm.getMessageType(intent); if (extras != null) { try { if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { JSONObject json = new JSONObject(); json.put("event", "error"); json.put("message", extras.toString()); PushPlugin.sendJavascript(json); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { JSONObject json = new JSONObject(); json.put("event", "deleted"); json.put("message", extras.toString()); PushPlugin.sendJavascript(json); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } catch (JSONException exception) { Log.d(TAG, "JSON Exception was had!"); } } } public void createNotification(Context context, Bundle extras) { int notId = 0; try { notId = Integer.parseInt(extras.getString("notId")); } catch (NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } if (notId == 0) { // no notId passed, so assume we want to show all notifications, so make it a random number notId = new Random().nextInt(100000); Log.d(TAG, "Generated random notId: " + notId); } else { Log.d(TAG, "Received notId: " + notId); } NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(context); Intent notificationIntent = new Intent(context, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(context, notId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException ignore) { } } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) .setSmallIcon(getSmallIcon(context, extras)) .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setColor(getColor(extras)) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } String soundName = extras.getString("sound"); if (soundName != null) { Resources r = context.getResources(); int resourceId = r.getIdentifier(soundName, "raw", context.getPackageName()); Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceId); mBuilder.setSound(soundUri); defaults &= ~Notification.DEFAULT_SOUND; mBuilder.setDefaults(defaults); } final Notification notification = mBuilder.build(); final int largeIcon = getLargeIcon(context, extras); if (largeIcon > -1) { final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), largeIcon); mBuilder.setLargeIcon(bitmap); } mNotificationManager.notify(appName, notId, notification); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String) appName; } private int getColor(Bundle extras) { int theColor = 0; // default, transparent final String passedColor = extras.getString("color"); // something like "#FFFF0000", or "red" if (passedColor != null) { try { theColor = Color.parseColor(passedColor); } catch (IllegalArgumentException ignore) {} } return theColor; } private int getSmallIcon(Context context, Bundle extras) { int icon = -1; // first try an iconname possible passed in the server payload final String iconNameFromServer = extras.getString("smallIcon"); if (iconNameFromServer != null) { icon = getIconValue(context.getPackageName(), iconNameFromServer); } // try a custom included icon in our bundle named ic_stat_notify(.png) if (icon == -1) { icon = getIconValue(context.getPackageName(), "ic_stat_notify"); } // fall back to the regular app icon if (icon == -1) { icon = context.getApplicationInfo().icon; } return icon; } private int getLargeIcon(Context context, Bundle extras) { int icon = -1; // first try an iconname possible passed in the server payload final String iconNameFromServer = extras.getString("largeIcon"); if (iconNameFromServer != null) { icon = getIconValue(context.getPackageName(), iconNameFromServer); } // try a custom included icon in our bundle named ic_stat_notify(.png) if (icon == -1) { icon = getIconValue(context.getPackageName(), "ic_notify"); } // fall back to the regular app icon if (icon == -1) { icon = context.getApplicationInfo().icon; } return icon; } private int getIconValue(String className, String iconName) { try { Class<?> clazz = Class.forName(className + ".R$drawable"); return (Integer) clazz.getDeclaredField(iconName).get(Integer.class); } catch (Exception ignore) {} return -1; } }
src/android/com/plugin/gcm/CordovaGCMBroadcastReceiver.java
package com.plugin.gcm; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.Resources; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NotificationCompat; import android.support.v4.content.WakefulBroadcastReceiver; import android.util.Log; import com.google.android.gms.gcm.GoogleCloudMessaging; import org.json.JSONException; import org.json.JSONObject; import java.util.Random; /* * Implementation of GCMBroadcastReceiver that hard-wires the intent service to be * com.plugin.gcm.GcmntentService, instead of your_package.GcmIntentService */ public class CordovaGCMBroadcastReceiver extends WakefulBroadcastReceiver { private static final String TAG = "GcmIntentService"; @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "onHandleIntent - context: " + context); // Extract the payload from the message Bundle extras = intent.getExtras(); GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(context); String messageType = gcm.getMessageType(intent); if (extras != null) { try { if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR.equals(messageType)) { JSONObject json = new JSONObject(); json.put("event", "error"); json.put("message", extras.toString()); PushPlugin.sendJavascript(json); } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED.equals(messageType)) { JSONObject json = new JSONObject(); json.put("event", "deleted"); json.put("message", extras.toString()); PushPlugin.sendJavascript(json); } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) { // if we are in the foreground, just surface the payload, else post it to the statusbar if (PushPlugin.isInForeground()) { extras.putBoolean("foreground", true); PushPlugin.sendExtras(extras); } else { extras.putBoolean("foreground", false); // Send a notification if there is a message if (extras.getString("message") != null && extras.getString("message").length() != 0) { createNotification(context, extras); } } } } catch (JSONException exception) { Log.d(TAG, "JSON Exception was had!"); } } } public void createNotification(Context context, Bundle extras) { int notId = 0; try { notId = Integer.parseInt(extras.getString("notId")); } catch (NumberFormatException e) { Log.e(TAG, "Number format exception - Error parsing Notification ID: " + e.getMessage()); } catch (Exception e) { Log.e(TAG, "Number format exception - Error parsing Notification ID" + e.getMessage()); } if (notId == 0) { // no notId passed, so assume we want to show all notifications, so make it a random number notId = new Random().nextInt(100000); Log.d(TAG, "Generated random notId: " + notId); } else { Log.d(TAG, "Received notId: " + notId); } NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); String appName = getAppName(context); Intent notificationIntent = new Intent(context, PushHandlerActivity.class); notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP); notificationIntent.putExtra("pushBundle", extras); PendingIntent contentIntent = PendingIntent.getActivity(context, notId, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); int defaults = Notification.DEFAULT_ALL; if (extras.getString("defaults") != null) { try { defaults = Integer.parseInt(extras.getString("defaults")); } catch (NumberFormatException ignore) { } } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) .setDefaults(defaults) .setSmallIcon(getSmallIcon(context, extras)) .setWhen(System.currentTimeMillis()) .setContentTitle(extras.getString("title")) .setTicker(extras.getString("title")) .setContentIntent(contentIntent) .setColor(getColor(extras)) .setAutoCancel(true); String message = extras.getString("message"); if (message != null) { mBuilder.setContentText(message); } else { mBuilder.setContentText("<missing message content>"); } String msgcnt = extras.getString("msgcnt"); if (msgcnt != null) { mBuilder.setNumber(Integer.parseInt(msgcnt)); } String soundName = extras.getString("sound"); if (soundName != null) { Resources r = context.getResources(); int resourceId = r.getIdentifier(soundName, "raw", context.getPackageName()); Uri soundUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + resourceId); mBuilder.setSound(soundUri); defaults &= ~Notification.DEFAULT_SOUND; mBuilder.setDefaults(defaults); } final Notification notification = mBuilder.build(); final int largeIcon = getLargeIcon(context, extras); if (largeIcon > -1) { notification.contentView.setImageViewResource(android.R.id.icon, largeIcon); } mNotificationManager.notify(appName, notId, notification); } private static String getAppName(Context context) { CharSequence appName = context .getPackageManager() .getApplicationLabel(context.getApplicationInfo()); return (String) appName; } private int getColor(Bundle extras) { int theColor = 0; // default, transparent final String passedColor = extras.getString("color"); // something like "#FFFF0000", or "red" if (passedColor != null) { try { theColor = Color.parseColor(passedColor); } catch (IllegalArgumentException ignore) {} } return theColor; } private int getSmallIcon(Context context, Bundle extras) { int icon = -1; // first try an iconname possible passed in the server payload final String iconNameFromServer = extras.getString("smallIcon"); if (iconNameFromServer != null) { icon = getIconValue(context.getPackageName(), iconNameFromServer); } // try a custom included icon in our bundle named ic_stat_notify(.png) if (icon == -1) { icon = getIconValue(context.getPackageName(), "ic_stat_notify"); } // fall back to the regular app icon if (icon == -1) { icon = context.getApplicationInfo().icon; } return icon; } private int getLargeIcon(Context context, Bundle extras) { int icon = -1; // first try an iconname possible passed in the server payload final String iconNameFromServer = extras.getString("largeIcon"); if (iconNameFromServer != null) { icon = getIconValue(context.getPackageName(), iconNameFromServer); } // try a custom included icon in our bundle named ic_stat_notify(.png) if (icon == -1) { icon = getIconValue(context.getPackageName(), "ic_notify"); } // fall back to the regular app icon if (icon == -1) { icon = context.getApplicationInfo().icon; } return icon; } private int getIconValue(String className, String iconName) { try { Class<?> clazz = Class.forName(className + ".R$drawable"); return (Integer) clazz.getDeclaredField(iconName).get(Integer.class); } catch (Exception ignore) {} return -1; } }
Crash on Android 7 when using 'largeIcon' #88
src/android/com/plugin/gcm/CordovaGCMBroadcastReceiver.java
Crash on Android 7 when using 'largeIcon' #88
<ide><path>rc/android/com/plugin/gcm/CordovaGCMBroadcastReceiver.java <ide> import android.content.Context; <ide> import android.content.Intent; <ide> import android.content.res.Resources; <add>import android.graphics.Bitmap; <add>import android.graphics.BitmapFactory; <ide> import android.graphics.Color; <ide> import android.net.Uri; <ide> import android.os.Bundle; <ide> final Notification notification = mBuilder.build(); <ide> final int largeIcon = getLargeIcon(context, extras); <ide> if (largeIcon > -1) { <del> notification.contentView.setImageViewResource(android.R.id.icon, largeIcon); <add> final Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), largeIcon); <add> mBuilder.setLargeIcon(bitmap); <ide> } <ide> <ide> mNotificationManager.notify(appName, notId, notification);
Java
mit
fbd9d84f68af0302c502778bc248ea72b5917119
0
NamelessMC/Nameless-Plugin
package com.namelessmc.NamelessBungee.commands; import com.namelessmc.NamelessAPI.NamelessException; import com.namelessmc.NamelessAPI.NamelessPlayer; import com.namelessmc.NamelessBungee.NamelessMessages; import com.namelessmc.NamelessBungee.NamelessPlugin; import net.md_5.bungee.api.ChatColor; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.chat.ComponentBuilder; import net.md_5.bungee.api.chat.TextComponent; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; public class RegisterCommand extends Command { private String commandName; public RegisterCommand(String name) { super(name); commandName = name; } @Override public void execute(CommandSender sender, String[] args) { if (!sender.hasPermission(NamelessPlugin.permission + ".register")) { sender.sendMessage(NamelessMessages.NO_PERMISSION.getComponents()); return; } if (args.length != 1) { sender.sendMessage(TextComponent.fromLegacyText( NamelessMessages.INCORRECT_USAGE_REGISTER.getMessage().replace("%command%", commandName))); return; } if (!(sender instanceof ProxiedPlayer)) { sender.sendMessage(NamelessMessages.MUST_BE_INGAME.getComponents()); return; } ProxiedPlayer player = (ProxiedPlayer) sender; ProxyServer.getInstance().getScheduler().runAsync(NamelessPlugin.getInstance(), () -> { NamelessPlayer namelessPlayer = new NamelessPlayer(player.getUniqueId(), NamelessPlugin.baseApiURL); if (namelessPlayer.exists()) { sender.sendMessage(NamelessMessages.REGISTER_USERNAME_EXISTS.getComponents()); return; } try { namelessPlayer.register(player.getName(), args[0]); } catch (NamelessException e) { player.sendMessage(new ComponentBuilder("An error occured: " + e.getMessage()).color(ChatColor.RED).create()); } }); } }
NamelessBungee/src/com/namelessmc/NamelessBungee/commands/RegisterCommand.java
package com.namelessmc.NamelessBungee.commands; import com.namelessmc.namelessplugin.bungeecord.NamelessPlugin; import com.namelessmc.namelessplugin.bungeecord.API.NamelessAPI; import com.namelessmc.namelessplugin.bungeecord.API.Player.NamelessPlayer; import com.namelessmc.namelessplugin.bungeecord.API.Utils.NamelessChat; import com.namelessmc.namelessplugin.bungeecord.API.Utils.NamelessMessages; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.plugin.Command; /* * Register CMD */ public class RegisterCommand extends Command { private String commandName; public RegisterCommand(String name) { super(name); commandName = name; } /* * Handle inputted command */ @Override public void execute(CommandSender sender, String[] args) { // Instance is Player if (sender instanceof ProxiedPlayer) { if (sender.hasPermission(NamelessPlugin.permission + ".register")) { ProxiedPlayer player = (ProxiedPlayer) sender; // Try to register user ProxyServer.getInstance().getScheduler().runAsync(plugin, new Runnable() { @Override public void run() { NamelessAPI api = plugin.getAPI(); NamelessPlayer swPlayer = api.getPlayer(player.getUniqueId().toString()); if (!swPlayer.exists()) { // Ensure email is set if (args.length < 1 || args.length > 1) { sender.sendMessage(NamelessChat.convertColors( NamelessChat.getMessage(NamelessMessages.INCORRECT_USAGE_REGISTER) .replaceAll("%command%", commandName))); } else { api.registerPlayer(player, args[0]); } }else{ sender.sendMessage(NamelessChat.convertColors(NamelessChat.getMessage(NamelessMessages.REGISTER_USERNAME_EXISTS))); } } }); } else { sender.sendMessage(NamelessChat.convertColors(NamelessChat.getMessage(NamelessMessages.NO_PERMISSION))); } } else { sender.sendMessage(NamelessChat.convertColors(NamelessChat.getMessage(NamelessMessages.MUST_BE_INGAME))); } } }
Register command
NamelessBungee/src/com/namelessmc/NamelessBungee/commands/RegisterCommand.java
Register command
<ide><path>amelessBungee/src/com/namelessmc/NamelessBungee/commands/RegisterCommand.java <ide> package com.namelessmc.NamelessBungee.commands; <ide> <del>import com.namelessmc.namelessplugin.bungeecord.NamelessPlugin; <del>import com.namelessmc.namelessplugin.bungeecord.API.NamelessAPI; <del>import com.namelessmc.namelessplugin.bungeecord.API.Player.NamelessPlayer; <del>import com.namelessmc.namelessplugin.bungeecord.API.Utils.NamelessChat; <del>import com.namelessmc.namelessplugin.bungeecord.API.Utils.NamelessMessages; <add>import com.namelessmc.NamelessAPI.NamelessException; <add>import com.namelessmc.NamelessAPI.NamelessPlayer; <add>import com.namelessmc.NamelessBungee.NamelessMessages; <add>import com.namelessmc.NamelessBungee.NamelessPlugin; <ide> <add>import net.md_5.bungee.api.ChatColor; <ide> import net.md_5.bungee.api.CommandSender; <ide> import net.md_5.bungee.api.ProxyServer; <add>import net.md_5.bungee.api.chat.ComponentBuilder; <add>import net.md_5.bungee.api.chat.TextComponent; <ide> import net.md_5.bungee.api.connection.ProxiedPlayer; <ide> import net.md_5.bungee.api.plugin.Command; <ide> <del>/* <del> * Register CMD <del> */ <ide> <ide> public class RegisterCommand extends Command { <ide> <ide> <ide> public RegisterCommand(String name) { <ide> super(name); <del> <ide> commandName = name; <ide> } <ide> <del> /* <del> * Handle inputted command <del> */ <ide> @Override <ide> public void execute(CommandSender sender, String[] args) { <del> // Instance is Player <del> if (sender instanceof ProxiedPlayer) { <del> if (sender.hasPermission(NamelessPlugin.permission + ".register")) { <del> <del> ProxiedPlayer player = (ProxiedPlayer) sender; <del> <del> // Try to register user <del> ProxyServer.getInstance().getScheduler().runAsync(plugin, new Runnable() { <del> @Override <del> public void run() { <del> <del> NamelessAPI api = plugin.getAPI(); <del> NamelessPlayer swPlayer = api.getPlayer(player.getUniqueId().toString()); <del> if (!swPlayer.exists()) { <del> <del> // Ensure email is set <del> if (args.length < 1 || args.length > 1) { <del> sender.sendMessage(NamelessChat.convertColors( <del> NamelessChat.getMessage(NamelessMessages.INCORRECT_USAGE_REGISTER) <del> .replaceAll("%command%", commandName))); <del> } else { <del> api.registerPlayer(player, args[0]); <del> } <del> }else{ <del> sender.sendMessage(NamelessChat.convertColors(NamelessChat.getMessage(NamelessMessages.REGISTER_USERNAME_EXISTS))); <del> } <del> } <del> }); <del> } else { <del> sender.sendMessage(NamelessChat.convertColors(NamelessChat.getMessage(NamelessMessages.NO_PERMISSION))); <add> if (!sender.hasPermission(NamelessPlugin.permission + ".register")) { <add> sender.sendMessage(NamelessMessages.NO_PERMISSION.getComponents()); <add> return; <add> } <add> <add> if (args.length != 1) { <add> sender.sendMessage(TextComponent.fromLegacyText( <add> NamelessMessages.INCORRECT_USAGE_REGISTER.getMessage().replace("%command%", commandName))); <add> return; <add> } <add> <add> if (!(sender instanceof ProxiedPlayer)) { <add> sender.sendMessage(NamelessMessages.MUST_BE_INGAME.getComponents()); <add> return; <add> } <add> <add> ProxiedPlayer player = (ProxiedPlayer) sender; <add> <add> ProxyServer.getInstance().getScheduler().runAsync(NamelessPlugin.getInstance(), () -> { <add> NamelessPlayer namelessPlayer = new NamelessPlayer(player.getUniqueId(), NamelessPlugin.baseApiURL); <add> <add> if (namelessPlayer.exists()) { <add> sender.sendMessage(NamelessMessages.REGISTER_USERNAME_EXISTS.getComponents()); <add> return; <ide> } <del> <del> } else { <del> sender.sendMessage(NamelessChat.convertColors(NamelessChat.getMessage(NamelessMessages.MUST_BE_INGAME))); <del> } <add> <add> try { <add> namelessPlayer.register(player.getName(), args[0]); <add> } catch (NamelessException e) { <add> player.sendMessage(new ComponentBuilder("An error occured: " + e.getMessage()).color(ChatColor.RED).create()); <add> } <add> <add> }); <ide> } <ide> <ide> }
Java
mit
ff14171e5ba842daaa758a8e290b2170e29a2770
0
miami-acm/arcade-machine-highscore
package edu.miamioh.acm.highscore; public class Player { private int id; private String name; /** * Construct a new Player object with the given id and name. * * @param id The ID number to be given to this Player * @param name The name to be given to this Player */ private Player(int id, String name) { this.id = id; this.name = name; } /** * Search the Player database and if a Player with a matching name exists, * return that Player, otherwise create it and save to the database. * * @param id The ID number to use for looking up a Player */ public static Player getOrCreate(int id) { return new Player(0, "Nate"); } }
src/main/java/edu/miamioh/acm/highscore/Player.java
package edu.miamioh.acm.highscore; public class Player { private int id; private String name; /** * Construct a new Player object with the given id and name. * * @param id The ID number to be given to this Player * @param name The name to be given to this Player */ private Player(int id, String name) { this.id = id; this.name = name; } /** * Search the Player database and if a Player with a matching name exists, * return that Player, otherwise create it and save to the database. * * @param name The name to search for in the database */ public static Player getOrCreate(int id) { return new Player(0, "Nate"); } }
fix javadoc comment
src/main/java/edu/miamioh/acm/highscore/Player.java
fix javadoc comment
<ide><path>rc/main/java/edu/miamioh/acm/highscore/Player.java <ide> * Search the Player database and if a Player with a matching name exists, <ide> * return that Player, otherwise create it and save to the database. <ide> * <del> * @param name The name to search for in the database <add> * @param id The ID number to use for looking up a Player <ide> */ <ide> public static Player getOrCreate(int id) { <ide> return new Player(0, "Nate");
Java
apache-2.0
27e6d7c9ec4c644c3991c2dfd59e71f276d7ab77
0
sys1yagi/loader_closet
package com.cookpad.android.loadercloset.sample.activities; import com.cookpad.android.loadercloset.sample.R; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends ActionBarActivity { enum Pages { ONE_SHOT_LOADER_ACTIVITY("OneShotLoader with Activity") { @Override public void open(ActionBarActivity activity) { super.open(activity); } }, ONE_SHOT_LOADER_FRAGMENT("OneShotLoader with Fragment") { @Override public void open(ActionBarActivity activity) { super.open(activity); } },; private String title; Pages(String title) { this.title = title; } public void open(ActionBarActivity activity) { // } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.list_view); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, -1); for (Pages pages : Pages.values()) { adapter.add(pages.title); } listView.setAdapter(adapter); } }
sample/src/main/java/com/cookpad/android/loadercloset/sample/activities/MainActivity.java
package com.cookpad.android.loadercloset.sample.activities; import com.sys1yagi.loadercloset.sample.R; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends ActionBarActivity { enum Pages { ONE_SHOT_LOADER_ACTIVITY("OneShotLoader with Activity") { @Override public void open(ActionBarActivity activity) { super.open(activity); } }, ONE_SHOT_LOADER_FRAGMENT("OneShotLoader with Fragment") { @Override public void open(ActionBarActivity activity) { super.open(activity); } },; private String title; Pages(String title) { this.title = title; } public void open(ActionBarActivity activity) { // } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ListView listView = (ListView) findViewById(R.id.list_view); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, -1); for (Pages pages : Pages.values()) { adapter.add(pages.title); } listView.setAdapter(adapter); } }
Fix package name.
sample/src/main/java/com/cookpad/android/loadercloset/sample/activities/MainActivity.java
Fix package name.
<ide><path>ample/src/main/java/com/cookpad/android/loadercloset/sample/activities/MainActivity.java <ide> package com.cookpad.android.loadercloset.sample.activities; <ide> <del>import com.sys1yagi.loadercloset.sample.R; <add>import com.cookpad.android.loadercloset.sample.R; <ide> <ide> import android.os.Bundle; <ide> import android.support.v7.app.ActionBarActivity; <ide> import android.widget.ArrayAdapter; <ide> import android.widget.ListView; <del> <ide> <ide> public class MainActivity extends ActionBarActivity { <ide>
Java
apache-2.0
94b93b334fc1c32165d0916811ce5f7b41cc85f1
0
telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform,telefonicaid/fiware-cosmos-platform
package es.tid.cosmos.mobility; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import es.tid.cosmos.mobility.btslabelling.BtsLabellingRunner; import es.tid.cosmos.mobility.clientbtslabelling.ClientBtsLabellingRunner; import es.tid.cosmos.mobility.clientlabelling.ClientLabellingRunner; import es.tid.cosmos.mobility.labeljoining.LabelJoiningRunner; import es.tid.cosmos.mobility.parsing.ParsingRunner; import es.tid.cosmos.mobility.pois.PoisRunner; import es.tid.cosmos.mobility.preparing.PreparingRunner; import es.tid.cosmos.mobility.util.Logger; /** * * @author dmicol */ public class MobilityMain extends Configured implements Tool { @Override public int run(String[] args) throws Exception { ArgumentParser arguments = new ArgumentParser(); arguments.parse(args); final Configuration conf = this.getConf(); Path tmpPath; if (arguments.has("tmpDir")) { tmpPath = new Path(arguments.getString("tmpDir")); } else { tmpPath = new Path("/tmp/mobility"); } Path cdrsPath = new Path(arguments.getString("cdrs")); Path cellsPath = new Path(arguments.getString("cells")); Path adjBtsPath = new Path(arguments.getString("adjBts")); Path btsVectorTxtPath = new Path(arguments.getString("btsVectorTxt")); boolean shouldRunAll = arguments.getBoolean("run_all"); boolean isDebug = arguments.getBoolean("debug"); Path tmpParsingPath = new Path(tmpPath, "parsing"); Path cdrsMobPath = new Path(tmpParsingPath, "cdrs_mob"); Path cellsMobPath = new Path(tmpParsingPath, "cells_mob"); Path pairbtsAdjPath = new Path(tmpParsingPath, "pairbts_adj"); Path btsComareaPath = new Path(tmpParsingPath, "bts_comarea"); boolean shouldParse = arguments.getBoolean("parse"); if (shouldRunAll || shouldParse) { ParsingRunner.run(cdrsPath, cdrsMobPath, cellsPath, cellsMobPath, adjBtsPath, pairbtsAdjPath, btsVectorTxtPath, btsComareaPath, conf); } Path tmpPreparingPath = new Path(tmpPath, "preparing"); Path cdrsInfoPath = new Path(tmpPreparingPath, "cdrs_info"); Path cdrsNoinfoPath = new Path(tmpPreparingPath, "cdrs_noinfo"); Path clientsBtsPath = new Path(tmpPreparingPath, "clients_bts"); Path btsCommsPath = new Path(tmpPreparingPath, "bts_comms"); Path cdrsNoBtsPath = new Path(tmpPreparingPath, "cdrs_no_bts"); Path viTelmonthBtsPath = new Path(tmpPreparingPath, "vi_telmonth_bts"); boolean shouldPrepare = arguments.getBoolean("prepare"); if (shouldRunAll || shouldPrepare) { PreparingRunner.run(tmpPreparingPath, cdrsMobPath, cdrsInfoPath, cdrsNoinfoPath, cellsMobPath, clientsBtsPath, btsCommsPath, cdrsNoBtsPath, viTelmonthBtsPath, conf); } Path tmpExtractPoisPath = new Path(tmpPath, "extract_pois"); Path clientsInfoPath = new Path(tmpExtractPoisPath, "clients_info"); Path clientsInfoFilteredPath = new Path(tmpExtractPoisPath, "clients_info_filtered"); Path clientsRepbtsPath = new Path(tmpExtractPoisPath, "clients_repbts"); boolean shouldExtractPois = arguments.getBoolean("extractPOIs"); if (shouldRunAll || shouldExtractPois) { PoisRunner.run(tmpExtractPoisPath, clientsBtsPath, clientsInfoPath, cdrsNoinfoPath, cdrsNoBtsPath, clientsInfoFilteredPath, clientsRepbtsPath, isDebug, conf); } Path tmpLabelClientPath = new Path(tmpPath, "label_client"); Path vectorClientClusterPath = new Path(tmpLabelClientPath, "vector_client_clusterPath"); boolean shouldLabelClient = arguments.getBoolean("labelClient"); if (shouldRunAll || shouldLabelClient) { Path centroidsPath = new Path(arguments.getString( "centroids_client", true)); ClientLabellingRunner.run(cdrsMobPath, clientsInfoFilteredPath, centroidsPath, vectorClientClusterPath, tmpLabelClientPath, isDebug, conf); } Path tmpLabelBtsPath = new Path(tmpPath, "label_bts"); Path vectorBtsClusterPath = new Path(tmpLabelBtsPath, "vector_bts_cluster"); boolean shouldLabelBts = arguments.getBoolean("labelBTS"); if (shouldRunAll || shouldLabelBts) { Path centroidsPath = new Path(arguments.getString( "centroids_bts", true)); BtsLabellingRunner.run(btsCommsPath, btsComareaPath, centroidsPath, vectorBtsClusterPath, tmpLabelBtsPath, isDebug, conf); } Path tmpLabelClientbtsPath = new Path(tmpPath, "label_clientbts"); Path pointsOfInterestTempPath = new Path(tmpLabelClientbtsPath, "vector_clientbts_cluster"); Path vectorClientbtsClusterPath = new Path(tmpLabelClientbtsPath, "vector_clientbts_cluster"); boolean shouldLabelClientbts = arguments.getBoolean("labelClientBTS"); if (shouldRunAll || shouldLabelClientbts) { Path centroidsPath = new Path(arguments.getString( "centroids_clientbts", true)); ClientBtsLabellingRunner.run(clientsInfoPath, clientsRepbtsPath, centroidsPath, pointsOfInterestTempPath, vectorClientbtsClusterPath, tmpLabelBtsPath, isDebug, conf); } Path tmpLabelJoining = new Path(tmpPath, "label_joining"); boolean shouldJoinLabels = arguments.getBoolean("joinLabels"); if (shouldRunAll || shouldJoinLabels) { LabelJoiningRunner.run(pointsOfInterestTempPath, vectorClientClusterPath, vectorClientbtsClusterPath, vectorBtsClusterPath, tmpLabelJoining, conf); } return 0; } public static void main(String[] args) throws Exception { try { int res = ToolRunner.run(new Configuration(), new MobilityMain(), args); if (res != 0) { throw new Exception("Unknown error"); } } catch (Exception ex) { Logger.get().fatal(ex); throw ex; } } }
cosmos/models/mobility/src/main/java/es/tid/cosmos/mobility/MobilityMain.java
package es.tid.cosmos.mobility; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import es.tid.cosmos.mobility.btslabelling.BtsLabellingRunner; import es.tid.cosmos.mobility.clientbtslabelling.ClientBtsLabellingRunner; import es.tid.cosmos.mobility.clientlabelling.ClientLabellingRunner; import es.tid.cosmos.mobility.labeljoining.LabelJoiningRunner; import es.tid.cosmos.mobility.parsing.ParsingRunner; import es.tid.cosmos.mobility.pois.PoisRunner; import es.tid.cosmos.mobility.preparing.PreparingRunner; import es.tid.cosmos.mobility.util.Logger; /** * * @author dmicol */ public class MobilityMain extends Configured implements Tool { @Override public int run(String[] args) throws Exception { ArgumentParser arguments = new ArgumentParser(); arguments.parse(args); final Configuration conf = this.getConf(); Path tmpPath; if (arguments.has("tmpDir")) { tmpPath = new Path(arguments.getString("tmpDir")); } else { tmpPath = new Path("/tmp/mobility"); } Path cdrsPath = new Path(arguments.getString("cdrs")); Path cellsPath = new Path(arguments.getString("cells")); Path adjBtsPath = new Path(arguments.getString("adjBts")); Path btsVectorTxtPath = new Path(arguments.getString("btsVectorTxt")); boolean shouldRunAll = arguments.getBoolean("run_all"); boolean isDebug = arguments.getBoolean("debug"); Path tmpParsingPath = new Path(tmpPath, "parsing"); Path cdrsMobPath = new Path(tmpParsingPath, "cdrs_mob"); Path cellsMobPath = new Path(tmpParsingPath, "cells_mob"); Path pairbtsAdjPath = new Path(tmpParsingPath, "pairbts_adj"); Path btsComareaPath = new Path(tmpParsingPath, "bts_comarea"); boolean shouldParse = arguments.getBoolean("parse"); if (shouldRunAll || shouldParse) { ParsingRunner.run(cdrsPath, cdrsMobPath, cellsPath, cellsMobPath, adjBtsPath, pairbtsAdjPath, btsVectorTxtPath, btsComareaPath, conf); } Path tmpPreparingPath = new Path(tmpPath, "preparing"); Path cdrsInfoPath = new Path(tmpPreparingPath, "cdrs_info"); Path cdrsNoinfoPath = new Path(tmpPreparingPath, "cdrs_noinfo"); Path clientsBtsPath = new Path(tmpPreparingPath, "clients_bts"); Path btsCommsPath = new Path(tmpPreparingPath, "bts_comms"); Path cdrsNoBtsPath = new Path(tmpPreparingPath, "cdrs_no_bts"); Path viTelmonthBtsPath = new Path(tmpPreparingPath, "vi_telmonth_bts"); boolean shouldPrepare = arguments.getBoolean("prepare"); if (shouldRunAll || shouldPrepare) { PreparingRunner.run(tmpPreparingPath, cdrsMobPath, cdrsInfoPath, cdrsNoinfoPath, cellsMobPath, clientsBtsPath, btsCommsPath, cdrsNoBtsPath, viTelmonthBtsPath, conf); } Path tmpExtractPoisPath = new Path(tmpPath, "extract_pois"); Path clientsInfoPath = new Path(tmpPath, "clients_info"); Path clientsInfoFilteredPath = new Path(tmpExtractPoisPath, "clients_info_filtered"); Path clientsRepbtsPath = new Path(tmpExtractPoisPath, "clients_repbts"); boolean shouldExtractPois = arguments.getBoolean("extractPOIs"); if (shouldRunAll || shouldExtractPois) { PoisRunner.run(tmpExtractPoisPath, clientsBtsPath, clientsInfoPath, cdrsNoinfoPath, cdrsNoBtsPath, clientsInfoFilteredPath, clientsRepbtsPath, isDebug, conf); } Path tmpLabelClientPath = new Path(tmpPath, "label_client"); Path vectorClientClusterPath = new Path(tmpLabelClientPath, "vector_client_clusterPath"); boolean shouldLabelClient = arguments.getBoolean("labelClient"); if (shouldRunAll || shouldLabelClient) { Path centroidsPath = new Path(arguments.getString( "centroids_client", true)); ClientLabellingRunner.run(cdrsMobPath, clientsInfoFilteredPath, centroidsPath, vectorClientClusterPath, tmpLabelClientPath, isDebug, conf); } Path tmpLabelBtsPath = new Path(tmpPath, "label_bts"); Path vectorBtsClusterPath = new Path(tmpLabelBtsPath, "vector_bts_cluster"); boolean shouldLabelBts = arguments.getBoolean("labelBTS"); if (shouldRunAll || shouldLabelBts) { Path centroidsPath = new Path(arguments.getString( "centroids_bts", true)); BtsLabellingRunner.run(btsCommsPath, btsComareaPath, centroidsPath, vectorBtsClusterPath, tmpLabelBtsPath, isDebug, conf); } Path tmpLabelClientbtsPath = new Path(tmpPath, "label_clientbts"); Path pointsOfInterestTempPath = new Path(tmpLabelClientbtsPath, "vector_clientbts_cluster"); Path vectorClientbtsClusterPath = new Path(tmpLabelClientbtsPath, "vector_clientbts_cluster"); boolean shouldLabelClientbts = arguments.getBoolean("labelClientBTS"); if (shouldRunAll || shouldLabelClientbts) { Path centroidsPath = new Path(arguments.getString( "centroids_clientbts", true)); ClientBtsLabellingRunner.run(clientsInfoPath, clientsRepbtsPath, centroidsPath, pointsOfInterestTempPath, vectorClientbtsClusterPath, tmpLabelBtsPath, isDebug, conf); } Path tmpLabelJoining = new Path(tmpPath, "label_joining"); boolean shouldJoinLabels = arguments.getBoolean("joinLabels"); if (shouldRunAll || shouldJoinLabels) { LabelJoiningRunner.run(pointsOfInterestTempPath, vectorClientClusterPath, vectorClientbtsClusterPath, vectorBtsClusterPath, tmpLabelJoining, conf); } return 0; } public static void main(String[] args) throws Exception { try { int res = ToolRunner.run(new Configuration(), new MobilityMain(), args); if (res != 0) { throw new Exception("Unknown error"); } } catch (Exception ex) { Logger.get().fatal(ex); throw ex; } } }
Path bug fix.
cosmos/models/mobility/src/main/java/es/tid/cosmos/mobility/MobilityMain.java
Path bug fix.
<ide><path>osmos/models/mobility/src/main/java/es/tid/cosmos/mobility/MobilityMain.java <ide> } <ide> <ide> Path tmpExtractPoisPath = new Path(tmpPath, "extract_pois"); <del> Path clientsInfoPath = new Path(tmpPath, "clients_info"); <add> Path clientsInfoPath = new Path(tmpExtractPoisPath, "clients_info"); <ide> Path clientsInfoFilteredPath = new Path(tmpExtractPoisPath, <ide> "clients_info_filtered"); <ide> Path clientsRepbtsPath = new Path(tmpExtractPoisPath, "clients_repbts");
Java
bsd-2-clause
ba108ea8834ac02d3cff2328e997cd0e272bcf43
0
jayantk/jklol,jayantk/jklol,jayantk/jklol,jayantk/jklol
package com.jayantkrish.jklol.cvsm.tree; import java.util.Arrays; import java.util.List; import com.google.common.base.Preconditions; import com.jayantkrish.jklol.cvsm.CvsmGradient; import com.jayantkrish.jklol.cvsm.lrt.LowRankTensor; import com.jayantkrish.jklol.cvsm.lrt.TensorLowRankTensor; import com.jayantkrish.jklol.tensor.Tensor; /** * A hyperbolic tangent operator. * * @author jayantk */ public class CvsmTanhTree extends AbstractCvsmTree { private final CvsmTree subtree; public CvsmTanhTree(CvsmTree subtree) { super(new TensorLowRankTensor(subtree.getValue().getTensor().elementwiseTanh())); this.subtree = Preconditions.checkNotNull(subtree); } @Override public List<CvsmTree> getSubtrees() { return Arrays.asList(subtree); } @Override public CvsmTree replaceSubtrees(List<CvsmTree> subtrees) { Preconditions.checkArgument(subtrees.size() == 1); return new CvsmTanhTree(subtrees.get(0)); } @Override public void backpropagateGradient(LowRankTensor treeGradient, CvsmGradient gradient) { Tensor tanh = getValue().getTensor(); Tensor nodeGradient = tanh.elementwiseProduct(tanh).elementwiseProduct(-1.0).elementwiseAddition(1.0); Tensor subtreeGradient = nodeGradient.elementwiseProduct(treeGradient.getTensor()); subtree.backpropagateGradient(new TensorLowRankTensor(subtreeGradient), gradient); } @Override public double getLoss() { return 0; } }
src/com/jayantkrish/jklol/cvsm/tree/CvsmTanhTree.java
package com.jayantkrish.jklol.cvsm.tree; import java.util.Arrays; import java.util.List; import com.google.common.base.Preconditions; import com.jayantkrish.jklol.cvsm.CvsmGradient; import com.jayantkrish.jklol.cvsm.lrt.LowRankTensor; import com.jayantkrish.jklol.cvsm.lrt.TensorLowRankTensor; import com.jayantkrish.jklol.tensor.Tensor; /** * A hyperbolic tangent operator. * * @author jayantk */ public class CvsmTanhTree extends AbstractCvsmTree { private final CvsmTree subtree; public CvsmTanhTree(CvsmTree subtree) { super(new TensorLowRankTensor(subtree.getValue().getTensor().elementwiseTanh())); this.subtree = Preconditions.checkNotNull(subtree); } @Override public List<CvsmTree> getSubtrees() { return Arrays.asList(subtree); } @Override public CvsmTree replaceSubtrees(List<CvsmTree> subtrees) { Preconditions.checkArgument(subtrees.size() == 1); return new CvsmTanhTree(subtrees.get(0)); } @Override public void backpropagateGradient(LowRankTensor treeGradient, CvsmGradient gradient) { Tensor tanh = getValue().getTensor(); Tensor nodeGradient = tanh.elementwiseProduct(tanh).elementwiseProduct(-1.0).elementwiseAddition(1.0); Tensor subtreeGradient = nodeGradient.elementwiseInverse().elementwiseProduct(treeGradient.getTensor()); subtree.backpropagateGradient(new TensorLowRankTensor(subtreeGradient), gradient); } @Override public double getLoss() { return 0; } }
fixing tanh derivative (really, this time)
src/com/jayantkrish/jklol/cvsm/tree/CvsmTanhTree.java
fixing tanh derivative (really, this time)
<ide><path>rc/com/jayantkrish/jklol/cvsm/tree/CvsmTanhTree.java <ide> Tensor tanh = getValue().getTensor(); <ide> Tensor nodeGradient = tanh.elementwiseProduct(tanh).elementwiseProduct(-1.0).elementwiseAddition(1.0); <ide> <del> Tensor subtreeGradient = nodeGradient.elementwiseInverse().elementwiseProduct(treeGradient.getTensor()); <add> Tensor subtreeGradient = nodeGradient.elementwiseProduct(treeGradient.getTensor()); <ide> subtree.backpropagateGradient(new TensorLowRankTensor(subtreeGradient), gradient); <ide> } <ide>
Java
mit
a0260d30c125ba67f1b0e53f8289559a7f94031d
0
jbannick/hellokata-java,jbannick/hellokata-java
src/modules/simplest/hellomodjar/src/appmod/module-info.java
module appmod { }
Delete module-info.java
src/modules/simplest/hellomodjar/src/appmod/module-info.java
Delete module-info.java
<ide><path>rc/modules/simplest/hellomodjar/src/appmod/module-info.java <del>module appmod { <del> <del>}
Java
agpl-3.0
b23b1e569384f98f359d62d5df0d1a4fe8567364
0
SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart,SoftInstigate/restheart
/* * uIAM - the IAM for microservices * Copyright (C) SoftInstigate Srl * * 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 io.uiam.handlers.exchange; import io.uiam.Bootstrapper; import io.undertow.connector.PooledByteBuffer; import io.undertow.server.HttpServerExchange; import io.undertow.util.AttachmentKey; import java.io.IOException; import org.slf4j.Logger; /** * * @author Andrea Di Cesare <[email protected]> */ public abstract class AbstractExchange<T> { protected static Logger LOGGER; private static final AttachmentKey<Boolean> IN_ERROR = AttachmentKey.create(Boolean.class); private static final AttachmentKey<Boolean> RESPONSE_INTERCEPTOR_EXECUTED = AttachmentKey.create(Boolean.class); public static final int MAX_CONTENT_SIZE = 16 * 1024 * 1024; // 16byte public static final int MAX_BUFFERS; static { MAX_BUFFERS = 1 + (MAX_CONTENT_SIZE / (Bootstrapper .getConfiguration() != null ? Bootstrapper.getConfiguration().getBufferSize() : 1024)); } public enum METHOD { GET, POST, PUT, DELETE, PATCH, OPTIONS, OTHER } protected final HttpServerExchange wrapped; public AbstractExchange(HttpServerExchange exchange) { this.wrapped = exchange; } /** * @return the wrapped */ HttpServerExchange getWrapped() { return wrapped; } public static boolean isInError(HttpServerExchange exchange) { return exchange.getAttachment(IN_ERROR) != null && exchange.getAttachment(IN_ERROR); } public static boolean isAuthenticated(HttpServerExchange exchange) { return exchange.getSecurityContext() != null && exchange.getSecurityContext().getAuthenticatedAccount() != null; } public static void setInError(HttpServerExchange exchange) { exchange .putAttachment(IN_ERROR, true); } public static boolean responseInterceptorsExecuted(HttpServerExchange exchange) { return exchange.getAttachment(RESPONSE_INTERCEPTOR_EXECUTED) != null && exchange.getAttachment(RESPONSE_INTERCEPTOR_EXECUTED); } public static void setResponseInterceptorsExecuted(HttpServerExchange exchange) { exchange .putAttachment(RESPONSE_INTERCEPTOR_EXECUTED, true); } public abstract T readContent() throws IOException; public abstract void writeContent(T content) throws IOException; protected abstract void setContentLength(int length); protected abstract AttachmentKey<PooledByteBuffer[]> getRawContentKey(); public PooledByteBuffer[] getRawContent() { if (!isContentAvailable()) { throw new IllegalStateException("Response content is not available. " + "Add a Response Inteceptor overriding requiresResponseContent() " + "to return true in order to make the content available."); } return getWrapped().getAttachment(getRawContentKey()); } public void setRawContent(PooledByteBuffer[] raw) { getWrapped().putAttachment(getRawContentKey(), raw); } // protected abstract AttachmentKey<T> getContentKey(); public abstract String getContentType(); public boolean isContentAvailable() { return null != getWrapped().getAttachment(getRawContentKey()); } /** * helper method to check if the request content is Json * * @return true if Content-Type request header is application/json */ public boolean isContentTypeJson() { return "application/json".equals(getContentType()) || (getContentType() != null && getContentType().startsWith("application/json;")); } /** * helper method to check if the request content is Xm * * @return true if Content-Type request header is application/xml or * text/xml */ public boolean isContentTypeXml() { return "text/xml".equals(getContentType()) || (getContentType() != null && getContentType().startsWith("text/xml;")) || "application/xml".equals(getContentType()) || (getContentType() != null && getContentType().startsWith("application/xml;")); } /** * helper method to check if the request content is text * * @return true if Content-Type request header starts with text/ */ public boolean isContentTypeText() { return getContentType() != null && getContentType().startsWith("text/"); } }
security/src/main/java/io/uiam/handlers/exchange/AbstractExchange.java
/* * uIAM - the IAM for microservices * Copyright (C) SoftInstigate Srl * * 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 io.uiam.handlers.exchange; import io.uiam.Bootstrapper; import io.undertow.connector.PooledByteBuffer; import io.undertow.server.HttpServerExchange; import io.undertow.util.AttachmentKey; import java.io.IOException; import org.slf4j.Logger; /** * * @author Andrea Di Cesare <[email protected]> */ public abstract class AbstractExchange<T> { protected static Logger LOGGER; private static final AttachmentKey<Boolean> IN_ERROR = AttachmentKey.create(Boolean.class); private static final AttachmentKey<Boolean> RESPONSE_INTERCEPTOR_EXECUTED = AttachmentKey.create(Boolean.class); public static final int MAX_CONTENT_SIZE = 16 * 1024 * 1024; // 16byte public static final int MAX_BUFFERS; static { MAX_BUFFERS = 1 + (MAX_CONTENT_SIZE / (Bootstrapper .getConfiguration() != null ? Bootstrapper.getConfiguration().getBufferSize() : 1024)); } public enum METHOD { GET, POST, PUT, DELETE, PATCH, OPTIONS, OTHER } protected final HttpServerExchange wrapped; public AbstractExchange(HttpServerExchange exchange) { this.wrapped = exchange; } /** * @return the wrapped */ public HttpServerExchange getWrapped() { return wrapped; } public static boolean isInError(HttpServerExchange exchange) { return exchange.getAttachment(IN_ERROR) != null && exchange.getAttachment(IN_ERROR); } public static boolean isAuthenticated(HttpServerExchange exchange) { return exchange.getSecurityContext() != null && exchange.getSecurityContext().getAuthenticatedAccount() != null; } public static void setInError(HttpServerExchange exchange) { exchange .putAttachment(IN_ERROR, true); } public static boolean responseInterceptorsExecuted(HttpServerExchange exchange) { return exchange.getAttachment(RESPONSE_INTERCEPTOR_EXECUTED) != null && exchange.getAttachment(RESPONSE_INTERCEPTOR_EXECUTED); } public static void setResponseInterceptorsExecuted(HttpServerExchange exchange) { exchange .putAttachment(RESPONSE_INTERCEPTOR_EXECUTED, true); } public abstract T readContent() throws IOException; public abstract void writeContent(T content) throws IOException; protected abstract void setContentLength(int length); protected abstract AttachmentKey<PooledByteBuffer[]> getRawContentKey(); public PooledByteBuffer[] getRawContent() { if (!isContentAvailable()) { throw new IllegalStateException("Response content is not available. " + "Add a Response Inteceptor overriding requiresResponseContent() " + "to return true in order to make the content available."); } return getWrapped().getAttachment(getRawContentKey()); } public void setRawContent(PooledByteBuffer[] raw) { getWrapped().putAttachment(getRawContentKey(), raw); } // protected abstract AttachmentKey<T> getContentKey(); public abstract String getContentType(); public boolean isContentAvailable() { return null != getWrapped().getAttachment(getRawContentKey()); } /** * helper method to check if the request content is Json * * @return true if Content-Type request header is application/json */ public boolean isContentTypeJson() { return "application/json".equals(getContentType()) || (getContentType() != null && getContentType().startsWith("application/json;")); } /** * helper method to check if the request content is Xm * * @return true if Content-Type request header is application/xml or * text/xml */ public boolean isContentTypeXml() { return "text/xml".equals(getContentType()) || (getContentType() != null && getContentType().startsWith("text/xml;")) || "application/xml".equals(getContentType()) || (getContentType() != null && getContentType().startsWith("application/xml;")); } /** * helper method to check if the request content is text * * @return true if Content-Type request header starts with text/ */ public boolean isContentTypeText() { return getContentType() != null && getContentType().startsWith("text/"); } }
AbstractExchange.getWrapped() package access
security/src/main/java/io/uiam/handlers/exchange/AbstractExchange.java
AbstractExchange.getWrapped() package access
<ide><path>ecurity/src/main/java/io/uiam/handlers/exchange/AbstractExchange.java <ide> /** <ide> * @return the wrapped <ide> */ <del> public HttpServerExchange getWrapped() { <add> HttpServerExchange getWrapped() { <ide> return wrapped; <ide> } <ide>
Java
lgpl-2.1
bc8d9bea3ee2d3d7ce6f42fb2cbcb46888637dc0
0
languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool,languagetool-org/languagetool
/* LanguageTool, a natural language style checker * Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev.dumpcheck; import org.apache.commons.cli.*; import org.apache.commons.lang3.StringUtils; import org.languagetool.*; import org.languagetool.rules.CategoryId; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.patterns.AbstractPatternRule; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.NumberFormat; import java.util.*; import java.util.regex.Pattern; /** * Checks texts from one or more {@link SentenceSource}s. * @since 2.4 */ public class SentenceSourceChecker { private SentenceSourceChecker() { // no public constructor } public static void main(String[] args) throws IOException { SentenceSourceChecker prg = new SentenceSourceChecker(); CommandLine commandLine = ensureCorrectUsageOrExit(args); File propFile = null; if (commandLine.hasOption('d')) { propFile = new File(commandLine.getOptionValue('d')); if (!propFile.exists() || propFile.isDirectory()) { throw new IOException("File not found or isn't a file: " + propFile.getAbsolutePath()); } } String languageCode = commandLine.getOptionValue('l'); Set<String> disabledRuleIds = new HashSet<>(); if (commandLine.hasOption("rule-properties")) { File disabledRulesPropFile = new File(commandLine.getOptionValue("rule-properties")); if (!disabledRulesPropFile.exists() || disabledRulesPropFile.isDirectory()) { throw new IOException("File not found or isn't a file: " + disabledRulesPropFile.getAbsolutePath()); } Properties disabledRules = new Properties(); try (FileInputStream stream = new FileInputStream(disabledRulesPropFile)) { disabledRules.load(stream); addDisabledRules("all", disabledRuleIds, disabledRules); addDisabledRules(languageCode, disabledRuleIds, disabledRules); } } String motherTongue = commandLine.getOptionValue('m'); int maxArticles = Integer.parseInt(commandLine.getOptionValue("max-sentences", "0")); int maxErrors = Integer.parseInt(commandLine.getOptionValue("max-errors", "0")); int contextSize = Integer.parseInt(commandLine.getOptionValue("context-size", "50")); prg.run(propFile, disabledRuleIds, languageCode, motherTongue, maxArticles, maxErrors, contextSize, commandLine); } private static void addDisabledRules(String languageCode, Set<String> disabledRuleIds, Properties disabledRules) { String disabledRulesString = disabledRules.getProperty(languageCode); if (disabledRulesString != null) { String[] ids = disabledRulesString.split(","); disabledRuleIds.addAll(Arrays.asList(ids)); } } private static CommandLine ensureCorrectUsageOrExit(String[] args) { Options options = new Options(); options.addOption(Option.builder("l").longOpt("language").argName("code").hasArg() .desc("language code like 'en' or 'de'").required().build()); options.addOption(Option.builder("m").longOpt("mother-tongue").argName("code").hasArg() .desc("language code like 'en' or 'de'").build()); options.addOption(Option.builder("d").longOpt("db-properties").argName("file").hasArg() .desc("A file to set database access properties. If not set, the output will be written to STDOUT. " + "The file needs to set the properties dbUrl ('jdbc:...'), dbUser, and dbPassword. " + "It can optionally define the batchSize for insert statements, which defaults to 1.").build()); options.addOption(Option.builder().longOpt("rule-properties").argName("file").hasArg() .desc("A file to set rules which should be disabled per language (e.g. en=RULE1,RULE2 or all=RULE3,RULE4)").build()); options.addOption(Option.builder("r").longOpt("rule-ids").argName("id").hasArg() .desc("comma-separated list of rule-ids to activate").build()); options.addOption(Option.builder().longOpt("also-enable-categories").argName("categories").hasArg() .desc("comma-separated list of categories to activate, additionally to rules activated anyway").build()); options.addOption(Option.builder("f").longOpt("file").argName("file").hasArg() .desc("an unpacked Wikipedia XML dump; (must be named *.xml, dumps are available from http://dumps.wikimedia.org/backup-index.html) " + "or a Tatoeba CSV file filtered to contain only one language (must be named tatoeba-*). You can specify this option more than once.") .required().build()); options.addOption(Option.builder().longOpt("max-sentences").argName("number").hasArg() .desc("maximum number of sentences to check").build()); options.addOption(Option.builder().longOpt("max-errors").argName("number").hasArg() .desc("maximum number of errors, stop when finding more").build()); options.addOption(Option.builder().longOpt("context-size").argName("number").hasArg() .desc("context size per error, in characters").build()); options.addOption(Option.builder().longOpt("languagemodel").argName("indexDir").hasArg() .desc("directory with a '3grams' sub directory that contains an ngram index").build()); options.addOption(Option.builder().longOpt("neuralnetworkmodel").argName("baseDir").hasArg() .desc("base directory for saved neural network models (deprecated)").build()); options.addOption(Option.builder().longOpt("remoterules").argName("configFile").hasArg() .desc("JSON file with configuration of remote rules").build()); options.addOption(Option.builder().longOpt("filter").argName("regex").hasArg() .desc("Consider only sentences that contain this regular expression (for speed up)").build()); options.addOption(Option.builder().longOpt("spelling") .desc("Don't skip spell checking rules").build()); options.addOption(Option.builder().longOpt("rulesource").hasArg() .desc("Activate only rules from this XML file (e.g. 'grammar.xml')").build()); options.addOption(Option.builder().longOpt("skip").hasArg() .desc("Skip this many sentences from input before actually checking sentences").build()); options.addOption(Option.builder().longOpt("print-duration") .desc("Print the duration of analysis in milliseconds").build()); options.addOption(Option.builder().longOpt("nerUrl").argName("url").hasArg() .desc("URL of a named entity recognition service").build()); try { CommandLineParser parser = new DefaultParser(); return parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(80); formatter.setSyntaxPrefix("Usage: "); formatter.printHelp(SentenceSourceChecker.class.getSimpleName() + " [OPTION]... --file <file> --language <code>", options); System.exit(1); } throw new IllegalStateException(); } private void run(File propFile, Set<String> disabledRules, String langCode, String motherTongueCode, int maxSentences, int maxErrors, int contextSize, CommandLine options) throws IOException { long startTime = System.currentTimeMillis(); String[] ruleIds = options.hasOption('r') ? options.getOptionValue('r').split(",") : null; String[] additionalCategoryIds = options.hasOption("also-enable-categories") ? options.getOptionValue("also-enable-categories").split(",") : null; String[] fileNames = options.getOptionValues('f'); File languageModelDir = options.hasOption("languagemodel") ? new File(options.getOptionValue("languagemodel")) : null; File word2vecModelDir = options.hasOption("word2vecmodel") ? new File(options.getOptionValue("word2vecmodel")) : null; File neuralNetworkModelDir = options.hasOption("neuralnetworkmodel") ? new File(options.getOptionValue("neuralnetworkmodel")) : null; File remoteRules = options.hasOption("remoterules") ? new File(options.getOptionValue("remoterules")) : null; Pattern filter = options.hasOption("filter") ? Pattern.compile(options.getOptionValue("filter")) : null; String ruleSource = options.hasOption("rulesource") ? options.getOptionValue("rulesource") : null; int sentencesToSkip = options.hasOption("skip") ? Integer.parseInt(options.getOptionValue("skip")) : 0; Language lang = Languages.getLanguageForShortCode(langCode); Language motherTongue = motherTongueCode != null ? Languages.getLanguageForShortCode(motherTongueCode) : null; GlobalConfig globalConfig = new GlobalConfig(); if (options.hasOption("nerUrl")) { System.out.println("Using NER service: " + options.getOptionValue("nerUrl")); globalConfig.setNERUrl(options.getOptionValue("nerUrl")); } MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(lang, motherTongue, -1, globalConfig, null); lt.setCleanOverlappingMatches(false); if (languageModelDir != null) { lt.activateLanguageModelRules(languageModelDir); } if (word2vecModelDir != null) { lt.activateWord2VecModelRules(word2vecModelDir); } if (neuralNetworkModelDir != null) { lt.activateNeuralNetworkRules(neuralNetworkModelDir); } int activatedBySource = 0; for (Rule rule : lt.getAllRules()) { if (rule.isDefaultTempOff()) { System.out.println("Activating " + rule.getFullId() + ", which is default='temp_off'"); lt.enableRule(rule.getId()); } if (ruleSource != null) { boolean enable = false; if (rule instanceof AbstractPatternRule) { String sourceFile = ((AbstractPatternRule) rule).getSourceFile(); if (sourceFile != null && sourceFile.endsWith("/" + ruleSource) && !rule.isDefaultOff()) { enable = true; activatedBySource++; } } if (enable) { lt.enableRule(rule.getId()); } else { lt.disableRule(rule.getId()); } } } lt.activateRemoteRules(remoteRules); if (ruleSource == null) { if (ruleIds != null) { enableOnlySpecifiedRules(ruleIds, lt); } else { applyRuleDeactivation(lt, disabledRules); } } else { System.out.println("Activated " + activatedBySource + " rules from " + ruleSource); } if (filter != null) { System.out.println("*** NOTE: only sentences that match regular expression '" + filter + "' will be checked"); } activateAdditionalCategories(additionalCategoryIds, lt); if (options.hasOption("spelling")) { System.out.println("Spelling rules active: yes (only if you're using a language code like en-US which comes with spelling)"); } else if (ruleIds == null) { disableSpellingRules(lt); System.out.println("Spelling rules active: no"); } System.out.println("Working on: " + StringUtils.join(fileNames, ", ")); System.out.println("Sentence limit: " + (maxSentences > 0 ? maxSentences : "no limit")); System.out.println("Context size: " + contextSize); System.out.println("Error limit: " + (maxErrors > 0 ? maxErrors : "no limit")); System.out.println("Skip: " + sentencesToSkip); //System.out.println("Version: " + JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ")"); ResultHandler resultHandler = null; int ruleMatchCount = 0; int sentenceCount = 0; int skipCount = 0; int ignoredCount = 0; boolean skipMessageShown = false; try { if (propFile != null) { resultHandler = new DatabaseHandler(propFile, maxSentences, maxErrors); } else { resultHandler = new StdoutHandler(maxSentences, maxErrors, contextSize); } MixingSentenceSource mixingSource = MixingSentenceSource.create(Arrays.asList(fileNames), lang, filter); while (mixingSource.hasNext()) { Sentence sentence = mixingSource.next(); if (sentencesToSkip > 0 && skipCount < sentencesToSkip) { if (skipCount % 5000 == 0) { System.err.printf("%s sentences skipped...\n", NumberFormat.getNumberInstance(Locale.US).format(skipCount)); } skipCount++; continue; } else if (sentencesToSkip > 0 && !skipMessageShown) { System.err.println("Done skipping " + sentencesToSkip + " sentences."); skipMessageShown = true; } try { List<RuleMatch> matches = lt.check(sentence.getText()); resultHandler.handleResult(sentence, matches, lang); sentenceCount++; if (sentenceCount % 5000 == 0) { System.err.printf("%s sentences checked...\n", NumberFormat.getNumberInstance(Locale.US).format(sentenceCount)); } ruleMatchCount += matches.size(); } catch (DocumentLimitReachedException | ErrorLimitReachedException e) { throw e; } catch (Exception e) { throw new RuntimeException("Check failed on sentence: " + StringUtils.abbreviate(sentence.getText(), 250), e); } } ignoredCount = mixingSource.getIgnoredCount(); } catch (DocumentLimitReachedException | ErrorLimitReachedException e) { System.out.println(getClass().getSimpleName() + ": " + e); } finally { lt.shutdown(); if (resultHandler != null) { System.out.printf(lang + ": %d total matches\n", ruleMatchCount); System.out.printf(lang + ": %d total sentences considered\n", sentenceCount); float matchesPerSentence = (float)ruleMatchCount / sentenceCount; System.out.printf(Locale.ENGLISH, lang + ": ø%.2f rule matches per sentence\n", matchesPerSentence); System.out.printf(Locale.ENGLISH, lang + ": %d input lines ignored (e.g. not between %d and %d chars or at least %d tokens)\n", ignoredCount, SentenceSource.MIN_SENTENCE_LENGTH, SentenceSource.MAX_SENTENCE_LENGTH, SentenceSource.MIN_SENTENCE_TOKEN_COUNT); if (options.hasOption("print-duration")) { System.out.println("The analysis took " + (System.currentTimeMillis() - startTime) + "ms"); } try { resultHandler.close(); } catch (Exception e) { e.printStackTrace(); } } } } private static void enableOnlySpecifiedRules(String[] ruleIds, JLanguageTool lt) { for (Rule rule : lt.getAllRules()) { lt.disableRule(rule.getId()); } for (String ruleId : ruleIds) { lt.enableRule(ruleId); } warnOnNonExistingRuleIds(ruleIds, lt); System.out.println("Only these rules are enabled: " + Arrays.toString(ruleIds)); } private static void warnOnNonExistingRuleIds(String[] ruleIds, JLanguageTool lt) { for (String ruleId : ruleIds) { boolean found = false; for (Rule rule : lt.getAllRules()) { if (rule.getId().equals(ruleId)) { found = true; break; } } if (!found) { System.out.println("WARNING: Could not find rule '" + ruleId + "'"); } } } private static void applyRuleDeactivation(JLanguageTool lt, Set<String> disabledRules) { // disabled via config file, usually to avoid too many false alarms: for (String disabledRuleId : disabledRules) { lt.disableRule(disabledRuleId); } System.out.println("These rules are disabled: " + lt.getDisabledRules()); } private static void activateAdditionalCategories(String[] additionalCategoryIds, JLanguageTool lt) { if (additionalCategoryIds != null) { for (String categoryId : additionalCategoryIds) { for (Rule rule : lt.getAllRules()) { CategoryId id = rule.getCategory().getId(); if (id != null && id.toString().equals(categoryId)) { System.out.println("Activating " + rule.getId() + " in category " + categoryId); lt.enableRule(rule.getId()); } } } } } private static void disableSpellingRules(JLanguageTool lt) { List<Rule> allActiveRules = lt.getAllActiveRules(); for (Rule rule : allActiveRules) { if (rule.isDictionaryBasedSpellingRule()) { lt.disableRule(rule.getId()); } } } }
languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/SentenceSourceChecker.java
/* LanguageTool, a natural language style checker * Copyright (C) 2013 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.dev.dumpcheck; import org.apache.commons.cli.*; import org.apache.commons.lang3.StringUtils; import org.languagetool.*; import org.languagetool.rules.CategoryId; import org.languagetool.rules.Rule; import org.languagetool.rules.RuleMatch; import org.languagetool.rules.patterns.AbstractPatternRule; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.text.NumberFormat; import java.util.*; import java.util.regex.Pattern; /** * Checks texts from one or more {@link SentenceSource}s. * @since 2.4 */ public class SentenceSourceChecker { private SentenceSourceChecker() { // no public constructor } public static void main(String[] args) throws IOException { SentenceSourceChecker prg = new SentenceSourceChecker(); CommandLine commandLine = ensureCorrectUsageOrExit(args); File propFile = null; if (commandLine.hasOption('d')) { propFile = new File(commandLine.getOptionValue('d')); if (!propFile.exists() || propFile.isDirectory()) { throw new IOException("File not found or isn't a file: " + propFile.getAbsolutePath()); } } String languageCode = commandLine.getOptionValue('l'); Set<String> disabledRuleIds = new HashSet<>(); if (commandLine.hasOption("rule-properties")) { File disabledRulesPropFile = new File(commandLine.getOptionValue("rule-properties")); if (!disabledRulesPropFile.exists() || disabledRulesPropFile.isDirectory()) { throw new IOException("File not found or isn't a file: " + disabledRulesPropFile.getAbsolutePath()); } Properties disabledRules = new Properties(); try (FileInputStream stream = new FileInputStream(disabledRulesPropFile)) { disabledRules.load(stream); addDisabledRules("all", disabledRuleIds, disabledRules); addDisabledRules(languageCode, disabledRuleIds, disabledRules); } } String motherTongue = commandLine.getOptionValue('m'); int maxArticles = Integer.parseInt(commandLine.getOptionValue("max-sentences", "0")); int maxErrors = Integer.parseInt(commandLine.getOptionValue("max-errors", "0")); int contextSize = Integer.parseInt(commandLine.getOptionValue("context-size", "50")); prg.run(propFile, disabledRuleIds, languageCode, motherTongue, maxArticles, maxErrors, contextSize, commandLine); } private static void addDisabledRules(String languageCode, Set<String> disabledRuleIds, Properties disabledRules) { String disabledRulesString = disabledRules.getProperty(languageCode); if (disabledRulesString != null) { String[] ids = disabledRulesString.split(","); disabledRuleIds.addAll(Arrays.asList(ids)); } } private static CommandLine ensureCorrectUsageOrExit(String[] args) { Options options = new Options(); options.addOption(Option.builder("l").longOpt("language").argName("code").hasArg() .desc("language code like 'en' or 'de'").required().build()); options.addOption(Option.builder("m").longOpt("mother-tongue").argName("code").hasArg() .desc("language code like 'en' or 'de'").build()); options.addOption(Option.builder("d").longOpt("db-properties").argName("file").hasArg() .desc("A file to set database access properties. If not set, the output will be written to STDOUT. " + "The file needs to set the properties dbUrl ('jdbc:...'), dbUser, and dbPassword. " + "It can optionally define the batchSize for insert statements, which defaults to 1.").build()); options.addOption(Option.builder().longOpt("rule-properties").argName("file").hasArg() .desc("A file to set rules which should be disabled per language (e.g. en=RULE1,RULE2 or all=RULE3,RULE4)").build()); options.addOption(Option.builder("r").longOpt("rule-ids").argName("id").hasArg() .desc("comma-separated list of rule-ids to activate").build()); options.addOption(Option.builder().longOpt("also-enable-categories").argName("categories").hasArg() .desc("comma-separated list of categories to activate, additionally to rules activated anyway").build()); options.addOption(Option.builder("f").longOpt("file").argName("file").hasArg() .desc("an unpacked Wikipedia XML dump; (must be named *.xml, dumps are available from http://dumps.wikimedia.org/backup-index.html) " + "or a Tatoeba CSV file filtered to contain only one language (must be named tatoeba-*). You can specify this option more than once.") .required().build()); options.addOption(Option.builder().longOpt("max-sentences").argName("number").hasArg() .desc("maximum number of sentences to check").build()); options.addOption(Option.builder().longOpt("max-errors").argName("number").hasArg() .desc("maximum number of errors, stop when finding more").build()); options.addOption(Option.builder().longOpt("context-size").argName("number").hasArg() .desc("context size per error, in characters").build()); options.addOption(Option.builder().longOpt("languagemodel").argName("indexDir").hasArg() .desc("directory with a '3grams' sub directory that contains an ngram index").build()); options.addOption(Option.builder().longOpt("neuralnetworkmodel").argName("baseDir").hasArg() .desc("base directory for saved neural network models (deprecated)").build()); options.addOption(Option.builder().longOpt("remoterules").argName("configFile").hasArg() .desc("JSON file with configuration of remote rules").build()); options.addOption(Option.builder().longOpt("filter").argName("regex").hasArg() .desc("Consider only sentences that contain this regular expression (for speed up)").build()); options.addOption(Option.builder().longOpt("spelling") .desc("Don't skip spell checking rules").build()); options.addOption(Option.builder().longOpt("rulesource").hasArg() .desc("Activate only rules from this XML file (e.g. 'grammar.xml')").build()); options.addOption(Option.builder().longOpt("skip").hasArg() .desc("Skip this many sentences from input before actually checking sentences").build()); options.addOption(Option.builder().longOpt("print-duration") .desc("Print the duration of analysis in milliseconds").build()); options.addOption(Option.builder().longOpt("nerUrl").argName("url").hasArg() .desc("URL of a named entity recognition service").build()); try { CommandLineParser parser = new DefaultParser(); return parser.parse(options, args); } catch (ParseException e) { System.err.println("Error: " + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(80); formatter.setSyntaxPrefix("Usage: "); formatter.printHelp(SentenceSourceChecker.class.getSimpleName() + " [OPTION]... --file <file> --language <code>", options); System.exit(1); } throw new IllegalStateException(); } private void run(File propFile, Set<String> disabledRules, String langCode, String motherTongueCode, int maxSentences, int maxErrors, int contextSize, CommandLine options) throws IOException { long startTime = System.currentTimeMillis(); String[] ruleIds = options.hasOption('r') ? options.getOptionValue('r').split(",") : null; String[] additionalCategoryIds = options.hasOption("also-enable-categories") ? options.getOptionValue("also-enable-categories").split(",") : null; String[] fileNames = options.getOptionValues('f'); File languageModelDir = options.hasOption("languagemodel") ? new File(options.getOptionValue("languagemodel")) : null; File word2vecModelDir = options.hasOption("word2vecmodel") ? new File(options.getOptionValue("word2vecmodel")) : null; File neuralNetworkModelDir = options.hasOption("neuralnetworkmodel") ? new File(options.getOptionValue("neuralnetworkmodel")) : null; File remoteRules = options.hasOption("remoterules") ? new File(options.getOptionValue("remoterules")) : null; Pattern filter = options.hasOption("filter") ? Pattern.compile(options.getOptionValue("filter")) : null; String ruleSource = options.hasOption("rulesource") ? options.getOptionValue("rulesource") : null; int sentencesToSkip = options.hasOption("skip") ? Integer.parseInt(options.getOptionValue("skip")) : 0; Language lang = Languages.getLanguageForShortCode(langCode); Language motherTongue = motherTongueCode != null ? Languages.getLanguageForShortCode(motherTongueCode) : null; GlobalConfig globalConfig = new GlobalConfig(); if (options.hasOption("nerUrl")) { System.out.println("Using NER service: " + options.getOptionValue("nerUrl")); globalConfig.setNERUrl(options.getOptionValue("nerUrl")); } MultiThreadedJLanguageTool lt = new MultiThreadedJLanguageTool(lang, motherTongue, -1, globalConfig, null); lt.setCleanOverlappingMatches(false); if (languageModelDir != null) { lt.activateLanguageModelRules(languageModelDir); } if (word2vecModelDir != null) { lt.activateWord2VecModelRules(word2vecModelDir); } if (neuralNetworkModelDir != null) { lt.activateNeuralNetworkRules(neuralNetworkModelDir); } int activatedBySource = 0; for (Rule rule : lt.getAllRules()) { if (rule.isDefaultTempOff()) { System.out.println("Activating " + rule.getFullId() + ", which is default='temp_off'"); lt.enableRule(rule.getId()); } if (ruleSource != null) { boolean enable = false; if (rule instanceof AbstractPatternRule) { String sourceFile = ((AbstractPatternRule) rule).getSourceFile(); if (sourceFile != null && sourceFile.endsWith("/" + ruleSource) && !rule.isDefaultOff()) { enable = true; activatedBySource++; } } if (enable) { lt.enableRule(rule.getId()); } else { lt.disableRule(rule.getId()); } } } lt.activateRemoteRules(remoteRules); if (ruleSource == null) { if (ruleIds != null) { enableOnlySpecifiedRules(ruleIds, lt); } else { applyRuleDeactivation(lt, disabledRules); } } else { System.out.println("Activated " + activatedBySource + " rules from " + ruleSource); } if (filter != null) { System.out.println("*** NOTE: only sentences that match regular expression '" + filter + "' will be checked"); } activateAdditionalCategories(additionalCategoryIds, lt); if (options.hasOption("spelling")) { System.out.println("Spelling rules active: yes (only if you're using a language code like en-US which comes with spelling)"); } else if (ruleIds == null) { disableSpellingRules(lt); System.out.println("Spelling rules active: no"); } System.out.println("Working on: " + StringUtils.join(fileNames, ", ")); System.out.println("Sentence limit: " + (maxSentences > 0 ? maxSentences : "no limit")); System.out.println("Context size: " + contextSize); System.out.println("Error limit: " + (maxErrors > 0 ? maxErrors : "no limit")); System.out.println("Skip: " + sentencesToSkip); //System.out.println("Version: " + JLanguageTool.VERSION + " (" + JLanguageTool.BUILD_DATE + ")"); ResultHandler resultHandler = null; int ruleMatchCount = 0; int sentenceCount = 0; int skipCount = 0; int ignoredCount = 0; boolean skipMessageShown = false; try { if (propFile != null) { resultHandler = new DatabaseHandler(propFile, maxSentences, maxErrors); } else { resultHandler = new StdoutHandler(maxSentences, maxErrors, contextSize); } MixingSentenceSource mixingSource = MixingSentenceSource.create(Arrays.asList(fileNames), lang, filter); while (mixingSource.hasNext()) { Sentence sentence = mixingSource.next(); if (sentencesToSkip > 0 && skipCount < sentencesToSkip) { if (skipCount % 5000 == 0) { System.err.printf("%s sentences skipped...\n", NumberFormat.getNumberInstance(Locale.US).format(skipCount)); } skipCount++; continue; } else if (sentencesToSkip > 0 && !skipMessageShown) { System.err.println("Done skipping " + sentencesToSkip + " sentences."); skipMessageShown = true; } try { List<RuleMatch> matches = lt.check(sentence.getText()); resultHandler.handleResult(sentence, matches, lang); sentenceCount++; if (sentenceCount % 5000 == 0) { System.err.printf("%s sentences checked...\n", NumberFormat.getNumberInstance(Locale.US).format(sentenceCount)); } ruleMatchCount += matches.size(); } catch (DocumentLimitReachedException | ErrorLimitReachedException e) { throw e; } catch (Exception e) { throw new RuntimeException("Check failed on sentence: " + StringUtils.abbreviate(sentence.getText(), 250), e); } } ignoredCount = mixingSource.getIgnoredCount(); } catch (DocumentLimitReachedException | ErrorLimitReachedException e) { System.out.println(getClass().getSimpleName() + ": " + e); } finally { lt.shutdown(); if (resultHandler != null) { float matchesPerSentence = (float)ruleMatchCount / sentenceCount; System.out.printf(lang + ": %d total matches\n", ruleMatchCount); System.out.printf(Locale.ENGLISH, lang + ": ø%.2f rule matches per sentence\n", matchesPerSentence); System.out.printf(Locale.ENGLISH, lang + ": %d input lines ignored (e.g. not between %d and %d chars or at least %d tokens)\n", ignoredCount, SentenceSource.MIN_SENTENCE_LENGTH, SentenceSource.MAX_SENTENCE_LENGTH, SentenceSource.MIN_SENTENCE_TOKEN_COUNT); if (options.hasOption("print-duration")) { System.out.println("The analysis took " + (System.currentTimeMillis() - startTime) + "ms"); } try { resultHandler.close(); } catch (Exception e) { e.printStackTrace(); } } } } private static void enableOnlySpecifiedRules(String[] ruleIds, JLanguageTool lt) { for (Rule rule : lt.getAllRules()) { lt.disableRule(rule.getId()); } for (String ruleId : ruleIds) { lt.enableRule(ruleId); } warnOnNonExistingRuleIds(ruleIds, lt); System.out.println("Only these rules are enabled: " + Arrays.toString(ruleIds)); } private static void warnOnNonExistingRuleIds(String[] ruleIds, JLanguageTool lt) { for (String ruleId : ruleIds) { boolean found = false; for (Rule rule : lt.getAllRules()) { if (rule.getId().equals(ruleId)) { found = true; break; } } if (!found) { System.out.println("WARNING: Could not find rule '" + ruleId + "'"); } } } private static void applyRuleDeactivation(JLanguageTool lt, Set<String> disabledRules) { // disabled via config file, usually to avoid too many false alarms: for (String disabledRuleId : disabledRules) { lt.disableRule(disabledRuleId); } System.out.println("These rules are disabled: " + lt.getDisabledRules()); } private static void activateAdditionalCategories(String[] additionalCategoryIds, JLanguageTool lt) { if (additionalCategoryIds != null) { for (String categoryId : additionalCategoryIds) { for (Rule rule : lt.getAllRules()) { CategoryId id = rule.getCategory().getId(); if (id != null && id.toString().equals(categoryId)) { System.out.println("Activating " + rule.getId() + " in category " + categoryId); lt.enableRule(rule.getId()); } } } } } private static void disableSpellingRules(JLanguageTool lt) { List<Rule> allActiveRules = lt.getAllActiveRules(); for (Rule rule : allActiveRules) { if (rule.isDictionaryBasedSpellingRule()) { lt.disableRule(rule.getId()); } } } }
print total number of sentences in summary at the end
languagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/SentenceSourceChecker.java
print total number of sentences in summary at the end
<ide><path>anguagetool-wikipedia/src/main/java/org/languagetool/dev/dumpcheck/SentenceSourceChecker.java <ide> } finally { <ide> lt.shutdown(); <ide> if (resultHandler != null) { <add> System.out.printf(lang + ": %d total matches\n", ruleMatchCount); <add> System.out.printf(lang + ": %d total sentences considered\n", sentenceCount); <ide> float matchesPerSentence = (float)ruleMatchCount / sentenceCount; <del> System.out.printf(lang + ": %d total matches\n", ruleMatchCount); <ide> System.out.printf(Locale.ENGLISH, lang + ": ø%.2f rule matches per sentence\n", matchesPerSentence); <ide> System.out.printf(Locale.ENGLISH, lang + ": %d input lines ignored (e.g. not between %d and %d chars or at least %d tokens)\n", ignoredCount, <ide> SentenceSource.MIN_SENTENCE_LENGTH, SentenceSource.MAX_SENTENCE_LENGTH, SentenceSource.MIN_SENTENCE_TOKEN_COUNT);
Java
agpl-3.0
8fae958e245749966ffc14e5f5339ac7feec87f9
0
fayezasar/jPOS,jpos/jPOS,juanibdn/jPOS,alcarraz/jPOS,alcarraz/jPOS,c0deh4xor/jPOS,yinheli/jPOS,yinheli/jPOS,bharavi/jPOS,c0deh4xor/jPOS,jpos/jPOS,bharavi/jPOS,imam-san/jPOS-1,bharavi/jPOS,barspi/jPOS,jpos/jPOS,atancasis/jPOS,barspi/jPOS,yinheli/jPOS,imam-san/jPOS-1,barspi/jPOS,atancasis/jPOS,poynt/jPOS,atancasis/jPOS,juanibdn/jPOS,chhil/jPOS,c0deh4xor/jPOS,juanibdn/jPOS,sebastianpacheco/jPOS,alcarraz/jPOS,sebastianpacheco/jPOS,poynt/jPOS,chhil/jPOS,poynt/jPOS,fayezasar/jPOS,imam-san/jPOS-1,sebastianpacheco/jPOS
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2008 Alejandro P. Revilla * * 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.jpos.q2; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.MissingResourceException; import java.util.Properties; import java.util.ResourceBundle; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.MBeanException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import org.jdom.Element; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.core.SimpleConfiguration; import org.jpos.core.XmlConfigurable; import org.jpos.util.LogSource; import org.jpos.util.Logger; /** * @author <a href="mailto:[email protected]">Alireza Taherkordi</a> * @author <a href="mailto:[email protected]">Alejandro P. Revilla</a> * @version $Revision$ $Date$ */ public class QFactory { ObjectName loaderName; Q2 q2; ResourceBundle classMapping; public QFactory (ObjectName loaderName, Q2 q2) { super (); this.loaderName = loaderName; this.q2 = q2; classMapping = ResourceBundle.getBundle(this.getClass().getName()); } public Object instantiate (Q2 server, Element e) throws ReflectionException, MBeanException, InstanceNotFoundException { String clazz = e.getAttributeValue ("class"); if (clazz == null) { try { clazz = classMapping.getString (e.getName()); } catch (MissingResourceException ex) { // no class attribute, no mapping // let MBeanServer do the yelling } } MBeanServer mserver = server.getMBeanServer(); getExtraPath (server.getLoader (), e); return mserver.instantiate (clazz, loaderName); } public ObjectInstance createQBean (Q2 server, Element e, Object obj) throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedObjectNameException, MalformedURLException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException, MBeanException, NotCompliantMBeanException, InvalidAttributeValueException, ReflectionException, ConfigurationException { String name = e.getAttributeValue ("name"); if (name == null) name = e.getName (); ObjectName objectName = new ObjectName (Q2.QBEAN_NAME + name); MBeanServer mserver = server.getMBeanServer(); if(mserver.isRegistered(objectName)) { throw new InstanceAlreadyExistsException (name+" has already been deployed in another file."); } ObjectInstance instance = mserver.registerMBean ( obj, objectName ); try { setAttribute (mserver, objectName, "Name", name); String logger = e.getAttributeValue ("logger"); if (logger != null) setAttribute (mserver, objectName, "Logger", logger); setAttribute (mserver, objectName, "Server", server); setAttribute (mserver, objectName, "Persist", e); configureQBean(mserver,objectName,e); setConfiguration (obj, e); // handle legacy (QSP v1) Configurables if (obj instanceof QBean) mserver.invoke (objectName, "init", null, null); } catch (ConfigurationException ce) { mserver.unregisterMBean(objectName); throw ce; } return instance; } public Q2 getQ2() { return q2; } public void getExtraPath (QClassLoader loader, Element e) { Element classpathElement = e.getChild ("classpath"); if (classpathElement != null) { try { loader = loader.scan (true); // force a new classloader } catch (Throwable t) { getQ2().getLog().error(t); } Iterator iter = classpathElement.getChildren ("url").iterator(); while (iter.hasNext ()) { Element u = (Element) iter.next (); try { loader.addURL (u.getTextTrim ()); } catch (MalformedURLException ex) { q2.getLog().warn (u.getTextTrim(), ex); } } } } public void setAttribute (MBeanServer server, ObjectName objectName, String attribute, Object value) throws InstanceNotFoundException, MBeanException, InvalidAttributeValueException, ReflectionException { try { server.setAttribute ( objectName, new Attribute (attribute, value) ); } catch (AttributeNotFoundException ex) { // okay to fail } } public void startQBean (Q2 server, ObjectName objectName) throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedObjectNameException, MalformedURLException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException, MBeanException, NotCompliantMBeanException, InvalidAttributeValueException, ReflectionException { MBeanServer mserver = server.getMBeanServer(); mserver.invoke (objectName, "start", null, null); } public void destroyQBean (Q2 server, ObjectName objectName, Object obj) throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedObjectNameException, MalformedURLException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException, MBeanException, NotCompliantMBeanException, InvalidAttributeValueException, ReflectionException { MBeanServer mserver = server.getMBeanServer(); if (obj instanceof QBean) { mserver.invoke (objectName, "stop", null, null); mserver.invoke (objectName, "destroy", null, null); } if (objectName != null) mserver.unregisterMBean (objectName); } public void configureQBean(MBeanServer server, ObjectName objectName, Element e) throws ConfigurationException { try { AttributeList attributeList = getAttributeList(e); Iterator attributes = attributeList.iterator(); while (attributes.hasNext()) server.setAttribute(objectName,(Attribute)attributes.next()); } catch (Exception e1) { throw new ConfigurationException(e1); } } public AttributeList getAttributeList(Element e) throws ConfigurationException { AttributeList attributeList = new AttributeList(); List childs = e.getChildren("attr"); Iterator childsIterator = childs.iterator(); while (childsIterator.hasNext()) { Element childElement = (Element)childsIterator.next(); String name = childElement.getAttributeValue("name"); name = getAttributeName(name); Attribute attr = new Attribute(name,getObject(childElement)); attributeList.add(attr); } return attributeList; } /** creates an object from a definition element. * The element may have an attribute called type indicating the type of the object * to create, if this attribute is not present java.lang.String is assumed. * int, long and boolean are converted to their wrappers. * @return The created object. * @param childElement Dom Element with the definition of the object. * @throws ConfigurationException If an exception is found trying to create the object. */ protected Object getObject(Element childElement) throws ConfigurationException { String type = childElement.getAttributeValue("type","java.lang.String"); if ("int".equals (type)) type = "java.lang.Integer"; else if ("long".equals (type)) type = "java.lang.Long"; else if ("boolean".equals (type)) type = "java.lang.Boolean"; String value = childElement.getText(); try { Class attributeType = Class.forName(type); if(Collection.class.isAssignableFrom(attributeType)) return getCollection(attributeType, childElement); else{ Class[] parameterTypes = {"".getClass()}; Object[] parameterValues = {value}; return attributeType.getConstructor(parameterTypes).newInstance(parameterValues); } } catch (Exception e1) { throw new ConfigurationException(e1); } } /** Creats a collection from a definition element with the format. * <PRE> * <{attr|item} type="..."> * <item [type="..."]>...</item> * ... * </attr> * </PRE> * @param type * @param e * @throws ConfigurationException * @return */ protected Collection getCollection(Class type, Element e) throws ConfigurationException { try{ Collection col = (Collection)type.newInstance(); Iterator childs = e.getChildren("item").iterator(); while(childs.hasNext()) col.add(getObject((Element)childs.next())); return col; }catch(Exception e1){ throw new ConfigurationException(e1); } } /** * sets the first character of the string to the upper case * @param name * @return attribute name */ public String getAttributeName(String name) { StringBuffer tmp = new StringBuffer(name); tmp.setCharAt(0,name.toUpperCase().charAt(0)) ; return tmp.toString(); } public Object newInstance (String clazz) throws ConfigurationException { try { MBeanServer mserver = q2.getMBeanServer(); return mserver.instantiate (clazz, loaderName); } catch (Exception e) { throw new ConfigurationException (clazz, e); } } public Configuration getConfiguration (Element e) throws ConfigurationException { Properties props = new Properties (); Iterator iter = e.getChildren ("property").iterator(); while (iter.hasNext()) { Element property = (Element) iter.next (); String name = property.getAttributeValue("name"); String value = property.getAttributeValue("value"); String file = property.getAttributeValue("file"); if (file != null) try { props.load (new FileInputStream (new File (file))); } catch (Exception ex) { throw new ConfigurationException (file, ex); } else if (name != null && value != null) { Object obj = props.get (name); if (obj instanceof String[]) { String[] mobj = (String[]) obj; String[] m = new String[mobj.length + 1]; System.arraycopy(mobj,0,m,0,mobj.length); m[mobj.length] = value; props.put (name, m); } else if (obj instanceof String) { String[] m = new String[2]; m[0] = (String) obj; m[1] = value; props.put (name, m); } else props.put (name, value); } } return new SimpleConfiguration (props); } public void setLogger (Object obj, Element e) { if (obj instanceof LogSource) { String loggerName = e.getAttributeValue ("logger"); if (loggerName != null) { String realm = e.getAttributeValue ("realm"); if (realm == null) realm = e.getName(); Logger logger = Logger.getLogger (loggerName); ((LogSource)obj).setLogger (logger, realm); } } } public void setConfiguration (Object obj, Element e) throws ConfigurationException { try { if (obj instanceof Configurable) ((Configurable)obj).setConfiguration (getConfiguration (e)); if (obj instanceof XmlConfigurable) ((XmlConfigurable)obj).setConfiguration(e); } catch (ConfigurationException ex) { throw new ConfigurationException (ex); } } /** * Try to invoke a method (usually a setter) on the given object * silently ignoring if method does not exist * @param obj the object * @param m method to invoke * @param p parameter * @throws ConfigurationException if method happens to throw an exception */ public static void invoke (Object obj, String m, Object p) throws ConfigurationException { invoke (obj, m, p, p != null ? p.getClass() : null); } /** * Try to invoke a method (usually a setter) on the given object * silently ignoring if method does not exist * @param obj the object * @param m method to invoke * @param p parameter * @param pc parameter class * @throws ConfigurationException if method happens to throw an exception */ public static void invoke (Object obj, String m, Object p, Class pc) throws ConfigurationException { try { if (p!=null) { Class[] paramTemplate = { pc }; Method method = obj.getClass().getMethod(m, paramTemplate); Object[] param = new Object[1]; param[0] = p; method.invoke (obj, param); } else { Method method = obj.getClass().getMethod(m,null); method.invoke (obj,null); } } catch (NoSuchMethodException e) { } catch (NullPointerException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { throw new ConfigurationException ( obj.getClass().getName() + "." + m + "("+p.toString()+")" , ((Exception) e.getTargetException()) ); } } }
jpos6/modules/q2/src/org/jpos/q2/QFactory.java
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2008 Alejandro P. Revilla * * 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.jpos.q2; import java.io.File; import java.io.FileInputStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.MalformedURLException; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.MissingResourceException; import java.util.Properties; import java.util.ResourceBundle; import javax.management.Attribute; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; import javax.management.InstanceAlreadyExistsException; import javax.management.InstanceNotFoundException; import javax.management.InvalidAttributeValueException; import javax.management.MBeanException; import javax.management.MBeanRegistrationException; import javax.management.MBeanServer; import javax.management.MalformedObjectNameException; import javax.management.NotCompliantMBeanException; import javax.management.ObjectInstance; import javax.management.ObjectName; import javax.management.ReflectionException; import org.jdom.Element; import org.jpos.core.Configurable; import org.jpos.core.Configuration; import org.jpos.core.ConfigurationException; import org.jpos.core.SimpleConfiguration; import org.jpos.core.XmlConfigurable; import org.jpos.util.LogSource; import org.jpos.util.Logger; /** * @author <a href="mailto:[email protected]">Alireza Taherkordi</a> * @author <a href="mailto:[email protected]">Alejandro P. Revilla</a> * @version $Revision$ $Date$ */ public class QFactory { ObjectName loaderName; Q2 q2; ResourceBundle classMapping; public QFactory (ObjectName loaderName, Q2 q2) { super (); this.loaderName = loaderName; this.q2 = q2; classMapping = ResourceBundle.getBundle(this.getClass().getName()); } public Object instantiate (Q2 server, Element e) throws ReflectionException, MBeanException, InstanceNotFoundException { String clazz = e.getAttributeValue ("class"); if (clazz == null) { try { clazz = classMapping.getString (e.getName()); } catch (MissingResourceException ex) { // no class attribute, no mapping // let MBeanServer do the yelling } } MBeanServer mserver = server.getMBeanServer(); getExtraPath (server.getLoader (), e); return mserver.instantiate (clazz, loaderName); } public ObjectInstance createQBean (Q2 server, Element e, Object obj) throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedObjectNameException, MalformedURLException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException, MBeanException, NotCompliantMBeanException, InvalidAttributeValueException, ReflectionException, ConfigurationException { String name = e.getAttributeValue ("name"); if (name == null) name = e.getName (); ObjectName objectName = new ObjectName (Q2.QBEAN_NAME + name); MBeanServer mserver = server.getMBeanServer(); if(mserver.isRegistered(objectName)) { throw new InstanceAlreadyExistsException (name+" has already been deployed in another file."); } ObjectInstance instance = mserver.registerMBean ( obj, objectName ); try { setAttribute (mserver, objectName, "Name", name); String logger = e.getAttributeValue ("logger"); if (logger != null) setAttribute (mserver, objectName, "Logger", logger); setAttribute (mserver, objectName, "Server", server); setAttribute (mserver, objectName, "Persist", e); configureQBean(mserver,objectName,e); setConfiguration (obj, e); // handle legacy (QSP v1) Configurables if (obj instanceof QBean) mserver.invoke (objectName, "init", null, null); } catch (ConfigurationException ce) { mserver.unregisterMBean(objectName); throw ce; } return instance; } public Q2 getQ2() { return q2; } public void getExtraPath (QClassLoader loader, Element e) { Element classpathElement = e.getChild ("classpath"); if (classpathElement != null) { try { loader = loader.scan (true); // force a new classloader } catch (Throwable t) { getQ2().getLog().error(t); } Iterator iter = classpathElement.getChildren ("url").iterator(); while (iter.hasNext ()) { Element u = (Element) iter.next (); try { loader.addURL (u.getTextTrim ()); } catch (MalformedURLException ex) { q2.getLog().warn (u.getTextTrim(), ex); } } } } public void setAttribute (MBeanServer server, ObjectName objectName, String attribute, Object value) throws InstanceNotFoundException, MBeanException, InvalidAttributeValueException, ReflectionException { try { server.setAttribute ( objectName, new Attribute (attribute, value) ); } catch (AttributeNotFoundException ex) { // okay to fail } } public void startQBean (Q2 server, ObjectName objectName) throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedObjectNameException, MalformedURLException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException, MBeanException, NotCompliantMBeanException, InvalidAttributeValueException, ReflectionException { MBeanServer mserver = server.getMBeanServer(); mserver.invoke (objectName, "start", null, null); } public void destroyQBean (Q2 server, ObjectName objectName, Object obj) throws ClassNotFoundException, InstantiationException, IllegalAccessException, MalformedObjectNameException, MalformedURLException, InstanceAlreadyExistsException, MBeanRegistrationException, InstanceNotFoundException, MBeanException, NotCompliantMBeanException, InvalidAttributeValueException, ReflectionException { MBeanServer mserver = server.getMBeanServer(); if (obj instanceof QBean) { mserver.invoke (objectName, "stop", null, null); mserver.invoke (objectName, "destroy", null, null); } if (objectName != null) mserver.unregisterMBean (objectName); } public void configureQBean(MBeanServer server, ObjectName objectName, Element e) throws ConfigurationException { try { AttributeList attributeList = getAttributeList(e); Iterator attributes = attributeList.iterator(); while (attributes.hasNext()) server.setAttribute(objectName,(Attribute)attributes.next()); } catch (Exception e1) { throw new ConfigurationException(e1); } } public AttributeList getAttributeList(Element e) throws ConfigurationException { AttributeList attributeList = new AttributeList(); List childs = e.getChildren("attr"); Iterator childsIterator = childs.iterator(); while (childsIterator.hasNext()) { Element childElement = (Element)childsIterator.next(); String name = childElement.getAttributeValue("name"); name = getAttributeName(name); Attribute attr = new Attribute(name,getObject(childElement)); attributeList.add(attr); } return attributeList; } /** creates an object from a definition element. * The element may have an attribute called type indicating the type of the object * to create, if this attribute is not present java.lang.String is assumed. * int, long and boolean are converted to their wrappers. * @return The created object. * @param childElement Dom Element with the definition of the object. * @throws ConfigurationException If an exception is found trying to create the object. */ protected Object getObject(Element childElement) throws ConfigurationException { String type = childElement.getAttributeValue("type","java.lang.String"); if ("int".equals (type)) type = "java.lang.Integer"; else if ("long".equals (type)) type = "java.lang.Long"; else if ("boolean".equals (type)) type = "java.lang.Boolean"; String value = childElement.getText(); try { Class attributeType = Class.forName(type); if(Collection.class.isAssignableFrom(attributeType)) return getCollection(attributeType, childElement); else{ Class[] parameterTypes = {"".getClass()}; Object[] parameterValues = {value}; return attributeType.getConstructor(parameterTypes).newInstance(parameterValues); } } catch (Exception e1) { throw new ConfigurationException(e1); } } /** Creats a collection from a definition element with the format. * <PRE> * <{attr|item} type="..."> * <item [type="..."]>...</item> * ... * </attr> * </PRE> * @param type * @param e * @throws ConfigurationException * @return */ protected Collection getCollection(Class type, Element e) throws ConfigurationException { try{ Collection col = (Collection)type.newInstance(); Iterator childs = e.getChildren("item").iterator(); while(childs.hasNext()) col.add(getObject((Element)childs.next())); return col; }catch(Exception e1){ throw new ConfigurationException(e1); } } /** * sets the first character of the string to the upper case * @param name * @return attribute name */ public String getAttributeName(String name) { StringBuffer tmp = new StringBuffer(name); tmp.setCharAt(0,name.toUpperCase().charAt(0)) ; return tmp.toString(); } public Object newInstance (String clazz) throws ConfigurationException { try { MBeanServer mserver = q2.getMBeanServer(); return mserver.instantiate (clazz, loaderName); } catch (Exception e) { throw new ConfigurationException (clazz, e); } } public Configuration getConfiguration (Element e) throws ConfigurationException { Properties props = new Properties (); Iterator iter = e.getChildren ("property").iterator(); while (iter.hasNext()) { Element property = (Element) iter.next (); String name = property.getAttributeValue("name"); String value = property.getAttributeValue("value"); String file = property.getAttributeValue("file"); if (file != null) try { props.load (new FileInputStream (new File (file))); } catch (Exception ex) { throw new ConfigurationException (file, ex); } else if (name != null && value != null) { Object obj = props.get (name); if (obj instanceof String[]) { String[] mobj = (String[]) obj; String[] m = new String[mobj.length + 1]; System.arraycopy(mobj,0,m,0,mobj.length); m[mobj.length] = value; props.put (name, m); } else if (obj instanceof String) { String[] m = new String[2]; m[0] = (String) obj; m[1] = value; props.put (name, m); } else props.put (name, value); } } return new SimpleConfiguration (props); } public void setLogger (Object obj, Element e) { if (obj instanceof LogSource) { String loggerName = e.getAttributeValue ("logger"); if (loggerName != null) { String realm = e.getAttributeValue ("realm"); if (realm == null) realm = e.getName(); Logger logger = Logger.getLogger (loggerName); ((LogSource)obj).setLogger (logger, realm); } } } public void setConfiguration (Object obj, Element e) throws ConfigurationException { try { if (obj instanceof Configurable) ((Configurable)obj).setConfiguration (getConfiguration (e)); if (obj instanceof XmlConfigurable) ((XmlConfigurable)obj).setConfiguration(e); } catch (ConfigurationException ex) { throw new ConfigurationException (ex); } } /** * Try to invoke a method (usually a setter) on the given object * silently ignoring if method does not exist * @param obj the object * @param m method to invoke * @param p parameter * @throws ConfigurationException if method happens to throw an exception */ public static void invoke (Object obj, String m, Object p) throws ConfigurationException { invoke (obj, m, p, p != null ? p.getClass() : null); } /** * Try to invoke a method (usually a setter) on the given object * silently ignoring if method does not exist * @param obj the object * @param m method to invoke * @param p parameter * @param pc parameter class * @throws ConfigurationException if method happens to throw an exception */ public static void invoke (Object obj, String m, Object p, Class pc) throws ConfigurationException { try { if(p!=null){ Class[] paramTemplate = { pc }; Method method = obj.getClass().getMethod(m, paramTemplate); Object[] param = new Object[1]; param[0] = p; method.invoke (obj, param); }else{ Method method = obj.getClass().getMethod(m,null); method.invoke (obj,null); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (NullPointerException e) { } catch (IllegalAccessException e) { } catch (InvocationTargetException e) { throw new ConfigurationException ( obj.getClass().getName() + "." + m + "("+p.toString()+")" , ((Exception) e.getTargetException()) ); } } }
I'm removing Bharavi's call to e.printStackTrace() because a) we do a lot of Duck Typing and b) the output was going to stdout and got very noisy.
jpos6/modules/q2/src/org/jpos/q2/QFactory.java
I'm removing Bharavi's call to e.printStackTrace() because a) we do a lot of Duck Typing and b) the output was going to stdout and got very noisy.
<ide><path>pos6/modules/q2/src/org/jpos/q2/QFactory.java <ide> throws ConfigurationException <ide> { <ide> try { <del> if(p!=null){ <del> Class[] paramTemplate = { pc }; <del> Method method = obj.getClass().getMethod(m, paramTemplate); <del> Object[] param = new Object[1]; <del> param[0] = p; <del> method.invoke (obj, param); <del> }else{ <add> if (p!=null) { <add> Class[] paramTemplate = { pc }; <add> Method method = obj.getClass().getMethod(m, paramTemplate); <add> Object[] param = new Object[1]; <add> param[0] = p; <add> method.invoke (obj, param); <add> } else { <ide> Method method = obj.getClass().getMethod(m,null); <ide> method.invoke (obj,null); <ide> } <ide> } catch (NoSuchMethodException e) { <del> e.printStackTrace(); <ide> } catch (NullPointerException e) { <ide> } catch (IllegalAccessException e) { <ide> } catch (InvocationTargetException e) {
Java
mit
ebaef8aa228cf5529312f9fb750808e48ee96e2f
0
spixi/Dijkstra
/** * ConnectionVisualization * <p> * This widget is a visualization of the airport data model * * @author Marius Spix */ package de.bwv_aachen.dijkstra.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import de.bwv_aachen.dijkstra.controller.Controller; import de.bwv_aachen.dijkstra.helpers.Pathfinder; import de.bwv_aachen.dijkstra.model.Airport; public class ConnectionVisualization extends View implements ActionListener { private static final long serialVersionUID = 1527659470763038523L; private BufferedImage airportPicture; private final Dimension panelDimension = new Dimension(660,660); private final Color labelColor = Color.BLACK; private final Font labelFont = new Font("sans-serif", Font.BOLD, 14); private final ConnectionVisualizationMouseAdapter mouseAdapter = new ConnectionVisualizationMouseAdapter(this); private Point2D.Double picCenter; private HashMap<Airport,Point2D.Double> points; private HashMap<Rectangle2D.Double,Airport> actionAreas; private final JButton calcButton; private Airport startAirport = null; private Airport destinationAirport = null; private Collection<Airport> route = null; private final String space = " "; private JLabel statusText; private final double circleRadius = 200D; private VisualizationPanel visualizationPanel; public void setStartAirport(Airport ap) { this.startAirport = ap; this.route = null; } public void setDestinationAirport(Airport ap) { this.destinationAirport = ap; this.route = null; } public Airport getStartAirport() { return this.startAirport; } public Airport getDestinationAirport() { return this.destinationAirport; } public HashMap<Rectangle2D.Double,Airport> getActionAreas() { return this.actionAreas; } public ConnectionVisualization(Controller c) { super("ConnectionVisualization",c); try { //Let the controller do this? airportPicture = ImageIO.read(new File("res/airport-icon_2.gif")); } catch (IOException e) { //TODO System.out.println("Bild nicht gefunden"); } picCenter = new Point2D.Double(airportPicture.getWidth()/2, airportPicture.getHeight()/2); points = new HashMap<Airport,Point2D.Double>(); actionAreas = new HashMap<Rectangle2D.Double,Airport>(); //Pseudo initialization of the JPanel statusText = new JLabel(space); //Initialization of the JButton calcButton = new JButton("Berechnen"); calcButton.setActionCommand("calculate"); calcButton.addActionListener(this); visualizationPanel = new VisualizationPanel(); visualizationPanel.addMouseListener(mouseAdapter); visualizationPanel.addMouseMotionListener(mouseAdapter); } class VisualizationPanel extends JPanel { private static final long serialVersionUID = -3979908130673351633L; @Override public void paint(Graphics g) { try { //Some performance boosts (may lower the quality, will increase the performance) Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint( RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); g2d.setRenderingHint( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } catch (ClassCastException e) { } super.paint(g); // call superclass's paint //Causes recalculation on each change of the window size, position etc ... //determinePoints(); //No runtime-intensive calculations here, since this method is called a huge amount of times! g.setFont(labelFont); g.setColor(labelColor); for(Map.Entry<Airport, Point2D.Double> entry: points.entrySet()) { Airport a = entry.getKey(); Point2D.Double p = entry.getValue(); //Set paint mode on ... g.setColor(labelColor); g.setPaintMode(); //Paint the airport ... g.drawImage(airportPicture, (int)Math.round(p.x-picCenter.x), (int)Math.round(p.y-picCenter.y), this); //If the airport is the start or the destination airport, change the color if (a == ConnectionVisualization.this.startAirport) { g.setColor(Color.RED); } if (a == ConnectionVisualization.this.destinationAirport) { g.setColor(Color.CYAN); } //Paint the airport's name g.drawString(a.toString(), (int)Math.round(p.x), (int)Math.round(p.y)); //Set paint mode on ... g.setColor(labelColor); g.setPaintMode(); //Draw the connections to the destinations drawConnectionsOfAirport(a, g); } //Set the status text statusText.setText(getStatusText()); //Set the calculation button if (startAirport == null || destinationAirport == null) { calcButton.setEnabled(false); } else { //Only enable when startAirport and destinationAirport are selected calcButton.setEnabled(true); } //a given route is painted in green if (route != null) { Airport source = null, dest = null; g.setColor(Color.GREEN); Iterator<Airport> it = route.iterator(); while(it.hasNext()) { dest = it.next(); drawConnectionBetween(source, dest, g); source = dest; } } else { //No route is given. Assume that we are in selection mode //redraw the connections of the startAirport //Note: we are using XOR mode to show bidirectional connection as RED xor CYAN = WHITE !! g.setXORMode(Color.RED); drawConnectionsOfAirport(startAirport, g); //redraw the connections of the destinationAirport g.setXORMode(Color.CYAN); drawConnectionsOfAirport(destinationAirport, g); } } } /** * drawConnectionsOfAirport * <p> * Draws all connections of an airport * @param ap the airport * @param g which graphics instance should be used * * @author Marius Spix */ private void drawConnectionsOfAirport(Airport ap, Graphics g) { //do nothing if ap is null if (ap == null) { return; } for(Airport dest: ap.getConnections().keySet()) { //Draw the connections to the destinations drawConnectionBetween(ap, dest, g); } } /** * drawConnectionsBetween * <p> * Draws a single connection between two airports * @param source the source airport * @param dest the destination airport * @param g which graphics instance should be used * * @author Marius Spix */ private void drawConnectionBetween(Airport source, Airport dest, Graphics g) { Point2D.Double sourceP, destP; //return if the source or the destination is null if (source == null || dest == null) { return; } sourceP = points.get(source); destP = points.get(dest); g.drawLine((int)Math.round(sourceP.x), (int)Math.round(sourceP.y), (int)Math.round(destP.x), (int)Math.round(destP.y)); } @Override public void draw() { this.getContentPane().removeAll(); reset(); JPanel statusbar = new JPanel(); statusbar.setLayout(new FlowLayout(FlowLayout.LEFT)); statusbar.add(statusText); statusbar.add(calcButton); if (startAirport != null && destinationAirport != null) { calcButton.setEnabled(true); } this.getContentPane().add(statusbar, BorderLayout.SOUTH); this.setMinimumSize(panelDimension); this.getContentPane().add(visualizationPanel); if ( points.isEmpty() ) { //determine the points for the airports determinePoints(); } super.setLocationRelativeTo(null); this.setVisible(true); } /** * reset * <p> * Resets metadata of the ConnectionVisualization instance * (startAirport, destinationAirport and route respectively) * * @author Marius Spix */ public void reset() { this.startAirport = null; this.destinationAirport = null; this.route = null; } /** * getStatusText * <p> * Determines a text for the statusbar depending on which of the fields * startAirport and destinationAirport are selected. * @author Marius Spix */ public String getStatusText() { String statusTextValue; if(startAirport != null) { statusTextValue = "Verbindung von " + startAirport.getName(); if(destinationAirport != null) { statusTextValue += " nach " + destinationAirport.getName(); } } else { statusTextValue = space; } return statusTextValue; } /** * determinePoints * <p> * Determines the points where the airport images are put. They are arranged in a circle with the same distance to each neighbor * @author Marius Spix */ //The controller may also call this method. So we make it public! public void determinePoints() { //Here is a bug. After you change your selection it the Mainwindow selectboxes the points are invalid. Why??? Object[] airports = controller.getModel().getAirportList().values().toArray(); Point panelCenter = new Point(this.getWidth()/2, this.getHeight()/2); points.clear(); int numOfNodes = airports.length; if (numOfNodes == 0) return; final double angle = Math.toRadians( 360D / numOfNodes ); for (int i = 0; i < numOfNodes; i++) { double alpha = angle * i; //The points are arranged in a n-gon with the radius circleRadius double x = panelCenter.x + Math.sin(alpha) * circleRadius; double y = panelCenter.y - Math.cos(alpha) * circleRadius; //Remember the points for further use points.put((Airport) airports[i], new Point2D.Double(x,y)); //create actionAreas for catching mouse events actionAreas.clear(); for(Map.Entry<Airport, Point2D.Double> entry: points.entrySet()) { Airport a = entry.getKey(); Point2D.Double p = entry.getValue(); actionAreas.put( new Rectangle2D.Double(p.x-picCenter.x, p.y-picCenter.y, airportPicture.getHeight(), airportPicture.getWidth()), a); } } } public void actionPerformed(ActionEvent ev) { switch (ev.getActionCommand()) { case "calculate": route = new Pathfinder(startAirport,points.keySet()).determineShortestPathTo(destinationAirport); this.getContentPane().repaint(); Vector<Vector<Object>> tData = controller.getModel().getRoute(startAirport, destinationAirport); new ConnectionTableWindow(tData).draw(); break; } } }
src/de/bwv_aachen/dijkstra/gui/ConnectionVisualization.java
/** * ConnectionVisualization * <p> * This widget is a visualization of the airport data model * * @author Marius Spix */ package de.bwv_aachen.dijkstra.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Vector; import javax.imageio.ImageIO; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import de.bwv_aachen.dijkstra.controller.Controller; import de.bwv_aachen.dijkstra.helpers.Pathfinder; import de.bwv_aachen.dijkstra.model.Airport; public class ConnectionVisualization extends View implements ActionListener { private static final long serialVersionUID = 1527659470763038523L; private BufferedImage airportPicture; private final Dimension panelDimension = new Dimension(660,660); private final Color labelColor = Color.BLACK; private final Font labelFont = new Font("sans-serif", Font.BOLD, 14); private final ConnectionVisualizationMouseAdapter mouseAdapter = new ConnectionVisualizationMouseAdapter(this); private Point2D.Double picCenter; private HashMap<Airport,Point2D.Double> points; private HashMap<Rectangle2D.Double,Airport> actionAreas; private final JButton calcButton; private Airport startAirport = null; private Airport destinationAirport = null; private Collection<Airport> route = null; private final String space = " "; private JLabel statusText; private final double circleRadius = 200D; private VisualizationPanel visualizationPanel; public void setStartAirport(Airport ap) { this.startAirport = ap; this.route = null; } public void setDestinationAirport(Airport ap) { this.destinationAirport = ap; this.route = null; } public Airport getStartAirport() { return this.startAirport; } public Airport getDestinationAirport() { return this.destinationAirport; } public HashMap<Rectangle2D.Double,Airport> getActionAreas() { return this.actionAreas; } public ConnectionVisualization(Controller c) { super("ConnectionVisualization",c); try { //Let the controller do this? airportPicture = ImageIO.read(new File("res/airport-icon_2.gif")); } catch (IOException e) { //TODO System.out.println("Bild nicht gefunden"); } picCenter = new Point2D.Double(airportPicture.getWidth()/2, airportPicture.getHeight()/2); points = new HashMap<Airport,Point2D.Double>(); actionAreas = new HashMap<Rectangle2D.Double,Airport>(); //Pseudo initialization of the JPanel statusText = new JLabel(space); //Initialization of the JButton calcButton = new JButton("Berechnen"); calcButton.setActionCommand("calculate"); calcButton.addActionListener(this); visualizationPanel = new VisualizationPanel(); visualizationPanel.addMouseListener(mouseAdapter); visualizationPanel.addMouseMotionListener(mouseAdapter); } class VisualizationPanel extends JPanel { private static final long serialVersionUID = -3979908130673351633L; @Override public void paint(Graphics g) { try { //Some performance boosts (may lower the quality, will increase the performance) Graphics2D g2d = (Graphics2D) g; g2d.setRenderingHint( RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_DISABLE); g2d.setRenderingHint( RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_SPEED); g2d.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); g2d.setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } catch (ClassCastException e) { } super.paint(g); // call superclass's paint //Causes recalculation on each change of the window size, position etc ... //determinePoints(); //No runtime-intensive calculations here, since this method is called a huge amount of times! g.setFont(labelFont); g.setColor(labelColor); for(Map.Entry<Airport, Point2D.Double> entry: points.entrySet()) { Airport a = entry.getKey(); Point2D.Double p = entry.getValue(); //Set paint mode on ... g.setColor(labelColor); g.setPaintMode(); //Paint the airport ... g.drawImage(airportPicture, (int)Math.round(p.x-picCenter.x), (int)Math.round(p.y-picCenter.y), this); //If the airport is the start or the destination airport, change the color if (a == ConnectionVisualization.this.startAirport) { g.setColor(Color.RED); } if (a == ConnectionVisualization.this.destinationAirport) { g.setColor(Color.CYAN); } //Paint the airport's name g.drawString(a.toString(), (int)Math.round(p.x), (int)Math.round(p.y)); //Set paint mode on ... g.setColor(labelColor); g.setPaintMode(); //Draw the connections to the destinations drawConnectionsOfAirport(a, g); } //Set the status text statusText.setText(getStatusText()); //Set the calculation button if (startAirport == null || destinationAirport == null) { calcButton.setEnabled(false); } else { //Only enable when startAirport and destinationAirport are selected calcButton.setEnabled(true); } //a given route is painted in green if (route != null) { Airport source = null, dest = null; g.setColor(Color.GREEN); Iterator<Airport> it = route.iterator(); while(it.hasNext()) { dest = it.next(); drawConnectionBetween(source, dest, g); source = dest; } } else { //No route is given. Assume that we are in selection mode //redraw the connections of the startAirport //Note: we are using XOR mode to show bidirectional connection as RED xor CYAN = WHITE !! g.setXORMode(Color.RED); drawConnectionsOfAirport(startAirport, g); //redraw the connections of the destinationAirport g.setXORMode(Color.CYAN); drawConnectionsOfAirport(destinationAirport, g); } } } /** * drawConnectionsOfAirport * <p> * Draws all connections of an airport * @param ap the airport * @param g which graphics instance should be used * * @author Marius Spix */ private void drawConnectionsOfAirport(Airport ap, Graphics g) { //do nothing if ap is null if (ap == null) { return; } for(Airport dest: ap.getConnections().keySet()) { //Draw the connections to the destinations drawConnectionBetween(ap, dest, g); } } /** * drawConnectionsBetween * <p> * Draws a single connection between two airports * @param source the source airport * @param dest the destination airport * @param g which graphics instance should be used * * @author Marius Spix */ private void drawConnectionBetween(Airport source, Airport dest, Graphics g) { Point2D.Double sourceP, destP; //return if the source or the destination is null if (source == null || dest == null) { return; } sourceP = points.get(source); destP = points.get(dest); g.drawLine((int)Math.round(sourceP.x), (int)Math.round(sourceP.y), (int)Math.round(destP.x), (int)Math.round(destP.y)); } @Override public void draw() { this.getContentPane().removeAll(); reset(); JPanel statusbar = new JPanel(); statusbar.setLayout(new FlowLayout(FlowLayout.LEFT)); statusbar.add(statusText); statusbar.add(calcButton); if (startAirport != null && destinationAirport != null) { calcButton.setEnabled(true); } this.getContentPane().add(statusbar, BorderLayout.SOUTH); this.setMinimumSize(panelDimension); this.getContentPane().add(visualizationPanel); if ( points.isEmpty() ) { //determine the points for the airports determinePoints(); } super.setLocationRelativeTo(null); this.setVisible(true); } /** * reset * <p> * Resets metadata of the ConnectionVisualization instance * (startAirport, destinationAirport and route respectively) * * @author Marius Spix */ public void reset() { this.startAirport = null; this.destinationAirport = null; this.route = null; } /** * getStatusText * <p> * Determines a text for the statusbar depending on which of the fields * startAirport and destinationAirport are selected. * @author Marius Spix */ public String getStatusText() { String statusTextValue; if(startAirport != null) { statusTextValue = "Verbindung von " + startAirport.getName(); if(destinationAirport != null) { statusTextValue += " nach " + destinationAirport.getName(); } } else { statusTextValue = space; } return statusTextValue; } /** * determinePoints * <p> * Determines the points where the airport images are put. They are arranged in a circle with the same distance to each neighbor * @author Marius Spix */ //The controller may also call this method. So we make it public! public void determinePoints() { //Here is a bug. After you change your selection it the Mainwindow selectboxes the points are invalid. Why??? Object[] airports = controller.getModel().getAirportList().values().toArray(); Point panelCenter = new Point(this.getWidth()/2, this.getHeight()/2); points.clear(); int numOfNodes = airports.length; if (numOfNodes == 0) return; final double angle = Math.toRadians( 360D / numOfNodes ); for (int i = 0; i < numOfNodes; i++) { double alpha = angle * i; //The points are arranged in a n-gon with the radius circleRadius double x = panelCenter.x + Math.sin(alpha) * circleRadius; double y = panelCenter.y - Math.cos(alpha) * circleRadius; //Remember the points for further use points.put((Airport) airports[i], new Point2D.Double(x,y)); //create actionAreas for catching mouse events actionAreas.clear(); for(Map.Entry<Airport, Point2D.Double> entry: points.entrySet()) { Airport a = entry.getKey(); Point2D.Double p = entry.getValue(); actionAreas.put( new Rectangle2D.Double(p.x-picCenter.x, p.y-picCenter.y, airportPicture.getHeight(), airportPicture.getWidth()), a); } } } public void actionPerformed(ActionEvent ev) { switch (ev.getActionCommand()) { case "calculate": Vector<Vector<Object>> tData = controller.getModel().getRoute(startAirport, destinationAirport); new ConnectionTableWindow(tData).draw(); break; } } }
fixed the line color issu
src/de/bwv_aachen/dijkstra/gui/ConnectionVisualization.java
fixed the line color issu
<ide><path>rc/de/bwv_aachen/dijkstra/gui/ConnectionVisualization.java <ide> <ide> public void actionPerformed(ActionEvent ev) { <ide> switch (ev.getActionCommand()) { <del> case "calculate": <add> case "calculate": <add> route = new Pathfinder(startAirport,points.keySet()).determineShortestPathTo(destinationAirport); <add> this.getContentPane().repaint(); <add> <add> <ide> Vector<Vector<Object>> tData = controller.getModel().getRoute(startAirport, destinationAirport); <ide> new ConnectionTableWindow(tData).draw(); <ide> break;
Java
lgpl-2.1
96fe88243b994dbcb9d4e0d335ecf788d2466b13
0
kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe,kaffe/kaffe
/** * Test socket timeouts for accept and read for simple stream sockets * * @author Godmar Back <[email protected]> */ import java.net.*; import java.io.*; public class SoTimeout { public static void main(String av[]) throws Exception { final String foo = "foo"; int tryport = 45054; ServerSocket server; for(;;++tryport) { try { server = new ServerSocket(tryport); break; } catch (IOException _) {} } final int port = tryport; Thread watchdog = new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException _) { } System.out.println("Failure: Time out."); System.exit(-1); } }; watchdog.start(); Thread t = new Thread() { public void run() { try { Socket s = new Socket(InetAddress.getLocalHost(), port); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Failure " + e); } PrintWriter p = new PrintWriter(s.getOutputStream()); p.println(foo); p.close(); } catch (Exception e) { System.out.println("Failure " + e); } } }; server.setSoTimeout(1000); Socket rsocket = null; try { rsocket = server.accept(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 1."); } t.start(); rsocket = server.accept(); System.out.println("Success 2."); rsocket.setSoTimeout(2000); // NB: 2 * 2000 > 3000 InputStream is = rsocket.getInputStream(); LineNumberReader r = new LineNumberReader(new InputStreamReader(is)); byte []b = null; try { r.readLine(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 3."); } String s = r.readLine(); if (s.equals(foo)) { System.out.println("Success 4."); } System.exit(0); } } /* Expected Output: Success 1. Success 2. Success 3. Success 4. */
test/regression/SoTimeout.java
/** * Test socket timeouts for accept and read for simple stream sockets * * @author Godmar Back <[email protected]> */ import java.net.*; import java.io.*; public class SoTimeout { public static void main(String av[]) throws Exception { final String foo = "foo"; int tryport = 45054; ServerSocket server; for(;;++tryport) { try { server = new ServerSocket(tryport); break; } catch (IOException _) {} } final int port = tryport; Thread watchdog = new Thread() { public void run() { try { Thread.sleep(10000); } catch (InterruptedException _) { } System.out.println("Failure: Time out."); System.exit(-1); } }; watchdog.start(); Thread t = new Thread() { public void run() { try { Socket s = new Socket(InetAddress.getLocalHost(), port); try { Thread.sleep(3000); } catch (InterruptedException e) { System.out.println("Failure " + e); } PrintWriter p = new PrintWriter(s.getOutputStream()); p.println(foo); p.close(); } catch (Exception e) { System.out.println("Failure " + e); } } }; server.setSoTimeout(1000); Socket rsocket = null; try { rsocket = server.accept(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 1."); } t.start(); rsocket = server.accept(); System.out.println("Success 2."); rsocket.setSoTimeout(2000); // NB: 2 * 2000 > 3000 InputStream is = rsocket.getInputStream(); LineNumberReader r = new LineNumberReader(new InputStreamReader(is)); byte []b = null; try { r.readLine(); } catch (InterruptedIOException e) { // System.out.println(e); System.out.println("Success 3."); } String s = r.readLine(); if (s.equals(foo)) { System.out.println("Success 4."); } } } /* Expected Output: Success 1. Success 2. Success 3. Success 4. */
* Fixed watchdog timeout.
test/regression/SoTimeout.java
* Fixed watchdog timeout.
<ide><path>est/regression/SoTimeout.java <ide> if (s.equals(foo)) { <ide> System.out.println("Success 4."); <ide> } <add> System.exit(0); <ide> } <ide> } <ide>
JavaScript
agpl-3.0
3500cfd0d90b617a9744173e63e63790cc6588c9
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
/* * (c) Copyright Ascensio System SIA 2010-2017 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; (/** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { /* * Import * ----------------------------------------------------------------------------- */ var CellValueType = AscCommon.CellValueType; var c_oAscBorderStyles = AscCommon.c_oAscBorderStyles; var c_oAscBorderType = AscCommon.c_oAscBorderType; var c_oAscLockTypes = AscCommon.c_oAscLockTypes; var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState; var c_oAscPrintDefaultSettings = AscCommon.c_oAscPrintDefaultSettings; var AscBrowser = AscCommon.AscBrowser; var CColor = AscCommon.CColor; var fSortAscending = AscCommon.fSortAscending; var parserHelp = AscCommon.parserHelp; var gc_nMaxDigCountView = AscCommon.gc_nMaxDigCountView; var gc_nMaxRow0 = AscCommon.gc_nMaxRow0; var gc_nMaxCol0 = AscCommon.gc_nMaxCol0; var gc_nMaxRow = AscCommon.gc_nMaxRow; var gc_nMaxCol = AscCommon.gc_nMaxCol; var History = AscCommon.History; var asc = window["Asc"]; var asc_applyFunction = AscCommonExcel.applyFunction; var asc_calcnpt = asc.calcNearestPt; var asc_getcvt = asc.getCvtRatio; var asc_floor = asc.floor; var asc_ceil = asc.ceil; var asc_obj2Color = asc.colorObjToAscColor; var asc_typeof = asc.typeOf; var asc_incDecFonSize = asc.incDecFonSize; var asc_debug = asc.outputDebugStr; var asc_Range = asc.Range; var asc_CMM = AscCommonExcel.asc_CMouseMoveData; var asc_VR = AscCommonExcel.VisibleRange; var asc_CFont = AscCommonExcel.asc_CFont; var asc_CFill = AscCommonExcel.asc_CFill; var asc_CCellInfo = AscCommonExcel.asc_CCellInfo; var asc_CHyperlink = asc.asc_CHyperlink; var asc_CPageOptions = asc.asc_CPageOptions; var asc_CPageSetup = asc.asc_CPageSetup; var asc_CPageMargins = asc.asc_CPageMargins; var asc_CPagePrint = AscCommonExcel.CPagePrint; var asc_CAutoFilterInfo = AscCommonExcel.asc_CAutoFilterInfo; var c_oTargetType = AscCommonExcel.c_oTargetType; var c_oAscCanChangeColWidth = AscCommonExcel.c_oAscCanChangeColWidth; var c_oAscLockTypeElemSubType = AscCommonExcel.c_oAscLockTypeElemSubType; var c_oAscLockTypeElem = AscCommonExcel.c_oAscLockTypeElem; var c_oAscGraphicOption = AscCommonExcel.c_oAscGraphicOption; var c_oAscError = asc.c_oAscError; var c_oAscMergeOptions = asc.c_oAscMergeOptions; var c_oAscInsertOptions = asc.c_oAscInsertOptions; var c_oAscDeleteOptions = asc.c_oAscDeleteOptions; var c_oAscBorderOptions = asc.c_oAscBorderOptions; var c_oAscCleanOptions = asc.c_oAscCleanOptions; var c_oAscSelectionType = asc.c_oAscSelectionType; var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType; var c_oAscAutoFilterTypes = asc.c_oAscAutoFilterTypes; var c_oAscChangeTableStyleInfo = asc.c_oAscChangeTableStyleInfo; var c_oAscChangeSelectionFormatTable = asc.c_oAscChangeSelectionFormatTable; var asc_CSelectionMathInfo = AscCommonExcel.asc_CSelectionMathInfo; var vector_koef = AscCommonExcel.vector_koef; /* * Constants * ----------------------------------------------------------------------------- */ /** * header styles * @const */ var kHeaderDefault = 0; var kHeaderActive = 1; var kHeaderHighlighted = 2; /** * cursor styles * @const */ var kCurDefault = "default"; var kCurCorner = "pointer"; var kCurColSelect = "pointer"; var kCurColResize = "col-resize"; var kCurRowSelect = "pointer"; var kCurRowResize = "row-resize"; // Курсор для автозаполнения var kCurFillHandle = "crosshair"; // Курсор для гиперссылки var kCurHyperlink = "pointer"; // Курсор для перемещения области выделения var kCurMove = "move"; var kCurSEResize = "se-resize"; var kCurNEResize = "ne-resize"; var kCurAutoFilter = "pointer"; var kCurCells = ''; var kCurFormatPainterExcel = ''; if (AscBrowser.isIE) { // Пути указаны относительно html в меню, не надо их исправлять // и коммитить на пути относительно тестового меню var cursorRetina = AscBrowser.isRetina ? '_2x' : ''; cursorRetina = ''; // ToDo 2x cursors kCurCells = 'url(../../../../sdkjs/common/Images/plus' + cursorRetina + '.cur), pointer'; kCurFormatPainterExcel = 'url(../../../../sdkjs/common/Images/plus_copy' + cursorRetina + '.cur), pointer'; } else if (AscBrowser.isOpera) { kCurCells = 'cell'; kCurFormatPainterExcel = 'pointer'; } else { // ToDo 2x cursors /*if (AscBrowser.isRetina) { kCurCells = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGtJREFUeNpidHFxYSAS/Ccgz0iMIUwMdAYspGrYvXs3Ct/V1ZUk/XT34aiFoxYOfgtZiChBqFUSDXBJg16CkFvy4AKwEmk0ldIuDokt9YdcbcFCbE09ZGv8UQtHLRxCJQ2xgNSSZcB9CBBgAA9FEd4uFbt8AAAAAElFTkSuQmCC') 12 12, pointer"; kCurFormatPainterExcel = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAAqCAYAAADFw8lbAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAASFJREFUeNrsmU0SgyAMhQnD0eDUcre4KU5EwMQpf0pW2kX7zePlJVpARDVD6YHZcAZQjGH1qJDW2tO9HhmSwpre3ouLwCnvfbgEPQOkUkqZjt7LVoC01kK4hkY5KoYMSoYyPSAJTPLYewQ+C5JTphUkBUx9NswIjbNRqixwDM6Jltj827Zlm6jk0Vwz1VYUOOpxxBJ79KfUUc45Dix670/HT7LyNppaehRSDcWFrAqaOM6sDegkGmVxvsBSJUtergZa+NEDlqNkM0VjLyZ8CJxMrTaZQhoAwOmepAZIvm/kh7uLov/a81DSUG96XE57NJ44TyfVnWff+AJigbbxKNdDD7an7ynKzTXRhr+aaYEu0AX6tckk3dyXorlpMssfYvsAnpmCy8p26IoAAAAASUVORK5CYII=') 12 25, pointer"; } else {*/ kCurCells = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAFJJREFUeNpidHFxYcAC/qPxGdEVMDHgALt37wZjXACnRkKA/hpZsAQEMYHFwAAM1f+kApAeipzK4OrqijU6cMnBNDJSNQEMznjECnAFCgwABBgAcX1BU/hbd0sAAAAASUVORK5CYII=') 6 6, pointer"; kCurFormatPainterExcel = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAUCAYAAABiS3YzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAK1JREFUeNrUk+ESxBAMhG3Hm+GpeTfF0Eld0uLcj9uZTP3xdZMsxBjVRhXYsRNora2n5HSxbjLGtKPSX7uqCiHkD1adUlcfLnMdKw6zq94plXbOiVskKm1575GAF1iS6DQBSjECdUp+gFcoJ9LyBe6B09BuluCA09A8fwCK7AHsopiljCxOBLY5xVnVO2KWd779W/uKy2qLk5DjVyhGwz+qn7T/P1D9FPRVnQIMABDnBAmTp4GtAAAAAElFTkSuQmCC') 6 12, pointer"; //} } var kNewLine = "\n"; var kMaxAutoCompleteCellEdit = 20000; function CacheElement() { if (!(this instanceof CacheElement)) { return new CacheElement(); } this.columnsWithText = {}; // Колонки, в которых есть текст this.columns = {}; this.erased = {}; return this; } function Cache() { if (!(this instanceof Cache)) { return new Cache(); } this.rows = {}; this.sectors = []; this.reset = function () { this.rows = {}; this.sectors = []; }; // Structure of cache // // cache : { // // rows : { // 0 : { // columns : { // 0 : { // text : { // cellHA : String, // cellVA : String, // cellW : Number, // color : String, // metrics : TextMetrics, // sideL : Number, // sideR : Number, // state : StringRenderInternalState // } // } // }, // erased : { // 1 : true, 2 : true // } // } // }, // // sectors: [ // 0 : Range // ] // // } } function CellFlags() { this.wrapText = false; this.shrinkToFit = false; this.merged = null; this.textAlign = null; } CellFlags.prototype.clone = function () { var oRes = new CellFlags(); oRes.wrapText = this.wrapText; oRes.shrinkToFit = this.shrinkToFit; oRes.merged = this.merged ? this.merged.clone() : null; oRes.textAlign = this.textAlign; return oRes; }; CellFlags.prototype.isMerged = function () { return null !== this.merged; }; function CellBorderObject(borders, mergeInfo, col, row) { this.borders = borders; this.mergeInfo = mergeInfo; this.col = col; this.row = row; } CellBorderObject.prototype.isMerge = function () { return null != this.mergeInfo; }; CellBorderObject.prototype.getLeftBorder = function () { if (!this.borders || (this.isMerge() && (this.col !== this.mergeInfo.c1 || this.col - 1 !== this.mergeInfo.c2))) { return null; } return this.borders.l; }; CellBorderObject.prototype.getRightBorder = function () { if (!this.borders || (this.isMerge() && (this.col - 1 !== this.mergeInfo.c1 || this.col !== this.mergeInfo.c2))) { return null; } return this.borders.r; }; CellBorderObject.prototype.getTopBorder = function () { if (!this.borders || (this.isMerge() && (this.row !== this.mergeInfo.r1 || this.row - 1 !== this.mergeInfo.r2))) { return null; } return this.borders.t; }; CellBorderObject.prototype.getBottomBorder = function () { if (!this.borders || (this.isMerge() && (this.row - 1 !== this.mergeInfo.r1 || this.row !== this.mergeInfo.r2))) { return null; } return this.borders.b; }; /** * Widget for displaying and editing Worksheet object * ----------------------------------------------------------------------------- * @param {Worksheet} model Worksheet * @param {AscCommonExcel.asc_CHandlersList} handlers Event handlers * @param {Object} buffers DrawingContext + Overlay * @param {AscCommonExcel.StringRender} stringRender StringRender * @param {Number} maxDigitWidth Максимальный размер цифры * @param {CCollaborativeEditing} collaborativeEditing * @param {Object} settings Settings * * @constructor * @memberOf Asc */ function WorksheetView(model, handlers, buffers, stringRender, maxDigitWidth, collaborativeEditing, settings) { this.settings = settings; this.vspRatio = 1.275; this.handlers = handlers; this.model = model; this.buffers = buffers; this.drawingCtx = this.buffers.main; this.overlayCtx = this.buffers.overlay; this.drawingGraphicCtx = this.buffers.mainGraphic; this.overlayGraphicCtx = this.buffers.overlayGraphic; this.shapeCtx = this.buffers.shapeCtx; this.shapeOverlayCtx = this.buffers.shapeOverlayCtx; this.stringRender = stringRender; // Флаг, сигнализирует о том, что мы сделали resize, но это не активный лист (поэтому как только будем показывать, нужно перерисовать и пересчитать кеш) this.updateResize = false; // Флаг, сигнализирует о том, что мы сменили zoom, но это не активный лист (поэтому как только будем показывать, нужно перерисовать и пересчитать кеш) this.updateZoom = false; // ToDo Флаг-заглушка, для того, чтобы на mobile не было изменения высоты строк при zoom (по правильному высота просто не должна меняться) this.notUpdateRowHeight = false; this.cache = new Cache(); //---member declaration--- // Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое) // Ecma-376 Office Open XML Part 1, пункт 18.3.1.13 this.maxDigitWidth = maxDigitWidth; this.defaultColWidthChars = 0; this.defaultColWidth = 0; this.defaultRowHeight = 0; this.defaultRowDescender = 0; this.headersLeft = 0; this.headersTop = 0; this.headersWidth = 0; this.headersHeight = 0; this.headersHeightByFont = 0; // Размер по шрифту (размер без скрытия заголовков) this.cellsLeft = 0; this.cellsTop = 0; this.cols = []; this.rows = []; this.width_1px = 0; this.width_2px = 0; this.width_3px = 0; this.width_4px = 0; this.width_padding = 0; this.height_1px = 0; this.height_2px = 0; this.height_3px = 0; this.height_4px = 0; this.highlightedCol = -1; this.highlightedRow = -1; this.topLeftFrozenCell = null; // Верхняя ячейка для закрепления диапазона this.visibleRange = new asc_Range(0, 0, 0, 0); this.isChanged = false; this.isCellEditMode = false; this.isFormulaEditMode = false; this.isChartAreaEditMode = false; this.lockDraw = false; this.isSelectOnShape = false; // Выделен shape this.stateFormatPainter = c_oAscFormatPainterState.kOff; this.selectionDialogType = c_oAscSelectionDialogType.None; this.isSelectionDialogMode = false; this.copyActiveRange = null; this.startCellMoveResizeRange = null; this.startCellMoveResizeRange2 = null; this.moveRangeDrawingObjectTo = null; // Координаты ячейки начала перемещения диапазона this.startCellMoveRange = null; // Дипазон перемещения this.activeMoveRange = null; // Range fillHandle this.activeFillHandle = null; // Горизонтальное (0) или вертикальное (1) направление автозаполнения this.fillHandleDirection = -1; // Зона автозаполнения this.fillHandleArea = -1; this.nRowsCount = 0; this.nColsCount = 0; // Массив ячеек для текущей формулы this.arrActiveFormulaRanges = []; this.arrActiveFormulaRangesPosition = -1; this.arrActiveChartRanges = [new AscCommonExcel.SelectionRange(this.model)]; //------------------------ this.collaborativeEditing = collaborativeEditing; this.drawingArea = new AscFormat.DrawingArea(this); this.cellCommentator = new AscCommonExcel.CCellCommentator(this); this.objectRender = null; this._init(); return this; } WorksheetView.prototype.getCellVisibleRange = function (col, row) { var vr, offsetX = 0, offsetY = 0, cFrozen, rFrozen; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0() - 1; rFrozen = this.topLeftFrozenCell.getRow0() - 1; if (col <= cFrozen && row <= rFrozen) { vr = new asc_Range(0, 0, cFrozen, rFrozen); } else if (col <= cFrozen) { vr = new asc_Range(0, this.visibleRange.r1, cFrozen, this.visibleRange.r2); offsetY -= this.rows[rFrozen + 1].top - this.cellsTop; } else if (row <= rFrozen) { vr = new asc_Range(this.visibleRange.c1, 0, this.visibleRange.c2, rFrozen); offsetX -= this.cols[cFrozen + 1].left - this.cellsLeft; } else { vr = this.visibleRange; offsetX -= this.cols[cFrozen + 1].left - this.cellsLeft; offsetY -= this.rows[rFrozen + 1].top - this.cellsTop; } } else { vr = this.visibleRange; } offsetX += this.cols[vr.c1].left - this.cellsLeft; offsetY += this.rows[vr.r1].top - this.cellsTop; return vr.contains(col, row) ? new asc_VR(vr, offsetX, offsetY) : null; }; WorksheetView.prototype.getCellMetrics = function (col, row) { var vr, nColSize, nRowSize; if (vr = this.getCellVisibleRange(col, row)) { nColSize = this.getColSize(col); nRowSize = this.getRowSize(row); if (nColSize && nRowSize) { return { left: nColSize.left - vr.offsetX, top: nRowSize.top - vr.offsetY, width: nColSize.width, height: nRowSize.height }; } } return null; }; WorksheetView.prototype.getColSize = function (col) { return (col >= 0 && col < this.cols.length) ? this.cols[col] : null; }; WorksheetView.prototype.getRowSize = function (row) { return (row >= 0 && row < this.rows.length) ? this.rows[row] : null; }; WorksheetView.prototype.getFrozenCell = function () { return this.topLeftFrozenCell; }; WorksheetView.prototype.getVisibleRange = function () { return this.visibleRange; }; WorksheetView.prototype.updateVisibleRange = function () { return this._updateCellsRange(this.getVisibleRange()); }; WorksheetView.prototype.getFirstVisibleCol = function (allowPane) { var tmp = 0; if (allowPane && this.topLeftFrozenCell) { tmp = this.topLeftFrozenCell.getCol0(); } return this.visibleRange.c1 - tmp; }; WorksheetView.prototype.getLastVisibleCol = function () { return this.visibleRange.c2; }; WorksheetView.prototype.getFirstVisibleRow = function (allowPane) { var tmp = 0; if (allowPane && this.topLeftFrozenCell) { tmp = this.topLeftFrozenCell.getRow0(); } return this.visibleRange.r1 - tmp; }; WorksheetView.prototype.getLastVisibleRow = function () { return this.visibleRange.r2; }; WorksheetView.prototype.getHorizontalScrollRange = function () { var ctxW = this.drawingCtx.getWidth() - this.cellsLeft; for (var w = 0, i = this.cols.length - 1; i >= 0; --i) { w += this.cols[i].width; if (w > ctxW) { break; } } return i; // Диапазон скрола должен быть меньше количества столбцов, чтобы не было прибавления столбцов при перетаскивании бегунка }; WorksheetView.prototype.getVerticalScrollRange = function () { var ctxH = this.drawingCtx.getHeight() - this.cellsTop; for (var h = 0, i = this.rows.length - 1; i >= 0; --i) { h += this.rows[i].height; if (h > ctxH) { break; } } return i; // Диапазон скрола должен быть меньше количества строк, чтобы не было прибавления строк при перетаскивании бегунка }; WorksheetView.prototype.getCellsOffset = function (units) { var u = units >= 0 && units <= 3 ? units : 0; return { left: this.cellsLeft * asc_getcvt(1/*pt*/, u, this._getPPIX()), top: this.cellsTop * asc_getcvt(1/*pt*/, u, this._getPPIY()) }; }; WorksheetView.prototype.getCellLeft = function (column, units) { if (column >= 0 && column < this.cols.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.cols[column].left * asc_getcvt(1/*pt*/, u, this._getPPIX()); } return null; }; WorksheetView.prototype.getCellTop = function (row, units) { if (row >= 0 && row < this.rows.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.rows[row].top * asc_getcvt(1/*pt*/, u, this._getPPIY()); } return null; }; WorksheetView.prototype.getCellLeftRelative = function (col, units) { if (col < 0 || col >= this.cols.length) { return null; } // С учетом видимой области var offsetX = 0; if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0(); offsetX = (col < cFrozen) ? 0 : this.cols[this.visibleRange.c1].left - this.cols[cFrozen].left; } else { offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; } var u = units >= 0 && units <= 3 ? units : 0; return (this.cols[col].left - offsetX) * asc_getcvt(1/*pt*/, u, this._getPPIX()); }; WorksheetView.prototype.getCellTopRelative = function (row, units) { if (row < 0 || row >= this.rows.length) { return null; } // С учетом видимой области var offsetY = 0; if (this.topLeftFrozenCell) { var rFrozen = this.topLeftFrozenCell.getRow0(); offsetY = (row < rFrozen) ? 0 : this.rows[this.visibleRange.r1].top - this.rows[rFrozen].top; } else { offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; } var u = units >= 0 && units <= 3 ? units : 0; return (this.rows[row].top - offsetY) * asc_getcvt(1/*pt*/, u, this._getPPIY()); }; WorksheetView.prototype.getColumnWidth = function (index, units) { if (index >= 0 && index < this.cols.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.cols[index].width * asc_getcvt(1/*pt*/, u, this._getPPIX()); } return null; }; WorksheetView.prototype.getSelectedColumnWidthInSymbols = function () { var c, res = null; var range = this.model.selectionRange.getLast(); for (c = range.c1; c <= range.c2 && c < this.cols.length; ++c) { if (null === res) { res = this.cols[c].charCount; } else if (res !== this.cols[c].charCount) { return null; } } // ToDo сравнить с default для проверки выделения всего return res; }; WorksheetView.prototype.getSelectedRowHeight = function () { var r, res = null; var range = this.model.selectionRange.getLast(); for (r = range.r1; r <= range.r2 && r < this.rows.length; ++r) { if (null === res) { res = this.rows[r].heightReal; } else if (res !== this.rows[r].heightReal) { return null; } } // ToDo сравнить с default для проверки выделения всего return res; }; WorksheetView.prototype.getRowHeight = function (index, units) { if (index >= 0 && index < this.rows.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.rows[index].height * asc_getcvt(1/*pt*/, u, this._getPPIY()); } return null; }; WorksheetView.prototype.getSelectedRange = function () { // ToDo multiselect ? var lastRange = this.model.selectionRange.getLast(); return this._getRange(lastRange.c1, lastRange.r1, lastRange.c2, lastRange.r2); }; WorksheetView.prototype.resize = function (isUpdate) { if (isUpdate) { this._initCellsArea(AscCommonExcel.recalcType.newLines); this._normalizeViewRange(); this._prepareCellTextMetricsCache(); this.updateResize = false; this.objectRender.resizeCanvas(); } else { this.updateResize = true; } return this; }; WorksheetView.prototype.getZoom = function () { return this.drawingCtx.getZoom(); }; WorksheetView.prototype.changeZoom = function (isUpdate) { if (isUpdate) { this.notUpdateRowHeight = true; this.cleanSelection(); this._initCellsArea(AscCommonExcel.recalcType.recalc); this._normalizeViewRange(); this._cleanCellsTextMetricsCache(); // ToDo fix with sheetView->topLeftCell on open var ar = this._getSelection().getLast(); if (ar.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, ar.c2 + 1); } if (ar.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, ar.r2 + 1); } var d = this._calcActiveRangeOffset(); if (d.deltaX) { this.scrollHorizontal(d.deltaX); } if (d.deltaY) { this.scrollVertical(d.deltaY); } this._prepareCellTextMetricsCache(); this.cellCommentator.updateActiveComment(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("toggleAutoCorrectOptions", null, true); this.handlers.trigger("onDocumentPlaceChanged"); this.objectRender.drawingArea.reinitRanges(); this.updateZoom = false; this.notUpdateRowHeight = false; } else { this.updateZoom = true; } return this; }; WorksheetView.prototype.changeZoomResize = function () { this.cleanSelection(); this._initCellsArea(AscCommonExcel.recalcType.full); this._normalizeViewRange(); this._cleanCellsTextMetricsCache(); // ToDo fix with sheetView->topLeftCell on open var ar = this._getSelection().getLast(); if (ar.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, ar.c2 + 1); } if (ar.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, ar.r2 + 1); } var d = this._calcActiveRangeOffset(); if (d.deltaX) { this.scrollHorizontal(d.deltaX); } if (d.deltaY) { this.scrollVertical(d.deltaY); } this._prepareCellTextMetricsCache(); this.cellCommentator.updateActiveComment(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("onDocumentPlaceChanged"); this.objectRender.drawingArea.reinitRanges(); this.updateResize = false; this.updateZoom = false; }; WorksheetView.prototype.getSheetViewSettings = function () { return this.model.getSheetViewSettings(); }; WorksheetView.prototype.getFrozenPaneOffset = function (noX, noY) { var offsetX = 0, offsetY = 0, c = this.cols, r = this.rows; if (this.topLeftFrozenCell) { if (!noX) { var cFrozen = this.topLeftFrozenCell.getCol0(); offsetX = c[cFrozen].left - c[0].left; } if (!noY) { var rFrozen = this.topLeftFrozenCell.getRow0(); offsetY = r[rFrozen].top - r[0].top; } } return {offsetX: offsetX, offsetY: offsetY}; }; // mouseX - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.changeColumnWidth = function (col, x2, mouseX) { var t = this; x2 *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIX()); // Учитываем координаты точки, где мы начали изменение размера x2 += mouseX; var offsetFrozenX = 0; var c1 = t.visibleRange.c1; if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0() - 1; if (0 <= cFrozen) { if (col < c1) { c1 = 0; } else { offsetFrozenX = t.cols[cFrozen].left + t.cols[cFrozen].width - t.cols[0].left; } } } var offsetX = t.cols[c1].left - t.cellsLeft; offsetX -= offsetFrozenX; var x1 = t.cols[col].left - offsetX - this.width_1px; var w = Math.max(x2 - x1, 0); if (w === t.cols[col].width) { return; } var cc = Math.min(this.model.colWidthToCharCount(w), Asc.c_oAscMaxColumnWidth); var onChangeWidthCallback = function (isSuccess) { if (false === isSuccess) { return; } t.model.setColWidth(cc, col, col); t._cleanCache(new asc_Range(0, 0, t.cols.length - 1, t.rows.length - 1)); t.changeWorksheet("update", {reinitRanges: true}); t._updateVisibleColsCount(); t.cellCommentator.updateActiveComment(); t.cellCommentator.updateAreaComments(); if (t.objectRender) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.ColumnResize, col: col}); t.objectRender.rebuildChartGraphicObjects([new asc_Range(col, 0, col, gc_nMaxRow0)]); } }; this._isLockedAll(onChangeWidthCallback); }; // mouseY - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.changeRowHeight = function (row, y2, mouseY) { var t = this; y2 *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIY()); // Учитываем координаты точки, где мы начали изменение размера y2 += mouseY; var offsetFrozenY = 0; var r1 = t.visibleRange.r1; if (this.topLeftFrozenCell) { var rFrozen = this.topLeftFrozenCell.getRow0() - 1; if (0 <= rFrozen) { if (row < r1) { r1 = 0; } else { offsetFrozenY = t.rows[rFrozen].top + t.rows[rFrozen].height - t.rows[0].top; } } } var offsetY = t.rows[r1].top - t.cellsTop; offsetY -= offsetFrozenY; var y1 = t.rows[row].top - offsetY - this.height_1px; var newHeight = Math.min(t.maxRowHeight, Math.max(y2 - y1, 0)); if (newHeight === t.rows[row].height) { return; } var onChangeHeightCallback = function (isSuccess) { if (false === isSuccess) { return; } t.model.setRowHeight(newHeight, row, row, true); t.model.autoFilters.reDrawFilter(null, row); t._cleanCache(new asc_Range(0, row, t.cols.length - 1, row)); t.changeWorksheet("update", {reinitRanges: true}); t._updateVisibleRowsCount(); t.cellCommentator.updateActiveComment(); t.cellCommentator.updateAreaComments(); if (t.objectRender) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: row}); t.objectRender.rebuildChartGraphicObjects([new asc_Range(0, row, gc_nMaxCol0, row)]); } }; this._isLockedAll(onChangeHeightCallback); }; // Проверяет, есть ли числовые значения в диапазоне WorksheetView.prototype._hasNumberValueInActiveRange = function () { var cell, cellType, isNumberFormat, arrCols = [], arrRows = []; // ToDo multiselect var selectionRange = this.model.selectionRange.getLast(); if (selectionRange.isOneCell()) { // Для одной ячейки не стоит ничего делать return null; } var mergedRange = this.model.getMergedByCell(selectionRange.r1, selectionRange.c1); if (mergedRange && mergedRange.isEqual(selectionRange)) { // Для одной ячейки не стоит ничего делать return null; } for (var c = selectionRange.c1; c <= selectionRange.c2; ++c) { for (var r = selectionRange.r1; r <= selectionRange.r2; ++r) { cell = this._getCellTextCache(c, r); if (cell) { // Нашли не пустую ячейку, проверим формат cellType = cell.cellType; isNumberFormat = (null == cellType || CellValueType.Number === cellType); if (isNumberFormat) { arrCols.push(c); arrRows.push(r); } } } } if (0 !== arrCols.length) { // Делаем массивы уникальными и сортируем arrCols = arrCols.filter(AscCommon.fOnlyUnique); arrRows = arrRows.filter(AscCommon.fOnlyUnique); return {arrCols: arrCols.sort(fSortAscending), arrRows: arrRows.sort(fSortAscending)}; } else { return null; } }; // Автодополняет формулу диапазоном, если это возможно WorksheetView.prototype.autoCompleteFormula = function (functionName) { var t = this; // ToDo autoComplete with multiselect var activeCell = this.model.selectionRange.activeCell; var ar = this.model.selectionRange.getLast(); var arCopy = null; var arHistorySelect = ar.clone(true); var vr = this.visibleRange; // Первая верхняя не числовая ячейка var topCell = null; // Первая левая не числовая ячейка var leftCell = null; var r = activeCell.row - 1; var c = activeCell.col - 1; var cell, cellType, isNumberFormat; var result = {}; // Проверим, есть ли числовые значения в диапазоне var hasNumber = this._hasNumberValueInActiveRange(); var val, text; if (hasNumber) { var i; // Есть ли значения в последней строке и столбце var hasNumberInLastColumn = (ar.c2 === hasNumber.arrCols[hasNumber.arrCols.length - 1]); var hasNumberInLastRow = (ar.r2 === hasNumber.arrRows[hasNumber.arrRows.length - 1]); // Нужно уменьшить зону выделения (если она реально уменьшилась) var startCol = hasNumber.arrCols[0]; var startRow = hasNumber.arrRows[0]; // Старые границы диапазона var startColOld = ar.c1; var startRowOld = ar.r1; // Нужно ли перерисовывать var bIsUpdate = false; if (startColOld !== startCol || startRowOld !== startRow) { bIsUpdate = true; } if (true === hasNumberInLastRow && true === hasNumberInLastColumn) { bIsUpdate = true; } if (bIsUpdate) { this.cleanSelection(); ar.c1 = startCol; ar.r1 = startRow; if (false === ar.contains(activeCell.col, activeCell.row)) { // Передвинуть первую ячейку в выделении activeCell.col = startCol; activeCell.row = startRow; } if (true === hasNumberInLastRow && true === hasNumberInLastColumn) { // Мы расширяем диапазон if (1 === hasNumber.arrRows.length) { // Одна строка или только в последней строке есть значения... (увеличиваем вправо) ar.c2 += 1; } else { // Иначе вводим в строку вниз ar.r2 += 1; } } this._drawSelection(); } arCopy = ar.clone(true); var functionAction = null; var changedRange = null; if (false === hasNumberInLastColumn && false === hasNumberInLastRow) { // Значений нет ни в последней строке ни в последнем столбце (значит нужно сделать формулы в каждой последней ячейке) changedRange = [new asc_Range(hasNumber.arrCols[0], arCopy.r2, hasNumber.arrCols[hasNumber.arrCols.length - 1], arCopy.r2), new asc_Range(arCopy.c2, hasNumber.arrRows[0], arCopy.c2, hasNumber.arrRows[hasNumber.arrRows.length - 1])]; functionAction = function () { // Пройдемся по последней строке for (i = 0; i < hasNumber.arrCols.length; ++i) { c = hasNumber.arrCols[i]; cell = t._getVisibleCell(c, arCopy.r2); text = t._getCellTitle(c, arCopy.r1) + ":" + t._getCellTitle(c, arCopy.r2 - 1); val = "=" + functionName + "(" + text + ")"; // ToDo - при вводе формулы в заголовок автофильтра надо писать "0" cell.setValue(val); } // Пройдемся по последнему столбцу for (i = 0; i < hasNumber.arrRows.length; ++i) { r = hasNumber.arrRows[i]; cell = t._getVisibleCell(arCopy.c2, r); text = t._getCellTitle(arCopy.c1, r) + ":" + t._getCellTitle(arCopy.c2 - 1, r); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } // Значение в правой нижней ячейке cell = t._getVisibleCell(arCopy.c2, arCopy.r2); text = t._getCellTitle(arCopy.c1, arCopy.r2) + ":" + t._getCellTitle(arCopy.c2 - 1, arCopy.r2); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); }; } else if (true === hasNumberInLastRow && false === hasNumberInLastColumn) { // Есть значения только в последней строке (значит нужно заполнить только последнюю колонку) changedRange = new asc_Range(arCopy.c2, hasNumber.arrRows[0], arCopy.c2, hasNumber.arrRows[hasNumber.arrRows.length - 1]); functionAction = function () { // Пройдемся по последнему столбцу for (i = 0; i < hasNumber.arrRows.length; ++i) { r = hasNumber.arrRows[i]; cell = t._getVisibleCell(arCopy.c2, r); text = t._getCellTitle(arCopy.c1, r) + ":" + t._getCellTitle(arCopy.c2 - 1, r); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } }; } else if (false === hasNumberInLastRow && true === hasNumberInLastColumn) { // Есть значения только в последнем столбце (значит нужно заполнить только последнюю строчку) changedRange = new asc_Range(hasNumber.arrCols[0], arCopy.r2, hasNumber.arrCols[hasNumber.arrCols.length - 1], arCopy.r2); functionAction = function () { // Пройдемся по последней строке for (i = 0; i < hasNumber.arrCols.length; ++i) { c = hasNumber.arrCols[i]; cell = t._getVisibleCell(c, arCopy.r2); text = t._getCellTitle(c, arCopy.r1) + ":" + t._getCellTitle(c, arCopy.r2 - 1); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } }; } else { // Есть значения и в последнем столбце, и в последней строке if (1 === hasNumber.arrRows.length) { changedRange = new asc_Range(arCopy.c2, arCopy.r2, arCopy.c2, arCopy.r2); functionAction = function () { // Одна строка или только в последней строке есть значения... cell = t._getVisibleCell(arCopy.c2, arCopy.r2); // ToDo вводить в первое свободное место, а не сразу за диапазоном text = t._getCellTitle(arCopy.c1, arCopy.r2) + ":" + t._getCellTitle(arCopy.c2 - 1, arCopy.r2); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); }; } else { changedRange = new asc_Range(hasNumber.arrCols[0], arCopy.r2, hasNumber.arrCols[hasNumber.arrCols.length - 1], arCopy.r2); functionAction = function () { // Иначе вводим в строку вниз for (i = 0; i < hasNumber.arrCols.length; ++i) { c = hasNumber.arrCols[i]; cell = t._getVisibleCell(c, arCopy.r2); // ToDo вводить в первое свободное место, а не сразу за диапазоном text = t._getCellTitle(c, arCopy.r1) + ":" + t._getCellTitle(c, arCopy.r2 - 1); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } }; } } var onAutoCompleteFormula = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.SetSelection(arHistorySelect.clone()); History.SetSelectionRedo(arCopy.clone()); History.StartTransaction(); asc_applyFunction(functionAction); t.handlers.trigger("selectionMathInfoChanged", t.getSelectionMathInfo()); History.EndTransaction(); }; // Можно ли применять автоформулу this._isLockedCells(changedRange, /*subType*/null, onAutoCompleteFormula); result.notEditCell = true; return result; } // Ищем первую ячейку с числом for (; r >= vr.r1; --r) { cell = this._getCellTextCache(activeCell.col, r); if (cell) { // Нашли не пустую ячейку, проверим формат cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (isNumberFormat) { // Это число, мы нашли то, что искали topCell = { c: activeCell.col, r: r, isFormula: cell.isFormula }; // смотрим вторую ячейку if (topCell.isFormula && r - 1 >= vr.r1) { cell = this._getCellTextCache(activeCell.col, r - 1); if (cell && cell.isFormula) { topCell.isFormulaSeq = true; } } break; } } } // Проверим, первой все равно должна быть колонка if (null === topCell || topCell.r !== activeCell.row - 1 || topCell.isFormula && !topCell.isFormulaSeq) { for (; c >= vr.c1; --c) { cell = this._getCellTextCache(c, activeCell.row); if (cell) { // Нашли не пустую ячейку, проверим формат cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (isNumberFormat) { // Это число, мы нашли то, что искали leftCell = { r: activeCell.row, c: c }; break; } } if (null !== topCell) { // Если это не первая ячейка слева от текущей и мы нашли верхнюю, то дальше не стоит искать break; } } } if (leftCell) { // Идем влево до первой не числовой ячейки --c; for (; c >= 0; --c) { cell = this._getCellTextCache(c, activeCell.row); if (!cell) { // Могут быть еще не закешированные данные this._addCellTextToCache(c, activeCell.row); cell = this._getCellTextCache(c, activeCell.row); if (!cell) { break; } } cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (!isNumberFormat) { break; } } // Мы ушли чуть дальше ++c; // Диапазон или только 1 ячейка if (activeCell.col - 1 !== c) { // Диапазон result = new asc_Range(c, leftCell.r, activeCell.col - 1, leftCell.r); } else { // Одна ячейка result = new asc_Range(c, leftCell.r, c, leftCell.r); } this._fixSelectionOfMergedCells(result); if (result.c1 === result.c2 && result.r1 === result.r2) { result.text = this._getCellTitle(result.c1, result.r1); } else { result.text = this._getCellTitle(result.c1, result.r1) + ":" + this._getCellTitle(result.c2, result.r2); } return result; } if (topCell) { // Идем вверх до первой не числовой ячейки --r; for (; r >= 0; --r) { cell = this._getCellTextCache(activeCell.col, r); if (!cell) { // Могут быть еще не закешированные данные this._addCellTextToCache(activeCell.col, r); cell = this._getCellTextCache(activeCell.col, r); if (!cell) { break; } } cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (!isNumberFormat) { break; } } // Мы ушли чуть дальше ++r; // Диапазон или только 1 ячейка if (activeCell.row - 1 !== r) { // Диапазон result = new asc_Range(topCell.c, r, topCell.c, activeCell.row - 1); } else { // Одна ячейка result = new asc_Range(topCell.c, r, topCell.c, r); } this._fixSelectionOfMergedCells(result); if (result.c1 === result.c2 && result.r1 === result.r2) { result.text = this._getCellTitle(result.c1, result.r1); } else { result.text = this._getCellTitle(result.c1, result.r1) + ":" + this._getCellTitle(result.c2, result.r2); } return result; } }; // ----- Initialization ----- WorksheetView.prototype._init = function () { this._initConstValues(); this._initWorksheetDefaultWidth(); this._initPane(); this._initCellsArea(AscCommonExcel.recalcType.full); this.model.setTableStyleAfterOpen(); this.model.setDirtyConditionalFormatting(null); this.model.initPivotTables(); this.model.updatePivotTablesStyle(null); this._cleanCellsTextMetricsCache(); this._prepareCellTextMetricsCache(); // initializing is completed this.handlers.trigger("initialized"); }; WorksheetView.prototype._prepareComments = function () { // ToDo возможно не нужно это делать именно тут.. if (0 < this.model.aComments.length) { this.model.workbook.handlers.trigger("asc_onAddComments", this.model.aComments); } }; WorksheetView.prototype._prepareDrawingObjects = function () { this.objectRender = new AscFormat.DrawingObjects(); if (!window["NATIVE_EDITOR_ENJINE"] || window['IS_NATIVE_EDITOR'] || window['DoctRendererMode']) { this.objectRender.init(this); } }; WorksheetView.prototype._initWorksheetDefaultWidth = function () { // Теперь рассчитываем число px var defaultColWidthChars = this.model.charCountToModelColWidth(this.model.getBaseColWidth()); var defaultColWidthPx = this.model.modelColWidthToColWidth(defaultColWidthChars) * asc_getcvt(1/*pt*/, 0/*px*/, 96); // Делаем кратным 8 (http://support.microsoft.com/kb/214123) defaultColWidthPx = asc_ceil(defaultColWidthPx / 8) * 8; this.defaultColWidthChars = this.model.colWidthToCharCount(defaultColWidthPx * asc_getcvt(0/*px*/, 1/*pt*/, 96)); AscCommonExcel.oDefaultMetrics.ColWidthChars = this.model.charCountToModelColWidth(this.defaultColWidthChars); this.defaultColWidth = this.model.modelColWidthToColWidth(AscCommonExcel.oDefaultMetrics.ColWidthChars); var defaultFontSize = this.model.getDefaultFontSize(); // ToDo разобраться со значениями this._setFont(undefined, this.model.getDefaultFontName(), defaultFontSize); var tm = this._roundTextMetrics(this.stringRender.measureString("A")); this.headersHeightByFont = tm.height + this.height_1px; this.maxRowHeight = asc_calcnpt(Asc.c_oAscMaxRowHeight, this._getPPIY()); this.defaultRowDescender = this._calcRowDescender(defaultFontSize); AscCommonExcel.oDefaultMetrics.RowHeight = this.defaultRowHeight = Math.min(this.maxRowHeight, this.model.getDefaultHeight() || this.headersHeightByFont); // Инициализируем число колонок и строк (при открытии). Причем нужно поставить на 1 больше, // чтобы могли показать последнюю строку/столбец (http://bugzilla.onlyoffice.com/show_bug.cgi?id=23513) this.nColsCount = Math.min(this.model.getColsCount() + 1, gc_nMaxCol); this.nRowsCount = Math.min(this.model.getRowsCount() + 1, gc_nMaxRow); }; WorksheetView.prototype._initConstValues = function () { var ppiX = this._getPPIX(); var ppiY = this._getPPIY(); this.width_1px = asc_calcnpt(0, ppiX, 1/*px*/); this.width_2px = asc_calcnpt(0, ppiX, 2/*px*/); this.width_3px = asc_calcnpt(0, ppiX, 3/*px*/); this.width_4px = asc_calcnpt(0, ppiX, 4/*px*/); this.width_padding = asc_calcnpt(0, ppiX, this.settings.cells.padding/*px*/); this.height_1px = asc_calcnpt(0, ppiY, 1/*px*/); this.height_2px = asc_calcnpt(0, ppiY, 2/*px*/); this.height_3px = asc_calcnpt(0, ppiY, 3/*px*/); this.height_4px = asc_calcnpt(0, ppiY, 4/*px*/); }; WorksheetView.prototype._initCellsArea = function (type) { // calculate rows heights and visible rows if (!(window["NATIVE_EDITOR_ENJINE"] && this.notUpdateRowHeight)) { this._calcHeaderRowHeight(); this._calcHeightRows(type); } this.visibleRange.r2 = 0; this._calcVisibleRows(); this._updateVisibleRowsCount(/*skipScrolReinit*/true); // calculate columns widths and visible columns if (!(window["NATIVE_EDITOR_ENJINE"] && this.notUpdateRowHeight)) { this._calcHeaderColumnWidth(); this._calcWidthColumns(type); } this.visibleRange.c2 = 0; this._calcVisibleColumns(); this._updateVisibleColsCount(/*skipScrolReinit*/true); }; WorksheetView.prototype._initPane = function () { var pane = this.model.sheetViews[0].pane; if ( null !== pane && pane.isInit() ) { this.topLeftFrozenCell = pane.topLeftFrozenCell; this.visibleRange.r1 = this.topLeftFrozenCell.getRow0(); this.visibleRange.c1 = this.topLeftFrozenCell.getCol0(); } }; WorksheetView.prototype._getSelection = function () { return (this.isFormulaEditMode) ? this.arrActiveFormulaRanges[this.arrActiveFormulaRangesPosition] : this.model.selectionRange; }; WorksheetView.prototype._fixVisibleRange = function ( range ) { var tmp; if ( null !== this.topLeftFrozenCell ) { tmp = this.topLeftFrozenCell.getRow0(); if ( range.r1 < tmp ) { range.r1 = tmp; tmp = this._findVisibleRow( range.r1, +1 ); if ( 0 < tmp ) { range.r1 = tmp; } } tmp = this.topLeftFrozenCell.getCol0(); if ( range.c1 < tmp ) { range.c1 = tmp; tmp = this._findVisibleCol( range.c1, +1 ); if ( 0 < tmp ) { range.c1 = tmp; } } } }; /** * Вычисляет ширину столбца для отрисовки * @param {Number} w Ширина столбца в символах * @returns {Number} Ширина столбца в пунктах (pt) */ WorksheetView.prototype._calcColWidth = function ( w ) { var t = this; var res = {}; var useDefault = w === undefined || w === null || w === -1; var width; res.width = useDefault ? t.defaultColWidth : (width = t.model.modelColWidthToColWidth(w), (width < t.width_1px ? 0 : width)); res.innerWidth = Math.max( res.width - this.width_padding * 2 - this.width_1px, 0 ); res.charCount = this.model.colWidthToCharCount(res.width); return res; }; /** * Вычисляет Descender строки * @param {Number} fontSize * @returns {Number} */ WorksheetView.prototype._calcRowDescender = function ( fontSize ) { return asc_calcnpt( fontSize * (this.vspRatio - 1), this._getPPIY() ); // ToDo возможно стоит тоже использовать 96 }; /** Вычисляет ширину колонки заголовков (в pt) */ WorksheetView.prototype._calcHeaderColumnWidth = function () { if (false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { this.headersWidth = 0; } else { // Ширина колонки заголовков считается - max число знаков в строке - перевести в символы - перевести в пикселы var numDigit = Math.max(AscCommonExcel.calcDecades(this.visibleRange.r2 + 1), 3); var nCharCount = this.model.charCountToModelColWidth(numDigit); this.headersWidth = this.model.modelColWidthToColWidth(nCharCount); } this.cellsLeft = this.headersLeft + this.headersWidth; }; /** Вычисляет высоту строки заголовков (в pt) */ WorksheetView.prototype._calcHeaderRowHeight = function () { if ( false === this.model.sheetViews[0].asc_getShowRowColHeaders() ) { this.headersHeight = 0; } else //this.headersHeight = this.model.getDefaultHeight() || this.defaultRowHeight; { this.headersHeight = this.headersHeightByFont; } //this.headersHeight = asc_calcnpt( this.settings.header.fontSize * this.vspRatio, this._getPPIY() ); this.cellsTop = this.headersTop + this.headersHeight; }; /** * Вычисляет ширину и позицию колонок (в pt) * @param {AscCommonExcel.recalcType} type */ WorksheetView.prototype._calcWidthColumns = function (type) { var x = this.cellsLeft; var visibleW = this.drawingCtx.getWidth(); var maxColObjects = this.objectRender ? this.objectRender.getMaxColRow().col : -1; var l = Math.max(this.model.getColsCount() + 1, this.nColsCount, maxColObjects); var i = 0, w, column, isBestFit, hiddenW = 0; // Берем дефалтовую ширину документа var defaultWidth = this.model.getDefaultWidth(); defaultWidth = (typeof defaultWidth === "number" && defaultWidth >= 0) ? defaultWidth : -1; if (AscCommonExcel.recalcType.full === type) { this.cols = []; } else if (AscCommonExcel.recalcType.newLines === type) { i = this.cols.length; x = this.cols[i - 1].left + this.cols[i - 1].width; } for (; ((AscCommonExcel.recalcType.recalc !== type) ? i < l || x + hiddenW < visibleW : i < this.cols.length) && i < gc_nMaxCol; ++i) { // Получаем свойства колонки column = this.model._getColNoEmptyWithAll(i); if (!column) { w = defaultWidth; // Используем дефолтное значение isBestFit = true; // Это уже оптимальная ширина } else if (column.getHidden()) { w = 0; // Если столбец скрытый, ширину выставляем 0 isBestFit = false; hiddenW += this._calcColWidth(column.width).width; } else { w = column.width || defaultWidth; isBestFit = !!(column.BestFit || (null === column.BestFit && null === column.CustomWidth)); } this.cols[i] = this._calcColWidth(w); this.cols[i].isCustomWidth = !isBestFit; this.cols[i].left = x; x += this.cols[i].width; } this.nColsCount = Math.min(Math.max(this.nColsCount, i), gc_nMaxCol); }; /** * Вычисляет высоту и позицию строк (в pt) * @param {AscCommonExcel.recalcType} type */ WorksheetView.prototype._calcHeightRows = function (type) { var t = this; var y = this.cellsTop; var visibleH = this.drawingCtx.getHeight(); var maxRowObjects = this.objectRender ? this.objectRender.getMaxColRow().row : -1; var l = Math.max(this.model.getRowsCount() + 1, this.nRowsCount, maxRowObjects); var defaultH = this.defaultRowHeight; var i = 0, h, hR, isCustomHeight, row, hiddenH = 0; if (AscCommonExcel.recalcType.full === type) { this.rows = []; } else if (AscCommonExcel.recalcType.newLines === type) { i = this.rows.length; y = this.rows[i - 1].top + this.rows[i - 1].height; } // ToDo calc all rows (not visible) for (; ((AscCommonExcel.recalcType.recalc !== type) ? i < l || y + hiddenH < visibleH : i < this.rows.length) && i < gc_nMaxRow; ++i) { this.model._getRowNoEmptyWithAll(i, function(row){ if (!row) { h = -1; // Будет использоваться дефолтная высота строки isCustomHeight = false; } else if (row.getHidden()) { hR = h = 0; // Скрытая строка, высоту выставляем 0 isCustomHeight = true; hiddenH += row.h > 0 ? row.h - t.height_1px : defaultH; } else { isCustomHeight = row.getCustomHeight(); // Берем высоту из модели, если она custom(баг 15618), либо дефолтную if (row.h > 0 && (isCustomHeight || row.getCalcHeight())) { hR = row.h; h = hR / 0.75; h = (h | h) * 0.75; // 0.75 - это размер 1px в pt (можно было 96/72) } else { h = -1; } } }); h = h < 0 ? (hR = defaultH) : h; this.rows[i] = { top: y, height: h, // Высота с точностью до 1 px heightReal: hR, // Реальная высота из файла (может быть не кратна 1 px, в Excel можно выставить через меню строки) descender: this.defaultRowDescender, isCustomHeight: isCustomHeight }; y += this.rows[i].height; } this.nRowsCount = Math.min(Math.max(this.nRowsCount, i), gc_nMaxRow); }; /** Вычисляет диапазон индексов видимых колонок */ WorksheetView.prototype._calcVisibleColumns = function () { var l = this.cols.length; var w = this.drawingCtx.getWidth(); var sumW = this.topLeftFrozenCell ? this.cols[this.topLeftFrozenCell.getCol0()].left : this.cellsLeft; for (var i = this.visibleRange.c1, f = false; i < l && sumW < w; ++i) { sumW += this.cols[i].width; f = true; } this.visibleRange.c2 = i - (f ? 1 : 0); }; /** Вычисляет диапазон индексов видимых строк */ WorksheetView.prototype._calcVisibleRows = function () { var l = this.rows.length; var h = this.drawingCtx.getHeight(); var sumH = this.topLeftFrozenCell ? this.rows[this.topLeftFrozenCell.getRow0()].top : this.cellsTop; for (var i = this.visibleRange.r1, f = false; i < l && sumH < h; ++i) { sumH += this.rows[i].height; f = true; } this.visibleRange.r2 = i - (f ? 1 : 0); }; /** Обновляет позицию колонок (в pt) */ WorksheetView.prototype._updateColumnPositions = function () { var x = this.cellsLeft; for (var l = this.cols.length, i = 0; i < l; ++i) { this.cols[i].left = x; x += this.cols[i].width; } }; /** Обновляет позицию строк (в pt) */ WorksheetView.prototype._updateRowPositions = function () { var y = this.cellsTop; for (var l = this.rows.length, i = 0; i < l; ++i) { this.rows[i].top = y; y += this.rows[i].height; } }; /** * Добавляет колонки, пока общая ширина листа не превысит rightSide * @param {Number} rightSide Правая граница */ WorksheetView.prototype._appendColumns = function (rightSide) { var i = this.cols.length; var lc = this.cols[i - 1]; var done = false; for (var x = lc.left + lc.width; i < gc_nMaxCol && (x < rightSide || !done); ++i) { if (x >= rightSide) { // add +1 column at the end and exit cycle done = true; } this.cols[i] = this._calcColWidth(this.model.getColWidth(i)); this.cols[i].left = x; x += this.cols[i].width; this.isChanged = true; } this.nColsCount = Math.min(Math.max(this.nColsCount, i), gc_nMaxCol); }; /** Устанаваливает видимый диапазон ячеек максимально возможным */ WorksheetView.prototype._normalizeViewRange = function () { var t = this; var vr = t.visibleRange; var w = t.drawingCtx.getWidth() - t.cellsLeft; var h = t.drawingCtx.getHeight() - t.cellsTop; var c = t.cols; var r = t.rows; var vw = c[vr.c2].left + c[vr.c2].width - c[vr.c1].left; var vh = r[vr.r2].top + r[vr.r2].height - r[vr.r1].top; var i; var offsetFrozen = t.getFrozenPaneOffset(); vw += offsetFrozen.offsetX; vh += offsetFrozen.offsetY; if ( vw < w ) { for ( i = vr.c1 - 1; i >= 0; --i ) { vw += c[i].width; if ( vw > w ) { break; } } vr.c1 = i + 1; if ( vr.c1 >= vr.c2 ) { vr.c1 = vr.c2 - 1; } if ( vr.c1 < 0 ) { vr.c1 = 0; } } if ( vh < h ) { for ( i = vr.r1 - 1; i >= 0; --i ) { vh += r[i].height; if ( vh > h ) { break; } } vr.r1 = i + 1; if ( vr.r1 >= vr.r2 ) { vr.r1 = vr.r2 - 1; } if ( vr.r1 < 0 ) { vr.r1 = 0; } } }; // ----- Drawing for print ----- WorksheetView.prototype.calcPagesPrint = function(pageOptions, printOnlySelection, indexWorksheet, arrPages) { var t = this; var range; var maxCols = this.model.getColsCount(); var maxRows = this.model.getRowsCount(); var lastC = -1, lastR = -1; // ToDo print each range on new page (now only last) var selectionRange = printOnlySelection ? this.model.selectionRange.getLast() : null; var bFitToWidth = false; var bFitToHeight = false; if (null === selectionRange) { range = new asc_Range(0, 0, maxCols, maxRows); this._prepareCellTextMetricsCache(range); var rowCache, rightSide, curRow = -1, skipRow = false; this.model._forEachCell(function(cell) { var c = cell.nCol; var r = cell.nRow; if (curRow !== r) { curRow = r; skipRow = t.height_1px > t.rows[r].height; rowCache = t._getRowCache(r); } if(!skipRow && !(t.width_1px > t.cols[c].width)){ var style = cell.getStyle(); if (style && ((style.fill && style.fill.notEmpty()) || (style.border && style.border.notEmpty()))) { lastC = Math.max(lastC, c); lastR = Math.max(lastR, r); } if (rowCache && rowCache.columnsWithText[c]) { rightSide = 0; var ct = t._getCellTextCache(c, r); if (ct !== undefined) { if (!ct.flags.isMerged() && !ct.flags.wrapText) { rightSide = ct.sideR; } lastC = Math.max(lastC, c + rightSide); lastR = Math.max(lastR, r); } } } }); var maxCell = this.model.autoFilters.getMaxColRow(); lastC = Math.max(lastC, maxCell.col); lastR = Math.max(lastR, maxCell.row); maxCols = lastC + 1; maxRows = lastR + 1; // Получаем максимальную колонку/строку для изображений/чатов maxCell = this.objectRender.getMaxColRow(); maxCols = Math.max(maxCols, maxCell.col); maxRows = Math.max(maxRows, maxCell.row); } else { maxCols = selectionRange.c2 + 1; maxRows = selectionRange.r2 + 1; range = new asc_Range(0, 0, maxCols, maxRows); this._prepareCellTextMetricsCache(range); } var pageMargins, pageSetup, pageGridLines, pageHeadings; if (pageOptions instanceof asc_CPageOptions) { pageMargins = pageOptions.asc_getPageMargins(); pageSetup = pageOptions.asc_getPageSetup(); pageGridLines = pageOptions.asc_getGridLines(); pageHeadings = pageOptions.asc_getHeadings(); } var pageWidth, pageHeight, pageOrientation; if (pageSetup instanceof asc_CPageSetup) { pageWidth = pageSetup.asc_getWidth(); pageHeight = pageSetup.asc_getHeight(); pageOrientation = pageSetup.asc_getOrientation(); bFitToWidth = pageSetup.asc_getFitToWidth(); bFitToHeight = pageSetup.asc_getFitToHeight(); } var pageLeftField, pageRightField, pageTopField, pageBottomField; if (pageMargins instanceof asc_CPageMargins) { pageLeftField = Math.max(pageMargins.asc_getLeft(), c_oAscPrintDefaultSettings.MinPageLeftField); pageRightField = Math.max(pageMargins.asc_getRight(), c_oAscPrintDefaultSettings.MinPageRightField); pageTopField = Math.max(pageMargins.asc_getTop(), c_oAscPrintDefaultSettings.MinPageTopField); pageBottomField = Math.max(pageMargins.asc_getBottom(), c_oAscPrintDefaultSettings.MinPageBottomField); } if (null == pageGridLines) { pageGridLines = c_oAscPrintDefaultSettings.PageGridLines; } if (null == pageHeadings) { pageHeadings = c_oAscPrintDefaultSettings.PageHeadings; } if (null == pageWidth) { pageWidth = c_oAscPrintDefaultSettings.PageWidth; } if (null == pageHeight) { pageHeight = c_oAscPrintDefaultSettings.PageHeight; } if (null == pageOrientation) { pageOrientation = c_oAscPrintDefaultSettings.PageOrientation; } if (null == pageLeftField) { pageLeftField = c_oAscPrintDefaultSettings.PageLeftField; } if (null == pageRightField) { pageRightField = c_oAscPrintDefaultSettings.PageRightField; } if (null == pageTopField) { pageTopField = c_oAscPrintDefaultSettings.PageTopField; } if (null == pageBottomField) { pageBottomField = c_oAscPrintDefaultSettings.PageBottomField; } if (Asc.c_oAscPageOrientation.PageLandscape === pageOrientation) { var tmp = pageWidth; pageWidth = pageHeight; pageHeight = tmp; } if (0 === maxCols || 0 === maxRows) { // Ничего нет, возвращаем пустой массив return null; } else { var pageWidthWithFields = pageWidth - pageLeftField - pageRightField; var pageHeightWithFields = pageHeight - pageTopField - pageBottomField; // 1px offset for borders var leftFieldInPt = pageLeftField / vector_koef + this.width_1px; var topFieldInPt = pageTopField / vector_koef + this.height_1px; var rightFieldInPt = pageRightField / vector_koef + this.width_1px; var bottomFieldInPt = pageBottomField / vector_koef + this.height_1px; if (pageHeadings) { // Рисуем заголовки, нужно чуть сдвинуться leftFieldInPt += this.cellsLeft; topFieldInPt += this.cellsTop; } var pageWidthWithFieldsHeadings = (pageWidth - pageRightField) / vector_koef - leftFieldInPt; var pageHeightWithFieldsHeadings = (pageHeight - pageBottomField) / vector_koef - topFieldInPt; var currentColIndex = (null !== selectionRange) ? selectionRange.c1 : 0; var currentWidth = 0; var currentRowIndex = (null !== selectionRange) ? selectionRange.r1 : 0; var currentHeight = 0; var isCalcColumnsWidth = true; var bIsAddOffset = false; var nCountOffset = 0; while (AscCommonExcel.c_kMaxPrintPages > arrPages.length) { if (currentColIndex === maxCols && currentRowIndex === maxRows) { break; } var newPagePrint = new asc_CPagePrint(); var colIndex = currentColIndex, rowIndex = currentRowIndex; newPagePrint.indexWorksheet = indexWorksheet; newPagePrint.pageWidth = pageWidth; newPagePrint.pageHeight = pageHeight; newPagePrint.pageClipRectLeft = pageLeftField / vector_koef; newPagePrint.pageClipRectTop = pageTopField / vector_koef; newPagePrint.pageClipRectWidth = pageWidthWithFields / vector_koef; newPagePrint.pageClipRectHeight = pageHeightWithFields / vector_koef; newPagePrint.leftFieldInPt = leftFieldInPt; newPagePrint.topFieldInPt = topFieldInPt; newPagePrint.rightFieldInPt = rightFieldInPt; newPagePrint.bottomFieldInPt = bottomFieldInPt; for (rowIndex = currentRowIndex; rowIndex < maxRows; ++rowIndex) { var currentRowHeight = this.rows[rowIndex].height; if (!bFitToHeight && currentHeight + currentRowHeight > pageHeightWithFieldsHeadings) { // Закончили рисовать страницу break; } if (isCalcColumnsWidth) { for (colIndex = currentColIndex; colIndex < maxCols; ++colIndex) { var currentColWidth = this.cols[colIndex].width; if (bIsAddOffset) { newPagePrint.startOffset = ++nCountOffset; newPagePrint.startOffsetPt = (pageWidthWithFieldsHeadings * newPagePrint.startOffset); currentColWidth -= newPagePrint.startOffsetPt; } if (!bFitToWidth && currentWidth + currentColWidth > pageWidthWithFieldsHeadings && colIndex !== currentColIndex) { break; } currentWidth += currentColWidth; if (!bFitToWidth && currentWidth > pageWidthWithFieldsHeadings && colIndex === currentColIndex) { // Смещаем в селедующий раз ячейку bIsAddOffset = true; ++colIndex; break; } else { bIsAddOffset = false; } } isCalcColumnsWidth = false; if (pageHeadings) { currentWidth += this.cellsLeft; } if (bFitToWidth) { newPagePrint.pageClipRectWidth = Math.max(currentWidth, newPagePrint.pageClipRectWidth); newPagePrint.pageWidth = newPagePrint.pageClipRectWidth * vector_koef + (pageLeftField + pageRightField); } else { newPagePrint.pageClipRectWidth = Math.min(currentWidth, newPagePrint.pageClipRectWidth); } } currentHeight += currentRowHeight; currentWidth = 0; } if (bFitToHeight) { newPagePrint.pageClipRectHeight = Math.max(currentHeight, newPagePrint.pageClipRectHeight); newPagePrint.pageHeight = newPagePrint.pageClipRectHeight * vector_koef + (pageTopField + pageBottomField); } else { newPagePrint.pageClipRectHeight = Math.min(currentHeight, newPagePrint.pageClipRectHeight); } // Нужно будет пересчитывать колонки isCalcColumnsWidth = true; // Рисуем сетку if (pageGridLines) { newPagePrint.pageGridLines = true; } if (pageHeadings) { // Нужно отрисовать заголовки newPagePrint.pageHeadings = true; } newPagePrint.pageRange = new asc_Range(currentColIndex, currentRowIndex, colIndex - 1, rowIndex - 1); if (bIsAddOffset) { // Мы еще не дорисовали колонку colIndex -= 1; } else { nCountOffset = 0; } if (colIndex < maxCols) { // Мы еще не все колонки отрисовали currentColIndex = colIndex; currentHeight = 0; } else { // Мы дорисовали все колонки, нужна новая строка и стартовая колонка currentColIndex = (null !== selectionRange) ? selectionRange.c1 : 0; currentRowIndex = rowIndex; currentHeight = 0; } if (rowIndex === maxRows) { // Мы вышли, т.к. дошли до конца отрисовки по строкам if (colIndex < maxCols) { currentColIndex = colIndex; currentHeight = 0; } else { // Мы дошли до конца отрисовки currentColIndex = colIndex; currentRowIndex = rowIndex; } } arrPages.push(newPagePrint); } } }; WorksheetView.prototype.drawForPrint = function(drawingCtx, printPagesData) { if (null === printPagesData) { // Напечатаем пустую страницу drawingCtx.BeginPage(c_oAscPrintDefaultSettings.PageWidth, c_oAscPrintDefaultSettings.PageHeight); drawingCtx.EndPage(); } else { drawingCtx.BeginPage(printPagesData.pageWidth, printPagesData.pageHeight); drawingCtx.AddClipRect(printPagesData.pageClipRectLeft, printPagesData.pageClipRectTop, printPagesData.pageClipRectWidth, printPagesData.pageClipRectHeight); var offsetCols = printPagesData.startOffsetPt; var range = printPagesData.pageRange; var offsetX = this.cols[range.c1].left - printPagesData.leftFieldInPt + offsetCols; var offsetY = this.rows[range.r1].top - printPagesData.topFieldInPt; var tmpVisibleRange = this.visibleRange; // Сменим visibleRange для прохождения проверок отрисовки this.visibleRange = range; // Нужно отрисовать заголовки if (printPagesData.pageHeadings) { this._drawColumnHeaders(drawingCtx, range.c1, range.c2, /*style*/ undefined, offsetX, printPagesData.topFieldInPt - this.cellsTop); this._drawRowHeaders(drawingCtx, range.r1, range.r2, /*style*/ undefined, printPagesData.leftFieldInPt - this.cellsLeft, offsetY); } // Рисуем сетку if (printPagesData.pageGridLines) { this._drawGrid(drawingCtx, range, offsetX, offsetY, printPagesData.pageWidth / vector_koef, printPagesData.pageHeight / vector_koef); } // Отрисовываем ячейки и бордеры this._drawCellsAndBorders(drawingCtx, range, offsetX, offsetY); var drawingPrintOptions = { ctx: drawingCtx, printPagesData: printPagesData }; this.objectRender.showDrawingObjectsEx(false, null, drawingPrintOptions); this.visibleRange = tmpVisibleRange; drawingCtx.RemoveClipRect(); drawingCtx.EndPage(); } }; // ----- Drawing ----- WorksheetView.prototype.draw = function (lockDraw) { if (lockDraw || this.model.workbook.bCollaborativeChanges || window['IS_NATIVE_EDITOR']) { return this; } this.handlers.trigger("checkLastWork"); this._clean(); this._drawCorner(); this._drawColumnHeaders(null); this._drawRowHeaders(null); this._drawGrid(null); this._drawCellsAndBorders(null); this._drawFrozenPane(); this._drawFrozenPaneLines(); this._fixSelectionOfMergedCells(); this._drawElements(this.af_drawButtons); this.cellCommentator.drawCommentCells(); this.objectRender.showDrawingObjectsEx(true); if (this.overlayCtx) { this._drawSelection(); } return this; }; WorksheetView.prototype._clean = function () { this.drawingCtx .setFillStyle( this.settings.cells.defaultState.background ) .fillRect( 0, 0, this.drawingCtx.getWidth(), this.drawingCtx.getHeight() ); if ( this.overlayCtx ) { this.overlayCtx.clear(); } }; WorksheetView.prototype.drawHighlightedHeaders = function (col, row) { this._activateOverlayCtx(); if (col >= 0 && col !== this.highlightedCol) { this._doCleanHighlightedHeaders(); this.highlightedCol = col; this._drawColumnHeaders(null, col, col, kHeaderHighlighted); } else if (row >= 0 && row !== this.highlightedRow) { this._doCleanHighlightedHeaders(); this.highlightedRow = row; this._drawRowHeaders(null, row, row, kHeaderHighlighted); } this._deactivateOverlayCtx(); return this; }; WorksheetView.prototype.cleanHighlightedHeaders = function () { this._activateOverlayCtx(); this._doCleanHighlightedHeaders(); this._deactivateOverlayCtx(); return this; }; WorksheetView.prototype._activateOverlayCtx = function () { this.drawingCtx = this.buffers.overlay; }; WorksheetView.prototype._deactivateOverlayCtx = function () { this.drawingCtx = this.buffers.main; }; WorksheetView.prototype._doCleanHighlightedHeaders = function () { // ToDo highlighted! var hlc = this.highlightedCol, hlr = this.highlightedRow, arn = this.model.selectionRange.getLast(); var hStyle = this.objectRender.selectedGraphicObjectsExists() ? kHeaderDefault : kHeaderActive; if (hlc >= 0) { if (hlc >= arn.c1 && hlc <= arn.c2) { this._drawColumnHeaders(null, hlc, hlc, hStyle); } else { this._cleanColumnHeaders(hlc); if (hlc + 1 === arn.c1) { this._drawColumnHeaders(null, hlc + 1, hlc + 1, kHeaderActive); } else if (hlc - 1 === arn.c2) { this._drawColumnHeaders(null, hlc - 1, hlc - 1, hStyle); } } this.highlightedCol = -1; } if (hlr >= 0) { if (hlr >= arn.r1 && hlr <= arn.r2) { this._drawRowHeaders(null, hlr, hlr, hStyle); } else { this._cleanRowHeaders(hlr); if (hlr + 1 === arn.r1) { this._drawRowHeaders(null, hlr + 1, hlr + 1, kHeaderActive); } else if (hlr - 1 === arn.r2) { this._drawRowHeaders(null, hlr - 1, hlr - 1, hStyle); } } this.highlightedRow = -1; } }; WorksheetView.prototype._drawActiveHeaders = function () { var vr = this.visibleRange; var range, c1, c2, r1, r2; this._activateOverlayCtx(); for (var i = 0; i < this.model.selectionRange.ranges.length; ++i) { range = this.model.selectionRange.ranges[i]; c1 = Math.max(vr.c1, range.c1); c2 = Math.min(vr.c2, range.c2); r1 = Math.max(vr.r1, range.r1); r2 = Math.min(vr.r2, range.r2); this._drawColumnHeaders(null, c1, c2, kHeaderActive); this._drawRowHeaders(null, r1, r2, kHeaderActive); if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0() - 1; var rFrozen = this.topLeftFrozenCell.getRow0() - 1; if (0 <= cFrozen) { c1 = Math.max(0, range.c1); c2 = Math.min(cFrozen, range.c2); this._drawColumnHeaders(null, c1, c2, kHeaderActive); } if (0 <= rFrozen) { r1 = Math.max(0, range.r1); r2 = Math.min(rFrozen, range.r2); this._drawRowHeaders(null, r1, r2, kHeaderActive); } } } this._deactivateOverlayCtx(); }; WorksheetView.prototype._drawCorner = function () { if (false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { return; } var x2 = this.headersLeft + this.headersWidth; var x1 = x2 - this.headersHeight; var y2 = this.headersTop + this.headersHeight; var y1 = this.headersTop; var dx = 4 * this.width_1px; var dy = 4 * this.height_1px; this._drawHeader(null, this.headersLeft, this.headersTop, this.headersWidth, this.headersHeight, kHeaderDefault, true, -1); this.drawingCtx.beginPath() .moveTo(x2 - dx, y1 + dy) .lineTo(x2 - dx, y2 - dy) .lineTo(x1 + dx, y2 - dy) .lineTo(x2 - dx, y1 + dy) .setFillStyle(this.settings.header.cornerColor) .fill(); }; /** Рисует заголовки видимых колонок */ WorksheetView.prototype._drawColumnHeaders = function (drawingCtx, start, end, style, offsetXForDraw, offsetYForDraw) { if (null === drawingCtx && false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { return; } var vr = this.visibleRange; var c = this.cols; var offsetX = (undefined !== offsetXForDraw) ? offsetXForDraw : c[vr.c1].left - this.cellsLeft; var offsetY = (undefined !== offsetYForDraw) ? offsetYForDraw : this.headersTop; if (null === drawingCtx && this.topLeftFrozenCell && undefined === offsetXForDraw) { var cFrozen = this.topLeftFrozenCell.getCol0(); if (start < vr.c1) { offsetX = c[0].left - this.cellsLeft; } else { offsetX -= c[cFrozen].left - c[0].left; } } if (asc_typeof(start) !== "number") { start = vr.c1; } if (asc_typeof(end) !== "number") { end = vr.c2; } if (style === undefined) { style = kHeaderDefault; } this._setFont(drawingCtx, this.model.getDefaultFontName(), this.model.getDefaultFontSize()); // draw column headers for (var i = start; i <= end; ++i) { this._drawHeader(drawingCtx, c[i].left - offsetX, offsetY, c[i].width, this.headersHeight, style, true, i); } }; /** Рисует заголовки видимых строк */ WorksheetView.prototype._drawRowHeaders = function (drawingCtx, start, end, style, offsetXForDraw, offsetYForDraw) { if (null === drawingCtx && false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { return; } var vr = this.visibleRange; var r = this.rows; var offsetX = (undefined !== offsetXForDraw) ? offsetXForDraw : this.headersLeft; var offsetY = (undefined !== offsetYForDraw) ? offsetYForDraw : r[vr.r1].top - this.cellsTop; if (null === drawingCtx && this.topLeftFrozenCell && undefined === offsetYForDraw) { var rFrozen = this.topLeftFrozenCell.getRow0(); if (start < vr.r1) { offsetY = r[0].top - this.cellsTop; } else { offsetY -= r[rFrozen].top - r[0].top; } } if (asc_typeof(start) !== "number") { start = vr.r1; } if (asc_typeof(end) !== "number") { end = vr.r2; } if (style === undefined) { style = kHeaderDefault; } this._setFont(drawingCtx, this.model.getDefaultFontName(), this.model.getDefaultFontSize()); // draw row headers for (var i = start; i <= end; ++i) { this._drawHeader(drawingCtx, offsetX, r[i].top - offsetY, this.headersWidth, r[i].height, style, false, i); } }; /** * Рисует заголовок, принимает координаты и размеры в pt * @param {DrawingContext} drawingCtx * @param {Number} x Координата левого угла в pt * @param {Number} y Координата левого угла в pt * @param {Number} w Ширина в pt * @param {Number} h Высота в pt * @param {Number} style Стиль заголовка (kHeaderDefault, kHeaderActive, kHeaderHighlighted) * @param {Boolean} isColHeader Тип заголовка: true - колонка, false - строка * @param {Number} index Индекс столбца/строки или -1 */ WorksheetView.prototype._drawHeader = function (drawingCtx, x, y, w, h, style, isColHeader, index) { // Для отрисовки невидимого столбца/строки var isZeroHeader = false; if (-1 !== index) { if (isColHeader) { if (w < this.width_1px) { if (style !== kHeaderDefault) { return; } // Это невидимый столбец isZeroHeader = true; // Отрисуем только границу w = this.width_1px; // Возможно мы уже рисовали границу невидимого столбца (для последовательности невидимых) if (0 < index && 0 === this.cols[index - 1].width) { // Мы уже нарисовали border для невидимой границы return; } } else if (0 < index && 0 === this.cols[index - 1].width) { // Мы уже нарисовали border для невидимой границы (поэтому нужно чуть меньше рисовать для соседнего столбца) w -= this.width_1px; x += this.width_1px; } } else { if (h < this.height_1px) { if (style !== kHeaderDefault) { return; } // Это невидимая строка isZeroHeader = true; // Отрисуем только границу h = this.height_1px; // Возможно мы уже рисовали границу невидимой строки (для последовательности невидимых) if (0 < index && 0 === this.rows[index - 1].height) { // Мы уже нарисовали border для невидимой границы return; } } else if (0 < index && 0 === this.rows[index - 1].height) { // Мы уже нарисовали border для невидимой границы (поэтому нужно чуть меньше рисовать для соседней строки) h -= this.height_1px; y += this.height_1px; } } } var ctx = drawingCtx || this.drawingCtx; var st = this.settings.header.style[style]; var x2 = x + w; var y2 = y + h; var x2WithoutBorder = x2 - this.width_1px; var y2WithoutBorder = y2 - this.height_1px; // background только для видимых if (!isZeroHeader) { // draw background ctx.setFillStyle(st.background) .fillRect(x, y, w, h); } // draw border ctx.setStrokeStyle(st.border) .setLineWidth(1) .beginPath(); if (style !== kHeaderDefault && !isColHeader) { // Select row (top border) ctx.lineHorPrevPx(x, y, x2); } // Right border ctx.lineVerPrevPx(x2, y, y2); // Bottom border ctx.lineHorPrevPx(x, y2, x2); if (style !== kHeaderDefault && isColHeader) { // Select col (left border) ctx.lineVerPrevPx(x, y, y2); } ctx.stroke(); // Для невидимых кроме border-а ничего не рисуем if (isZeroHeader || -1 === index) { return; } // draw text var text = isColHeader ? this._getColumnTitle(index) : this._getRowTitle(index); var sr = this.stringRender; var tm = this._roundTextMetrics(sr.measureString(text)); var bl = y2WithoutBorder - (isColHeader ? this.defaultRowDescender : this.rows[index].descender); var textX = this._calcTextHorizPos(x, x2WithoutBorder, tm, tm.width < w ? AscCommon.align_Center : AscCommon.align_Left); var textY = this._calcTextVertPos(y, y2WithoutBorder, bl, tm, Asc.c_oAscVAlign.Bottom); ctx.AddClipRect(x, y, w, h); ctx.setFillStyle(st.color).fillText(text, textX, textY + tm.baseline, undefined, sr.charWidths); ctx.RemoveClipRect(); }; WorksheetView.prototype._cleanColumnHeaders = function (colStart, colEnd) { var offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; var i, cFrozen = 0; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); offsetX -= this.cols[cFrozen].left - this.cols[0].left; } if (colEnd === undefined) { colEnd = colStart; } var colStartTmp = Math.max(this.visibleRange.c1, colStart); var colEndTmp = Math.min(this.visibleRange.c2, colEnd); for (i = colStartTmp; i <= colEndTmp; ++i) { this.drawingCtx.clearRectByX(this.cols[i].left - offsetX, this.headersTop, this.cols[i].width, this.headersHeight); } if (0 !== cFrozen) { offsetX = this.cols[0].left - this.cellsLeft; // Почистим для pane colStart = Math.max(0, colStart); colEnd = Math.min(cFrozen, colEnd); for (i = colStart; i <= colEnd; ++i) { this.drawingCtx.clearRectByX(this.cols[i].left - offsetX, this.headersTop, this.cols[i].width, this.headersHeight); } } }; WorksheetView.prototype._cleanRowHeaders = function (rowStart, rowEnd) { var offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; var i, rFrozen = 0; if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); offsetY -= this.rows[rFrozen].top - this.rows[0].top; } if (rowEnd === undefined) { rowEnd = rowStart; } var rowStartTmp = Math.max(this.visibleRange.r1, rowStart); var rowEndTmp = Math.min(this.visibleRange.r2, rowEnd); for (i = rowStartTmp; i <= rowEndTmp; ++i) { if (this.height_1px > this.rows[i].height) { continue; } this.drawingCtx.clearRectByY(this.headersLeft, this.rows[i].top - offsetY, this.headersWidth, this.rows[i].height); } if (0 !== rFrozen) { offsetY = this.rows[0].top - this.cellsTop; // Почистим для pane rowStart = Math.max(0, rowStart); rowEnd = Math.min(rFrozen, rowEnd); for (i = rowStart; i <= rowEnd; ++i) { if (this.height_1px > this.rows[i].height) { continue; } this.drawingCtx.clearRectByY(this.headersLeft, this.rows[i].top - offsetY, this.headersWidth, this.rows[i].height); } } }; WorksheetView.prototype._cleanColumnHeadersRect = function () { this.drawingCtx.clearRect(this.cellsLeft, this.headersTop, this.drawingCtx.getWidth() - this.cellsLeft, this.headersHeight); }; /** Рисует сетку таблицы */ WorksheetView.prototype._drawGrid = function (drawingCtx, range, leftFieldInPt, topFieldInPt, width, height) { // Возможно сетку не нужно рисовать (при печати свои проверки) if (null === drawingCtx && false === this.model.sheetViews[0].asc_getShowGridLines()) { return; } if (range === undefined) { range = this.visibleRange; } var ctx = drawingCtx || this.drawingCtx; var c = this.cols; var r = this.rows; var widthCtx = (width) ? width : ctx.getWidth(); var heightCtx = (height) ? height : ctx.getHeight(); var offsetX = (undefined !== leftFieldInPt) ? leftFieldInPt : c[this.visibleRange.c1].left - this.cellsLeft; var offsetY = (undefined !== topFieldInPt) ? topFieldInPt : r[this.visibleRange.r1].top - this.cellsTop; if (null === drawingCtx && this.topLeftFrozenCell) { if (undefined === leftFieldInPt) { var cFrozen = this.topLeftFrozenCell.getCol0(); offsetX -= c[cFrozen].left - c[0].left; } if (undefined === topFieldInPt) { var rFrozen = this.topLeftFrozenCell.getRow0(); offsetY -= r[rFrozen].top - r[0].top; } } var x1 = c[range.c1].left - offsetX; var y1 = r[range.r1].top - offsetY; var x2 = Math.min(c[range.c2].left - offsetX + c[range.c2].width, widthCtx); var y2 = Math.min(r[range.r2].top - offsetY + r[range.r2].height, heightCtx); ctx.setFillStyle(this.settings.cells.defaultState.background) .fillRect(x1, y1, x2 - x1, y2 - y1) .setStrokeStyle(this.settings.cells.defaultState.border) .setLineWidth(1).beginPath(); var i, d, l; for (i = range.c1, d = x1; i <= range.c2 && d <= x2; ++i) { l = c[i].width; d += l; if (l >= this.width_1px) { ctx.lineVerPrevPx(d, y1, y2); } } for (i = range.r1, d = y1; i <= range.r2 && d <= y2; ++i) { l = r[i].height; d += l; if (l >= this.height_1px) { ctx.lineHorPrevPx(x1, d, x2); } } ctx.stroke(); // Clear grid for pivot tables with classic and outline layout var clearRange, pivotRange, clearRanges = this.model.getPivotTablesClearRanges(range); ctx.setFillStyle(this.settings.cells.defaultState.background); for (i = 0; i < clearRanges.length; i += 2) { clearRange = clearRanges[i]; pivotRange = clearRanges[i + 1]; x1 = c[clearRange.c1].left - offsetX + (clearRange.c1 === pivotRange.c1 ? this.width_1px : 0); y1 = r[clearRange.r1].top - offsetY + (clearRange.r1 === pivotRange.r1 ? this.height_1px : 0); x2 = Math.min(c[clearRange.c2].left - offsetX + c[clearRange.c2].width - (clearRange.c2 === pivotRange.c2 ? this.width_1px : 0), widthCtx); y2 = Math.min(r[clearRange.r2].top - offsetY + r[clearRange.r2].height - (clearRange.r2 === pivotRange.r2 ? this.height_1px : 0), heightCtx); ctx.fillRect(x1, y1, x2 - x1, y2 - y1); } }; WorksheetView.prototype._drawCellsAndBorders = function ( drawingCtx, range, offsetXForDraw, offsetYForDraw ) { if ( range === undefined ) { range = this.visibleRange; } var left, top, cFrozen, rFrozen; var offsetX = (undefined === offsetXForDraw) ? this.cols[this.visibleRange.c1].left - this.cellsLeft : offsetXForDraw; var offsetY = (undefined === offsetYForDraw) ? this.rows[this.visibleRange.r1].top - this.cellsTop : offsetYForDraw; if ( null === drawingCtx && this.topLeftFrozenCell ) { if ( undefined === offsetXForDraw ) { cFrozen = this.topLeftFrozenCell.getCol0(); offsetX -= this.cols[cFrozen].left - this.cols[0].left; } if ( undefined === offsetYForDraw ) { rFrozen = this.topLeftFrozenCell.getRow0(); offsetY -= this.rows[rFrozen].top - this.rows[0].top; } } if ( !drawingCtx && !window['IS_NATIVE_EDITOR'] ) { left = this.cols[range.c1].left; top = this.rows[range.r1].top; // set clipping rect to cells area this.drawingCtx.save() .beginPath() .rect( left - offsetX, top - offsetY, Math.min( this.cols[range.c2].left - left + this.cols[range.c2].width, this.drawingCtx.getWidth() - this.cellsLeft ), Math.min( this.rows[range.r2].top - top + this.rows[range.r2].height, this.drawingCtx.getHeight() - this.cellsTop ) ) .clip(); } var mergedCells = this._drawCells( drawingCtx, range, offsetX, offsetY ); this._drawCellsBorders( drawingCtx, range, offsetX, offsetY, mergedCells ); if ( !drawingCtx && !window['IS_NATIVE_EDITOR'] ) { // restore canvas' original clipping range this.drawingCtx.restore(); } }; /** Рисует спарклайны */ WorksheetView.prototype._drawSparklines = function(drawingCtx, range, offsetX, offsetY) { this.objectRender.drawSparkLineGroups(drawingCtx || this.drawingCtx, this.model.aSparklineGroups, range, offsetX, offsetY); }; /** Рисует ячейки таблицы */ WorksheetView.prototype._drawCells = function ( drawingCtx, range, offsetX, offsetY ) { this._prepareCellTextMetricsCache( range ); var mergedCells = [], mc, i; for ( var row = range.r1; row <= range.r2; ++row ) { mergedCells = mergedCells.concat(this._drawRowBG(drawingCtx, row, range.c1, range.c2, offsetX, offsetY, null), this._drawRowText(drawingCtx, row, range.c1, range.c2, offsetX, offsetY)); } // draw merged cells at last stage to fix cells background issue for (i = 0; i < mergedCells.length; ++i) { if (i === mergedCells.indexOf(mergedCells[i])) { mc = mergedCells[i]; this._drawRowBG(drawingCtx, mc.r1, mc.c1, mc.c1, offsetX, offsetY, mc); this._drawCellText(drawingCtx, mc.c1, mc.r1, range.c1, range.c2, offsetX, offsetY, true); } } this._drawSparklines(drawingCtx, range, offsetX, offsetY); return mergedCells; }; /** Рисует фон ячеек в строке */ WorksheetView.prototype._drawRowBG = function ( drawingCtx, row, colStart, colEnd, offsetX, offsetY, oMergedCell ) { var mergedCells = []; if ( this.rows[row].height < this.height_1px && null === oMergedCell ) { return mergedCells; } var ctx = drawingCtx || this.drawingCtx; for ( var col = colStart; col <= colEnd; ++col ) { if ( this.cols[col].width < this.width_1px && null === oMergedCell ) { continue; } // ToDo подумать, может стоит не брать ячейку из модели (а брать из кеш-а) var c = this._getVisibleCell( col, row ); var findFillColor = this.handlers.trigger('selectSearchingResults') && this.model.inFindResults(row, col) ? this.settings.findFillColor : null; var fillColor = c.getFill(); var bg = fillColor || findFillColor; var mc = null; var mwidth = 0, mheight = 0; if ( null === oMergedCell ) { mc = this.model.getMergedByCell( row, col ); if ( null !== mc ) { mergedCells.push(mc); col = mc.c2; continue; } } else { mc = oMergedCell; } if ( null !== mc ) { if ( col !== mc.c1 || row !== mc.r1 ) { continue; } for ( var i = mc.c1 + 1; i <= mc.c2 && i < this.cols.length; ++i ) { mwidth += this.cols[i].width; } for ( var j = mc.r1 + 1; j <= mc.r2 && j < this.rows.length; ++j ) { mheight += this.rows[j].height; } } else { if ( bg === null ) { if ( col === colEnd && col < this.cols.length - 1 && row < this.rows.length - 1 ) { var c2 = this._getVisibleCell( col + 1, row ); var bg2 = c2.getFill(); if ( bg2 !== null ) { ctx.setFillStyle( bg2 ) .fillRect( this.cols[col + 1].left - offsetX - this.width_1px, this.rows[row].top - offsetY - this.height_1px, this.width_1px, this.rows[row].height + this.height_1px ); } var c3 = this._getVisibleCell( col, row + 1 ); var bg3 = c3.getFill(); if ( bg3 !== null ) { ctx.setFillStyle( bg3 ) .fillRect( this.cols[col].left - offsetX - this.width_1px, this.rows[row + 1].top - offsetY - this.height_1px, this.cols[col].width + this.width_1px, this.height_1px ); } } continue; } } var x = this.cols[col].left - (bg !== null ? this.width_1px : 0); var y = this.rows[row].top - (bg !== null ? this.height_1px : 0); var w = this.cols[col].width + this.width_1px * (bg !== null ? +1 : -1) + mwidth; var h = this.rows[row].height + this.height_1px * (bg !== null ? +1 : -1) + mheight; var color = bg !== null ? bg : this.settings.cells.defaultState.background; ctx.setFillStyle( color ).fillRect( x - offsetX, y - offsetY, w, h ); if (fillColor && findFillColor) { ctx.setFillStyle(findFillColor).fillRect(x - offsetX, y - offsetY, w, h); } } return mergedCells; }; /** Рисует текст ячеек в строке */ WorksheetView.prototype._drawRowText = function ( drawingCtx, row, colStart, colEnd, offsetX, offsetY ) { var mergedCells = []; if ( this.rows[row].height < this.height_1px ) { return mergedCells; } var dependentCells = {}, i, mc, col; // draw cells' text for ( col = colStart; col <= colEnd; ++col ) { if ( this.cols[col].width < this.width_1px ) { continue; } mc = this._drawCellText( drawingCtx, col, row, colStart, colEnd, offsetX, offsetY, false ); if ( mc !== null ) { mergedCells.push(mc); } // check if long text overlaps this cell i = this._findSourceOfCellText( col, row ); if ( i >= 0 ) { dependentCells[i] = (dependentCells[i] || []); dependentCells[i].push( col ); } } // draw long text that overlaps own cell's borders for ( i in dependentCells ) { var arr = dependentCells[i], j = arr.length - 1; col = i >> 0; // if source cell belongs to cells range then skip it (text has been drawn already) if ( col >= arr[0] && col <= arr[j] ) { continue; } // draw long text fragment this._drawCellText( drawingCtx, col, row, arr[0], arr[j], offsetX, offsetY, false ); } return mergedCells; }; /** Рисует текст ячейки */ WorksheetView.prototype._drawCellText = function (drawingCtx, col, row, colStart, colEnd, offsetX, offsetY, drawMergedCells) { var c = this._getVisibleCell(col, row); var color = c.getFont().getColor(); var ct = this._getCellTextCache(col, row); if (!ct) { return null; } var isMerged = ct.flags.isMerged(), range = undefined, isWrapped = ct.flags.wrapText; var ctx = drawingCtx || this.drawingCtx; if (isMerged) { range = ct.flags.merged; if (!drawMergedCells) { return range; } if (col !== range.c1 || row !== range.r1) { return null; } } var colL = isMerged ? range.c1 : Math.max(colStart, col - ct.sideL); var colR = isMerged ? Math.min(range.c2, this.nColsCount - 1) : Math.min(colEnd, col + ct.sideR); var rowT = isMerged ? range.r1 : row; var rowB = isMerged ? Math.min(range.r2, this.nRowsCount - 1) : row; var isTrimmedR = !isMerged && colR !== col + ct.sideR; if (!(ct.angle || 0)) { if (!isMerged && !isWrapped) { this._eraseCellRightBorder(drawingCtx, colL, colR + (isTrimmedR ? 1 : 0), row, offsetX, offsetY); } } var x1 = this.cols[colL].left - offsetX; var y1 = this.rows[rowT].top - offsetY; var w = this.cols[colR].left + this.cols[colR].width - offsetX - x1; var h = this.rows[rowB].top + this.rows[rowB].height - offsetY - y1; var x2 = x1 + w - (isTrimmedR ? 0 : this.width_1px); var y2 = y1 + h - this.height_1px; var bl = !isMerged ? (y2 - this.rows[rowB].descender) : (y2 - ct.metrics.height + ct.metrics.baseline - this.height_1px); var x1ct = isMerged ? x1 : this.cols[col].left - offsetX; var x2ct = isMerged ? x2 : x1ct + this.cols[col].width - this.width_1px; var textX = this._calcTextHorizPos(x1ct, x2ct, ct.metrics, ct.cellHA); var textY = this._calcTextVertPos(y1, y2, bl, ct.metrics, ct.cellVA); var textW = this._calcTextWidth(x1ct, x2ct, ct.metrics, ct.cellHA); var xb1, yb1, wb, hb, colLeft, colRight, i; var txtRotX, txtRotW, clipUse = false; if (ct.angle || 0) { xb1 = this.cols[col].left - offsetX; yb1 = this.rows[row].top - offsetY; wb = this.cols[col].width; hb = this.rows[row].height; txtRotX = xb1 - ct.textBound.offsetX; txtRotW = ct.textBound.width + xb1 - ct.textBound.offsetX; if (isMerged) { wb = 0; for (i = colL; i <= colR && i < this.nColsCount; ++i) { wb += this.cols[i].width; } hb = 0; for (i = rowT; i <= rowB && i < this.nRowsCount; ++i) { hb += this.rows[i].height; } ctx.AddClipRect(xb1, yb1, wb, hb); clipUse = true; } this.stringRender.angle = ct.angle; this.stringRender.fontNeedUpdate = true; if (90 === ct.angle || -90 === ct.angle) { // клип по ячейке if (!isMerged) { ctx.AddClipRect(xb1, yb1, wb, hb); clipUse = true; } } else { // клип по строке if (!isMerged) { ctx.AddClipRect(0, y1, this.drawingCtx.getWidth(), h); clipUse = true; } if (!isMerged && !isWrapped) { colLeft = col; if (0 !== txtRotX) { while (true) { if (0 == colLeft) { break; } if (txtRotX >= this.cols[colLeft].left) { break; } --colLeft; } } colRight = Math.min(col, this.nColsCount - 1); if (0 !== txtRotW) { while (true) { ++colRight; if (colRight >= this.nColsCount) { --colRight; break; } if (txtRotW <= this.cols[colRight].left) { --colRight; break; } } } colLeft = isMerged ? range.c1 : colLeft; colRight = isMerged ? Math.min(range.c2, this.nColsCount - 1) : colRight; this._eraseCellRightBorder(drawingCtx, colLeft, colRight + (isTrimmedR ? 1 : 0), row, offsetX, offsetY); } } this.stringRender.rotateAtPoint(drawingCtx, ct.angle, xb1, yb1, ct.textBound.dx, ct.textBound.dy); this.stringRender.restoreInternalState(ct.state); if (isWrapped) { if (ct.angle < 0) { if (Asc.c_oAscVAlign.Top === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Left; } else if (Asc.c_oAscVAlign.Center === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Center; } else if (Asc.c_oAscVAlign.Bottom === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Right; } } else { if (Asc.c_oAscVAlign.Top === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Right; } else if (Asc.c_oAscVAlign.Center === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Center; } else if (Asc.c_oAscVAlign.Bottom === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Left; } } } this.stringRender.render(drawingCtx, 0, 0, textW, color); this.stringRender.resetTransform(drawingCtx); if (clipUse) { ctx.RemoveClipRect(); } } else { ctx.AddClipRect(x1, y1, w, h); this.stringRender.restoreInternalState(ct.state).render(drawingCtx, textX, textY, textW, color); ctx.RemoveClipRect(); } return null; }; /** Удаляет вертикальные границы ячейки, если текст выходит за границы и соседние ячейки пусты */ WorksheetView.prototype._eraseCellRightBorder = function ( drawingCtx, colBeg, colEnd, row, offsetX, offsetY ) { if ( colBeg >= colEnd ) { return; } var nextCell = -1; var ctx = drawingCtx || this.drawingCtx; ctx.setFillStyle( this.settings.cells.defaultState.background ); for ( var col = colBeg; col < colEnd; ++col ) { var c = -1 !== nextCell ? nextCell : this._getCell( col, row ); var bg = null !== c ? c.getFill() : null; if ( bg !== null ) { continue; } nextCell = this._getCell( col + 1, row ); bg = null !== nextCell ? nextCell.getFill() : null; if ( bg !== null ) { continue; } ctx.fillRect( this.cols[col].left + this.cols[col].width - offsetX - this.width_1px, this.rows[row].top - offsetY, this.width_1px, this.rows[row].height - this.height_1px ); } }; /** Рисует рамки для ячеек */ WorksheetView.prototype._drawCellsBorders = function (drawingCtx, range, offsetX, offsetY, mergedCells) { //TODO: использовать стили линий при рисовании границ var t = this; var ctx = drawingCtx || this.drawingCtx; var c = this.cols; var r = this.rows; var objectMergedCells = {}; // Двумерный map вида строка-колонка {1: {1: range, 4: range}} var i, mergeCellInfo, startCol, endRow, endCol, col, row; for (i in mergedCells) { mergeCellInfo = mergedCells[i]; startCol = Math.max(range.c1, mergeCellInfo.c1); endRow = Math.min(mergeCellInfo.r2, range.r2, this.nRowsCount); endCol = Math.min(mergeCellInfo.c2, range.c2, this.nColsCount); for (row = Math.max(range.r1, mergeCellInfo.r1); row <= endRow; ++row) { if (!objectMergedCells.hasOwnProperty(row)) { objectMergedCells[row] = {}; } for (col = startCol; col <= endCol; ++col) { objectMergedCells[row][col] = mergeCellInfo; } } } var bc = null, bs = c_oAscBorderStyles.None, isNotFirst = false; // cached border color function drawBorder(type, border, x1, y1, x2, y2) { var isStroke = false, isNewColor = !AscCommonExcel.g_oColorManager.isEqual(bc, border.c), isNewStyle = bs !== border.s; if (isNotFirst && (isNewColor || isNewStyle)) { ctx.stroke(); isStroke = true; } if (isNewColor) { bc = border.c; ctx.setStrokeStyle(bc); } if (isNewStyle) { bs = border.s; ctx.setLineWidth(border.w); ctx.setLineDash(border.getDashSegments()); } if (isStroke || false === isNotFirst) { isNotFirst = true; ctx.beginPath(); } switch (type) { case c_oAscBorderType.Hor: ctx.lineHor(x1, y1, x2); break; case c_oAscBorderType.Ver: ctx.lineVer(x1, y1, y2); break; case c_oAscBorderType.Diag: ctx.lineDiag(x1, y1, x2, y2); break; } } function drawVerticalBorder(borderLeftObject, borderRightObject, x, y1, y2) { var borderLeft = borderLeftObject ? borderLeftObject.borders : null, borderRight = borderRightObject ? borderRightObject.borders : null; var border = AscCommonExcel.getMatchingBorder(borderLeft && borderLeft.r, borderRight && borderRight.l); if (!border || border.w < 1) { return; } // ToDo переделать рассчет var tbw = t._calcMaxBorderWidth(borderLeftObject && borderLeftObject.getTopBorder(), borderRightObject && borderRightObject.getTopBorder()); // top border width var bbw = t._calcMaxBorderWidth(borderLeftObject && borderLeftObject.getBottomBorder(), borderRightObject && borderRightObject.getBottomBorder()); // bottom border width var dy1 = tbw > border.w ? tbw - 1 : (tbw > 1 ? -1 : 0); var dy2 = bbw > border.w ? -2 : (bbw > 2 ? 1 : 0); drawBorder(c_oAscBorderType.Ver, border, x, y1 + (-1 + dy1) * t.height_1px, x, y2 + (1 + dy2) * t.height_1px); } function drawHorizontalBorder(borderTopObject, borderBottomObject, x1, y, x2) { var borderTop = borderTopObject ? borderTopObject.borders : null, borderBottom = borderBottomObject ? borderBottomObject.borders : null; var border = AscCommonExcel.getMatchingBorder(borderTop && borderTop.b, borderBottom && borderBottom.t); if (border && border.w > 0) { // ToDo переделать рассчет var lbw = t._calcMaxBorderWidth(borderTopObject && borderTopObject.getLeftBorder(), borderBottomObject && borderBottomObject.getLeftBorder()); var rbw = t._calcMaxBorderWidth(borderTopObject && borderTopObject.getRightBorder(), borderTopObject && borderTopObject.getRightBorder()); var dx1 = border.w > lbw ? (lbw > 1 ? -1 : 0) : (lbw > 2 ? 2 : 1); var dx2 = border.w > rbw ? (rbw > 2 ? 1 : 0) : (rbw > 1 ? -2 : -1); drawBorder(c_oAscBorderType.Hor, border, x1 + (-1 + dx1) * t.width_1px, y, x2 + (1 + dx2) * t.width_1px, y); } } var arrPrevRow = [], arrCurrRow = [], arrNextRow = []; var objMCPrevRow = null, objMCRow = null, objMCNextRow = null; var bCur, bPrev, bNext, bTopCur, bTopPrev, bTopNext, bBotCur, bBotPrev, bBotNext; bCur = bPrev = bNext = bTopCur = bTopNext = bBotCur = bBotNext = null; row = range.r1 - 1; var prevCol = range.c1 - 1; // Определим первую колонку (т.к. могут быть скрытые колонки) while (0 <= prevCol && c[prevCol].width < t.width_1px) --prevCol; // Сначала пройдемся по верхней строке (над отрисовываемым диапазоном) while (0 <= row) { if (r[row].height >= t.height_1px) { objMCPrevRow = objectMergedCells[row]; for (col = prevCol; col <= range.c2 && col < t.nColsCount; ++col) { if (0 > col || c[col].width < t.width_1px) { continue; } arrPrevRow[col] = new CellBorderObject(t._getVisibleCell(col, row).getBorder(), objMCPrevRow ? objMCPrevRow[col] : null, col, row); } break; } --row; } var mc = null, nextRow, isFirstRow = true; var isPrevColExist = (0 <= prevCol); for (row = range.r1; row <= range.r2 && row < t.nRowsCount; row = nextRow) { nextRow = row + 1; if (r[row].height < t.height_1px) { continue; } // Нужно отсеять пустые снизу for (; nextRow <= range.r2 && nextRow < t.nRowsCount; ++nextRow) { if (r[nextRow].height >= t.height_1px) { break; } } var isFirstRowTmp = isFirstRow, isLastRow = nextRow > range.r2 || nextRow >= t.nRowsCount; isFirstRow = false; // Это уже не первая строка (определяем не по совпадению с range.r1, а по видимости) objMCRow = isFirstRowTmp ? objectMergedCells[row] : objMCNextRow; objMCNextRow = objectMergedCells[nextRow]; var rowCache = t._fetchRowCache(row); var y1 = r[row].top - offsetY; var y2 = y1 + r[row].height - t.height_1px; var nextCol, isFirstCol = true; for (col = range.c1; col <= range.c2 && col < t.nColsCount; col = nextCol) { nextCol = col + 1; if (c[col].width < t.width_1px) { continue; } // Нужно отсеять пустые справа for (; nextCol <= range.c2 && nextCol < t.nColsCount; ++nextCol) { if (c[nextCol].width >= t.width_1px) { break; } } var isFirstColTmp = isFirstCol, isLastCol = nextCol > range.c2 || nextCol >= t.nColsCount; isFirstCol = false; // Это уже не первая колонка (определяем не по совпадению с range.c1, а по видимости) mc = objMCRow ? objMCRow[col] : null; var x1 = c[col].left - offsetX; var x2 = x1 + c[col].width - this.width_1px; if (row === t.nRowsCount) { bBotPrev = bBotCur = bBotNext = null; } else { if (isFirstColTmp) { bBotPrev = arrNextRow[prevCol] = new CellBorderObject(isPrevColExist ? t._getVisibleCell(prevCol, nextRow).getBorder() : null, objMCNextRow ? objMCNextRow[prevCol] : null, prevCol, nextRow); bBotCur = arrNextRow[col] = new CellBorderObject(t._getVisibleCell(col, nextRow).getBorder(), objMCNextRow ? objMCNextRow[col] : null, col, nextRow); } else { bBotPrev = bBotCur; bBotCur = bBotNext; } } if (isFirstColTmp) { bPrev = arrCurrRow[prevCol] = new CellBorderObject(isPrevColExist ? t._getVisibleCell(prevCol, row).getBorder() : null, objMCRow ? objMCRow[prevCol] : null, prevCol, row); bCur = arrCurrRow[col] = new CellBorderObject(t._getVisibleCell(col, row).getBorder(), mc, col, row); bTopPrev = arrPrevRow[prevCol]; bTopCur = arrPrevRow[col]; } else { bPrev = bCur; bCur = bNext; bTopPrev = bTopCur; bTopCur = bTopNext; } if (col === t.nColsCount) { bNext = null; bTopNext = null; } else { bNext = arrCurrRow[nextCol] = new CellBorderObject(t._getVisibleCell(nextCol, row).getBorder(), objMCRow ? objMCRow[nextCol] : null, nextCol, row); bTopNext = arrPrevRow[nextCol]; if (row === t.nRowsCount) { bBotNext = null; } else { bBotNext = arrNextRow[nextCol] = new CellBorderObject(t._getVisibleCell(nextCol, nextRow).getBorder(), objMCNextRow ? objMCNextRow[nextCol] : null, nextCol, nextRow); } } if (mc && row !== mc.r1 && row !== mc.r2 && col !== mc.c1 && col !== mc.c2) { continue; } // draw diagonal borders if ((bCur.borders.dd || bCur.borders.du) && (!mc || (row === mc.r1 && col === mc.c1))) { var x2Diagonal = x2; var y2Diagonal = y2; if (mc) { // Merge cells x2Diagonal = c[mc.c2].left + c[mc.c2].width - offsetX - t.width_1px; y2Diagonal = r[mc.r2].top + r[mc.r2].height - offsetY - t.height_1px; } // ToDo Clip diagonal borders /*ctx.save() .beginPath() .rect(x1 + this.width_1px * (lb.w < 1 ? -1 : (lb.w < 3 ? 0 : +1)), y1 + this.width_1px * (tb.w < 1 ? -1 : (tb.w < 3 ? 0 : +1)), c[col].width + this.width_1px * ( -1 + (lb.w < 1 ? +1 : (lb.w < 3 ? 0 : -1)) + (rb.w < 1 ? +1 : (rb.w < 2 ? 0 : -1)) ), r[row].height + this.height_1px * ( -1 + (tb.w < 1 ? +1 : (tb.w < 3 ? 0 : -1)) + (bb.w < 1 ? +1 : (bb.w < 2 ? 0 : -1)) )) .clip(); */ if (bCur.borders.dd) { // draw diagonal line l,t - r,b drawBorder(c_oAscBorderType.Diag, bCur.borders.d, x1 - t.width_1px, y1 - t.height_1px, x2Diagonal, y2Diagonal); } if (bCur.borders.du) { // draw diagonal line l,b - r,t drawBorder(c_oAscBorderType.Diag, bCur.borders.d, x1 - t.width_1px, y2Diagonal, x2Diagonal, y1 - t.height_1px); } // ToDo Clip diagonal borders //ctx.restore(); // canvas context has just been restored, so destroy border color cache //bc = undefined; } // draw left border if (isFirstColTmp && !t._isLeftBorderErased(col, rowCache)) { drawVerticalBorder(bPrev, bCur, x1 - t.width_1px, y1, y2); // Если мы в печати и печатаем первый столбец, то нужно напечатать бордеры // if (lb.w >= 1 && drawingCtx && 0 === col) { // Иначе они будут не такой ширины // ToDo посмотреть что с этим ? в печати будет обрезка // drawVerticalBorder(lb, tb, tbPrev, bb, bbPrev, x1, y1, y2); // } } // draw right border if ((!mc || col === mc.c2) && !t._isRightBorderErased(col, rowCache)) { drawVerticalBorder(bCur, bNext, x2, y1, y2); } // draw top border if (isFirstRowTmp) { drawHorizontalBorder(bTopCur, bCur, x1, y1 - t.height_1px, x2); // Если мы в печати и печатаем первую строку, то нужно напечатать бордеры // if (tb.w > 0 && drawingCtx && 0 === row) { // ToDo посмотреть что с этим ? в печати будет обрезка // drawHorizontalBorder.call(this, tb, lb, lbPrev, rb, rbPrev, x1, y1, x2); // } } if (!mc || row === mc.r2) { // draw bottom border drawHorizontalBorder(bCur, bBotCur, x1, y2, x2); } } arrPrevRow = arrCurrRow; arrCurrRow = arrNextRow; arrNextRow = []; } if (isNotFirst) { ctx.stroke(); } }; /** Рисует закрепленные области областей */ WorksheetView.prototype._drawFrozenPane = function ( noCells ) { if ( this.topLeftFrozenCell ) { var row = this.topLeftFrozenCell.getRow0(); var col = this.topLeftFrozenCell.getCol0(); var tmpRange, offsetX, offsetY; if ( 0 < row && 0 < col ) { offsetX = this.cols[0].left - this.cellsLeft; offsetY = this.rows[0].top - this.cellsTop; tmpRange = new asc_Range( 0, 0, col - 1, row - 1 ); if ( !noCells ) { this._drawGrid( null, tmpRange, offsetX, offsetY ); this._drawCellsAndBorders(null, tmpRange, offsetX, offsetY ); } } if ( 0 < row ) { row -= 1; offsetX = undefined; offsetY = this.rows[0].top - this.cellsTop; tmpRange = new asc_Range( this.visibleRange.c1, 0, this.visibleRange.c2, row ); this._drawRowHeaders( null, 0, row, kHeaderDefault, offsetX, offsetY ); if ( !noCells ) { this._drawGrid( null, tmpRange, offsetX, offsetY ); this._drawCellsAndBorders(null, tmpRange, offsetX, offsetY ); } } if ( 0 < col ) { col -= 1; offsetX = this.cols[0].left - this.cellsLeft; offsetY = undefined; tmpRange = new asc_Range( 0, this.visibleRange.r1, col, this.visibleRange.r2 ); this._drawColumnHeaders( null, 0, col, kHeaderDefault, offsetX, offsetY ); if ( !noCells ) { this._drawGrid( null, tmpRange, offsetX, offsetY ); this._drawCellsAndBorders(null, tmpRange, offsetX, offsetY ); } } } }; /** Рисует закрепление областей */ WorksheetView.prototype._drawFrozenPaneLines = function (drawingCtx) { // Возможно стоит отрисовывать на overlay, а не на основной канве var ctx = drawingCtx || this.drawingCtx; var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, this.model.getId(), AscCommonExcel.c_oAscLockNameFrozenPane); var isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false); var color = isLocked ? AscCommonExcel.c_oAscCoAuthoringOtherBorderColor : this.settings.frozenColor; ctx.setLineWidth(1).setStrokeStyle(color).beginPath(); var fHorLine, fVerLine; if (isLocked) { fHorLine = ctx.dashLineCleverHor; fVerLine = ctx.dashLineCleverVer; } else { fHorLine = ctx.lineHorPrevPx; fVerLine = ctx.lineVerPrevPx; } if (this.topLeftFrozenCell) { var row = this.topLeftFrozenCell.getRow0(); var col = this.topLeftFrozenCell.getCol0(); if (0 < row) { fHorLine.apply(ctx, [0, this.rows[row].top, ctx.getWidth()]); } else { fHorLine.apply(ctx, [0, this.headersHeight, this.headersWidth]); } if (0 < col) { fVerLine.apply(ctx, [this.cols[col].left, 0, ctx.getHeight()]); } else { fVerLine.apply(ctx, [this.headersWidth, 0, this.headersHeight]); } ctx.stroke(); } else if (this.model.sheetViews[0].asc_getShowRowColHeaders()) { fHorLine.apply(ctx, [0, this.headersHeight, this.headersWidth]); fVerLine.apply(ctx, [this.headersWidth, 0, this.headersHeight]); ctx.stroke(); } }; WorksheetView.prototype.drawFrozenGuides = function ( x, y, target ) { var data, offsetFrozen; var ctx = this.overlayCtx; ctx.clear(); this._drawSelection(); switch ( target ) { case c_oTargetType.FrozenAnchorV: x *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIX() ); data = this._findColUnderCursor( x, true, true ); if ( data ) { data.col += 1; if ( 0 <= data.col && data.col < this.cols.length ) { var h = ctx.getHeight(); var offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; offsetFrozen = this.getFrozenPaneOffset( false, true ); offsetX -= offsetFrozen.offsetX; ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( this.cols[data.col].left - offsetX - this.width_1px, 0, this.width_1px, h ); } } break; case c_oTargetType.FrozenAnchorH: y *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIY() ); data = this._findRowUnderCursor( y, true, true ); if ( data ) { data.row += 1; if ( 0 <= data.row && data.row < this.rows.length ) { var w = ctx.getWidth(); var offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; offsetFrozen = this.getFrozenPaneOffset( true, false ); offsetY -= offsetFrozen.offsetY; ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( 0, this.rows[data.row].top - offsetY - this.height_1px, w, this.height_1px ); } } break; } }; WorksheetView.prototype._isFrozenAnchor = function ( x, y ) { var result = {result: false, cursor: "move", name: ""}; if ( false === this.model.sheetViews[0].asc_getShowRowColHeaders() ) { return result; } var _this = this; var frozenCell = this.topLeftFrozenCell ? this.topLeftFrozenCell : new AscCommon.CellAddress( 0, 0, 0 ); x *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIX() ); y *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIY() ); function isPointInAnchor( x, y, rectX, rectY, rectW, rectH ) { var delta = 2 * asc_getcvt( 0/*px*/, 1/*pt*/, _this._getPPIX() ); return (x >= rectX - delta) && (x <= rectX + rectW + delta) && (y >= rectY - delta) && (y <= rectY + rectH + delta); } // vertical var _x = this.getCellLeft( frozenCell.getCol0(), 1 ) - 0.5; var _y = _this.headersTop; var w = 0; var h = _this.headersHeight; if ( isPointInAnchor( x, y, _x, _y, w, h ) ) { result.result = true; result.name = c_oTargetType.FrozenAnchorV; } // horizontal _x = _this.headersLeft; _y = this.getCellTop( frozenCell.getRow0(), 1 ) - 0.5; w = _this.headersWidth - 0.5; h = 0; if ( isPointInAnchor( x, y, _x, _y, w, h ) ) { result.result = true; result.name = c_oTargetType.FrozenAnchorH; } return result; }; WorksheetView.prototype.applyFrozenAnchor = function ( x, y, target ) { var t = this; var onChangeFrozenCallback = function ( isSuccess ) { if ( false === isSuccess ) { t.overlayCtx.clear(); t._drawSelection(); return; } var lastCol = 0, lastRow = 0, data; if ( t.topLeftFrozenCell ) { lastCol = t.topLeftFrozenCell.getCol0(); lastRow = t.topLeftFrozenCell.getRow0(); } switch ( target ) { case c_oTargetType.FrozenAnchorV: x *= asc_getcvt( 0/*px*/, 1/*pt*/, t._getPPIX() ); data = t._findColUnderCursor( x, true, true ); if ( data ) { data.col += 1; if ( 0 <= data.col && data.col < t.cols.length ) { lastCol = data.col; } } break; case c_oTargetType.FrozenAnchorH: y *= asc_getcvt( 0/*px*/, 1/*pt*/, t._getPPIY() ); data = t._findRowUnderCursor( y, true, true ); if ( data ) { data.row += 1; if ( 0 <= data.row && data.row < t.rows.length ) { lastRow = data.row; } } break; } t._updateFreezePane( lastCol, lastRow ); }; this._isLockedFrozenPane( onChangeFrozenCallback ); }; /** Для api закрепленных областей */ WorksheetView.prototype.freezePane = function () { var t = this; var activeCell = this.model.selectionRange.activeCell.clone(); var onChangeFreezePane = function (isSuccess) { if (false === isSuccess) { return; } var col, row, mc; if (null !== t.topLeftFrozenCell) { col = row = 0; } else { col = activeCell.col; row = activeCell.row; if (0 !== row || 0 !== col) { mc = t.model.getMergedByCell(row, col); if (mc) { col = mc.c1; row = mc.r1; } } if (0 === col && 0 === row) { col = ((t.visibleRange.c2 - t.visibleRange.c1) / 2) >> 0; row = ((t.visibleRange.r2 - t.visibleRange.r1) / 2) >> 0; } } t._updateFreezePane(col, row); }; return this._isLockedFrozenPane(onChangeFreezePane); }; WorksheetView.prototype._updateFreezePane = function (col, row, lockDraw) { var lastCol = 0, lastRow = 0; if (this.topLeftFrozenCell) { lastCol = this.topLeftFrozenCell.getCol0(); lastRow = this.topLeftFrozenCell.getRow0(); } History.Create_NewPoint(); var oData = new AscCommonExcel.UndoRedoData_FromTo(new AscCommonExcel.UndoRedoData_BBox(new asc_Range(lastCol, lastRow, lastCol, lastRow)), new AscCommonExcel.UndoRedoData_BBox(new asc_Range(col, row, col, row)), null); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeFrozenCell, this.model.getId(), null, oData); var isUpdate = false; if (0 === col && 0 === row) { // Очистка if (null !== this.topLeftFrozenCell) { isUpdate = true; } this.topLeftFrozenCell = this.model.sheetViews[0].pane = null; } else { // Создание if (null === this.topLeftFrozenCell) { isUpdate = true; } var pane = this.model.sheetViews[0].pane = new AscCommonExcel.asc_CPane(); this.topLeftFrozenCell = pane.topLeftFrozenCell = new AscCommon.CellAddress(row, col, 0); } this.visibleRange.c1 = col; this.visibleRange.r1 = row; if (col >= this.nColsCount) { this.expandColsOnScroll(false, true); } if (row >= this.nRowsCount) { this.expandRowsOnScroll(false, true); } this.visibleRange.r2 = 0; this._calcVisibleRows(); this.visibleRange.c2 = 0; this._calcVisibleColumns(); this.handlers.trigger("reinitializeScroll"); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.init(); } if (!lockDraw) { this.draw(); } // Эвент на обновление if (isUpdate && !this.model.workbook.bUndoChanges && !this.model.workbook.bRedoChanges) { this.handlers.trigger("updateSheetViewSettings"); } }; /** */ WorksheetView.prototype._drawSelectionElement = function (visibleRange, offsetX, offsetY, args) { var range = args[0]; var selectionLineType = args[1]; var strokeColor = args[2]; var isAllRange = args[3]; var colorN = this.settings.activeCellBorderColor2; var ctx = this.overlayCtx; var c = this.cols; var r = this.rows; var oIntersection = range.intersectionSimple(visibleRange); var ppiX = this._getPPIX(), ppiY = this._getPPIY(); if (!oIntersection) { return true; } var width_1px = asc_calcnpt(0, ppiX, 1/*px*/), width_2px = asc_calcnpt(0, ppiX, 2 /*px*/), width_3px = asc_calcnpt(0, ppiX, 3/*px*/), width_4px = asc_calcnpt(0, ppiX, 4 /*px*/), width_5px = asc_calcnpt(0, ppiX, 5/*px*/), width_7px = asc_calcnpt(0, ppiX, 7/*px*/), height_1px = asc_calcnpt(0, ppiY, 1/*px*/), height_2px = asc_calcnpt(0, ppiY, 2 /*px*/), height_3px = asc_calcnpt(0, ppiY, 3/*px*/), height_4px = asc_calcnpt(0, ppiY, 4 /*px*/), height_5px = asc_calcnpt(0, ppiY, 5/*px*/), height_7px = asc_calcnpt(0, ppiY, 7/*px*/); var fHorLine, fVerLine; var canFill = AscCommonExcel.selectionLineType.Selection & selectionLineType; var isDashLine = AscCommonExcel.selectionLineType.Dash & selectionLineType; if (isDashLine) { fHorLine = ctx.dashLineCleverHor; fVerLine = ctx.dashLineCleverVer; } else { fHorLine = ctx.lineHorPrevPx; fVerLine = ctx.lineVerPrevPx; } var firstCol = oIntersection.c1 === visibleRange.c1 && !isAllRange; var firstRow = oIntersection.r1 === visibleRange.r1 && !isAllRange; var drawLeftSide = oIntersection.c1 === range.c1; var drawRightSide = oIntersection.c2 === range.c2; var drawTopSide = oIntersection.r1 === range.r1; var drawBottomSide = oIntersection.r2 === range.r2; var x1 = c[oIntersection.c1].left - offsetX; var x2 = c[oIntersection.c2].left + c[oIntersection.c2].width - offsetX; var y1 = r[oIntersection.r1].top - offsetY; var y2 = r[oIntersection.r2].top + r[oIntersection.r2].height - offsetY; if (canFill) { var fillColor = strokeColor.Copy(); fillColor.a = 0.15; ctx.setFillStyle(fillColor).fillRect(x1, y1, x2 - x1, y2 - y1); } ctx.setLineWidth(isDashLine ? 1 : 2).setStrokeStyle(strokeColor); ctx.beginPath(); if (drawTopSide && !firstRow) { fHorLine.apply(ctx, [x1 - !isDashLine * width_2px, y1, x2 + !isDashLine * width_1px]); } if (drawBottomSide) { fHorLine.apply(ctx, [x1, y2 + !isDashLine * height_1px, x2]); } if (drawLeftSide && !firstCol) { fVerLine.apply(ctx, [x1, y1, y2 + !isDashLine * height_1px]); } if (drawRightSide) { fVerLine.apply(ctx, [x2 + !isDashLine * width_1px, y1, y2 + !isDashLine * height_1px]); } ctx.closePath().stroke(); // draw active cell in selection var isActive = AscCommonExcel.selectionLineType.ActiveCell & selectionLineType; if (isActive) { var cell = (this.isSelectionDialogMode ? this.copyActiveRange : this.model.selectionRange).activeCell; var fs = this.model.getMergedByCell(cell.row, cell.col); fs = range.intersectionSimple( fs ? fs : new asc_Range(cell.col, cell.row, cell.col, cell.row)); if (fs) { var _x1 = c[fs.c1].left - offsetX + width_1px; var _y1 = r[fs.r1].top - offsetY + height_1px; var _w = c[fs.c2].left - c[fs.c1].left + c[fs.c2].width - width_2px; var _h = r[fs.r2].top - r[fs.r1].top + r[fs.r2].height - height_2px; if (0 < _w && 0 < _h) { ctx.clearRect(_x1, _y1, _w, _h); } } } if (canFill) {/*Отрисовка светлой полосы при выборе ячеек для формулы*/ ctx.setLineWidth(1); ctx.setStrokeStyle(colorN); ctx.beginPath(); if (drawTopSide) { fHorLine.apply(ctx, [x1, y1 + height_1px, x2 - width_1px]); } if (drawBottomSide) { fHorLine.apply(ctx, [x1, y2 - height_1px, x2 - width_1px]); } if (drawLeftSide) { fVerLine.apply(ctx, [x1 + width_1px, y1, y2 - height_2px]); } if (drawRightSide) { fVerLine.apply(ctx, [x2 - width_1px, y1, y2 - height_2px]); } ctx.closePath().stroke(); } // Отрисовка квадратов для move/resize var isResize = AscCommonExcel.selectionLineType.Resize & selectionLineType; var isPromote = AscCommonExcel.selectionLineType.Promote & selectionLineType; if (isResize || isPromote) { ctx.setFillStyle(colorN); if (drawRightSide && drawBottomSide) { ctx.fillRect(x2 - width_4px, y2 - height_4px, width_7px, height_7px); } ctx.setFillStyle(strokeColor); if (drawRightSide && drawBottomSide) { ctx.fillRect(x2 - width_3px, y2 - height_3px, width_5px, height_5px); } if (isResize) { ctx.setFillStyle(colorN); if (drawLeftSide && drawTopSide) { ctx.fillRect(x1 - width_4px, y1 - height_4px, width_7px, height_7px); } if (drawRightSide && drawTopSide) { ctx.fillRect(x2 - width_4px, y1 - height_4px, width_7px, height_7px); } if (drawLeftSide && drawBottomSide) { ctx.fillRect(x1 - width_4px, y2 - height_4px, width_7px, height_7px); } ctx.setFillStyle(strokeColor); if (drawLeftSide && drawTopSide) { ctx.fillRect(x1 - width_3px, y1 - height_3px, width_5px, height_5px); } if (drawRightSide && drawTopSide) { ctx.fillRect(x2 - width_3px, y1 - height_3px, width_5px, height_5px); } if (drawLeftSide && drawBottomSide) { ctx.fillRect(x1 - width_3px, y2 - height_3px, width_5px, height_5px); } } } return true; }; /**Отрисовывает диапазон с заданными параметрами*/ WorksheetView.prototype._drawElements = function (drawFunction) { var cFrozen = 0, rFrozen = 0, args = Array.prototype.slice.call(arguments, 1), c = this.cols, r = this.rows, offsetX = c[this.visibleRange.c1].left - this.cellsLeft, offsetY = r[this.visibleRange.r1].top - this.cellsTop, res; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); rFrozen = this.topLeftFrozenCell.getRow0(); offsetX -= this.cols[cFrozen].left - this.cols[0].left; offsetY -= this.rows[rFrozen].top - this.rows[0].top; var oFrozenRange; cFrozen -= 1; rFrozen -= 1; if (0 <= cFrozen && 0 <= rFrozen) { oFrozenRange = new asc_Range(0, 0, cFrozen, rFrozen); res = drawFunction.call(this, oFrozenRange, c[0].left - this.cellsLeft, r[0].top - this.cellsTop, args); if (!res) { return; } } if (0 <= cFrozen) { oFrozenRange = new asc_Range(0, this.visibleRange.r1, cFrozen, this.visibleRange.r2); res = drawFunction.call(this, oFrozenRange, c[0].left - this.cellsLeft, offsetY, args); if (!res) { return; } } if (0 <= rFrozen) { oFrozenRange = new asc_Range(this.visibleRange.c1, 0, this.visibleRange.c2, rFrozen); res = drawFunction.call(this, oFrozenRange, offsetX, r[0].top - this.cellsTop, args); if (!res) { return; } } } // Можно вместо call попользовать apply, но тогда нужно каждый раз соединять массив аргументов и 3 объекта drawFunction.call(this, this.visibleRange, offsetX, offsetY, args); }; /** * Рисует выделение вокруг ячеек */ WorksheetView.prototype._drawSelection = function () { var isShapeSelect = false; if (window['IS_NATIVE_EDITOR']) { return; } this.handlers.trigger("checkLastWork"); // set clipping rect to cells area var ctx = this.overlayCtx; ctx.save().beginPath() .rect(this.cellsLeft, this.cellsTop, ctx.getWidth() - this.cellsLeft, ctx.getHeight() - this.cellsTop) .clip(); if (!this.isSelectionDialogMode) { this._drawCollaborativeElements(); } var isOtherSelectionMode = this.isSelectionDialogMode || this.isFormulaEditMode; if (isOtherSelectionMode && !this.handlers.trigger('isActive')) { if (this.isSelectionDialogMode) { this._drawSelectRange(); } else if (this.isFormulaEditMode) { this._drawFormulaRanges(this.arrActiveFormulaRanges); } } else { isShapeSelect = (asc["editor"].isStartAddShape || this.objectRender.selectedGraphicObjectsExists()); if (isShapeSelect) { if (this.isChartAreaEditMode) { this._drawFormulaRanges(this.arrActiveChartRanges); } } else { this._drawFormulaRanges(this.arrActiveFormulaRanges); if (this.isChartAreaEditMode) { this._drawFormulaRanges(this.arrActiveChartRanges); } this._drawSelectionRange(); if (this.activeFillHandle) { this._drawElements(this._drawSelectionElement, this.activeFillHandle.clone(true), AscCommonExcel.selectionLineType.None, this.settings.activeCellBorderColor); } if (this.isSelectionDialogMode) { this._drawSelectRange(); } if (this.stateFormatPainter && this.handlers.trigger('isActive')) { this._drawFormatPainterRange(); } if (null !== this.activeMoveRange) { this._drawElements(this._drawSelectionElement, this.activeMoveRange, AscCommonExcel.selectionLineType.None, new CColor(0, 0, 0)); } } } // restore canvas' original clipping range ctx.restore(); if (!isOtherSelectionMode && !isShapeSelect) { this._drawActiveHeaders(); } }; WorksheetView.prototype._drawSelectionRange = function () { var type, ranges = (this.isSelectionDialogMode ? this.copyActiveRange : this.model.selectionRange).ranges; var range, selectionLineType; for (var i = 0, l = ranges.length; i < l; ++i) { range = ranges[i].clone(); type = range.getType(); if (c_oAscSelectionType.RangeMax === type) { range.c2 = this.cols.length - 1; range.r2 = this.rows.length - 1; } else if (c_oAscSelectionType.RangeCol === type) { range.r2 = this.rows.length - 1; } else if (c_oAscSelectionType.RangeRow === type) { range.c2 = this.cols.length - 1; } selectionLineType = AscCommonExcel.selectionLineType.Selection; if (1 === l) { selectionLineType |= AscCommonExcel.selectionLineType.ActiveCell | AscCommonExcel.selectionLineType.Promote; } else if (i === this.model.selectionRange.activeCellId) { selectionLineType |= AscCommonExcel.selectionLineType.ActiveCell; } this._drawElements(this._drawSelectionElement, range, selectionLineType, this.settings.activeCellBorderColor); } this.handlers.trigger("drawMobileSelection", this.settings.activeCellBorderColor); }; WorksheetView.prototype._drawFormatPainterRange = function () { var t = this, color = new CColor(0, 0, 0); this.copyActiveRange.ranges.forEach(function (item) { t._drawElements(t._drawSelectionElement, item, AscCommonExcel.selectionLineType.Dash, color); }); }; WorksheetView.prototype._drawFormulaRanges = function (arrRanges) { var i, ranges, length = AscCommonExcel.c_oAscFormulaRangeBorderColor.length; var strokeColor, colorIndex, uniqueColorIndex = 0, tmpColors = []; for (i = 0; i < arrRanges.length; ++i) { ranges = arrRanges[i].ranges; for (var j = 0, l = ranges.length; j < l; ++j) { colorIndex = asc.getUniqueRangeColor(ranges, j, tmpColors); if (null == colorIndex) { colorIndex = uniqueColorIndex++; } tmpColors.push(colorIndex); if (ranges[j].noColor) { colorIndex = 0; } strokeColor = AscCommonExcel.c_oAscFormulaRangeBorderColor[colorIndex % length]; this._drawElements(this._drawSelectionElement, ranges[j], AscCommonExcel.selectionLineType.Selection | (ranges[j].isName ? AscCommonExcel.selectionLineType.None : AscCommonExcel.selectionLineType.Resize), strokeColor); } } }; WorksheetView.prototype._drawSelectRange = function () { var ranges = this.model.selectionRange.ranges; for (var i = 0, l = ranges.length; i < l; ++i) { this._drawElements(this._drawSelectionElement, ranges[i], AscCommonExcel.selectionLineType.Dash, AscCommonExcel.c_oAscCoAuthoringOtherBorderColor); } }; WorksheetView.prototype._drawCollaborativeElements = function () { if ( this.collaborativeEditing.getCollaborativeEditing() ) { this._drawCollaborativeElementsMeOther(c_oAscLockTypes.kLockTypeMine); this._drawCollaborativeElementsMeOther(c_oAscLockTypes.kLockTypeOther); this._drawCollaborativeElementsAllLock(); } }; WorksheetView.prototype._drawCollaborativeElementsAllLock = function () { var currentSheetId = this.model.getId(); var nLockAllType = this.collaborativeEditing.isLockAllOther(currentSheetId); if (Asc.c_oAscMouseMoveLockedObjectType.None !== nLockAllType) { var isAllRange = true, strokeColor = (Asc.c_oAscMouseMoveLockedObjectType.TableProperties === nLockAllType) ? AscCommonExcel.c_oAscCoAuthoringLockTablePropertiesBorderColor : AscCommonExcel.c_oAscCoAuthoringOtherBorderColor, oAllRange = new asc_Range(0, 0, gc_nMaxCol0, gc_nMaxRow0); this._drawElements(this._drawSelectionElement, oAllRange, AscCommonExcel.selectionLineType.Dash, strokeColor, isAllRange); } }; WorksheetView.prototype._drawCollaborativeElementsMeOther = function (type) { var currentSheetId = this.model.getId(), i, strokeColor, arrayCells, oCellTmp; if (c_oAscLockTypes.kLockTypeMine === type) { strokeColor = AscCommonExcel.c_oAscCoAuthoringMeBorderColor; arrayCells = this.collaborativeEditing.getLockCellsMe(currentSheetId); arrayCells = arrayCells.concat(this.collaborativeEditing.getArrayInsertColumnsBySheetId(currentSheetId)); arrayCells = arrayCells.concat(this.collaborativeEditing.getArrayInsertRowsBySheetId(currentSheetId)); } else { strokeColor = AscCommonExcel.c_oAscCoAuthoringOtherBorderColor; arrayCells = this.collaborativeEditing.getLockCellsOther(currentSheetId); } for (i = 0; i < arrayCells.length; ++i) { oCellTmp = new asc_Range(arrayCells[i].c1, arrayCells[i].r1, arrayCells[i].c2, arrayCells[i].r2); this._drawElements(this._drawSelectionElement, oCellTmp, AscCommonExcel.selectionLineType.Dash, strokeColor); } }; WorksheetView.prototype.cleanSelection = function (range, isFrozen) { if (window['IS_NATIVE_EDITOR']) { return; } isFrozen = !!isFrozen; if (range === undefined) { range = this.visibleRange; } var ctx = this.overlayCtx; var width = ctx.getWidth(); var height = ctx.getHeight(); var offsetX, offsetY, diffWidth = 0, diffHeight = 0; var x1 = Number.MAX_VALUE; var x2 = -Number.MAX_VALUE; var y1 = Number.MAX_VALUE; var y2 = -Number.MAX_VALUE; var _x1, _x2, _y1, _y2; var i; if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0(); var rFrozen = this.topLeftFrozenCell.getRow0(); diffWidth = this.cols[cFrozen].left - this.cols[0].left; diffHeight = this.rows[rFrozen].top - this.rows[0].top; if (!isFrozen) { var oFrozenRange; cFrozen -= 1; rFrozen -= 1; if (0 <= cFrozen && 0 <= rFrozen) { oFrozenRange = new asc_Range(0, 0, cFrozen, rFrozen); this.cleanSelection(oFrozenRange, true); } if (0 <= cFrozen) { oFrozenRange = new asc_Range(0, this.visibleRange.r1, cFrozen, this.visibleRange.r2); this.cleanSelection(oFrozenRange, true); } if (0 <= rFrozen) { oFrozenRange = new asc_Range(this.visibleRange.c1, 0, this.visibleRange.c2, rFrozen); this.cleanSelection(oFrozenRange, true); } } } if (isFrozen) { if (range.c1 !== this.visibleRange.c1) { diffWidth = 0; } if (range.r1 !== this.visibleRange.r1) { diffHeight = 0; } offsetX = this.cols[range.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[range.r1].top - this.cellsTop - diffHeight; } else { offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop - diffHeight; } this._activateOverlayCtx(); var t = this; this.model.selectionRange.ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_2px; _x2 = t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + /* Это ширина "квадрата" для автофильтра от границы ячейки */t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_2px; _y2 = t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + /* Это высота "квадрата" для автофильтра от границы ячейки */t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } if (!isFrozen) { t._cleanColumnHeaders(item.c1, item.c2); t._cleanRowHeaders(item.r1, item.r2); } }); this._deactivateOverlayCtx(); // Если есть активное автозаполнения, то нужно его тоже очистить if (this.activeFillHandle !== null) { var activeFillClone = this.activeFillHandle.clone(true); // Координаты для автозаполнения _x1 = this.cols[activeFillClone.c1].left - offsetX - this.width_2px; _x2 = this.cols[activeFillClone.c2].left + this.cols[activeFillClone.c2].width - offsetX + this.width_1px + this.width_2px; _y1 = this.rows[activeFillClone.r1].top - offsetY - this.height_2px; _y2 = this.rows[activeFillClone.r2].top + this.rows[activeFillClone.r2].height - offsetY + this.height_1px + this.height_2px; // Выбираем наибольший range для очистки x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } if (this.collaborativeEditing.getCollaborativeEditing()) { var currentSheetId = this.model.getId(); var nLockAllType = this.collaborativeEditing.isLockAllOther(currentSheetId); if (Asc.c_oAscMouseMoveLockedObjectType.None !== nLockAllType) { this.overlayCtx.clear(); } else { var arrayElementsMe = this.collaborativeEditing.getLockCellsMe(currentSheetId); var arrayElementsOther = this.collaborativeEditing.getLockCellsOther(currentSheetId); var arrayElements = arrayElementsMe.concat(arrayElementsOther); arrayElements = arrayElements.concat(this.collaborativeEditing.getArrayInsertColumnsBySheetId(currentSheetId)); arrayElements = arrayElements.concat(this.collaborativeEditing.getArrayInsertRowsBySheetId(currentSheetId)); for (i = 0; i < arrayElements.length; ++i) { var arFormulaTmp = new asc_Range(arrayElements[i].c1, arrayElements[i].r1, arrayElements[i].c2, arrayElements[i].r2); var aFormulaIntersection = arFormulaTmp.intersection(range); if (aFormulaIntersection) { // Координаты для автозаполнения _x1 = this.cols[aFormulaIntersection.c1].left - offsetX - this.width_2px; _x2 = this.cols[aFormulaIntersection.c2].left + this.cols[aFormulaIntersection.c2].width - offsetX + this.width_1px + this.width_2px; _y1 = this.rows[aFormulaIntersection.r1].top - offsetY - this.height_2px; _y2 = this.rows[aFormulaIntersection.r2].top + this.rows[aFormulaIntersection.r2].height - offsetY + this.height_1px + this.height_2px; // Выбираем наибольший range для очистки x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } } } } for (i = 0; i < this.arrActiveFormulaRanges.length; ++i) { this.arrActiveFormulaRanges[i].ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_3px; _x2 = arnIntersection.c2 > t.cols.length ? width : t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_3px; _y2 = arnIntersection.r2 > t.rows.length ? height : t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } }); } for (i = 0; i < this.arrActiveChartRanges.length; ++i) { this.arrActiveChartRanges[i].ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_3px; _x2 = arnIntersection.c2 > t.cols.length ? width : t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_3px; _y2 = arnIntersection.r2 > t.rows.length ? height : t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } }); } if (null !== this.activeMoveRange) { var activeMoveRangeClone = this.activeMoveRange.clone(true); // Увеличиваем, если выходим за область видимости // Critical Bug 17413 while (!this.cols[activeMoveRangeClone.c2]) { this.expandColsOnScroll(true); this.handlers.trigger("reinitializeScrollX"); } while (!this.rows[activeMoveRangeClone.r2]) { this.expandRowsOnScroll(true); this.handlers.trigger("reinitializeScrollY"); } // Координаты для перемещения диапазона _x1 = this.cols[activeMoveRangeClone.c1].left - offsetX - this.width_2px; _x2 = this.cols[activeMoveRangeClone.c2].left + this.cols[activeMoveRangeClone.c2].width - offsetX + this.width_1px + this.width_2px; _y1 = this.rows[activeMoveRangeClone.r1].top - offsetY - this.height_2px; _y2 = this.rows[activeMoveRangeClone.r2].top + this.rows[activeMoveRangeClone.r2].height - offsetY + this.height_1px + this.height_2px; // Выбираем наибольший range для очистки x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } if (null !== this.copyActiveRange) { this.copyActiveRange.ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_2px; _x2 = t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + /* Это ширина "квадрата" для автофильтра от границы ячейки */t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_2px; _y2 = t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + /* Это высота "квадрата" для автофильтра от границы ячейки */t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } }); } if (!(Number.MAX_VALUE === x1 && -Number.MAX_VALUE === x2 && Number.MAX_VALUE === y1 && -Number.MAX_VALUE === y2)) { ctx.save() .beginPath() .rect(this.cellsLeft, this.cellsTop, ctx.getWidth() - this.cellsLeft, ctx.getHeight() - this.cellsTop) .clip() .clearRect(x1, y1, x2 - x1, y2 - y1) .restore(); } return this; }; WorksheetView.prototype.updateSelection = function () { this.cleanSelection(); this._drawSelection(); }; WorksheetView.prototype.updateSelectionWithSparklines = function () { if (!this.checkSelectionSparkline()) { this._drawSelection(); } }; // mouseX - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.drawColumnGuides = function ( col, x, y, mouseX ) { x *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIX() ); // Учитываем координаты точки, где мы начали изменение размера x += mouseX; var ctx = this.overlayCtx; var offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; var offsetFrozen = this.getFrozenPaneOffset( false, true ); offsetX -= offsetFrozen.offsetX; var x1 = this.cols[col].left - offsetX - this.width_1px; var h = ctx.getHeight(); var widthPt = (x - x1); if ( 0 > widthPt ) { widthPt = 0; } ctx.clear(); this._drawSelection(); ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( x1, 0, this.width_1px, h ) .fillRect( x, 0, this.width_1px, h ); return new asc_CMM( { type : Asc.c_oAscMouseMoveType.ResizeColumn, sizeCCOrPt: this.model.colWidthToCharCount(widthPt), sizePx : widthPt * 96 / 72, x : (x1 + this.cols[col].width) * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIX() ), y : this.cellsTop * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIY() ) } ); }; // mouseY - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.drawRowGuides = function ( row, x, y, mouseY ) { y *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIY() ); // Учитываем координаты точки, где мы начали изменение размера y += mouseY; var ctx = this.overlayCtx; var offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; var offsetFrozen = this.getFrozenPaneOffset( true, false ); offsetY -= offsetFrozen.offsetY; var y1 = this.rows[row].top - offsetY - this.height_1px; var w = ctx.getWidth(); var heightPt = (y - y1); if ( 0 > heightPt ) { heightPt = 0; } ctx.clear(); this._drawSelection(); ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( 0, y1, w, this.height_1px ) .fillRect( 0, y, w, this.height_1px ); return new asc_CMM( { type : Asc.c_oAscMouseMoveType.ResizeRow, sizeCCOrPt: heightPt, sizePx : heightPt * 96 / 72, x : this.cellsLeft * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIX() ), y : (y1 + this.rows[row].height) * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIY() ) } ); }; // --- Cache --- WorksheetView.prototype._cleanCache = function (range) { var r, c, row; if (range === undefined) { range = this.model.selectionRange.getLast(); } for (r = range.r1; r <= range.r2; ++r) { row = this.cache.rows[r]; if (row !== undefined) { // Должны еще крайнюю удалить c = range.c1; if (row.erased[c - 1]) { delete row.erased[c - 1]; } for (; c <= range.c2; ++c) { if (row.columns[c]) { delete row.columns[c]; } if (row.columnsWithText[c]) { delete row.columnsWithText[c]; } if (row.erased[c]) { delete row.erased[c]; } } } } }; // ----- Cell text cache ----- /** Очищает кэш метрик текста ячеек */ WorksheetView.prototype._cleanCellsTextMetricsCache = function () { var s = this.cache.sectors = []; var vr = this.visibleRange; var h = vr.r2 + 1 - vr.r1; var rl = this.rows.length; var rc = asc_floor(rl / h) + (rl % h > 0 ? 1 : 0); var range = new asc_Range(0, 0, this.cols.length - 1, h - 1); var j; for (j = rc; j > 0; --j, range.r1 += h, range.r2 += h) { if (j === 1 && rl % h > 0) { range.r2 = rl - 1; } s.push(range.clone()); } }; /** * Обновляет общий кэш и кэширует метрики текста ячеек для указанного диапазона * @param {Asc.Range} [range] Диапазон кэширования текта */ WorksheetView.prototype._prepareCellTextMetricsCache = function (range) { var firstUpdateRow = null; if (!range) { range = this.visibleRange; if (this.topLeftFrozenCell) { var row = this.topLeftFrozenCell.getRow0(); var col = this.topLeftFrozenCell.getCol0(); if (0 < row && 0 < col) { firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2(new Asc.Range(0, 0, col - 1, row - 1))); } if (0 < row) { firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2( new Asc.Range(this.visibleRange.c1, 0, this.visibleRange.c2, row - 1))); } if (0 < col) { firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2( new Asc.Range(0, this.visibleRange.r1, col - 1, this.visibleRange.r2))); } } } firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2(range)); if (null !== firstUpdateRow || this.isChanged) { // Убрал это из _calcCellsTextMetrics, т.к. вызов был для каждого сектора(добавляло тормоза: баг 20388) // Код нужен для бага http://bugzilla.onlyoffice.com/show_bug.cgi?id=13875 this._updateRowPositions(); this._calcVisibleRows(); if (this.objectRender) { this.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: firstUpdateRow}, true); } } }; /** * Обновляет общий кэш и кэширует метрики текста ячеек для указанного диапазона (сама реализация, напрямую не вызывать, только из _prepareCellTextMetricsCache) * @param {Asc.Range} [range] Диапазон кэширования текта */ WorksheetView.prototype._prepareCellTextMetricsCache2 = function (range) { var firstUpdateRow = null; var s = this.cache.sectors; for (var i = 0; i < s.length;) { if (s[i].isIntersect(range)) { this._calcCellsTextMetrics(s[i]); s.splice(i, 1); firstUpdateRow = null !== firstUpdateRow ? Math.min(range.r1, firstUpdateRow) : range.r1; continue; } ++i; } return firstUpdateRow; }; /** * Кэширует метрики текста для диапазона ячеек * @param {Asc.Range} range description */ WorksheetView.prototype._calcCellsTextMetrics = function (range) { var colsLength = this.cols.length; if (range === undefined) { range = new Asc.Range(0, 0, colsLength - 1, this.rows.length - 1); } var t = this; var curRow = -1, skipRow = false; this.model.getRange3(range.r1, 0, range.r2, range.c2)._foreachNoEmpty(function(cell, row, col) { if (curRow !== row) { curRow = row; skipRow = t.height_1px > t.rows[row].height; } if(!skipRow && !(colsLength <= col || t.width_1px > t.cols[col].width)) { t._addCellTextToCache(col, row); } }); this.isChanged = false; }; WorksheetView.prototype._fetchRowCache = function (row) { return (this.cache.rows[row] = ( this.cache.rows[row] || new CacheElement() )); }; WorksheetView.prototype._fetchCellCache = function (col, row) { var r = this._fetchRowCache(row); return (r.columns[col] = ( r.columns[col] || {} )); }; WorksheetView.prototype._fetchCellCacheText = function (col, row) { var r = this._fetchRowCache(row); return (r.columnsWithText[col] = ( r.columnsWithText[col] || {} )); }; WorksheetView.prototype._getRowCache = function (row) { return this.cache.rows[row]; }; WorksheetView.prototype._getCellCache = function (col, row) { var r = this.cache.rows[row]; return r ? r.columns[col] : undefined; }; WorksheetView.prototype._getCellTextCache = function (col, row, dontLookupMergedCells) { var r = this.cache.rows[row], c = r ? r.columns[col] : undefined; if (c && c.text) { return c.text; } else if (!dontLookupMergedCells) { // ToDo проверить это условие, возможно оно избыточно var range = this.model.getMergedByCell(row, col); return null !== range ? this._getCellTextCache(range.c1, range.r1, true) : undefined; } return undefined; }; WorksheetView.prototype._changeColWidth = function (col, width, pad) { var cc = Math.min(this.model.colWidthToCharCount(width + pad), Asc.c_oAscMaxColumnWidth); var modelw = this.model.charCountToModelColWidth(cc); var colw = this._calcColWidth(modelw); if (colw.width > this.cols[col].width) { this.cols[col].width = colw.width; this.cols[col].innerWidth = colw.innerWidth; this.cols[col].charCount = colw.charCount; History.Create_NewPoint(); History.StartTransaction(); // Выставляем, что это bestFit this.model.setColBestFit(true, modelw, col, col); History.EndTransaction(); this._updateColumnPositions(); this.isChanged = true; } }; WorksheetView.prototype._addCellTextToCache = function (col, row, canChangeColWidth) { var self = this; function makeFnIsGoodNumFormat(flags, width) { return function (str) { return self.stringRender.measureString(str, flags, width).width <= width; }; } var c = this._getCell(col, row); if (null === c) { return col; } var bUpdateScrollX = false; var bUpdateScrollY = false; // Проверка на увеличение колличества столбцов if (col >= this.cols.length) { bUpdateScrollX = this.expandColsOnScroll(/*isNotActive*/ false, /*updateColsCount*/ true); } // Проверка на увеличение колличества строк if (row >= this.rows.length) { bUpdateScrollY = this.expandRowsOnScroll(/*isNotActive*/ false, /*updateRowsCount*/ true); } if (bUpdateScrollX && bUpdateScrollY) { this.handlers.trigger("reinitializeScroll"); } else if (bUpdateScrollX) { this.handlers.trigger("reinitializeScrollX"); } else if (bUpdateScrollY) { this.handlers.trigger("reinitializeScrollY"); } var str, tm, isMerged = false, strCopy; // Range для замерженной ячейки var fl = this._getCellFlags(c); var mc = fl.merged; var fMergedColumns = false; // Замержены ли колонки (если да, то автоподбор ширины не должен работать) var fMergedRows = false; // Замержены ли строки (если да, то автоподбор высоты не должен работать) if (null !== mc) { if (col !== mc.c1 || row !== mc.r1) { // Проверим внесена ли первая ячейка в cache (иначе если была скрыта первая строка или первый столбец, то мы не внесем) if (undefined === this._getCellTextCache(mc.c1, mc.r1, true)) { return this._addCellTextToCache(mc.c1, mc.r1, canChangeColWidth); } return mc.c2; } // skip other merged cell from range if (mc.c1 !== mc.c2) { fMergedColumns = true; } if (mc.r1 !== mc.r2) { fMergedRows = true; } isMerged = true; } var align = c.getAlign(); var angle = align.getAngle(); var va = align.getAlignVertical(); if (c.isEmptyTextString()) { if (!angle && c.isNotDefaultFont()) { // Пустая ячейка с измененной гарнитурой или размером, учитвается в высоте str = c.getValue2(); if (0 < str.length) { strCopy = str[0]; if (!(tm = AscCommonExcel.g_oCacheMeasureEmpty.get(strCopy.format))) { // Без текста не будет толка strCopy = strCopy.clone(); strCopy.text = 'A'; tm = this._roundTextMetrics(this.stringRender.measureString([strCopy], fl)); AscCommonExcel.g_oCacheMeasureEmpty.add(strCopy.format, tm); } this._updateRowHeight(tm, col, row, fl, isMerged, fMergedRows, va); } } return mc ? mc.c2 : col; } var dDigitsCount = 0; var colWidth = 0; var cellType = c.getType(); fl.isNumberFormat = (null === cellType || CellValueType.String !== cellType); // Автоподбор делается по любому типу (кроме строки) var numFormatStr = c.getNumFormatStr(); var pad = this.width_padding * 2 + this.width_1px; var sstr, sfl, stm; if (!this.cols[col].isCustomWidth && fl.isNumberFormat && !fMergedColumns && (c_oAscCanChangeColWidth.numbers === canChangeColWidth || c_oAscCanChangeColWidth.all === canChangeColWidth)) { colWidth = this.cols[col].innerWidth; // Измеряем целую часть числа sstr = c.getValue2(gc_nMaxDigCountView, function () { return true; }); if ("General" === numFormatStr && c_oAscCanChangeColWidth.all !== canChangeColWidth) { // asc.truncFracPart изменяет исходный массив, поэтому клонируем var fragmentsTmp = []; for (var k = 0; k < sstr.length; ++k) { fragmentsTmp.push(sstr[k].clone()); } sstr = asc.truncFracPart(fragmentsTmp); } sfl = fl.clone(); sfl.wrapText = false; stm = this._roundTextMetrics(this.stringRender.measureString(sstr, sfl, colWidth)); // Если целая часть числа не убирается в ячейку, то расширяем столбец if (stm.width > colWidth) { this._changeColWidth(col, stm.width, pad); } // Обновленная ячейка dDigitsCount = this.cols[col].charCount; colWidth = this.cols[col].innerWidth; } else if (null === mc) { // Обычная ячейка dDigitsCount = this.cols[col].charCount; colWidth = this.cols[col].innerWidth; // подбираем ширину if (!this.cols[col].isCustomWidth && !fMergedColumns && !fl.wrapText && c_oAscCanChangeColWidth.all === canChangeColWidth) { sstr = c.getValue2(gc_nMaxDigCountView, function () { return true; }); stm = this._roundTextMetrics(this.stringRender.measureString(sstr, fl, colWidth)); if (stm.width > colWidth) { this._changeColWidth(col, stm.width, pad); // Обновленная ячейка dDigitsCount = this.cols[col].charCount; colWidth = this.cols[col].innerWidth; } } } else { // Замерженная ячейка, нужна сумма столбцов for (var i = mc.c1; i <= mc.c2 && i < this.cols.length; ++i) { colWidth += this.cols[i].width; dDigitsCount += this.cols[i].charCount; } colWidth -= pad; } var rowHeight = this.rows[row].height; // ToDo dDigitsCount нужно рассчитывать исходя не из дефалтового шрифта и размера, а исходя из текущего шрифта и размера ячейки str = c.getValue2(dDigitsCount, makeFnIsGoodNumFormat(fl, colWidth)); var ha = c.getAlignHorizontalByValue(align.getAlignHorizontal()); var maxW = fl.wrapText || fl.shrinkToFit || isMerged || asc.isFixedWidthCell(str) ? this._calcMaxWidth(col, row, mc) : undefined; tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, maxW)); var cto = (isMerged || fl.wrapText || fl.shrinkToFit) ? { maxWidth: maxW - this.cols[col].innerWidth + this.cols[col].width, leftSide: 0, rightSide: 0 } : this._calcCellTextOffset(col, row, ha, tm.width); // check right side of cell text and append columns if it exceeds existing cells borders if (!isMerged) { var rside = this.cols[col - cto.leftSide].left + tm.width; var lc = this.cols[this.cols.length - 1]; if (rside > lc.left + lc.width) { this._appendColumns(rside); cto = this._calcCellTextOffset(col, row, ha, tm.width); } } var textBound = {}; if (angle) { // повернутый текст учитывает мерж ячеек по строкам if (fMergedRows) { rowHeight = 0; for (var j = mc.r1; j <= mc.r2 && j < this.nRowsCount; ++j) { rowHeight += this.rows[j].height; } } var textW = tm.width; if (fl.wrapText) { if (this.rows[row].isCustomHeight) { tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, rowHeight)); textBound = this.stringRender.getTransformBound(angle, colWidth, rowHeight, tm.width, ha, va, rowHeight); } else { if (!fMergedRows) { rowHeight = tm.height; } tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, rowHeight)); textBound = this.stringRender.getTransformBound(angle, colWidth, rowHeight, tm.width, ha, va, tm.width); } } else { textBound = this.stringRender.getTransformBound(angle, colWidth, rowHeight, textW, ha, va, maxW); } // NOTE: если проекция строчки на Y больше высоты ячейки подставлять # и рисовать все по центру // if (fl.isNumberFormat) { // var prj = Math.abs(Math.sin(angle * Math.PI / 180.0) * tm.width); // if (prj > rowHeight) { // //if (maxW === undefined) {} // maxW = rowHeight / Math.abs(Math.cos(angle * Math.PI / 180.0)); // str = c.getValue2(gc_nMaxDigCountView, makeFnIsGoodNumFormat(fl, maxW)); // // for (i = 0; i < str.length; ++i) { // var f = str[i].format; // if (f) f.repeat = true; // } // // tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, maxW)); // } // } } this._fetchCellCache(col, row).text = { state: this.stringRender.getInternalState(), flags: fl, metrics: tm, cellW: cto.maxWidth, cellHA: ha, cellVA: va, sideL: cto.leftSide, sideR: cto.rightSide, cellType: cellType, isFormula: c.isFormula(), angle: angle, textBound: textBound }; this._fetchCellCacheText(col, row).hasText = true; if (!angle && (cto.leftSide !== 0 || cto.rightSide !== 0)) { this._addErasedBordersToCache(col - cto.leftSide, col + cto.rightSide, row); } fMergedRows = fMergedRows || (isMerged && fl.wrapText); this._updateRowHeight(tm, col, row, fl, isMerged, fMergedRows, va, ha, angle, maxW, colWidth, textBound); return mc ? mc.c2 : col; }; WorksheetView.prototype._updateRowHeight = function (tm, col, row, flags, isMerged, fMergedRows, va, ha, angle, maxW, colWidth, textBound) { var rowInfo = this.rows[row]; // update row's descender if (va !== Asc.c_oAscVAlign.Top && va !== Asc.c_oAscVAlign.Center && !isMerged) { rowInfo.descender = Math.max(rowInfo.descender, tm.height - tm.baseline); } // update row's height // Замерженная ячейка (с 2-мя или более строками) не влияет на высоту строк! if (!rowInfo.isCustomHeight && !(window["NATIVE_EDITOR_ENJINE"] && this.notUpdateRowHeight) && !fMergedRows) { var newHeight = tm.height + this.height_1px; if (angle && textBound) { newHeight = Math.max(rowInfo.height, textBound.height); } newHeight = Math.min(this.maxRowHeight, Math.max(rowInfo.height, newHeight)); if (newHeight !== rowInfo.height) { rowInfo.heightReal = rowInfo.height = newHeight; History.TurnOff(); this.model.setRowHeight(rowInfo.height, row, row, false); History.TurnOn(); if (angle) { if (flags.wrapText && !rowInfo.isCustomHeight) { maxW = tm.width; } textBound = this.stringRender.getTransformBound(angle, colWidth, rowInfo.height, tm.width, ha, va, maxW); this._fetchCellCache(col, row).text.textBound = textBound; } this.isChanged = true; } } }; WorksheetView.prototype._calcMaxWidth = function (col, row, mc) { if (null === mc) { return this.cols[col].innerWidth; } var width = this.cols[mc.c1].innerWidth; for (var c = mc.c1 + 1; c <= mc.c2 && c < this.cols.length; ++c) { width += this.cols[c].width; } return width; }; WorksheetView.prototype._calcCellTextOffset = function (col, row, textAlign, textWidth) { var sideL = [0], sideR = [0], i; var maxWidth = this.cols[col].width; var ls = 0, rs = 0; var pad = this.settings.cells.padding * asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); var textW = textAlign === AscCommon.align_Center ? (textWidth + maxWidth) * 0.5 : textWidth + pad; if (textAlign === AscCommon.align_Right || textAlign === AscCommon.align_Center) { sideL = this._calcCellsWidth(col, 0, row); // condition (sideL.lenght >= 1) is always true for (i = 0; i < sideL.length && textW > sideL[i]; ++i) {/* do nothing */ } ls = i !== sideL.length ? i : i - 1; } if (textAlign !== AscCommon.align_Right) { sideR = this._calcCellsWidth(col, this.cols.length - 1, row); // condition (sideR.lenght >= 1) is always true for (i = 0; i < sideR.length && textW > sideR[i]; ++i) {/* do nothing */ } rs = i !== sideR.length ? i : i - 1; } if (textAlign === AscCommon.align_Center) { maxWidth = (sideL[ls] - sideL[0]) + sideR[rs]; } else { maxWidth = textAlign === AscCommon.align_Right ? sideL[ls] : sideR[rs]; } return { maxWidth: maxWidth, leftSide: ls, rightSide: rs }; }; WorksheetView.prototype._calcCellsWidth = function (colBeg, colEnd, row) { var inc = colBeg <= colEnd ? 1 : -1, res = []; for (var i = colBeg; (colEnd - i) * inc >= 0; i += inc) { if (i !== colBeg && !this._isCellEmptyOrMerged(i, row)) { break; } res.push(this.cols[i].width); if (res.length > 1) { res[res.length - 1] += res[res.length - 2]; } } return res; }; // Ищет текст в строке (columnsWithText - это колонки, в которых есть текст) WorksheetView.prototype._findSourceOfCellText = function (col, row) { var r = this._getRowCache(row); if (r) { for (var i in r.columnsWithText) { if (!r.columns[i] || 0 === this.cols[i].width) { continue; } var ct = r.columns[i].text; if (!ct) { continue; } i >>= 0; var lc = i - ct.sideL, rc = i + ct.sideR; if (col >= lc && col <= rc) { return i; } } } return -1; }; // ----- Merged cells cache ----- WorksheetView.prototype._isMergedCells = function (range) { return range.isEqual(this.model.getMergedByCell(range.r1, range.c1)); }; // ----- Cell borders cache ----- WorksheetView.prototype._addErasedBordersToCache = function (colBeg, colEnd, row) { var rc = this._fetchRowCache(row); for (var col = colBeg; col < colEnd; ++col) { rc.erased[col] = true; } }; WorksheetView.prototype._isLeftBorderErased = function (col, rowCache) { return rowCache.erased[col - 1] === true; }; WorksheetView.prototype._isRightBorderErased = function (col, rowCache) { return rowCache.erased[col] === true; }; WorksheetView.prototype._calcMaxBorderWidth = function (b1, b2) { // ToDo пересмотреть return Math.max(b1 && b1.w, b2 && b2.w); }; // ----- Cells utilities ----- /** * Возвращает заголовок колонки по индексу * @param {Number} col Индекс колонки * @return {String} */ WorksheetView.prototype._getColumnTitle = function (col) { return AscCommon.g_oCellAddressUtils.colnumToColstrFromWsView(col + 1); }; /** * Возвращает заголовок строки по индексу * @param {Number} row Индекс строки * @return {String} */ WorksheetView.prototype._getRowTitle = function (row) { return "" + (row + 1); }; /** * Возвращает заголовок ячейки по индексу * @param {Number} col Индекс колонки * @param {Number} row Индекс строки * @return {String} */ WorksheetView.prototype._getCellTitle = function (col, row) { return this._getColumnTitle(col) + this._getRowTitle(row); }; /** * Возвращает ячейку таблицы (из Worksheet) * @param {Number} col Индекс колонки * @param {Number} row Индекс строки * @return {Range} */ WorksheetView.prototype._getCell = function (col, row) { if (this.nRowsCount < this.model.getRowsCount() + 1) { this.expandRowsOnScroll(false, true, 0); } // Передаем 0, чтобы увеличить размеры if (this.nColsCount < this.model.getColsCount() + 1) { this.expandColsOnScroll(false, true, 0); } // Передаем 0, чтобы увеличить размеры if (col < 0 || col >= this.nColsCount || row < 0 || row >= this.nRowsCount) { return null; } return this.model.getCell3(row, col); }; WorksheetView.prototype._getVisibleCell = function (col, row) { return this.model.getCell3(row, col); }; WorksheetView.prototype._getCellFlags = function (col, row) { var c = row !== undefined ? this._getCell(col, row) : col; var fl = new CellFlags(); if (null !== c) { var align = c.getAlign(); fl.wrapText = align.getWrap(); fl.shrinkToFit = fl.wrapText ? false : align.getShrinkToFit(); fl.merged = c.hasMerged(); fl.textAlign = c.getAlignHorizontalByValue(align.getAlignHorizontal()); } return fl; }; WorksheetView.prototype._isCellNullText = function (col, row) { var c = row !== undefined ? this._getCell(col, row) : col; return null === c || c.isNullText(); }; WorksheetView.prototype._isCellEmptyOrMerged = function (col, row) { var c = row !== undefined ? this._getCell(col, row) : col; return null === c || (c.isNullText() && null === c.hasMerged()); }; WorksheetView.prototype._getRange = function (c1, r1, c2, r2) { return this.model.getRange3(r1, c1, r2, c2); }; WorksheetView.prototype._selectColumnsByRange = function () { var ar = this.model.selectionRange.getLast(); var type = ar.getType(); if (c_oAscSelectionType.RangeMax !== type) { this.cleanSelection(); if (c_oAscSelectionType.RangeRow === type) { ar.assign(0, 0, gc_nMaxCol0, gc_nMaxRow0); } else { ar.assign(ar.c1, 0, ar.c2, gc_nMaxRow0); } this._drawSelection(); this._updateSelectionNameAndInfo(); } }; WorksheetView.prototype._selectRowsByRange = function () { var ar = this.model.selectionRange.getLast(); var type = ar.getType(); if (c_oAscSelectionType.RangeMax !== type) { this.cleanSelection(); if (c_oAscSelectionType.RangeCol === type) { ar.assign(0, 0, gc_nMaxCol0, gc_nMaxRow0); } else { ar.assign(0, ar.r1, gc_nMaxCol0, ar.r2); } this._drawSelection(); this._updateSelectionNameAndInfo(); } }; /** * Возвращает true, если диапазон больше видимой области, и операции над ним могут привести к задержкам * @param {Asc.Range} range Диапазон для проверки * @returns {Boolean} */ WorksheetView.prototype._isLargeRange = function (range) { var vr = this.visibleRange; return range.c2 - range.c1 + 1 > (vr.c2 - vr.c1 + 1) * 3 || range.r2 - range.r1 + 1 > (vr.r2 - vr.r1 + 1) * 3; }; WorksheetView.prototype.drawDepCells = function () { var ctx = this.overlayCtx, _cc = this.cellCommentator, c, node, that = this; ctx.clear(); this._drawSelection(); var color = new CColor(0, 0, 255); function draw_arrow(context, fromx, fromy, tox, toy) { var headlen = 9, showArrow = tox > that.getCellLeft(0, 0) && toy > that.getCellTop(0, 0), dx = tox - fromx, dy = toy - fromy, tox = tox > that.getCellLeft(0, 0) ? tox : that.getCellLeft(0, 0), toy = toy > that.getCellTop(0, 0) ? toy : that.getCellTop(0, 0), angle = Math.atan2(dy, dx), _a = Math.PI / 18; // ToDo посмотреть на четкость moveTo, lineTo context.save() .setLineWidth(1) .beginPath() .lineDiag .moveTo(_cc.pxToPt(fromx), _cc.pxToPt(fromy)) .lineTo(_cc.pxToPt(tox), _cc.pxToPt(toy)); // .dashLine(_cc.pxToPt(fromx-.5), _cc.pxToPt(fromy-.5), _cc.pxToPt(tox-.5), _cc.pxToPt(toy-.5), 15, 5) if (showArrow) { context .moveTo(_cc.pxToPt(tox - headlen * Math.cos(angle - _a)), _cc.pxToPt(toy - headlen * Math.sin(angle - _a))) .lineTo(_cc.pxToPt(tox), _cc.pxToPt(toy)) .lineTo(_cc.pxToPt(tox - headlen * Math.cos(angle + _a)), _cc.pxToPt(toy - headlen * Math.sin(angle + _a))) .lineTo(_cc.pxToPt(tox - headlen * Math.cos(angle - _a)), _cc.pxToPt(toy - headlen * Math.sin(angle - _a))); } context .setStrokeStyle(color) .setFillStyle(color) .stroke() .fill() .closePath() .restore(); } function gCM(_this, col, row) { var metrics = {top: 0, left: 0, width: 0, height: 0, result: false}; // px var fvr = _this.getFirstVisibleRow(); var fvc = _this.getFirstVisibleCol(); var mergedRange = _this.model.getMergedByCell(row, col); if (mergedRange && (fvc < mergedRange.c2) && (fvr < mergedRange.r2)) { var startCol = (mergedRange.c1 > fvc) ? mergedRange.c1 : fvc; var startRow = (mergedRange.r1 > fvr) ? mergedRange.r1 : fvr; metrics.top = _this.getCellTop(startRow, 0) - _this.getCellTop(fvr, 0) + _this.getCellTop(0, 0); metrics.left = _this.getCellLeft(startCol, 0) - _this.getCellLeft(fvc, 0) + _this.getCellLeft(0, 0); for (var i = startCol; i <= mergedRange.c2; i++) { metrics.width += _this.getColumnWidth(i, 0) } for (var i = startRow; i <= mergedRange.r2; i++) { metrics.height += _this.getRowHeight(i, 0) } metrics.result = true; } else { metrics.top = _this.getCellTop(row, 0) - _this.getCellTop(fvr, 0) + _this.getCellTop(0, 0); metrics.left = _this.getCellLeft(col, 0) - _this.getCellLeft(fvc, 0) + _this.getCellLeft(0, 0); metrics.width = _this.getColumnWidth(col, 0); metrics.height = _this.getRowHeight(row, 0); metrics.result = true; } return metrics } for (var id in this.depDrawCells) { c = this.depDrawCells[id].from; node = this.depDrawCells[id].to; var mainCellMetrics = gCM(this, c.nCol, c.nRow), nodeCellMetrics, _t1, _t2; for (var id in node) { if (!node[id].isArea) { _t1 = gCM(this, node[id].returnCell().nCol, node[id].returnCell().nRow) nodeCellMetrics = { t: _t1.top, l: _t1.left, w: _t1.width, h: _t1.height, apt: _t1.top + _t1.height / 2, apl: _t1.left + _t1.width / 4 }; } else { var _t1 = gCM(_wsV, me[id].getBBox0().c1, me[id].getBBox0().r1), _t2 = gCM(_wsV, me[id].getBBox0().c2, me[id].getBBox0().r2); nodeCellMetrics = { t: _t1.top, l: _t1.left, w: _t2.left + _t2.width - _t1.left, h: _t2.top + _t2.height - _t1.top, apt: _t1.top + _t1.height / 2, apl: _t1.left + _t1.width / 4 }; } var x1 = Math.floor(nodeCellMetrics.apl), y1 = Math.floor(nodeCellMetrics.apt), x2 = Math.floor( mainCellMetrics.left + mainCellMetrics.width / 4), y2 = Math.floor( mainCellMetrics.top + mainCellMetrics.height / 2); if (x1 < 0 && x2 < 0 || y1 < 0 && y2 < 0) { continue; } if (y1 < this.getCellTop(0, 0)) { y1 -= this.getCellTop(0, 0); } if (y1 < 0 && y2 > 0) { var _x1 = Math.floor(Math.sqrt((x1 - x2) * (x1 - x2) * y1 * y1 / ((y2 - y1) * (y2 - y1)))); // x1 -= (x1-x2>0?1:-1)*_x1; if (x1 > x2) { x1 -= _x1; } else if (x1 < x2) { x1 += _x1; } } else if (y1 > 0 && y2 < 0) { var _x2 = Math.floor(Math.sqrt((x1 - x2) * (x1 - x2) * y2 * y2 / ((y2 - y1) * (y2 - y1)))); // x2 -= (x2-x1>0?1:-1)*_x2; if (x2 > x1) { x2 -= _x2; } else if (x2 < x1) { x2 += _x2; } } if (x1 < 0 && x2 > 0) { var _y1 = Math.floor(Math.sqrt((y1 - y2) * (y1 - y2) * x1 * x1 / ((x2 - x1) * (x2 - x1)))) // y1 -= (y1-y2>0?1:-1)*_y1; if (y1 > y2) { y1 -= _y1; } else if (y1 < y2) { y1 += _y1; } } else if (x1 > 0 && x2 < 0) { var _y2 = Math.floor(Math.sqrt((y1 - y2) * (y1 - y2) * x2 * x2 / ((x2 - x1) * (x2 - x1)))) // y2 -= (y2-y1>0?1:-1)*_y2; if (y2 > y1) { y2 -= _y2; } else if (y2 < y1) { y2 += _y2; } } draw_arrow(ctx, x1 < this.getCellLeft(0, 0) ? this.getCellLeft(0, 0) : x1, y1 < this.getCellTop(0, 0) ? this.getCellTop(0, 0) : y1, x2, y2); // draw_arrow(ctx, x1, y1, x2, y2); // ToDo посмотреть на четкость rect if (nodeCellMetrics.apl > this.getCellLeft(0, 0) && nodeCellMetrics.apt > this.getCellTop(0, 0)) { ctx.save() .beginPath() .arc(_cc.pxToPt(Math.floor(nodeCellMetrics.apl)), _cc.pxToPt(Math.floor(nodeCellMetrics.apt)), 3, 0, 2 * Math.PI, false, -0.5, -0.5) .setFillStyle(color) .fill() .closePath() .setLineWidth(1) .setStrokeStyle(color) .rect(_cc.pxToPt(nodeCellMetrics.l), _cc.pxToPt(nodeCellMetrics.t), _cc.pxToPt(nodeCellMetrics.w - 1), _cc.pxToPt(nodeCellMetrics.h - 1)) .stroke() .restore(); } } } }; WorksheetView.prototype.prepareDepCells = function (se) { this.drawDepCells(); }; WorksheetView.prototype.cleanDepCells = function () { this.depDrawCells = null; this.drawDepCells(); }; // ----- Text drawing ----- WorksheetView.prototype._getPPIX = function () { return this.drawingCtx.getPPIX(); }; WorksheetView.prototype._getPPIY = function () { return this.drawingCtx.getPPIY(); }; WorksheetView.prototype._setFont = function (drawingCtx, name, size) { var ctx = drawingCtx || this.drawingCtx; ctx.setFont(new asc.FontProperties(name, size)); }; /** * @param {Asc.TextMetrics} tm * @return {Asc.TextMetrics} */ WorksheetView.prototype._roundTextMetrics = function (tm) { tm.width = asc_calcnpt(tm.width, this._getPPIX()); tm.height = asc_calcnpt(tm.height, 96); tm.baseline = asc_calcnpt(tm.baseline, 96); if (tm.centerline !== undefined) { tm.centerline = asc_calcnpt(tm.centerline, 96); } return tm; }; WorksheetView.prototype._calcTextHorizPos = function (x1, x2, tm, halign) { switch (halign) { case AscCommon.align_Center: return asc_calcnpt(0.5 * (x1 + x2 + this.width_1px - tm.width), this._getPPIX()); case AscCommon.align_Right: return x2 + this.width_1px - this.width_padding - tm.width; case AscCommon.align_Justify: default: return x1 + this.width_padding; } }; WorksheetView.prototype._calcTextVertPos = function (y1, y2, baseline, tm, valign) { switch (valign) { case Asc.c_oAscVAlign.Center: return asc_calcnpt(0.5 * (y1 + y2 - tm.height), this._getPPIY()) - this.height_1px; // ToDo возможно стоит тоже использовать 96 case Asc.c_oAscVAlign.Top: return y1 - this.height_1px; default: return baseline - tm.baseline; } }; WorksheetView.prototype._calcTextWidth = function (x1, x2, tm, halign) { switch (halign) { case AscCommon.align_Justify: return x2 + this.width_1px - this.width_padding * 2 - x1; default: return tm.width; } }; // ----- Scrolling ----- WorksheetView.prototype._calcCellPosition = function (c, r, dc, dr) { var t = this; var vr = t.visibleRange; function findNextCell(col, row, dx, dy) { var state = t._isCellNullText(col, row); var i = col + dx; var j = row + dy; while (i >= 0 && i < t.cols.length && j >= 0 && j < t.rows.length) { var newState = t._isCellNullText(i, j); if (newState !== state) { var ret = {}; ret.col = state ? i : i - dx; ret.row = state ? j : j - dy; if (ret.col !== col || ret.row !== row || state) { return ret; } state = newState; } i += dx; j += dy; } // Проверки для перехода в самый конец (ToDo пока убрал, чтобы не добавлять тормозов) /*if (i === t.cols.length && state) i = gc_nMaxCol; if (j === t.rows.length && state) j = gc_nMaxRow;*/ return {col: i - dx, row: j - dy}; } function findEOT() { var obr = t.objectRender ? t.objectRender.getMaxColRow() : new AscCommon.CellBase(-1, -1); var maxCols = t.model.getColsCount(); var maxRows = t.model.getRowsCount(); var lastC = -1, lastR = -1; for (var col = 0; col < maxCols; ++col) { for (var row = 0; row < maxRows; ++row) { if (!t._isCellNullText(col, row)) { lastC = Math.max(lastC, col); lastR = Math.max(lastR, row); } } } return {col: Math.max(lastC, obr.col), row: Math.max(lastR, obr.row)}; } var eot = dc > +2.0001 && dc < +2.9999 && dr > +2.0001 && dr < +2.9999 ? findEOT() : null; var newCol = (function () { if (dc > +0.0001 && dc < +0.9999) { return c + (vr.c2 - vr.c1 + 1); } // PageDown if (dc < -0.0001 && dc > -0.9999) { return c - (vr.c2 - vr.c1 + 1); } // PageUp if (dc > +1.0001 && dc < +1.9999) { return findNextCell(c, r, +1, 0).col; } // Ctrl + -> if (dc < -1.0001 && dc > -1.9999) { return findNextCell(c, r, -1, 0).col; } // Ctrl + <- if (dc > +2.0001 && dc < +2.9999) { return (eot || findNextCell(c, r, +1, 0)).col; } // End if (dc < -2.0001 && dc > -2.9999) { return 0; } // Home return c + dc; })(); var newRow = (function () { if (dr > +0.0001 && dr < +0.9999) { return r + (vr.r2 - vr.r1 + 1); } if (dr < -0.0001 && dr > -0.9999) { return r - (vr.r2 - vr.r1 + 1); } if (dr > +1.0001 && dr < +1.9999) { return findNextCell(c, r, 0, +1).row; } if (dr < -1.0001 && dr > -1.9999) { return findNextCell(c, r, 0, -1).row; } if (dr > +2.0001 && dr < +2.9999) { return !eot ? 0 : eot.row; } if (dr < -2.0001 && dr > -2.9999) { return 0; } return r + dr; })(); if (newCol >= t.cols.length && newCol <= gc_nMaxCol0) { t.nColsCount = newCol + 1; t._calcWidthColumns(AscCommonExcel.recalcType.newLines); } if (newRow >= t.rows.length && newRow <= gc_nMaxRow0) { t.nRowsCount = newRow + 1; t._calcHeightRows(AscCommonExcel.recalcType.newLines); } return { col: newCol < 0 ? 0 : Math.min(newCol, t.cols.length - 1), row: newRow < 0 ? 0 : Math.min(newRow, t.rows.length - 1) }; }; WorksheetView.prototype._isColDrawnPartially = function (col, leftCol, diffWidth) { if (col <= leftCol || col >= this.nColsCount) { return false; } diffWidth = diffWidth ? diffWidth : 0; var c = this.cols; return c[col].left + c[col].width - c[leftCol].left + this.cellsLeft + diffWidth > this.drawingCtx.getWidth(); }; WorksheetView.prototype._isRowDrawnPartially = function (row, topRow, diffHeight) { if (row <= topRow || row >= this.nRowsCount) { return false; } diffHeight = diffHeight ? diffHeight : 0; var r = this.rows; return r[row].top + r[row].height - r[topRow].top + this.cellsTop + diffHeight > this.drawingCtx.getHeight(); }; WorksheetView.prototype._isVisibleX = function () { var vr = this.visibleRange; var c = this.cols; var x = c[vr.c2].left + c[vr.c2].width; var offsetFrozen = this.getFrozenPaneOffset(false, true); x += offsetFrozen.offsetX; return x - c[vr.c1].left + this.cellsLeft < this.drawingCtx.getWidth(); }; WorksheetView.prototype._isVisibleY = function () { var vr = this.visibleRange; var r = this.rows; var y = r[vr.r2].top + r[vr.r2].height; var offsetFrozen = this.getFrozenPaneOffset(true, false); y += offsetFrozen.offsetY; return y - r[vr.r1].top + this.cellsTop < this.drawingCtx.getHeight(); }; WorksheetView.prototype._updateVisibleRowsCount = function (skipScrollReinit) { var isUpdate = false; this._calcVisibleRows(); while (this._isVisibleY() && !this.isMaxRow()) { // Добавим еще строки, чтоб не было видно фон под таблицей this.expandRowsOnScroll(true); this._calcVisibleRows(); isUpdate = true; } if (!skipScrollReinit && isUpdate) { this.handlers.trigger("reinitializeScrollY"); } }; WorksheetView.prototype._updateVisibleColsCount = function (skipScrollReinit) { var isUpdate = false; this._calcVisibleColumns(); while (this._isVisibleX() && !this.isMaxCol()) { // Добавим еще столбцы, чтоб не было видно фон под таблицей this.expandColsOnScroll(true); this._calcVisibleColumns(); isUpdate = true; } if (!skipScrollReinit && isUpdate) { this.handlers.trigger("reinitializeScrollX"); } }; WorksheetView.prototype.isMaxRow = function () { var rowsCountCurrent = this.rows.length; if (gc_nMaxRow === rowsCountCurrent) { return true; } var rowsCount = this.model.getRowsCount() + 1; return rowsCount <= rowsCountCurrent && this.model.isDefaultHeightHidden(); }; WorksheetView.prototype.isMaxCol = function () { var colsCountCurrent = this.cols.length; if (gc_nMaxCol === colsCountCurrent) { return true; } var colsCount = this.model.getColsCount() + 1; return colsCount <= colsCountCurrent && this.model.isDefaultWidthHidden(); }; WorksheetView.prototype.scrollVertical = function (delta, editor) { var vr = this.visibleRange; var fixStartRow = new asc_Range(vr.c1, vr.r1, vr.c2, vr.r1); this._fixSelectionOfHiddenCells(0, delta >= 0 ? +1 : -1, fixStartRow); var start = this._calcCellPosition(vr.c1, fixStartRow.r1, 0, delta).row; fixStartRow.assign(vr.c1, start, vr.c2, start); this._fixSelectionOfHiddenCells(0, delta >= 0 ? +1 : -1, fixStartRow); this._fixVisibleRange(fixStartRow); var reinitScrollY = start !== fixStartRow.r1; // Для скролла вверх обычный сдвиг + дорисовка if (reinitScrollY && 0 > delta) { delta += fixStartRow.r1 - start; } start = fixStartRow.r1; if (start === vr.r1) { if (reinitScrollY) { this.handlers.trigger("reinitializeScrollY"); } return this; } if (!this.notUpdateRowHeight) { this.cleanSelection(); this.cellCommentator.cleanSelectedComment(); } var ctx = this.drawingCtx; var ctxW = ctx.getWidth(); var ctxH = ctx.getHeight(); var offsetX, offsetY, diffWidth = 0, diffHeight = 0, cFrozen = 0, rFrozen = 0; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); rFrozen = this.topLeftFrozenCell.getRow0(); diffWidth = this.cols[cFrozen].left - this.cols[0].left; diffHeight = this.rows[rFrozen].top - this.rows[0].top; } var oldVRE_isPartial = this._isRowDrawnPartially(vr.r2, vr.r1, diffHeight); var oldVR = vr.clone(); var oldStart = vr.r1; var oldEnd = vr.r2; // ToDo стоит тут переделать весь scroll vr.r1 = start; this._updateVisibleRowsCount(); // Это необходимо для того, чтобы строки, у которых высота по тексту, рассчитались if (!oldVR.intersectionSimple(vr)) { // Полностью обновилась область this._prepareCellTextMetricsCache(vr); } else { if (0 > delta) { // Идем вверх this._prepareCellTextMetricsCache(new asc_Range(vr.c1, start, vr.c2, oldStart - 1)); } else { // Идем вниз this._prepareCellTextMetricsCache(new asc_Range(vr.c1, oldEnd + 1, vr.c2, vr.r2)); } } if (this.notUpdateRowHeight) { return this; } var oldDec = Math.max(AscCommonExcel.calcDecades(oldEnd + 1), 3); var oldW, x, dx; var dy = this.rows[start].top - this.rows[oldStart].top; var oldH = ctxH - this.cellsTop - Math.abs(dy) - diffHeight; var scrollDown = (dy > 0 && oldH > 0); var y = this.cellsTop + (scrollDown ? dy : 0) + diffHeight; var lastRowHeight = (scrollDown && oldVRE_isPartial) ? ctxH - (this.rows[oldEnd].top - this.rows[oldStart].top + this.cellsTop + diffHeight) : 0; if (this.isCellEditMode && editor && this.model.selectionRange.activeCell.row >= rFrozen) { editor.move(this.cellsLeft + (this.model.selectionRange.activeCell.col >= cFrozen ? diffWidth : 0), this.cellsTop + diffHeight, ctxW, ctxH); } var widthChanged = Math.max(AscCommonExcel.calcDecades(vr.r2 + 1), 3) !== oldDec; if (widthChanged) { x = this.cellsLeft; this._calcHeaderColumnWidth(); this._updateColumnPositions(); this._calcVisibleColumns(); this._drawCorner(); this._cleanColumnHeadersRect(); this._drawColumnHeaders(null); dx = this.cellsLeft - x; oldW = ctxW - x - Math.abs(dx); if (rFrozen) { ctx.drawImage(ctx.getCanvas(), x, this.cellsTop, oldW, diffHeight, x + dx, this.cellsTop, oldW, diffHeight); // ToDo Посмотреть с объектами!!! } this._drawFrozenPane(true); } else { dx = 0; x = this.headersLeft; oldW = ctxW; } // Перемещаем область var moveHeight = oldH - lastRowHeight; if (moveHeight > 0) { ctx.drawImage(ctx.getCanvas(), x, y, oldW, moveHeight, x + dx, y - dy, oldW, moveHeight); // Заглушка для safari (http://bugzilla.onlyoffice.com/show_bug.cgi?id=25546). Режим 'copy' сначала затирает, а // потом рисует (а т.к. мы рисуем сами на себе, то уже картинка будет пустой) if (AscBrowser.isSafari) { this.drawingGraphicCtx.moveImageDataSafari(x, y, oldW, moveHeight, x + dx, y - dy); } else { this.drawingGraphicCtx.moveImageData(x, y, oldW, moveHeight, x + dx, y - dy); } } // Очищаем область var clearTop = this.cellsTop + diffHeight + (scrollDown && moveHeight > 0 ? moveHeight : 0); var clearHeight = (moveHeight > 0) ? Math.abs(dy) + lastRowHeight : ctxH - (this.cellsTop + diffHeight); ctx.setFillStyle(this.settings.cells.defaultState.background) .fillRect(this.headersLeft, clearTop, ctxW, clearHeight); this.drawingGraphicCtx.clearRect(this.headersLeft, clearTop, ctxW, clearHeight); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } // Дорисовываем необходимое if (dy < 0 || vr.r2 !== oldEnd || oldVRE_isPartial || dx !== 0) { var r1, r2; if (moveHeight > 0) { if (scrollDown) { r1 = oldEnd + (oldVRE_isPartial ? 0 : 1); r2 = vr.r2; } else { r1 = vr.r1; r2 = vr.r1 - 1 - delta; } } else { r1 = vr.r1; r2 = vr.r2; } var range = new asc_Range(vr.c1, r1, vr.c2, r2); if (dx === 0) { this._drawRowHeaders(null, r1, r2); } else { // redraw all headres, because number of decades in row index has been changed this._drawRowHeaders(null); if (dx < 0) { // draw last column var r_; var r1_ = r2 + 1; var r2_ = vr.r2; if (r2_ >= r1_) { r_ = new asc_Range(vr.c2, r1_, vr.c2, r2_); this._drawGrid(null, r_); this._drawCellsAndBorders(null, r_); } if (0 < rFrozen) { r_ = new asc_Range(vr.c2, 0, vr.c2, rFrozen - 1); offsetY = this.rows[0].top - this.cellsTop; this._drawGrid(null, r_, /*offsetXForDraw*/undefined, offsetY); this._drawCellsAndBorders(null, r_, /*offsetXForDraw*/undefined, offsetY); } } } offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop - diffHeight; this._drawGrid(null, range); this._drawCellsAndBorders(null, range); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollVertical, range, { offsetX: offsetX, offsetY: offsetY })); if (0 < cFrozen) { range.c1 = 0; range.c2 = cFrozen - 1; offsetX = this.cols[0].left - this.cellsLeft; this._drawGrid(null, range, offsetX); this._drawCellsAndBorders(null, range, offsetX); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollVertical, range, { offsetX: offsetX, offsetY: offsetY })); } } // Отрисовывать нужно всегда, вдруг бордеры this._drawFrozenPaneLines(); this._fixSelectionOfMergedCells(); this._drawSelection(); if (widthChanged) { this.handlers.trigger("reinitializeScrollX"); } if (reinitScrollY) { this.handlers.trigger("reinitializeScrollY"); } this.handlers.trigger("onDocumentPlaceChanged"); //ToDo this.drawDepCells(); this.cellCommentator.updateActiveComment(); this.cellCommentator.drawCommentCells(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("toggleAutoCorrectOptions", true); return this; }; WorksheetView.prototype.scrollHorizontal = function (delta, editor) { var vr = this.visibleRange; var fixStartCol = new asc_Range(vr.c1, vr.r1, vr.c1, vr.r2); this._fixSelectionOfHiddenCells(delta >= 0 ? +1 : -1, 0, fixStartCol); var start = this._calcCellPosition(fixStartCol.c1, vr.r1, delta, 0).col; fixStartCol.assign(start, vr.r1, start, vr.r2); this._fixSelectionOfHiddenCells(delta >= 0 ? +1 : -1, 0, fixStartCol); this._fixVisibleRange(fixStartCol); var reinitScrollX = start !== fixStartCol.c1; // Для скролла влево обычный сдвиг + дорисовка if (reinitScrollX && 0 > delta) { delta += fixStartCol.c1 - start; } start = fixStartCol.c1; if (start === vr.c1) { if (reinitScrollX) { this.handlers.trigger("reinitializeScrollX"); } return this; } if (!this.notUpdateRowHeight) { this.cleanSelection(); this.cellCommentator.cleanSelectedComment(); } var ctx = this.drawingCtx; var ctxW = ctx.getWidth(); var ctxH = ctx.getHeight(); var dx = this.cols[start].left - this.cols[vr.c1].left; var oldStart = vr.c1; var oldEnd = vr.c2; var offsetX, offsetY, diffWidth = 0, diffHeight = 0; var oldW = ctxW - this.cellsLeft - Math.abs(dx); var scrollRight = (dx > 0 && oldW > 0); var x = this.cellsLeft + (scrollRight ? dx : 0); var y = this.headersTop; var cFrozen = 0, rFrozen = 0; if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); cFrozen = this.topLeftFrozenCell.getCol0(); diffWidth = this.cols[cFrozen].left - this.cols[0].left; diffHeight = this.rows[rFrozen].top - this.rows[0].top; x += diffWidth; oldW -= diffWidth; } var oldVCE_isPartial = this._isColDrawnPartially(vr.c2, vr.c1, diffWidth); var oldVR = vr.clone(); // ToDo стоит тут переделать весь scroll vr.c1 = start; this._updateVisibleColsCount(); // Это необходимо для того, чтобы строки, у которых высота по тексту, рассчитались if (!oldVR.intersectionSimple(vr)) { // Полностью обновилась область this._prepareCellTextMetricsCache(vr); } else { if (0 > delta) { // Идем влево this._prepareCellTextMetricsCache(new asc_Range(start, vr.r1, oldStart - 1, vr.r2)); } else { // Идем вправо this._prepareCellTextMetricsCache(new asc_Range(oldEnd + 1, vr.r1, vr.c2, vr.r2)); } } if (this.notUpdateRowHeight) { return this; } var lastColWidth = (scrollRight && oldVCE_isPartial) ? ctxW - (this.cols[oldEnd].left - this.cols[oldStart].left + this.cellsLeft + diffWidth) : 0; if (this.isCellEditMode && editor && this.model.selectionRange.activeCell.col >= cFrozen) { editor.move(this.cellsLeft + diffWidth, this.cellsTop + (this.model.selectionRange.activeCell.row >= rFrozen ? diffHeight : 0), ctxW, ctxH); } // Перемещаем область var moveWidth = oldW - lastColWidth; if (moveWidth > 0) { ctx.drawImage(ctx.getCanvas(), x, y, moveWidth, ctxH, x - dx, y, moveWidth, ctxH); // Заглушка для safari (http://bugzilla.onlyoffice.com/show_bug.cgi?id=25546). Режим 'copy' сначала затирает, а // потом рисует (а т.к. мы рисуем сами на себе, то уже картинка будет пустой) if (AscBrowser.isSafari) { this.drawingGraphicCtx.moveImageDataSafari(x, y, moveWidth, ctxH, x - dx, y); } else { this.drawingGraphicCtx.moveImageData(x, y, moveWidth, ctxH, x - dx, y); } } // Очищаем область var clearLeft = this.cellsLeft + diffWidth + (scrollRight && moveWidth > 0 ? moveWidth : 0); var clearWidth = (moveWidth > 0) ? Math.abs(dx) + lastColWidth : ctxW - (this.cellsLeft + diffWidth); ctx.setFillStyle(this.settings.cells.defaultState.background) .fillRect(clearLeft, y, clearWidth, ctxH); this.drawingGraphicCtx.clearRect(clearLeft, y, clearWidth, ctxH); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } // Дорисовываем необходимое if (dx < 0 || vr.c2 !== oldEnd || oldVCE_isPartial) { var c1, c2; if (moveWidth > 0) { if (scrollRight) { c1 = oldEnd + (oldVCE_isPartial ? 0 : 1); c2 = vr.c2; } else { c1 = vr.c1; c2 = vr.c1 - 1 - delta; } } else { c1 = vr.c1; c2 = vr.c2; } var range = new asc_Range(c1, vr.r1, c2, vr.r2); offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop - diffHeight; this._drawColumnHeaders(null, c1, c2); this._drawGrid(null, range); this._drawCellsAndBorders(null, range); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollHorizontal, range, { offsetX: offsetX, offsetY: offsetY })); if (rFrozen) { range.r1 = 0; range.r2 = rFrozen - 1; offsetY = this.rows[0].top - this.cellsTop; this._drawGrid(null, range, undefined, offsetY); this._drawCellsAndBorders(null, range, undefined, offsetY); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollHorizontal, range, { offsetX: offsetX, offsetY: offsetY })); } } // Отрисовывать нужно всегда, вдруг бордеры this._drawFrozenPaneLines(); this._fixSelectionOfMergedCells(); this._drawSelection(); if (reinitScrollX) { this.handlers.trigger("reinitializeScrollX"); } this.handlers.trigger("onDocumentPlaceChanged"); //ToDo this.drawDepCells(); this.cellCommentator.updateActiveComment(); this.cellCommentator.drawCommentCells(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("toggleAutoCorrectOptions", true); return this; }; // ----- Selection ----- // x,y - абсолютные координаты относительно листа (без учета заголовков) WorksheetView.prototype.findCellByXY = function (x, y, canReturnNull, skipCol, skipRow) { var r = 0, c = 0, tmpRow, tmpCol, result = new AscFormat.CCellObjectInfo(); if (canReturnNull) { result.col = result.row = null; } x += this.cellsLeft; y += this.cellsTop; if (!skipCol) { while (c < this.cols.length) { tmpCol = this.cols[c]; if (x <= tmpCol.left + tmpCol.width) { result.col = c; break; } ++c; } if (null !== result.col) { result.colOff = x - this.cols[result.col].left; } } if (!skipRow) { while (r < this.rows.length) { tmpRow = this.rows[r]; if (y <= tmpRow.top + tmpRow.height) { result.row = r; break; } ++r; } if (null !== result.row) { result.rowOff = y - this.rows[result.row].top; } } return result; }; /** * * @param x * @param canReturnNull * @param half - считать с половиной следующей ячейки * @returns {*} * @private */ WorksheetView.prototype._findColUnderCursor = function (x, canReturnNull, half) { var activeCellCol = half ? this._getSelection().activeCell.col : -1; var dx = 0; var c = this.visibleRange.c1; var offset = this.cols[c].left - this.cellsLeft; var c2, x1, x2, cFrozen, widthDiff = 0; if (x >= this.cellsLeft) { if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; if (x < this.cellsLeft + widthDiff && 0 !== widthDiff) { c = 0; widthDiff = 0; } } for (x1 = this.cellsLeft + widthDiff, c2 = this.cols.length - 1; c <= c2; ++c, x1 = x2) { x2 = x1 + this.cols[c].width; dx = half ? this.cols[c].width / 2.0 * Math.sign(c - activeCellCol) : 0; if (x1 + dx > x) { if (c !== this.visibleRange.c1) { if (dx) { c -= 1; x2 = x1; x1 -= this.cols[c].width; } return {col: c, left: x1, right: x2}; } else { c = c2; break; } } else if (x <= x2 + dx) { return {col: c, left: x1, right: x2}; } } if (!canReturnNull) { x1 = this.cols[c2].left - offset; return {col: c2, left: x1, right: x1 + this.cols[c2].width}; } } else { if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); if (0 !== cFrozen) { c = 0; offset = this.cols[c].left - this.cellsLeft; } } for (x2 = this.cellsLeft + this.cols[c].width, c2 = 0; c >= c2; --c, x2 = x1) { x1 = this.cols[c].left - offset; if (x1 <= x && x < x2) { return {col: c, left: x1, right: x2}; } } if (!canReturnNull) { return {col: c2, left: x1, right: x1 + this.cols[c2].width}; } } return null; }; /** * * @param y * @param canReturnNull * @param half - считать с половиной следующей ячейки * @returns {*} * @private */ WorksheetView.prototype._findRowUnderCursor = function (y, canReturnNull, half) { var activeCellRow = half ? this._getSelection().activeCell.row : -1; var dy = 0; var r = this.visibleRange.r1; var offset = this.rows[r].top - this.cellsTop; var r2, y1, y2, rFrozen, heightDiff = 0; if (y >= this.cellsTop) { if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); heightDiff = this.rows[rFrozen].top - this.rows[0].top; if (y < this.cellsTop + heightDiff && 0 !== heightDiff) { r = 0; heightDiff = 0; } } for (y1 = this.cellsTop + heightDiff, r2 = this.rows.length - 1; r <= r2; ++r, y1 = y2) { y2 = y1 + this.rows[r].height; dy = half ? this.rows[r].height / 2.0 * Math.sign(r - activeCellRow) : 0; if (y1 + dy > y) { if (r !== this.visibleRange.r1) { if (dy) { r -= 1; y2 = y1; y1 -= this.rows[r].height; } return {row: r, top: y1, bottom: y2}; } else { r = r2; break; } } else if (y <= y2 + dy) { return {row: r, top: y1, bottom: y2}; } } if (!canReturnNull) { y1 = this.rows[r2].top - offset; return {row: r2, top: y1, bottom: y1 + this.rows[r2].height}; } } else { if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); if (0 !== rFrozen) { r = 0; offset = this.rows[r].top - this.cellsTop; } } for (y2 = this.cellsTop + this.rows[r].height, r2 = 0; r >= r2; --r, y2 = y1) { y1 = this.rows[r].top - offset; if (y1 <= y && y < y2) { return {row: r, top: y1, bottom: y2}; } } if (!canReturnNull) { return {row: r2, top: y1, bottom: y1 + this.rows[r2].height}; } } return null; }; WorksheetView.prototype._hitResizeCorner = function (x1, y1, x2, y2) { var wEps = this.width_1px * AscCommon.global_mouseEvent.KoefPixToMM, hEps = this.height_1px * AscCommon.global_mouseEvent.KoefPixToMM; return Math.abs(x2 - x1) <= wEps + this.width_2px && Math.abs(y2 - y1) <= hEps + this.height_2px; }; WorksheetView.prototype._hitInRange = function (range, rangeType, vr, x, y, offsetX, offsetY) { var wEps = this.width_2px * AscCommon.global_mouseEvent.KoefPixToMM, hEps = this.height_2px * AscCommon.global_mouseEvent.KoefPixToMM; var cursor, x1, x2, y1, y2, isResize; var col = -1, row = -1; var oFormulaRangeIn = range.intersectionSimple(vr); if (oFormulaRangeIn) { x1 = this.cols[oFormulaRangeIn.c1].left - offsetX; x2 = this.cols[oFormulaRangeIn.c2].left + this.cols[oFormulaRangeIn.c2].width - offsetX; y1 = this.rows[oFormulaRangeIn.r1].top - offsetY; y2 = this.rows[oFormulaRangeIn.r2].top + this.rows[oFormulaRangeIn.r2].height - offsetY; isResize = AscCommonExcel.selectionLineType.Resize & rangeType; if (isResize && this._hitResizeCorner(x1 - this.width_1px, y1 - this.height_1px, x, y)) { /*TOP-LEFT*/ cursor = kCurSEResize; col = range.c2; row = range.r2; } else if (isResize && this._hitResizeCorner(x2, y1 - this.height_1px, x, y)) { /*TOP-RIGHT*/ cursor = kCurNEResize; col = range.c1; row = range.r2; } else if (isResize && this._hitResizeCorner(x1 - this.width_1px, y2, x, y)) { /*BOTTOM-LEFT*/ cursor = kCurNEResize; col = range.c2; row = range.r1; } else if (this._hitResizeCorner(x2, y2, x, y)) { /*BOTTOM-RIGHT*/ cursor = kCurSEResize; col = range.c1; row = range.r1; } else if ((((range.c1 === oFormulaRangeIn.c1 && Math.abs(x - x1) <= wEps) || (range.c2 === oFormulaRangeIn.c2 && Math.abs(x - x2) <= wEps)) && hEps <= y - y1 && y - y2 <= hEps) || (((range.r1 === oFormulaRangeIn.r1 && Math.abs(y - y1) <= hEps) || (range.r2 === oFormulaRangeIn.r2 && Math.abs(y - y2) <= hEps)) && wEps <= x - x1 && x - x2 <= wEps)) { cursor = kCurMove; } } return cursor ? { cursor: cursor, col: col, row: row } : null; }; WorksheetView.prototype._hitCursorSelectionRange = function (vr, x, y, offsetX, offsetY) { var res = this._hitInRange(this.model.selectionRange.getLast(), AscCommonExcel.selectionLineType.Selection | AscCommonExcel.selectionLineType.ActiveCell | AscCommonExcel.selectionLineType.Promote, vr, x, y, offsetX, offsetY); return res ? { cursor: kCurMove === res.cursor ? kCurMove : kCurFillHandle, target: kCurMove === res.cursor ? c_oTargetType.MoveRange : c_oTargetType.FillHandle, col: -1, row: -1 } : null; }; WorksheetView.prototype._hitCursorFormulaOrChart = function (vr, x, y, offsetX, offsetY) { var i, l, res; var oFormulaRange; var arrRanges = this.isFormulaEditMode ? this.arrActiveFormulaRanges : this.arrActiveChartRanges; var targetArr = this.isFormulaEditMode ? 0 : -1; for (i = 0, l = arrRanges.length; i < l; ++i) { oFormulaRange = arrRanges[i].getLast(); res = !oFormulaRange.isName && this._hitInRange(oFormulaRange, AscCommonExcel.selectionLineType.Resize, vr, x, y, offsetX, offsetY); if (res) { break; } } return res ? { cursor: res.cursor, target: c_oTargetType.MoveResizeRange, col: res.col, row: res.row, formulaRange: oFormulaRange, indexFormulaRange: i, targetArr: targetArr } : null; }; WorksheetView.prototype.getCursorTypeFromXY = function (x, y, isViewerMode) { this.handlers.trigger("checkLastWork"); var res, c, r, f, i, offsetX, offsetY, cellCursor; var sheetId = this.model.getId(), userId, lockRangePosLeft, lockRangePosTop, lockInfo, oHyperlink; var widthDiff = 0, heightDiff = 0, isLocked = false, target = c_oTargetType.Cells, row = -1, col = -1, isSelGraphicObject, isNotFirst; if (c_oAscSelectionDialogType.None === this.selectionDialogType) { var frozenCursor = this._isFrozenAnchor(x, y); if (!isViewerMode && frozenCursor.result) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, sheetId, AscCommonExcel.c_oAscLockNameFrozenPane); isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false); if (false !== isLocked) { // Кто-то сделал lock var frozenCell = this.topLeftFrozenCell ? this.topLeftFrozenCell : new AscCommon.CellAddress(0, 0, 0); userId = isLocked.UserId; lockRangePosLeft = this.getCellLeft(frozenCell.getCol0(), 0); lockRangePosTop = this.getCellTop(frozenCell.getRow0(), 0); } return { cursor: frozenCursor.cursor, target: frozenCursor.name, col: -1, row: -1, userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop }; } var drawingInfo = this.objectRender.checkCursorDrawingObject(x, y); if (asc["editor"].isStartAddShape && AscCommonExcel.CheckIdSatetShapeAdd(this.objectRender.controller.curState)) { return {cursor: kCurFillHandle, target: c_oTargetType.Shape, col: -1, row: -1}; } if (drawingInfo && drawingInfo.id) { // Возможно картинка с lock lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, sheetId, drawingInfo.id); isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false); if (false !== isLocked) { // Кто-то сделал lock userId = isLocked.UserId; lockRangePosLeft = drawingInfo.object.getVisibleLeftOffset(true); lockRangePosTop = drawingInfo.object.getVisibleTopOffset(true); } if (drawingInfo.hyperlink instanceof ParaHyperlink) { oHyperlink = new AscCommonExcel.Hyperlink(); oHyperlink.Tooltip = drawingInfo.hyperlink.ToolTip; var spl = drawingInfo.hyperlink.Value.split("!"); if (spl.length === 2) { oHyperlink.setLocation(drawingInfo.hyperlink.Value); } else { oHyperlink.Hyperlink = drawingInfo.hyperlink.Value; } cellCursor = {cursor: drawingInfo.cursor, target: c_oTargetType.Cells, col: -1, row: -1, userId: userId}; return { cursor: kCurHyperlink, target: c_oTargetType.Hyperlink, hyperlink: new asc_CHyperlink(oHyperlink), cellCursor: cellCursor, userId: userId }; } return { cursor: drawingInfo.cursor, target: c_oTargetType.Shape, drawingId: drawingInfo.id, col: -1, row: -1, userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop }; } } x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var oResDefault = {cursor: kCurDefault, target: c_oTargetType.None, col: -1, row: -1}; if (x < this.cellsLeft && y < this.cellsTop) { return {cursor: kCurCorner, target: c_oTargetType.Corner, col: -1, row: -1}; } var cFrozen = -1, rFrozen = -1; offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); rFrozen = this.topLeftFrozenCell.getRow0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; heightDiff = this.rows[rFrozen].top - this.rows[0].top; offsetX = (x < this.cellsLeft + widthDiff) ? 0 : offsetX - widthDiff; offsetY = (y < this.cellsTop + heightDiff) ? 0 : offsetY - heightDiff; } var epsChangeSize = 3 * AscCommon.global_mouseEvent.KoefPixToMM; if (x <= this.cellsLeft && y >= this.cellsTop) { r = this._findRowUnderCursor(y, true); if (r === null) { return oResDefault; } isNotFirst = (r.row !== (-1 !== rFrozen ? 0 : this.visibleRange.r1)); f = !isViewerMode && (isNotFirst && y < r.top + epsChangeSize || y >= r.bottom - epsChangeSize); // ToDo В Excel зависимость epsilon от размера ячейки (у нас фиксированный 3) return { cursor: f ? kCurRowResize : kCurRowSelect, target: f ? c_oTargetType.RowResize : c_oTargetType.RowHeader, col: -1, row: r.row + (isNotFirst && f && y < r.top + 3 ? -1 : 0), mouseY: f ? ((y < r.top + 3) ? (r.top - y - this.height_1px) : (r.bottom - y - this.height_1px)) : null }; } if (y <= this.cellsTop && x >= this.cellsLeft) { c = this._findColUnderCursor(x, true); if (c === null) { return oResDefault; } isNotFirst = c.col !== (-1 !== cFrozen ? 0 : this.visibleRange.c1); f = !isViewerMode && (isNotFirst && x < c.left + epsChangeSize || x >= c.right - epsChangeSize); // ToDo В Excel зависимость epsilon от размера ячейки (у нас фиксированный 3) return { cursor: f ? kCurColResize : kCurColSelect, target: f ? c_oTargetType.ColumnResize : c_oTargetType.ColumnHeader, col: c.col + (isNotFirst && f && x < c.left + 3 ? -1 : 0), row: -1, mouseX: f ? ((x < c.left + 3) ? (c.left - x - this.width_1px) : (c.right - x - this.width_1px)) : null }; } if (this.stateFormatPainter) { if (x <= this.cellsLeft && y >= this.cellsTop) { r = this._findRowUnderCursor(y, true); if (r !== null) { target = c_oTargetType.RowHeader; row = r.row; } } if (y <= this.cellsTop && x >= this.cellsLeft) { c = this._findColUnderCursor(x, true); if (c !== null) { target = c_oTargetType.ColumnHeader; col = c.col; } } return {cursor: kCurFormatPainterExcel, target: target, col: col, row: row}; } if (this.isFormulaEditMode || this.isChartAreaEditMode) { this._drawElements(function (_vr, _offsetX, _offsetY) { return (null === (res = this._hitCursorFormulaOrChart(_vr, x, y, _offsetX, _offsetY))); }); if (res) { return res; } } isSelGraphicObject = this.objectRender.selectedGraphicObjectsExists(); if (!isViewerMode && !isSelGraphicObject && this.model.selectionRange.isSingleRange() && c_oAscSelectionDialogType.None === this.selectionDialogType) { this._drawElements(function (_vr, _offsetX, _offsetY) { return (null === (res = this._hitCursorSelectionRange(_vr, x, y, _offsetX, _offsetY))); }); if (res) { return res; } } if (x > this.cellsLeft && y > this.cellsTop) { c = this._findColUnderCursor(x, true); r = this._findRowUnderCursor(y, true); if (c === null || r === null) { return oResDefault; } // Проверка на совместное редактирование var lockRange = undefined; var lockAllPosLeft = undefined; var lockAllPosTop = undefined; var userIdAllProps = undefined; var userIdAllSheet = undefined; if (!isViewerMode && this.collaborativeEditing.getCollaborativeEditing()) { var c1Recalc = null, r1Recalc = null; var selectRangeRecalc = new asc_Range(c.col, r.row, c.col, r.row); // Пересчет для входящих ячеек в добавленные строки/столбцы var isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, selectRangeRecalc); if (false === isIntersection) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, new AscCommonExcel.asc_CCollaborativeRange(selectRangeRecalc.c1, selectRangeRecalc.r1, selectRangeRecalc.c2, selectRangeRecalc.r2)); isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false); if (false !== isLocked) { // Кто-то сделал lock userId = isLocked.UserId; lockRange = isLocked.Element["rangeOrObjectId"]; c1Recalc = this.collaborativeEditing.m_oRecalcIndexColumns[sheetId].getLockOther(lockRange["c1"], c_oAscLockTypes.kLockTypeOther); r1Recalc = this.collaborativeEditing.m_oRecalcIndexRows[sheetId].getLockOther(lockRange["r1"], c_oAscLockTypes.kLockTypeOther); if (null !== c1Recalc && null !== r1Recalc) { lockRangePosLeft = this.getCellLeft(c1Recalc, /*pt*/1); lockRangePosTop = this.getCellTop(r1Recalc, /*pt*/1); // Пересчитываем X и Y относительно видимой области lockRangePosLeft -= offsetX; lockRangePosTop -= offsetY; lockRangePosLeft = this.cellsLeft > lockRangePosLeft ? this.cellsLeft : lockRangePosLeft; lockRangePosTop = this.cellsTop > lockRangePosTop ? this.cellsTop : lockRangePosTop; // Пересчитываем в px lockRangePosLeft *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); lockRangePosTop *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); } } } else { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, null); } // Проверим не удален ли весь лист (именно удален, т.к. если просто залочен, то не рисуем рамку вокруг) lockInfo["type"] = c_oAscLockTypeElem.Sheet; isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/true); if (false !== isLocked) { // Кто-то сделал lock userIdAllSheet = isLocked.UserId; lockAllPosLeft = this.cellsLeft * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); lockAllPosTop = this.cellsTop * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); } // Проверим не залочены ли все свойства листа (только если не удален весь лист) if (undefined === userIdAllSheet) { lockInfo["type"] = c_oAscLockTypeElem.Range; lockInfo["subType"] = c_oAscLockTypeElemSubType.InsertRows; isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/true); if (false !== isLocked) { // Кто-то сделал lock userIdAllProps = isLocked.UserId; lockAllPosLeft = this.cellsLeft * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); lockAllPosTop = this.cellsTop * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); } } } if (!isViewerMode) { var pivotButtons = this.model.getPivotTableButtons(new asc_Range(c.col, r.row, c.col, r.row)); var isPivot = pivotButtons.some(function (element) { return element.row === r.row && element.col === c.col; }); this._drawElements(function (_vr, _offsetX, _offsetY) { if (isPivot) { if (_vr.contains(c.col, r.row) && this._hitCursorFilterButton(x + _offsetX, y + _offsetY, c.col, r.row)) { res = {cursor: kCurAutoFilter, target: c_oTargetType.FilterObject, col: -1, row: -1}; } } else { res = this.af_checkCursor(x, y, _vr, _offsetX, _offsetY, r, c); } return (null === res); }); if (res) { return res; } } // Проверим есть ли комменты var comment = this.cellCommentator.getComment(c.col, r.row); var coords = null; var indexes = null; if (comment) { indexes = [comment.asc_getId()]; coords = this.cellCommentator.getCommentTooltipPosition(comment); } // Проверим, может мы в гиперлинке oHyperlink = this.model.getHyperlinkByCell(r.row, c.col); cellCursor = { cursor: kCurCells, target: c_oTargetType.Cells, col: (c ? c.col : -1), row: (r ? r.row : -1), userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop, userIdAllProps: userIdAllProps, lockAllPosLeft: lockAllPosLeft, lockAllPosTop: lockAllPosTop, userIdAllSheet: userIdAllSheet, commentIndexes: indexes, commentCoords: coords }; if (null !== oHyperlink) { return { cursor: kCurHyperlink, target: c_oTargetType.Hyperlink, hyperlink: new asc_CHyperlink(oHyperlink), cellCursor: cellCursor, userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop, userIdAllProps: userIdAllProps, userIdAllSheet: userIdAllSheet, lockAllPosLeft: lockAllPosLeft, lockAllPosTop: lockAllPosTop, commentIndexes: indexes, commentCoords: coords }; } return cellCursor; } return oResDefault; }; WorksheetView.prototype._fixSelectionOfMergedCells = function (fixedRange) { var selection; var ar = fixedRange ? fixedRange : ((selection = this._getSelection()) ? selection.getLast() : null); if (!ar || c_oAscSelectionType.RangeCells !== ar.getType()) { return; } // ToDo - переделать этот момент!!!! var res = this.model.expandRangeByMerged(ar.clone(true)); if (ar.c1 !== res.c1 && ar.c1 !== res.c2) { ar.c1 = ar.c1 <= ar.c2 ? res.c1 : res.c2; } ar.c2 = ar.c1 === res.c1 ? res.c2 : (res.c1); if (ar.r1 !== res.r1 && ar.r1 !== res.r2) { ar.r1 = ar.r1 <= ar.r2 ? res.r1 : res.r2; } ar.r2 = ar.r1 === res.r1 ? res.r2 : res.r1; ar.normalize(); if (!fixedRange) { selection.update(); } }; WorksheetView.prototype._findVisibleCol = function (from, dc, flag) { var to = dc < 0 ? -1 : this.cols.length, c; for (c = from; c !== to; c += dc) { if (this.cols[c].width > this.width_1px) { return c; } } return flag ? -1 : this._findVisibleCol(from, dc * -1, true); }; WorksheetView.prototype._findVisibleRow = function (from, dr, flag) { var to = dr < 0 ? -1 : this.rows.length, r; for (r = from; r !== to; r += dr) { if (this.rows[r].height > this.height_1px) { return r; } } return flag ? -1 : this._findVisibleRow(from, dr * -1, true); }; WorksheetView.prototype._fixSelectionOfHiddenCells = function (dc, dr, range) { var ar = (range) ? range : this.model.selectionRange.getLast(), c1, c2, r1, r2, mc, i, arn = ar.clone(true); if (dc === undefined) { dc = +1; } if (dr === undefined) { dr = +1; } if (ar.c2 === ar.c1) { if (this.cols[ar.c1].width < this.width_1px) { c1 = c2 = this._findVisibleCol(ar.c1, dc); } } else { if (0 !== dc && this.nColsCount > ar.c2 && this.cols[ar.c2].width < this.width_1px) { // Проверка для одновременно замерженных и скрытых ячеек (A1:C1 merge, B:C hidden) for (mc = null, i = arn.r1; i <= arn.r2; ++i) { mc = this.model.getMergedByCell(i, ar.c2); if (mc) { break; } } if (!mc) { c2 = this._findVisibleCol(ar.c2, dc); } } } if (c1 < 0 || c2 < 0) { throw "Error: all columns are hidden"; } if (ar.r2 === ar.r1) { if (this.rows[ar.r1].height < this.height_1px) { r1 = r2 = this._findVisibleRow(ar.r1, dr); } } else { if (0 !== dr && this.nRowsCount > ar.r2 && this.rows[ar.r2].height < this.height_1px) { //Проверка для одновременно замерженных и скрытых ячеек (A1:A3 merge, 2:3 hidden) for (mc = null, i = arn.c1; i <= arn.c2; ++i) { mc = this.model.getMergedByCell(ar.r2, i); if (mc) { break; } } if (!mc) { r2 = this._findVisibleRow(ar.r2, dr); } } } if (r1 < 0 || r2 < 0) { throw "Error: all rows are hidden"; } ar.assign(c1 !== undefined ? c1 : ar.c1, r1 !== undefined ? r1 : ar.r1, c2 !== undefined ? c2 : ar.c2, r2 !== undefined ? r2 : ar.r2); }; WorksheetView.prototype._getCellByXY = function (x, y) { var c1, r1, c2, r2; x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); if (x < this.cellsLeft && y < this.cellsTop) { c1 = r1 = 0; c2 = gc_nMaxCol0; r2 = gc_nMaxRow0; } else if (x < this.cellsLeft) { r1 = r2 = this._findRowUnderCursor(y).row; c1 = 0; c2 = gc_nMaxCol0; } else if (y < this.cellsTop) { c1 = c2 = this._findColUnderCursor(x).col; r1 = 0; r2 = gc_nMaxRow0; } else { c1 = c2 = this._findColUnderCursor(x).col; r1 = r2 = this._findRowUnderCursor(y).row; } return new asc_Range(c1, r1, c2, r2); }; WorksheetView.prototype._moveActiveCellToXY = function (x, y) { var selection = this._getSelection(); var ar = selection.getLast(); var range = this._getCellByXY(x, y); ar.assign(range.c1, range.r1, range.c2, range.r2); selection.setCell(range.r1, range.c1); if (c_oAscSelectionType.RangeCells !== ar.getType()) { this._fixSelectionOfHiddenCells(); } this._fixSelectionOfMergedCells(); }; WorksheetView.prototype._moveActiveCellToOffset = function (dc, dr) { var selection = this._getSelection(); var ar = selection.getLast(); var activeCell = selection.activeCell; var mc = this.model.getMergedByCell(activeCell.row, activeCell.col); var c = mc ? (dc < 0 ? mc.c1 : dc > 0 ? Math.min(mc.c2, this.nColsCount - 1 - dc) : activeCell.col) : activeCell.col; var r = mc ? (dr < 0 ? mc.r1 : dr > 0 ? Math.min(mc.r2, this.nRowsCount - 1 - dr) : activeCell.row) : activeCell.row; var p = this._calcCellPosition(c, r, dc, dr); ar.assign(p.col, p.row, p.col, p.row); this.model.selectionRange.setCell(p.row, p.col); this._fixSelectionOfHiddenCells(dc >= 0 ? +1 : -1, dr >= 0 ? +1 : -1); this._fixSelectionOfMergedCells(); }; // Движение активной ячейки в выделенной области WorksheetView.prototype._moveActivePointInSelection = function (dc, dr) { var t = this, cell = this.model.selectionRange.activeCell; // Если мы на скрытой строке или ячейке, то двигаться в выделении нельзя (так делает и Excel) if (this.width_1px > this.cols[cell.col].width || this.height_1px > this.rows[cell.row].height) { return; } return this.model.selectionRange.offsetCell(dr, dc, function (row, col) { return (0 <= row) ? (t.rows[row].height < t.height_1px) : (t.cols[col].width < t.width_1px); }); }; WorksheetView.prototype._calcSelectionEndPointByXY = function (x, y, keepType) { var activeCell = this._getSelection().activeCell; var range = this._getCellByXY(x, y); var res = (keepType ? this._getSelection().getLast() : range).clone(); var type = res.getType(); if (c_oAscSelectionType.RangeRow === type) { res.r1 = Math.min(range.r1, activeCell.row); res.r2 = Math.max(range.r1, activeCell.row); } else if (c_oAscSelectionType.RangeCol === type) { res.c1 = Math.min(range.c1, activeCell.col); res.c2 = Math.max(range.c1, activeCell.col); } else if (c_oAscSelectionType.RangeCells === type) { res.assign(activeCell.col, activeCell.row, range.c1, range.r1, true); } this._fixSelectionOfMergedCells(res); return res; }; WorksheetView.prototype._calcSelectionEndPointByOffset = function (dc, dr) { var selection = this._getSelection(); var ar = selection.getLast(); var c1, r1, c2, r2, tmp; tmp = asc.getEndValueRange(dc, selection.activeCell.col, ar.c1, ar.c2); c1 = tmp.x1; c2 = tmp.x2; tmp = asc.getEndValueRange(dr, selection.activeCell.row, ar.r1, ar.r2); r1 = tmp.x1; r2 = tmp.x2; var p1 = this._calcCellPosition(c2, r2, dc, dr), p2; var res = new asc_Range(c1, r1, c2 = p1.col, r2 = p1.row, true); dc = Math.sign(dc); dr = Math.sign(dr); if (c_oAscSelectionType.RangeCells === ar.getType()) { this._fixSelectionOfMergedCells(res); while (ar.isEqual(res)) { p2 = this._calcCellPosition(c2, r2, dc, dr); res.assign(c1, r1, c2 = p2.col, r2 = p2.row, true); this._fixSelectionOfMergedCells(res); if (p1.c2 === p2.c2 && p1.r2 === p2.r2) { break; } p1 = p2; } } var bIsHidden = false; if (0 !== dc && this.cols[c2].width < this.width_1px) { c2 = this._findVisibleCol(c2, dc); bIsHidden = true; } if (0 !== dr && this.rows[r2].height < this.height_1px) { r2 = this._findVisibleRow(r2, dr); bIsHidden = true; } if (bIsHidden) { res.assign(c1, r1, c2, r2, true); } return res; }; WorksheetView.prototype._calcActiveRangeOffsetIsCoord = function (x, y) { var ar = this._getSelection().getLast(); if (this.isFormulaEditMode) { // Для формул нужно сделать ограничение по range (у нас хранится полный диапазон) if (ar.c2 >= this.nColsCount || ar.r2 >= this.nRowsCount) { ar = ar.clone(true); ar.c2 = (ar.c2 >= this.nColsCount) ? this.nColsCount - 1 : ar.c2; ar.r2 = (ar.r2 >= this.nRowsCount) ? this.nRowsCount - 1 : ar.r2; } } x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var d = {}; if (y <= this.cellsTop + this.height_2px /*+ offsetFrozen.offsetY*/) { d.deltaY = -1; } else if (y >= this.drawingCtx.getHeight() - this.height_2px) { d.deltaY = 1; } if (x <= this.cellsLeft + this.width_2px /*+ offsetFrozen.offsetX*/) { d.deltaX = -1; } else if (x >= this.drawingCtx.getWidth() - this.width_2px) { d.deltaX = 1; } var type = ar.getType(); if (type === c_oAscSelectionType.RangeRow) { d.deltaX = 0; } else if (type === c_oAscSelectionType.RangeCol) { d.deltaY = 0; } else if (type === c_oAscSelectionType.RangeMax) { d.deltaX = 0; d.deltaY = 0; } return d; }; WorksheetView.prototype._calcActiveRangeOffset = function () { var vr = this.visibleRange; var ar = this._getSelection().getLast(); if (this.isFormulaEditMode) { // Для формул нужно сделать ограничение по range (у нас хранится полный диапазон) if (ar.c2 >= this.nColsCount || ar.r2 >= this.nRowsCount) { ar = ar.clone(true); ar.c2 = (ar.c2 >= this.nColsCount) ? this.nColsCount - 1 : ar.c2; ar.r2 = (ar.r2 >= this.nRowsCount) ? this.nRowsCount - 1 : ar.r2; } } var arn = ar.clone(true); var isMC = this._isMergedCells(arn); var adjustRight = ar.c2 >= vr.c2 || ar.c1 >= vr.c2 && isMC; var adjustBottom = ar.r2 >= vr.r2 || ar.r1 >= vr.r2 && isMC; var incX = ar.c1 < vr.c1 && isMC ? arn.c1 - vr.c1 : ar.c2 < vr.c1 ? ar.c2 - vr.c1 : 0; var incY = ar.r1 < vr.r1 && isMC ? arn.r1 - vr.r1 : ar.r2 < vr.r1 ? ar.r2 - vr.r1 : 0; var type = ar.getType(); var offsetFrozen = this.getFrozenPaneOffset(); if (adjustRight) { while (this._isColDrawnPartially(isMC ? arn.c2 : ar.c2, vr.c1 + incX, offsetFrozen.offsetX)) { ++incX; } } if (adjustBottom) { while (this._isRowDrawnPartially(isMC ? arn.r2 : ar.r2, vr.r1 + incY, offsetFrozen.offsetY)) { ++incY; } } return { deltaX: type === c_oAscSelectionType.RangeCol || type === c_oAscSelectionType.RangeCells ? incX : 0, deltaY: type === c_oAscSelectionType.RangeRow || type === c_oAscSelectionType.RangeCells ? incY : 0 }; }; /** * @param {Range} [range] * @returns {{deltaX: number, deltaY: number}} */ WorksheetView.prototype._calcActiveCellOffset = function (range) { var vr = this.visibleRange; var activeCell = this.model.selectionRange.activeCell; var ar = range ? range : this.model.selectionRange.getLast(); var mc = this.model.getMergedByCell(activeCell.row, activeCell.col); var startCol = mc ? mc.c1 : activeCell.col; var startRow = mc ? mc.r1 : activeCell.row; var incX = startCol < vr.c1 ? startCol - vr.c1 : 0; var incY = startRow < vr.r1 ? startRow - vr.r1 : 0; var type = ar.getType(); var offsetFrozen = this.getFrozenPaneOffset(); // adjustRight if (startCol >= vr.c2) { while (this._isColDrawnPartially(startCol, vr.c1 + incX, offsetFrozen.offsetX)) { ++incX; } } // adjustBottom if (startRow >= vr.r2) { while (this._isRowDrawnPartially(startRow, vr.r1 + incY, offsetFrozen.offsetY)) { ++incY; } } return { deltaX: type === c_oAscSelectionType.RangeCol || type === c_oAscSelectionType.RangeCells ? incX : 0, deltaY: type === c_oAscSelectionType.RangeRow || type === c_oAscSelectionType.RangeCells ? incY : 0 }; }; WorksheetView.prototype._calcFillHandleOffset = function (range) { var vr = this.visibleRange; var ar = range ? range : this.activeFillHandle; var arn = ar.clone(true); var isMC = this._isMergedCells(arn); var adjustRight = ar.c2 >= vr.c2 || ar.c1 >= vr.c2 && isMC; var adjustBottom = ar.r2 >= vr.r2 || ar.r1 >= vr.r2 && isMC; var incX = ar.c1 < vr.c1 && isMC ? arn.c1 - vr.c1 : ar.c2 < vr.c1 ? ar.c2 - vr.c1 : 0; var incY = ar.r1 < vr.r1 && isMC ? arn.r1 - vr.r1 : ar.r2 < vr.r1 ? ar.r2 - vr.r1 : 0; var offsetFrozen = this.getFrozenPaneOffset(); if (adjustRight) { try { while (this._isColDrawnPartially(isMC ? arn.c2 : ar.c2, vr.c1 + incX, offsetFrozen.offsetX)) { ++incX; } } catch (e) { this.expandColsOnScroll(true); this.handlers.trigger("reinitializeScrollX"); } } if (adjustBottom) { try { while (this._isRowDrawnPartially(isMC ? arn.r2 : ar.r2, vr.r1 + incY, offsetFrozen.offsetY)) { ++incY; } } catch (e) { this.expandRowsOnScroll(true); this.handlers.trigger("reinitializeScrollY"); } } return { deltaX: incX, deltaY: incY }; }; // Потеряем ли мы что-то при merge ячеек WorksheetView.prototype.getSelectionMergeInfo = function (options) { // ToDo now check only last selection range var arn = this.model.selectionRange.getLast().clone(true); var notEmpty = false; var r, c; if (this.cellCommentator.isMissComments(arn)) { return true; } switch (options) { case c_oAscMergeOptions.Merge: case c_oAscMergeOptions.MergeCenter: for (r = arn.r1; r <= arn.r2; ++r) { for (c = arn.c1; c <= arn.c2; ++c) { if (false === this._isCellNullText(c, r)) { if (notEmpty) { return true; } notEmpty = true; } } } break; case c_oAscMergeOptions.MergeAcross: for (r = arn.r1; r <= arn.r2; ++r) { notEmpty = false; for (c = arn.c1; c <= arn.c2; ++c) { if (false === this._isCellNullText(c, r)) { if (notEmpty) { return true; } notEmpty = true; } } } break; } return false; }; //нужно ли спрашивать пользователя о расширении диапазона WorksheetView.prototype.getSelectionSortInfo = function () { //в случае попытки сортировать мультиселект, необходимо выдавать ошибку var arn = this.model.selectionRange.getLast().clone(true); //null - не выдавать сообщение и не расширять, false - не выдавать сообщение и расширЯть, true - выдавать сообщение var bResult = false; //если внутри форматированной таблиц, никогда не выдаем сообщение if(this.model.autoFilters._isTablePartsContainsRange(arn)) { bResult = null; } else if(!arn.isOneCell())//в случае одной выделенной ячейки - всегда не выдаём сообщение и автоматически расширяем { var colCount = arn.c2 - arn.c1 + 1; var rowCount = arn.r2 - arn.r1 + 1; //если выделено более одного столбца и более одной строки - не выдаем сообщение и не расширяем if(colCount > 1 && rowCount > 1) { bResult = null; } else { //далее проверяем есть ли смежные ячейки у startCol/startRow var activeCell = this.model.selectionRange.activeCell; var activeCellRange = new Asc.Range(activeCell.col, activeCell.row, activeCell.col, activeCell.row); var expandRange = this.model.autoFilters._getAdjacentCellsAF(activeCellRange); //если диапазон не расширяется за счет близлежащих ячеек - не выдаем сообщение и не расширяем if(arn.isEqual(expandRange) || activeCellRange.isEqual(expandRange)) { bResult = null; } else if(arn.c1 === expandRange.c1 && arn.c2 === expandRange.c2) { bResult = null; } else { bResult = true; } } } return bResult; }; WorksheetView.prototype.getSelectionMathInfo = function () { var oSelectionMathInfo = new asc_CSelectionMathInfo(); var sum = 0; var oExistCells = {}; if (window["NATIVE_EDITOR_ENJINE"]) { return oSelectionMathInfo; } var t = this; this.model.selectionRange.ranges.forEach(function (item) { var cellValue; var range = t.model.getRange3(item.r1, item.c1, item.r2, item.c2); range._setPropertyNoEmpty(null, null, function (cell, r) { var idCell = cell.nCol + '-' + cell.nRow; if (!oExistCells[idCell] && !cell.isNullTextString() && t.height_1px <= t.rows[r].height) { oExistCells[idCell] = true; ++oSelectionMathInfo.count; if (CellValueType.Number === cell.getType()) { cellValue = cell.getNumberValue(); if (0 === oSelectionMathInfo.countNumbers) { oSelectionMathInfo.min = oSelectionMathInfo.max = cellValue; } else { oSelectionMathInfo.min = Math.min(oSelectionMathInfo.min, cellValue); oSelectionMathInfo.max = Math.max(oSelectionMathInfo.max, cellValue); } ++oSelectionMathInfo.countNumbers; sum += cellValue; } } }); }); // Показываем только данные для 2-х или более ячеек (http://bugzilla.onlyoffice.com/show_bug.cgi?id=24115) if (1 < oSelectionMathInfo.count && 0 < oSelectionMathInfo.countNumbers) { // Мы должны отдавать в формате активной ячейки var activeCell = this.model.selectionRange.activeCell; var numFormat = this.model.getRange3(activeCell.row, activeCell.col, activeCell.row, activeCell.col).getNumFormat(); if (Asc.c_oAscNumFormatType.Time === numFormat.getType()) { // Для времени нужно отдавать в формате [h]:mm:ss (http://bugzilla.onlyoffice.com/show_bug.cgi?id=26271) numFormat = AscCommon.oNumFormatCache.get('[h]:mm:ss'); } oSelectionMathInfo.sum = numFormat.formatToMathInfo(sum, CellValueType.Number, this.settings.mathMaxDigCount); oSelectionMathInfo.average = numFormat.formatToMathInfo(sum / oSelectionMathInfo.countNumbers, CellValueType.Number, this.settings.mathMaxDigCount); oSelectionMathInfo.min = numFormat.formatToMathInfo(oSelectionMathInfo.min, CellValueType.Number, this.settings.mathMaxDigCount); oSelectionMathInfo.max = numFormat.formatToMathInfo(oSelectionMathInfo.max, CellValueType.Number, this.settings.mathMaxDigCount); } return oSelectionMathInfo; }; WorksheetView.prototype.getSelectionName = function (bRangeText) { if (this.isSelectOnShape) { return " "; } // Пока отправим пустое имя(с пробелом, пустое не воспринимаем в меню..) ToDo var ar = this.model.selectionRange.getLast(); var cell = this.model.selectionRange.activeCell; var mc = this.model.getMergedByCell(cell.row, cell.col); var c1 = mc ? mc.c1 : cell.col, r1 = mc ? mc.r1 : cell.row, ar_norm = ar.normalize(), mc_norm = mc ? mc.normalize() : null, c2 = mc_norm ? mc_norm.isEqual(ar_norm) ? mc_norm.c1 : ar_norm.c2 : ar_norm.c2, r2 = mc_norm ? mc_norm.isEqual(ar_norm) ? mc_norm.r1 : ar_norm.r2 : ar_norm.r2, selectionSize = !bRangeText ? "" : (function (r) { var rc = Math.abs(r.r2 - r.r1) + 1; var cc = Math.abs(r.c2 - r.c1) + 1; switch (r.getType()) { case c_oAscSelectionType.RangeCells: return rc + "R x " + cc + "C"; case c_oAscSelectionType.RangeCol: return cc + "C"; case c_oAscSelectionType.RangeRow: return rc + "R"; case c_oAscSelectionType.RangeMax: return gc_nMaxRow + "R x " + gc_nMaxCol + "C"; } return ""; })(ar); if (selectionSize) { return selectionSize; } var dN = new Asc.Range(ar_norm.c1, ar_norm.r1, c2, r2, true); var defName = parserHelp.get3DRef(this.model.getName(), dN.getAbsName()); defName = this.model.workbook.findDefinesNames(defName, this.model.getId()); if (defName) { return defName; } return this._getColumnTitle(c1) + this._getRowTitle(r1); }; WorksheetView.prototype.getSelectionRangeValue = function () { // ToDo проблема с выбором целого столбца/строки var ar = this.model.selectionRange.getLast().clone(true); var sAbsName = ar.getAbsName(); var sName = (c_oAscSelectionDialogType.FormatTable === this.selectionDialogType) ? sAbsName : parserHelp.get3DRef(this.model.getName(), sAbsName); var type = ar.type; var selectionRangeValueObj = new AscCommonExcel.asc_CSelectionRangeValue(); selectionRangeValueObj.asc_setName(sName); selectionRangeValueObj.asc_setType(type); return selectionRangeValueObj; }; WorksheetView.prototype.getSelectionInfo = function () { return this.objectRender.selectedGraphicObjectsExists() ? this._getSelectionInfoObject() : this._getSelectionInfoCell(); }; WorksheetView.prototype._getSelectionInfoCell = function () { var selectionRange = this.model.selectionRange; var cell = selectionRange.activeCell; var mc = this.model.getMergedByCell(cell.row, cell.col); var c1 = mc ? mc.c1 : cell.col; var r1 = mc ? mc.r1 : cell.row; var c = this._getVisibleCell(c1, r1); var font = c.getFont(true); var fa = font.getVerticalAlign(); var bg = c.getFill(); var align = c.getAlign(); var cellType = c.getType(); var isNumberFormat = (!cellType || CellValueType.Number === cellType); var cell_info = new asc_CCellInfo(); cell_info.name = this._getColumnTitle(c1) + this._getRowTitle(r1); cell_info.formula = c.getFormula(); cell_info.text = c.getValueForEdit(); cell_info.halign = align.getAlignHorizontal(); cell_info.valign = align.getAlignVertical(); var tablePartsOptions = selectionRange.isSingleRange() ? this.model.autoFilters.searchRangeInTableParts(selectionRange.getLast()) : -2; var curTablePart = tablePartsOptions >= 0 ? this.model.TableParts[tablePartsOptions] : null; var tableStyleInfo = curTablePart && curTablePart.TableStyleInfo ? curTablePart.TableStyleInfo : null; cell_info.autoFilterInfo = new asc_CAutoFilterInfo(); if (-2 === tablePartsOptions || this.model.inPivotTable(selectionRange.getLast())) { cell_info.autoFilterInfo.isAutoFilter = null; cell_info.autoFilterInfo.isApplyAutoFilter = false; } else { var checkApplyFilterOrSort = this.model.autoFilters.checkApplyFilterOrSort(tablePartsOptions); cell_info.autoFilterInfo.isAutoFilter = checkApplyFilterOrSort.isAutoFilter; cell_info.autoFilterInfo.isApplyAutoFilter = checkApplyFilterOrSort.isFilterColumns; } if (curTablePart !== null) { cell_info.formatTableInfo = new AscCommonExcel.asc_CFormatTableInfo(); cell_info.formatTableInfo.tableName = curTablePart.DisplayName; if (tableStyleInfo) { cell_info.formatTableInfo.tableStyleName = tableStyleInfo.Name; cell_info.formatTableInfo.bandVer = tableStyleInfo.ShowColumnStripes; cell_info.formatTableInfo.firstCol = tableStyleInfo.ShowFirstColumn; cell_info.formatTableInfo.lastCol = tableStyleInfo.ShowLastColumn; cell_info.formatTableInfo.bandHor = tableStyleInfo.ShowRowStripes; } cell_info.formatTableInfo.lastRow = curTablePart.TotalsRowCount !== null; cell_info.formatTableInfo.firstRow = curTablePart.HeaderRowCount === null; cell_info.formatTableInfo.tableRange = curTablePart.Ref.getAbsName(); cell_info.formatTableInfo.filterButton = curTablePart.isShowButton(); cell_info.formatTableInfo.altText = curTablePart.altText; cell_info.formatTableInfo.altTextSummary = curTablePart.altTextSummary; this.af_setDisableProps(curTablePart, cell_info.formatTableInfo); } cell_info.styleName = c.getStyleName(); cell_info.angle = align.getAngle(); cell_info.flags = new AscCommonExcel.asc_CCellFlag(); cell_info.flags.shrinkToFit = align.getShrinkToFit(); cell_info.flags.wrapText = align.getWrap(); // ToDo activeRange type cell_info.flags.selectionType = selectionRange.getLast().getType(); cell_info.flags.multiselect = !selectionRange.isSingleRange(); cell_info.flags.lockText = ("" !== cell_info.text && (isNumberFormat || "" !== cell_info.formula)); cell_info.font = new asc_CFont(); cell_info.font.name = font.getName(); cell_info.font.size = font.getSize(); cell_info.font.bold = font.getBold(); cell_info.font.italic = font.getItalic(); // ToDo убрать, когда будет реализовано двойное подчеркивание cell_info.font.underline = (Asc.EUnderline.underlineNone !== font.getUnderline()); cell_info.font.strikeout = font.getStrikeout(); cell_info.font.subscript = fa === AscCommon.vertalign_SubScript; cell_info.font.superscript = fa === AscCommon.vertalign_SuperScript; cell_info.font.color = asc_obj2Color(font.getColor()); cell_info.fill = new asc_CFill((null != bg) ? asc_obj2Color(bg) : bg); cell_info.numFormat = c.getNumFormatStr(); cell_info.numFormatInfo = c.getNumFormatTypeInfo(); // Получаем гиперссылку (//ToDo) var ar = selectionRange.getLast().clone(); var range = this.model.getRange3(ar.r1, ar.c1, ar.r2, ar.c2); var hyperlink = range.getHyperlink(); var oHyperlink; if (null !== hyperlink) { // Гиперлинк oHyperlink = new asc_CHyperlink(hyperlink); oHyperlink.asc_setText(cell_info.text); cell_info.hyperlink = oHyperlink; } else { cell_info.hyperlink = null; } cell_info.comment = this.cellCommentator.getComment(ar.c1, ar.r1); cell_info.flags.merge = range.isOneCell() ? Asc.c_oAscMergeOptions.Disabled : null !== range.hasMerged() ? Asc.c_oAscMergeOptions.Merge : Asc.c_oAscMergeOptions.None; var sheetId = this.model.getId(); var lockInfo; // Пересчет для входящих ячеек в добавленные строки/столбцы var isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, ar); if (false === isIntersection) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, new AscCommonExcel.asc_CCollaborativeRange(ar.c1, ar.r1, ar.c2, ar.r2)); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже ячейку кто-то редактирует cell_info.isLocked = true; } } if (null !== curTablePart) { var tableAr = curTablePart.Ref.clone(); isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, tableAr); if (false === isIntersection) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, new AscCommonExcel.asc_CCollaborativeRange(tableAr.c1, tableAr.r1, tableAr.c2, tableAr.r2)); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже таблицу кто-то редактирует cell_info.isLockedTable = true; } } } cell_info.sparklineInfo = this.model.getSparklineGroup(c1, r1); if (cell_info.sparklineInfo) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null, sheetId, cell_info.sparklineInfo.Get_Id()); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { cell_info.isLockedSparkline = true; } } cell_info.pivotTableInfo = this.model.getPivotTable(c1, r1); return cell_info; }; WorksheetView.prototype._getSelectionInfoObject = function () { var objectInfo = new asc_CCellInfo(); objectInfo.flags = new AscCommonExcel.asc_CCellFlag(); var graphicObjects = this.objectRender.getSelectedGraphicObjects(); if (graphicObjects.length) { objectInfo.flags.selectionType = this.objectRender.getGraphicSelectionType(graphicObjects[0].Id); } var textPr = this.objectRender.controller.getParagraphTextPr(); var theme = this.objectRender.controller.getTheme(); if (textPr && theme && theme.themeElements && theme.themeElements.fontScheme) { if (textPr.FontFamily) { textPr.FontFamily.Name = theme.themeElements.fontScheme.checkFont(textPr.FontFamily.Name); } if (textPr.RFonts) { if (textPr.RFonts.Ascii) { textPr.RFonts.Ascii.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.Ascii.Name); } if (textPr.RFonts.EastAsia) { textPr.RFonts.EastAsia.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.EastAsia.Name); } if (textPr.RFonts.HAnsi) { textPr.RFonts.HAnsi.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.HAnsi.Name); } if (textPr.RFonts.CS) { textPr.RFonts.CS.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.CS.Name); } } } var paraPr = this.objectRender.controller.getParagraphParaPr(); if (!paraPr && textPr) { paraPr = new CParaPr(); } if (textPr && paraPr) { objectInfo.text = this.objectRender.controller.GetSelectedText(true); var horAlign = paraPr.Jc; var vertAlign = Asc.c_oAscVAlign.Center; var shape_props = this.objectRender.controller.getDrawingProps().shapeProps; var angle = null; if (shape_props) { switch (shape_props.verticalTextAlign) { case AscFormat.VERTICAL_ANCHOR_TYPE_BOTTOM: vertAlign = Asc.c_oAscVAlign.Bottom; break; case AscFormat.VERTICAL_ANCHOR_TYPE_CENTER: vertAlign = Asc.c_oAscVAlign.Center; break; case AscFormat.VERTICAL_ANCHOR_TYPE_TOP: case AscFormat.VERTICAL_ANCHOR_TYPE_DISTRIBUTED: case AscFormat.VERTICAL_ANCHOR_TYPE_JUSTIFIED: vertAlign = Asc.c_oAscVAlign.Top; break; } switch (shape_props.vert) { case AscFormat.nVertTTvert: angle = 90; break; case AscFormat.nVertTTvert270: angle = 270; break; default: angle = 0; break; } } objectInfo.halign = horAlign; objectInfo.valign = vertAlign; objectInfo.angle = angle; objectInfo.font = new asc_CFont(); objectInfo.font.name = textPr.FontFamily ? textPr.FontFamily.Name : null; objectInfo.font.size = textPr.FontSize; objectInfo.font.bold = textPr.Bold; objectInfo.font.italic = textPr.Italic; objectInfo.font.underline = textPr.Underline; objectInfo.font.strikeout = textPr.Strikeout; objectInfo.font.subscript = textPr.VertAlign == AscCommon.vertalign_SubScript; objectInfo.font.superscript = textPr.VertAlign == AscCommon.vertalign_SuperScript; if(textPr.Unifill){ if(theme){ textPr.Unifill.check(theme, this.objectRender.controller.getColorMap()); } var oColor = textPr.Unifill.getRGBAColor(); objectInfo.font.color = AscCommon.CreateAscColorCustom(oColor.R, oColor.G, oColor.B); } else if (textPr.Color) { objectInfo.font.color = AscCommon.CreateAscColorCustom(textPr.Color.r, textPr.Color.g, textPr.Color.b); } var shapeHyperlink = this.objectRender.controller.getHyperlinkInfo(); if (shapeHyperlink && (shapeHyperlink instanceof ParaHyperlink)) { var hyperlink = new AscCommonExcel.Hyperlink(); hyperlink.Tooltip = shapeHyperlink.ToolTip; var spl = shapeHyperlink.Value.split("!"); if (spl.length === 2) { hyperlink.setLocation(shapeHyperlink.Value); } else { hyperlink.Hyperlink = shapeHyperlink.Value; } objectInfo.hyperlink = new asc_CHyperlink(hyperlink); objectInfo.hyperlink.asc_setText(shapeHyperlink.GetSelectedText(true, true)); } } else { // Может быть не задано текста, поэтому выставим по умолчанию objectInfo.font = new asc_CFont(); objectInfo.font.name = null; objectInfo.font.size = null; } // Заливка не нужна как таковая objectInfo.fill = new asc_CFill(null); // ToDo locks return objectInfo; }; // Получаем координаты активной ячейки WorksheetView.prototype.getActiveCellCoord = function () { return this.getCellCoord(this.model.selectionRange.activeCell.col, this.model.selectionRange.activeCell.row); }; WorksheetView.prototype.getCellCoord = function (col, row) { var offsetX = 0, offsetY = 0; var vrCol = this.visibleRange.c1, vrRow = this.visibleRange.r1; if ( this.topLeftFrozenCell ) { var offsetFrozen = this.getFrozenPaneOffset(); var cFrozen = this.topLeftFrozenCell.getCol0(); var rFrozen = this.topLeftFrozenCell.getRow0(); if ( col >= cFrozen ) { offsetX = offsetFrozen.offsetX; } else { vrCol = 0; } if ( row >= rFrozen ) { offsetY = offsetFrozen.offsetY; } else { vrRow = 0; } } var xL = this.getCellLeft( col, /*pt*/1 ); var yL = this.getCellTop( row, /*pt*/1 ); // Пересчитываем X и Y относительно видимой области xL -= (this.cols[vrCol].left - this.cellsLeft); yL -= (this.rows[vrRow].top - this.cellsTop); // Пересчитываем X и Y относительно закрепленной области xL += offsetX; yL += offsetY; // Пересчитываем в px xL *= asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIX() ); yL *= asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIY() ); var width = this.getColumnWidth( col, /*px*/0 ); var height = this.getRowHeight( row, /*px*/0 ); if ( AscBrowser.isRetina ) { xL = AscCommon.AscBrowser.convertToRetinaValue(xL); yL = AscCommon.AscBrowser.convertToRetinaValue(yL); width = AscCommon.AscBrowser.convertToRetinaValue(width); height = AscCommon.AscBrowser.convertToRetinaValue(height); } return new AscCommon.asc_CRect( xL, yL, width, height ); }; WorksheetView.prototype._endSelectionShape = function () { var isSelectOnShape = this.isSelectOnShape; if (this.isSelectOnShape) { this.isSelectOnShape = false; this.objectRender.unselectDrawingObjects(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); } return isSelectOnShape; }; WorksheetView.prototype._updateSelectionNameAndInfo = function () { this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/false)); this.handlers.trigger("selectionChanged"); this.handlers.trigger("selectionMathInfoChanged", this.getSelectionMathInfo()); }; WorksheetView.prototype.getSelectionShape = function () { return this.isSelectOnShape; }; WorksheetView.prototype.setSelectionShape = function ( isSelectOnShape ) { this.isSelectOnShape = isSelectOnShape; // отправляем евент для получения свойств картинки, шейпа или группы this.model.workbook.handlers.trigger( "asc_onHideComment" ); this._updateSelectionNameAndInfo(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); }; WorksheetView.prototype.setSelection = function (range, validRange) { // Проверка на валидность range. if (validRange && (range.c2 >= this.nColsCount || range.r2 >= this.nRowsCount)) { if (range.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, range.c2 + 1); } if (range.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, range.r2 + 1); } } var oRes = null; var type = range.getType(); if (type === c_oAscSelectionType.RangeCells || type === c_oAscSelectionType.RangeCol || type === c_oAscSelectionType.RangeRow || type === c_oAscSelectionType.RangeMax) { this.cleanSelection(); this.model.selectionRange.assign2(range); this._fixSelectionOfMergedCells(); this.updateSelectionWithSparklines(); this._updateSelectionNameAndInfo(); oRes = this._calcActiveCellOffset(); } return oRes; }; WorksheetView.prototype.changeSelectionStartPoint = function (x, y, isCoord, isCtrl) { this.cleanSelection(); if (!this.isFormulaEditMode) { this.cleanFormulaRanges(); if (isCtrl) { this.model.selectionRange.addRange(); } else { this.model.selectionRange.clean(); } } var ar = this._getSelection().getLast().clone(); var ret = {}; var isChangeSelectionShape = false; var comment; if (isCoord) { comment = this.cellCommentator.getCommentByXY(x, y); // move active range to coordinates x,y this._moveActiveCellToXY(x, y); isChangeSelectionShape = this._endSelectionShape(); } else { comment = this.cellCommentator.getComment(x, y); // move active range to offset x,y this._moveActiveCellToOffset(x, y); ret = this._calcActiveRangeOffset(); } if (!comment) { this.cellCommentator.resetLastSelectedId(); } if (this.isSelectionDialogMode) { if (!this.model.selectionRange.isEqual(ar)) { // Смена диапазона this.handlers.trigger("selectionRangeChanged", this.getSelectionRangeValue()); } } else if (!this.isCellEditMode) { if (isChangeSelectionShape || !this.model.selectionRange.isEqual(ar)) { this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/false)); if (!isCoord) { this.handlers.trigger("selectionChanged"); this.handlers.trigger("selectionMathInfoChanged", this.getSelectionMathInfo()); } } } if (!isChangeSelectionShape) { if (!isCoord) { this.updateSelectionWithSparklines(); } else { this._drawSelection(); } } //ToDo this.drawDepCells(); return ret; }; // Смена селекта по нажатию правой кнопки мыши WorksheetView.prototype.changeSelectionStartPointRightClick = function (x, y) { var isSelectOnShape = this._endSelectionShape(); this.model.workbook.handlers.trigger("asc_onHideComment"); var _x = x * asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); var _y = y * asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var val, c1, c2, r1, r2; val = this._findColUnderCursor(_x, true); if (val) { c1 = c2 = val.col; } else { c1 = 0; c2 = gc_nMaxCol0; } val = this._findRowUnderCursor(_y, true); if (val) { r1 = r2 = val.row; } else { r1 = 0; r2 = gc_nMaxRow0; } if (!this.model.selectionRange.containsRange(new asc_Range(c1, r1, c2, r2))) { // Не попали в выделение (меняем первую точку) this.cleanSelection(); this.model.selectionRange.clean(); this._moveActiveCellToXY(x, y); this._drawSelection(); this._updateSelectionNameAndInfo(); } else if (isSelectOnShape) { this._updateSelectionNameAndInfo(); } }; /** * * @param x - координата или прибавка к column * @param y - координата или прибавка к row * @param isCoord - выделение с помощью мышки или с клавиатуры. При выделении с помощью мышки, не нужно отправлять эвенты о смене выделения и информации * @param keepType * @returns {*} */ WorksheetView.prototype.changeSelectionEndPoint = function (x, y, isCoord, keepType) { var isChangeSelectionShape = isCoord ? this._endSelectionShape() : false; var ar = this._getSelection().getLast(); var newRange = isCoord ? this._calcSelectionEndPointByXY(x, y, keepType) : this._calcSelectionEndPointByOffset(x, y); var isEqual = newRange.isEqual(ar); if (isEqual && !isCoord) { // При движении стрелками можем попасть на замерженную ячейку } if (!isEqual || isChangeSelectionShape) { this.cleanSelection(); ar.assign2(newRange); this._drawSelection(); //ToDo this.drawDepCells(); if (!this.isCellEditMode) { if (!this.isSelectionDialogMode) { this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/true)); if (!isCoord) { this.handlers.trigger("selectionChanged"); this.handlers.trigger("selectionMathInfoChanged", this.getSelectionMathInfo()); } } else { // Смена диапазона this.handlers.trigger("selectionRangeChanged", this.getSelectionRangeValue()); } } } this.model.workbook.handlers.trigger("asc_onHideComment"); return isCoord ? this._calcActiveRangeOffsetIsCoord(x, y) : this._calcActiveRangeOffset(); }; // Окончание выделения WorksheetView.prototype.changeSelectionDone = function () { if (this.stateFormatPainter) { this.applyFormatPainter(); } else { this.checkSelectionSparkline(); } }; // Обработка движения в выделенной области WorksheetView.prototype.changeSelectionActivePoint = function (dc, dr) { var ret; if (0 === dc && 0 === dr) { return this._calcActiveCellOffset(); } if (!this._moveActivePointInSelection(dc, dr)) { return this.changeSelectionStartPoint(dc, dr, /*isCoord*/false, false); } // Очищаем выделение this.cleanSelection(); // Перерисовываем this.updateSelectionWithSparklines(); // Смотрим, ушли ли мы за границу видимой области ret = this._calcActiveCellOffset(); // Эвент обновления this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/false)); this.handlers.trigger("selectionChanged"); return ret; }; WorksheetView.prototype.checkSelectionSparkline = function () { if (!this.getSelectionShape() && !this.isFormulaEditMode && !this.isCellEditMode) { var cell = this.model.selectionRange.activeCell; var mc = this.model.getMergedByCell(cell.row, cell.col); var c1 = mc ? mc.c1 : cell.col; var r1 = mc ? mc.r1 : cell.row; var oSparklineInfo = this.model.getSparklineGroup(c1, r1); if (oSparklineInfo) { this.cleanSelection(); this.cleanFormulaRanges(); var range = oSparklineInfo.getLocationRanges(); range.ranges.forEach(function (item) { item.isName = true; item.noColor = true; }); this.arrActiveFormulaRanges.push(range); this._drawSelection(); return true; } } }; // ----- Changing cells ----- WorksheetView.prototype.applyFormatPainter = function () { var t = this; var from = t.handlers.trigger('getRangeFormatPainter').getLast(), to = this.model.selectionRange.getLast().getAllRange(); var onApplyFormatPainterCallback = function (isSuccess) { // Очищаем выделение t.cleanSelection(); if (true === isSuccess) { AscCommonExcel.promoteFromTo(from, t.model, to, t.model); } t.expandColsOnScroll(false, true, to.c2 + 1); t.expandRowsOnScroll(false, true, to.r2 + 1); // Сбрасываем параметры t._updateCellsRange(to, /*canChangeColWidth*/c_oAscCanChangeColWidth.none, /*lockDraw*/true); if (c_oAscFormatPainterState.kMultiple !== t.stateFormatPainter) { t.handlers.trigger('onStopFormatPainter'); } // Перерисовываем t._recalculateAfterUpdate([to]); }; var result = AscCommonExcel.preparePromoteFromTo(from, to); if (!result) { // ToDo вывести ошибку onApplyFormatPainterCallback(false); return; } this._isLockedCells(to, null, onApplyFormatPainterCallback); }; WorksheetView.prototype.formatPainter = function (stateFormatPainter) { // Если передали состояние, то выставляем его. Если нет - то меняем на противоположное. this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn); if (this.stateFormatPainter) { this.copyActiveRange = this.model.selectionRange.clone(); this._drawFormatPainterRange(); } else { this.cleanSelection(); this.copyActiveRange = null; this._drawSelection(); } return this.copyActiveRange; }; /* Функция для работы автозаполнения (selection). (x, y) - координаты точки мыши на области */ WorksheetView.prototype.changeSelectionFillHandle = function (x, y) { // Возвращаемый результат var ret = null; // Если мы только первый раз попали сюда, то копируем выделенную область if (null === this.activeFillHandle) { this.activeFillHandle = this.model.selectionRange.getLast().clone(); // Для первого раза нормализуем (т.е. первая точка - это левый верхний угол) this.activeFillHandle.normalize(); return ret; } // Пересчитываем координаты x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); // Очищаем выделение, будем рисовать заново this.cleanSelection(); // Копируем выделенную область var ar = this.model.selectionRange.getLast().clone(true); // Получаем координаты левого верхнего угла выделения var xL = this.getCellLeft(ar.c1, /*pt*/1); var yL = this.getCellTop(ar.r1, /*pt*/1); // Получаем координаты правого нижнего угла выделения var xR = this.getCellLeft(ar.c2, /*pt*/1) + this.cols[ar.c2].width; var yR = this.getCellTop(ar.r2, /*pt*/1) + this.rows[ar.r2].height; // range для пересчета видимой области var activeFillHandleCopy; // Колонка по X и строка по Y var colByX = this._findColUnderCursor(x, /*canReturnNull*/false, true).col; var rowByY = this._findRowUnderCursor(y, /*canReturnNull*/false, true).row; // Колонка по X и строка по Y (без половинчатого счета). Для сдвига видимой области var colByXNoDX = this._findColUnderCursor(x, /*canReturnNull*/false, false).col; var rowByYNoDY = this._findRowUnderCursor(y, /*canReturnNull*/false, false).row; // Сдвиг в столбцах и строках от крайней точки var dCol; var dRow; // Пересчитываем X и Y относительно видимой области x += (this.cols[this.visibleRange.c1].left - this.cellsLeft); y += (this.rows[this.visibleRange.r1].top - this.cellsTop); // Вычисляем расстояние от (x, y) до (xL, yL) var dXL = x - xL; var dYL = y - yL; // Вычисляем расстояние от (x, y) до (xR, yR) var dXR = x - xR; var dYR = y - yR; var dXRMod; var dYRMod; // Определяем область попадания и точку /* (1) (2) (3) ------------|-----------------------|------------ | | (4) | (5) | (6) | | ------------|-----------------------|------------ (7) (8) (9) */ // Область точки (x, y) var _tmpArea = 0; if (dXR <= 0) { // Области (1), (2), (4), (5), (7), (8) if (dXL <= 0) { // Области (1), (4), (7) if (dYR <= 0) { // Области (1), (4) if (dYL <= 0) { // Область (1) _tmpArea = 1; } else { // Область (4) _tmpArea = 4; } } else { // Область (7) _tmpArea = 7; } } else { // Области (2), (5), (8) if (dYR <= 0) { // Области (2), (5) if (dYL <= 0) { // Область (2) _tmpArea = 2; } else { // Область (5) _tmpArea = 5; } } else { // Область (3) _tmpArea = 8; } } } else { // Области (3), (6), (9) if (dYR <= 0) { // Области (3), (6) if (dYL <= 0) { // Область (3) _tmpArea = 3; } else { // Область (6) _tmpArea = 6; } } else { // Область (9) _tmpArea = 9; } } // Проверяем, в каком направлении движение switch (_tmpArea) { case 2: case 8: // Двигаемся по вертикали. this.fillHandleDirection = 1; break; case 4: case 6: // Двигаемся по горизонтали. this.fillHandleDirection = 0; break; case 1: // Сравниваем расстояния от точки до левого верхнего угла выделения dXRMod = Math.abs(x - xL); dYRMod = Math.abs(y - yL); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c1); dRow = Math.abs(rowByY - ar.r1); // Определим направление позднее this.fillHandleDirection = -1; break; case 3: // Сравниваем расстояния от точки до правого верхнего угла выделения dXRMod = Math.abs(x - xR); dYRMod = Math.abs(y - yL); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c2); dRow = Math.abs(rowByY - ar.r1); // Определим направление позднее this.fillHandleDirection = -1; break; case 7: // Сравниваем расстояния от точки до левого нижнего угла выделения dXRMod = Math.abs(x - xL); dYRMod = Math.abs(y - yR); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c1); dRow = Math.abs(rowByY - ar.r2); // Определим направление позднее this.fillHandleDirection = -1; break; case 5: case 9: // Сравниваем расстояния от точки до правого нижнего угла выделения dXRMod = Math.abs(dXR); dYRMod = Math.abs(dYR); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c2); dRow = Math.abs(rowByY - ar.r2); // Определим направление позднее this.fillHandleDirection = -1; break; } //console.log(_tmpArea); // Возможно еще не определили направление if (-1 === this.fillHandleDirection) { // Проверим сдвиги по столбцам и строкам, если не поможет, то рассчитываем по расстоянию if (0 === dCol && 0 !== dRow) { // Двигаемся по вертикали. this.fillHandleDirection = 1; } else if (0 !== dCol && 0 === dRow) { // Двигаемся по горизонтали. this.fillHandleDirection = 0; } else if (dXRMod >= dYRMod) { // Двигаемся по горизонтали. this.fillHandleDirection = 0; } else { // Двигаемся по вертикали. this.fillHandleDirection = 1; } } // Проверяем, в каком направлении движение if (0 === this.fillHandleDirection) { // Определяем область попадания и точку /* | | | | (1) | (2) | (3) | | | | */ if (dXR <= 0) { // Область (1) или (2) if (dXL <= 0) { // Область (1) this.fillHandleArea = 1; } else { // Область (2) this.fillHandleArea = 2; } } else { // Область (3) this.fillHandleArea = 3; } // Находим колонку для точки this.activeFillHandle.c2 = colByX; switch (this.fillHandleArea) { case 1: // Первая точка (xR, yR), вторая точка (x, yL) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.r2 = ar.r1; // Случай, если мы еще не вышли из внутренней области if (this.activeFillHandle.c2 == ar.c1) { this.fillHandleArea = 2; } break; case 2: // Первая точка (xR, yR), вторая точка (x, yL) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.r2 = ar.r1; if (this.activeFillHandle.c2 > this.activeFillHandle.c1) { // Ситуация половинки последнего столбца this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.c2 = ar.c1; this.activeFillHandle.r2 = ar.r1; } break; case 3: // Первая точка (xL, yL), вторая точка (x, yR) this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.r2 = ar.r2; break; } // Копируем в range для пересчета видимой области activeFillHandleCopy = this.activeFillHandle.clone(); activeFillHandleCopy.c2 = colByXNoDX; } else { // Определяем область попадания и точку /* (1) ____________________________ (2) ____________________________ (3) */ if (dYR <= 0) { // Область (1) или (2) if (dYL <= 0) { // Область (1) this.fillHandleArea = 1; } else { // Область (2) this.fillHandleArea = 2; } } else { // Область (3) this.fillHandleArea = 3; } // Находим строку для точки this.activeFillHandle.r2 = rowByY; switch (this.fillHandleArea) { case 1: // Первая точка (xR, yR), вторая точка (xL, y) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.c2 = ar.c1; // Случай, если мы еще не вышли из внутренней области if (this.activeFillHandle.r2 == ar.r1) { this.fillHandleArea = 2; } break; case 2: // Первая точка (xR, yR), вторая точка (xL, y) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.c2 = ar.c1; if (this.activeFillHandle.r2 > this.activeFillHandle.r1) { // Ситуация половинки последней строки this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.c2 = ar.c1; this.activeFillHandle.r2 = ar.r1; } break; case 3: // Первая точка (xL, yL), вторая точка (xR, y) this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.c2 = ar.c2; break; } // Копируем в range для пересчета видимой области activeFillHandleCopy = this.activeFillHandle.clone(); activeFillHandleCopy.r2 = rowByYNoDY; } //console.log ("row1: " + this.activeFillHandle.r1 + " col1: " + this.activeFillHandle.c1 + " row2: " + this.activeFillHandle.r2 + " col2: " + this.activeFillHandle.c2); // Перерисовываем this._drawSelection(); // Смотрим, ушли ли мы за границу видимой области ret = this._calcFillHandleOffset(activeFillHandleCopy); this.model.workbook.handlers.trigger("asc_onHideComment"); return ret; }; /* Функция для применения автозаполнения */ WorksheetView.prototype.applyFillHandle = function (x, y, ctrlPress) { var t = this; // Текущее выделение (к нему применится автозаполнение) var arn = t.model.selectionRange.getLast(); var range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); // Были ли изменения var bIsHaveChanges = false; // Вычисляем индекс сдвига var nIndex = 0; /*nIndex*/ if (0 === this.fillHandleDirection) { // Горизонтальное движение nIndex = this.activeFillHandle.c2 - arn.c1; if (2 === this.fillHandleArea) { // Для внутренности нужно вычесть 1 из значения bIsHaveChanges = arn.c2 !== (this.activeFillHandle.c2 - 1); } else { bIsHaveChanges = arn.c2 !== this.activeFillHandle.c2; } } else { // Вертикальное движение nIndex = this.activeFillHandle.r2 - arn.r1; if (2 === this.fillHandleArea) { // Для внутренности нужно вычесть 1 из значения bIsHaveChanges = arn.r2 !== (this.activeFillHandle.r2 - 1); } else { bIsHaveChanges = arn.r2 !== this.activeFillHandle.r2; } } // Меняли ли что-то if (bIsHaveChanges && (this.activeFillHandle.r1 !== this.activeFillHandle.r2 || this.activeFillHandle.c1 !== this.activeFillHandle.c2)) { // Диапазон ячеек, который мы будем менять var changedRange = arn.clone(); // Очищаем выделение this.cleanSelection(); if (2 === this.fillHandleArea) { // Мы внутри, будет удаление cбрасываем первую ячейку // Проверяем, удалили ли мы все (если да, то область не меняется) if (arn.c1 !== this.activeFillHandle.c2 || arn.r1 !== this.activeFillHandle.r2) { // Уменьшаем диапазон (мы удалили не все) if (0 === this.fillHandleDirection) { // Горизонтальное движение (для внутренности необходимо вычесть 1) arn.c2 = this.activeFillHandle.c2 - 1; changedRange.c1 = changedRange.c2; changedRange.c2 = this.activeFillHandle.c2; } else { // Вертикальное движение (для внутренности необходимо вычесть 1) arn.r2 = this.activeFillHandle.r2 - 1; changedRange.r1 = changedRange.r2; changedRange.r2 = this.activeFillHandle.r2; } } } else { // Мы вне выделения. Увеличиваем диапазон if (0 === this.fillHandleDirection) { // Горизонтальное движение if (1 === this.fillHandleArea) { arn.c1 = this.activeFillHandle.c2; changedRange.c2 = changedRange.c1 - 1; changedRange.c1 = this.activeFillHandle.c2; } else { arn.c2 = this.activeFillHandle.c2; changedRange.c1 = changedRange.c2 + 1; changedRange.c2 = this.activeFillHandle.c2; } } else { // Вертикальное движение if (1 === this.fillHandleArea) { arn.r1 = this.activeFillHandle.r2; changedRange.r2 = changedRange.r1 - 1; changedRange.r1 = this.activeFillHandle.r2; } else { arn.r2 = this.activeFillHandle.r2; changedRange.r1 = changedRange.r2 + 1; changedRange.r2 = this.activeFillHandle.r2; } } } changedRange.normalize(); var applyFillHandleCallback = function (res) { if (res) { // Автозаполняем ячейки var oCanPromote = range.canPromote(/*bCtrl*/ctrlPress, /*bVertical*/(1 === t.fillHandleDirection), nIndex); if (null != oCanPromote) { History.Create_NewPoint(); History.StartTransaction(); if(t.model.autoFilters.bIsExcludeHiddenRows(changedRange, t.model.selectionRange.activeCell)){ t.model.excludeHiddenRows(true); } range.promote(/*bCtrl*/ctrlPress, /*bVertical*/(1 === t.fillHandleDirection), nIndex, oCanPromote); t.model.excludeHiddenRows(false); // Вызываем функцию пересчета для заголовков форматированной таблицы t.model.autoFilters.renameTableColumn(arn); // Сбрасываем параметры автозаполнения t.activeFillHandle = null; t.fillHandleDirection = -1; // Обновляем выделенные ячейки t.isChanged = true; t._updateCellsRange(arn); History.SetSelection(range.bbox.clone()); History.SetSelectionRedo(oCanPromote.to.clone()); History.EndTransaction(); } else { t.handlers.trigger("onErrorEvent", c_oAscError.ID.CannotFillRange, c_oAscError.Level.NoCritical); t.model.selectionRange.assign2(range.bbox); // Сбрасываем параметры автозаполнения t.activeFillHandle = null; t.fillHandleDirection = -1; t.updateSelection(); } } else { // Сбрасываем параметры автозаполнения t.activeFillHandle = null; t.fillHandleDirection = -1; // Перерисовываем t._drawSelection(); } }; if (this.model.inPivotTable(changedRange)) { // Сбрасываем параметры автозаполнения this.activeFillHandle = null; this.fillHandleDirection = -1; // Перерисовываем this._drawSelection(); this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } // Можно ли применять автозаполнение ? this._isLockedCells(changedRange, /*subType*/null, applyFillHandleCallback); } else { // Ничего не менялось, сбрасываем выделение this.cleanSelection(); // Сбрасываем параметры автозаполнения this.activeFillHandle = null; this.fillHandleDirection = -1; // Перерисовываем this._drawSelection(); } }; /* Функция для работы перемещения диапазона (selection). (x, y) - координаты точки мыши на области * ToDo нужно переделать, чтобы moveRange появлялся только после сдвига от текущей ячейки */ WorksheetView.prototype.changeSelectionMoveRangeHandle = function (x, y) { // Возвращаемый результат var ret = null; // Пересчитываем координаты x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); //если выделена ячейка заголовка ф/т, меняем выделение с ячейки на столбец ф/т //если выделена вся видимая часть форматированной таблицы, но не выделены последние скрытые строчки var selectionRange = this.model.selectionRange.getLast().clone(); if (null === this.startCellMoveRange) { this.af_changeSelectionTablePart(selectionRange); } // Колонка по X и строка по Y var colByX = this._findColUnderCursor(x, /*canReturnNull*/false, false).col; var rowByY = this._findRowUnderCursor(y, /*canReturnNull*/false, false).row; var type = selectionRange.getType(); if (type === c_oAscSelectionType.RangeRow) { colByX = 0; } else if (type === c_oAscSelectionType.RangeCol) { rowByY = 0; } else if (type === c_oAscSelectionType.RangeMax) { colByX = 0; rowByY = 0; } // Если мы только первый раз попали сюда, то копируем выделенную область if (null === this.startCellMoveRange) { // Учитываем погрешность (мы должны быть внутри диапазона при старте) if (colByX < selectionRange.c1) { colByX = selectionRange.c1; } else if (colByX > selectionRange.c2) { colByX = selectionRange.c2; } if (rowByY < selectionRange.r1) { rowByY = selectionRange.r1; } else if (rowByY > selectionRange.r2) { rowByY = selectionRange.r2; } this.startCellMoveRange = new asc_Range(colByX, rowByY, colByX, rowByY); this.startCellMoveRange.isChanged = false; // Флаг, сдвигались ли мы от первоначального диапазона return ret; } // Разница, на сколько мы сдвинулись var colDelta = colByX - this.startCellMoveRange.c1; var rowDelta = rowByY - this.startCellMoveRange.r1; // Проверяем, нужно ли отрисовывать перемещение (сдвигались или нет) if (false === this.startCellMoveRange.isChanged && 0 === colDelta && 0 === rowDelta) { return ret; } // Выставляем флаг this.startCellMoveRange.isChanged = true; // Очищаем выделение, будем рисовать заново this.cleanSelection(); this.activeMoveRange = selectionRange; // Для первого раза нормализуем (т.е. первая точка - это левый верхний угол) this.activeMoveRange.normalize(); // Выставляем this.activeMoveRange.c1 += colDelta; if (0 > this.activeMoveRange.c1) { colDelta -= this.activeMoveRange.c1; this.activeMoveRange.c1 = 0; } this.activeMoveRange.c2 += colDelta; this.activeMoveRange.r1 += rowDelta; if (0 > this.activeMoveRange.r1) { rowDelta -= this.activeMoveRange.r1; this.activeMoveRange.r1 = 0; } this.activeMoveRange.r2 += rowDelta; // Увеличиваем, если выходим за область видимости // Critical Bug 17413 while (!this.cols[this.activeMoveRange.c2]) { this.expandColsOnScroll(true); this.handlers.trigger("reinitializeScrollX"); } while (!this.rows[this.activeMoveRange.r2]) { this.expandRowsOnScroll(true); this.handlers.trigger("reinitializeScrollY"); } // Перерисовываем this._drawSelection(); var d = {}; /*var d = { deltaX : this.activeMoveRange.c1 < this.visibleRange.c1 ? this.activeMoveRange.c1-this.visibleRange.c1 : this.activeMoveRange.c2>this.visibleRange.c2 ? this.activeMoveRange.c2-this.visibleRange.c2 : 0, deltaY : this.activeMoveRange.r1 < this.visibleRange.r1 ? this.activeMoveRange.r1-this.visibleRange.r1 : this.activeMoveRange.r2>this.visibleRange.r2 ? this.activeMoveRange.r2-this.visibleRange.r2 : 0 }; while ( this._isColDrawnPartially( this.activeMoveRange.c2, this.visibleRange.c1 + d.deltaX) ) {++d.deltaX;} while ( this._isRowDrawnPartially( this.activeMoveRange.r2, this.visibleRange.r1 + d.deltaY) ) {++d.deltaY;}*/ if (y <= this.cellsTop + this.height_2px) { d.deltaY = -1; } else if (y >= this.drawingCtx.getHeight() - this.height_2px) { d.deltaY = 1; } if (x <= this.cellsLeft + this.width_2px) { d.deltaX = -1; } else if (x >= this.drawingCtx.getWidth() - this.width_2px) { d.deltaX = 1; } this.model.workbook.handlers.trigger("asc_onHideComment"); type = this.activeMoveRange.getType(); if (type === c_oAscSelectionType.RangeRow) { d.deltaX = 0; } else if (type === c_oAscSelectionType.RangeCol) { d.deltaY = 0; } else if (type === c_oAscSelectionType.RangeMax) { d.deltaX = 0; d.deltaY = 0; } return d; }; WorksheetView.prototype.changeSelectionMoveResizeRangeHandle = function (x, y, targetInfo, editor) { // Возвращаемый результат if (!targetInfo) { return null; } var type; var indexFormulaRange = targetInfo.indexFormulaRange, d = {deltaY: 0, deltaX: 0}, newFormulaRange = null; // Пересчитываем координаты x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var ar = (0 == targetInfo.targetArr ? this.arrActiveFormulaRanges[indexFormulaRange] : this.arrActiveChartRanges[indexFormulaRange]).getLast().clone(); // Колонка по X и строка по Y var colByX = this._findColUnderCursor(x, /*canReturnNull*/false, false).col; var rowByY = this._findRowUnderCursor(y, /*canReturnNull*/false, false).row; // Если мы только первый раз попали сюда, то копируем выделенную область if (null === this.startCellMoveResizeRange) { if ((targetInfo.cursor == kCurNEResize || targetInfo.cursor == kCurSEResize)) { this.startCellMoveResizeRange = ar.clone(true); this.startCellMoveResizeRange2 = new asc_Range(targetInfo.col, targetInfo.row, targetInfo.col, targetInfo.row, true); } else { this.startCellMoveResizeRange = ar.clone(true); if (colByX < ar.c1) { colByX = ar.c1; } else if (colByX > ar.c2) { colByX = ar.c2; } if (rowByY < ar.r1) { rowByY = ar.r1; } else if (rowByY > ar.r2) { rowByY = ar.r2; } this.startCellMoveResizeRange2 = new asc_Range(colByX, rowByY, colByX, rowByY); } return null; } // Очищаем выделение, будем рисовать заново // this.cleanSelection(); this.overlayCtx.clear(); if (targetInfo.cursor == kCurNEResize || targetInfo.cursor == kCurSEResize) { if (colByX < this.startCellMoveResizeRange2.c1) { ar.c2 = this.startCellMoveResizeRange2.c1; ar.c1 = colByX; } else if (colByX > this.startCellMoveResizeRange2.c1) { ar.c1 = this.startCellMoveResizeRange2.c1; ar.c2 = colByX; } else { ar.c1 = this.startCellMoveResizeRange2.c1; ar.c2 = this.startCellMoveResizeRange2.c1 } if (rowByY < this.startCellMoveResizeRange2.r1) { ar.r2 = this.startCellMoveResizeRange2.r2; ar.r1 = rowByY; } else if (rowByY > this.startCellMoveResizeRange2.r1) { ar.r1 = this.startCellMoveResizeRange2.r1; ar.r2 = rowByY; } else { ar.r1 = this.startCellMoveResizeRange2.r1; ar.r2 = this.startCellMoveResizeRange2.r1; } } else { this.startCellMoveResizeRange.normalize(); type = this.startCellMoveResizeRange.getType(); var colDelta = type !== c_oAscSelectionType.RangeRow && type !== c_oAscSelectionType.RangeMax ? colByX - this.startCellMoveResizeRange2.c1 : 0; var rowDelta = type !== c_oAscSelectionType.RangeCol && type !== c_oAscSelectionType.RangeMax ? rowByY - this.startCellMoveResizeRange2.r1 : 0; ar.c1 = this.startCellMoveResizeRange.c1 + colDelta; if (0 > ar.c1) { colDelta -= ar.c1; ar.c1 = 0; } ar.c2 = this.startCellMoveResizeRange.c2 + colDelta; ar.r1 = this.startCellMoveResizeRange.r1 + rowDelta; if (0 > ar.r1) { rowDelta -= ar.r1; ar.r1 = 0; } ar.r2 = this.startCellMoveResizeRange.r2 + rowDelta; } if (y <= this.cellsTop + this.height_2px) { d.deltaY = -1; } else if (y >= this.drawingCtx.getHeight() - this.height_2px) { d.deltaY = 1; } if (x <= this.cellsLeft + this.width_2px) { d.deltaX = -1; } else if (x >= this.drawingCtx.getWidth() - this.width_2px) { d.deltaX = 1; } type = this.startCellMoveResizeRange.getType(); if (type === c_oAscSelectionType.RangeRow) { d.deltaX = 0; } else if (type === c_oAscSelectionType.RangeCol) { d.deltaY = 0; } else if (type === c_oAscSelectionType.RangeMax) { d.deltaX = 0; d.deltaY = 0; } if (0 == targetInfo.targetArr) { var _p = this.arrActiveFormulaRanges[indexFormulaRange].cursorePos, _l = this.arrActiveFormulaRanges[indexFormulaRange].formulaRangeLength; this.arrActiveFormulaRanges[indexFormulaRange].getLast().assign2(ar.clone(true)); this.arrActiveFormulaRanges[indexFormulaRange].cursorePos = _p; this.arrActiveFormulaRanges[indexFormulaRange].formulaRangeLength = _l; newFormulaRange = this.arrActiveFormulaRanges[indexFormulaRange].getLast(); } else { this.arrActiveChartRanges[indexFormulaRange].getLast().assign2(ar.clone(true)); this.moveRangeDrawingObjectTo = ar.clone(); } this._drawSelection(); if (newFormulaRange) { editor.changeCellRange(newFormulaRange); } return d; }; WorksheetView.prototype._cleanSelectionMoveRange = function () { // Перерисовываем и сбрасываем параметры this.cleanSelection(); this.activeMoveRange = null; this.startCellMoveRange = null; this._drawSelection(); }; /* Функция для применения перемещения диапазона */ WorksheetView.prototype.applyMoveRangeHandle = function (ctrlKey) { if (null === this.activeMoveRange) { // Сбрасываем параметры this.startCellMoveRange = null; return; } var arnFrom = this.model.selectionRange.getLast(); var arnTo = this.activeMoveRange.clone(true); if (arnFrom.isEqual(arnTo)) { this._cleanSelectionMoveRange(); return; } if (this.model.inPivotTable([arnFrom, arnTo])) { this._cleanSelectionMoveRange(); this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } var resmove = this.model._prepareMoveRange(arnFrom, arnTo); if (resmove === -2) { this.handlers.trigger("onErrorEvent", c_oAscError.ID.CannotMoveRange, c_oAscError.Level.NoCritical); this._cleanSelectionMoveRange(); } else if (resmove === -1) { var t = this; this.model.workbook.handlers.trigger("asc_onConfirmAction", Asc.c_oAscConfirm.ConfirmReplaceRange, function (can) { if (can) { t.moveRangeHandle(arnFrom, arnTo, ctrlKey); } else { t._cleanSelectionMoveRange(); } }); } else { this.moveRangeHandle(arnFrom, arnTo, ctrlKey); } }; WorksheetView.prototype.applyMoveResizeRangeHandle = function ( target ) { if ( -1 == target.targetArr && !this.startCellMoveResizeRange.isEqual( this.moveRangeDrawingObjectTo ) ) { this.objectRender.moveRangeDrawingObject( this.startCellMoveResizeRange, this.moveRangeDrawingObjectTo ); } this.startCellMoveResizeRange = null; this.startCellMoveResizeRange2 = null; this.moveRangeDrawingObjectTo = null; }; WorksheetView.prototype.moveRangeHandle = function (arnFrom, arnTo, copyRange) { var t = this; var onApplyMoveRangeHandleCallback = function (isSuccess) { if (false === isSuccess) { t.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedAllError, c_oAscError.Level.NoCritical); t._cleanSelectionMoveRange(); return; } var onApplyMoveAutoFiltersCallback = function (isSuccess) { if (false === isSuccess) { t.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedAllError, c_oAscError.Level.NoCritical); t._cleanSelectionMoveRange(); return; } // Очищаем выделение t.cleanSelection(); //ToDo t.cleanDepCells(); History.Create_NewPoint(); History.SetSelection(arnFrom.clone()); History.SetSelectionRedo(arnTo.clone()); History.StartTransaction(); t.model.autoFilters._preMoveAutoFilters(arnFrom, arnTo, copyRange); t.model._moveRange(arnFrom, arnTo, copyRange); t.cellCommentator.moveRangeComments(arnFrom, arnTo, copyRange); t.objectRender.moveRangeDrawingObject(arnFrom, arnTo); // Вызываем функцию пересчета для заголовков форматированной таблицы t.model.autoFilters.renameTableColumn(arnFrom); t.model.autoFilters.renameTableColumn(arnTo); t.model.autoFilters.reDrawFilter(arnFrom); t.model.autoFilters.afterMoveAutoFilters(arnFrom, arnTo); t._updateCellsRange(arnTo, false, true); t.model.selectionRange.assign2(arnTo); // Сбрасываем параметры t.activeMoveRange = null; t.startCellMoveRange = null; t._updateCellsRange(arnFrom, false, true); // Тут будет отрисовка select-а t._recalculateAfterUpdate([arnFrom, arnTo]); // Вызовем на всякий случай, т.к. мы можем уже обновиться из-за формул ToDo возможно стоит убрать это в дальнейшем (но нужна переработка формул) - http://bugzilla.onlyoffice.com/show_bug.cgi?id=24505 t._updateSelectionNameAndInfo(); if (null !== t.model.getRange3(arnTo.r1, arnTo.c1, arnTo.r2, arnTo.c2).hasMerged() && false !== t.model.autoFilters._intersectionRangeWithTableParts(arnTo)) { t.model.autoFilters.unmergeTablesAfterMove(arnTo); t._updateCellsRange(arnTo, false, true); t._recalculateAfterUpdate([arnFrom, arnTo]); //не делаем действий в asc_onConfirmAction, потому что во время диалога может выполниться autosave и новые измения добавятся в точку, которую уже отправили //тем более результат диалога ни на что не влияет t.model.workbook.handlers.trigger("asc_onConfirmAction", Asc.c_oAscConfirm.ConfirmPutMergeRange, function () { }); } History.EndTransaction(); }; if (t.model.autoFilters._searchFiltersInRange(arnFrom, true)) { t._isLockedAll(onApplyMoveAutoFiltersCallback); if(copyRange){ t._isLockedDefNames(null, null); } } else { onApplyMoveAutoFiltersCallback(); } }; if (this.af_isCheckMoveRange(arnFrom, arnTo)) { this._isLockedCells([arnFrom, arnTo], null, onApplyMoveRangeHandleCallback); } else { this._cleanSelectionMoveRange(); } }; WorksheetView.prototype.emptySelection = function ( options ) { // Удаляем выделенные графичекие объекты if ( this.objectRender.selectedGraphicObjectsExists() ) { this.objectRender.controller.remove(); } else { this.setSelectionInfo( "empty", options ); } }; WorksheetView.prototype.setSelectionInfo = function (prop, val, onlyActive) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } var t = this; var checkRange = []; var activeCell = this.model.selectionRange.activeCell.clone(); var arn = this.model.selectionRange.getLast().clone(true); var onSelectionCallback = function (isSuccess) { if (false === isSuccess) { return; } var bIsUpdate = true; var oUpdateRanges = {}, hasUpdates = false; var callTrigger = false; var res; var mc, r, c, cell; function makeBorder(b) { var border = new AscCommonExcel.BorderProp(); if (b === false) { border.setStyle(c_oAscBorderStyles.None); } else if (b) { if (b.style !== null && b.style !== undefined) { border.setStyle(b.style); } if (b.color !== null && b.color !== undefined) { if (b.color instanceof Asc.asc_CColor) { border.c = AscCommonExcel.CorrectAscColor(b.color); } } } return border; } History.Create_NewPoint(); History.StartTransaction(); checkRange.forEach(function (item, i) { var range = t.model.getRange3(item.r1, item.c1, item.r2, item.c2); var isLargeRange = t._isLargeRange(range.bbox); var canChangeColWidth = c_oAscCanChangeColWidth.none; if(t.model.autoFilters.bIsExcludeHiddenRows(arn, activeCell)) { t.model.excludeHiddenRows(true); } switch (prop) { case "fn": range.setFontname(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "fs": range.setFontsize(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "b": range.setBold(val); break; case "i": range.setItalic(val); break; case "u": range.setUnderline(val); break; case "s": range.setStrikeout(val); break; case "fa": range.setFontAlign(val); break; case "a": range.setAlignHorizontal(val); break; case "va": range.setAlignVertical(val); break; case "c": range.setFontcolor(val); break; case "bc": range.setFill(val || null); break; // ToDo можно делать просто отрисовку case "wrap": range.setWrap(val); break; case "shrink": range.setShrinkToFit(val); break; case "value": range.setValue(val); break; case "format": range.setNumFormat(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "angle": range.setAngle(val); break; case "rh": range.removeHyperlink(null, true); break; case "border": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } // None if (val.length < 1) { range.setBorder(null); break; } res = new AscCommonExcel.Border(); // Diagonal res.d = makeBorder(val[c_oAscBorderOptions.DiagD] || val[c_oAscBorderOptions.DiagU]); res.dd = !!val[c_oAscBorderOptions.DiagD]; res.du = !!val[c_oAscBorderOptions.DiagU]; // Vertical res.l = makeBorder(val[c_oAscBorderOptions.Left]); res.iv = makeBorder(val[c_oAscBorderOptions.InnerV]); res.r = makeBorder(val[c_oAscBorderOptions.Right]); // Horizontal res.t = makeBorder(val[c_oAscBorderOptions.Top]); res.ih = makeBorder(val[c_oAscBorderOptions.InnerH]); res.b = makeBorder(val[c_oAscBorderOptions.Bottom]); // Change border range.setBorder(res); break; case "merge": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } switch (val) { case c_oAscMergeOptions.MergeCenter: case c_oAscMergeOptions.Merge: range.merge(val); t.cellCommentator.mergeComments(range.getBBox0()); break; case c_oAscMergeOptions.None: range.unmerge(); break; case c_oAscMergeOptions.MergeAcross: for (res = arn.r1; res <= arn.r2; ++res) { t.model.getRange3(res, arn.c1, res, arn.c2).merge(val); cell = new asc_Range(arn.c1, res, arn.c2, res); t.cellCommentator.mergeComments(cell); } break; } break; case "sort": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } t.cellCommentator.sortComments(range.sort(val.type, activeCell.col, val.color, true)); break; case "empty": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } /* отключаем отрисовку на случай необходимости пересчета ячеек, заносим ячейку, при необходимости в список перерисовываемых */ t.model.workbook.dependencyFormulas.lockRecal(); switch(val) { case c_oAscCleanOptions.All: range.cleanAll(); t.model.deletePivotTables(range.bbox); t.model.removeSparklines(arn); // Удаляем комментарии t.cellCommentator.deleteCommentsRange(arn); break; case c_oAscCleanOptions.Text: case c_oAscCleanOptions.Formula: range.cleanText(); t.model.deletePivotTables(range.bbox); break; case c_oAscCleanOptions.Format: range.cleanFormat(); break; case c_oAscCleanOptions.Comments: t.cellCommentator.deleteCommentsRange(arn); break; case c_oAscCleanOptions.Hyperlinks: range.cleanHyperlinks(); break; case c_oAscCleanOptions.Sparklines: t.model.removeSparklines(arn); break; case c_oAscCleanOptions.SparklineGroups: t.model.removeSparklineGroups(arn); break; } t.model.excludeHiddenRows(false); // Если нужно удалить автофильтры - удаляем if (window['AscCommonExcel'].filteringMode) { if (val === c_oAscCleanOptions.All || val === c_oAscCleanOptions.Text) { t.model.autoFilters.isEmptyAutoFilters(arn); } else if (val === c_oAscCleanOptions.Format) { t.model.autoFilters.cleanFormat(arn); } } // Вызываем функцию пересчета для заголовков форматированной таблицы if (val === c_oAscCleanOptions.All || val === c_oAscCleanOptions.Text) { t.model.autoFilters.renameTableColumn(arn); } /* возвращаем отрисовку. и перерисовываем ячейки с предварительным пересчетом */ t.model.workbook.dependencyFormulas.unlockRecal(); break; case "changeDigNum": res = t.cols.slice(arn.c1, arn.c2 + 1).reduce(function (r, c) { r.push(c.charCount); return r; }, []); range.shiftNumFormat(val, res); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "changeFontSize": mc = t.model.getMergedByCell(activeCell.row, activeCell.col); c = mc ? mc.c1 : activeCell.col; r = mc ? mc.r1 : activeCell.row; cell = t._getVisibleCell(c, r); var oldFontSize = cell.getFont().getSize(); var newFontSize = asc_incDecFonSize(val, oldFontSize); if (null !== newFontSize) { range.setFontsize(newFontSize); canChangeColWidth = c_oAscCanChangeColWidth.numbers; } break; case "style": range.setCellStyle(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; break; case "paste": var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; specialPasteHelper.specialPasteProps = specialPasteHelper.specialPasteProps ? specialPasteHelper.specialPasteProps : new Asc.SpecialPasteProps(); t._loadDataBeforePaste(isLargeRange, val.fromBinary, val.data, bIsUpdate, canChangeColWidth); bIsUpdate = false; break; case "hyperlink": if (val && val.hyperlinkModel) { if (Asc.c_oAscHyperlinkType.RangeLink === val.asc_getType()) { var hyperlinkRangeTmp = t.model.getRange2(val.asc_getRange()); if (null === hyperlinkRangeTmp) { bIsUpdate = false; break; } } val.hyperlinkModel.Ref = range; range.setHyperlink(val.hyperlinkModel); // Вставим текст в активную ячейку (а не так, как MSExcel в первую ячейку диапазона) mc = t.model.getMergedByCell(activeCell.row, activeCell.col); c = mc ? mc.c1 : activeCell.col; r = mc ? mc.r1 : activeCell.row; if (null !== val.asc_getText()) { t.model.getRange3(r, c, r, c).setValue(val.asc_getText()); // Вызываем функцию пересчета для заголовков форматированной таблицы t.model.autoFilters.renameTableColumn(arn); } break; } else { bIsUpdate = false; break; } default: bIsUpdate = false; break; } t.model.excludeHiddenRows(false); if (bIsUpdate) { hasUpdates = true; oUpdateRanges[i] = item; oUpdateRanges[i].canChangeColWidth = canChangeColWidth; bIsUpdate = false; } }); if (hasUpdates) { t.updateRanges(oUpdateRanges, false, true); } if (callTrigger) { t.handlers.trigger("slowOperation", false); } //в случае, если вставляем из глобального буфера, транзакцию закрываем внутри функции _loadDataBeforePaste на callbacks от загрузки шрифтов и картинок if (prop !== "paste" || (prop === "paste" && val.fromBinary)) { History.EndTransaction(); if(prop === "paste") { window['AscCommon'].g_specialPasteHelper.Paste_Process_End(); } } }; if ("paste" === prop) { if (val.onlyImages) { onSelectionCallback(true); return; } else { var newRange = val.fromBinary ? this._pasteFromBinary(val.data, true) : this._pasteFromHTML(val.data, true); checkRange = [newRange]; } } else if (onlyActive) { checkRange.push(new asc_Range(activeCell.col, activeCell.row, activeCell.col, activeCell.row)); } else { this.model.selectionRange.ranges.forEach(function (item) { checkRange.push(item.getAllRange()); }); } if (("merge" === prop || "paste" === prop || "sort" === prop || "hyperlink" === prop || "rh" === prop) && this.model.inPivotTable(checkRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } if ("empty" === prop && !this.model.checkDeletePivotTables(checkRange)) { // ToDo other error this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(checkRange, /*subType*/null, onSelectionCallback); }; WorksheetView.prototype.specialPaste = function (props) { var api = window["Asc"]["editor"]; var t = this; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteData = specialPasteHelper.specialPasteData; if(!specialPasteData) { return; } var isIntoShape = t.objectRender.controller.getTargetDocContent(); var onSelectionCallback = function(isSuccess) { if(!isSuccess) { return false; } window['AscCommon'].g_specialPasteHelper.Paste_Process_Start(); window['AscCommon'].g_specialPasteHelper.Special_Paste_Start(); api.asc_Undo(); //транзакция закроется в end_paste History.Create_NewPoint(); History.StartTransaction(); //далее специальная вставка specialPasteHelper.specialPasteProps = props; //TODO пока для закрытия транзации выставляю флаг. пересмотреть! window['AscCommon'].g_specialPasteHelper.bIsEndTransaction = true; AscCommonExcel.g_clipboardExcel.pasteData(t, specialPasteData._format, specialPasteData.data1, specialPasteData.data2, specialPasteData.text_data, true); }; if(specialPasteData.activeRange && !isIntoShape) { this._isLockedCells(specialPasteData.activeRange.ranges, /*subType*/null, onSelectionCallback); } else { onSelectionCallback(true); } }; WorksheetView.prototype._pasteData = function (isLargeRange, fromBinary, val, bIsUpdate, canChangeColWidth) { var t = this; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteProps = specialPasteHelper.specialPasteProps; if ( val.props && val.props.onlyImages === true ) { if(!specialPasteHelper.specialPasteStart) { this.handlers.trigger("showSpecialPasteOptions", [Asc.c_oSpecialPasteProps.picture]); } return; } var callTrigger = false; if (isLargeRange) { callTrigger = true; t.handlers.trigger("slowOperation", true); } //добавляем форматированные таблицы var arnToRange = t.model.selectionRange.getLast(); var pasteRange = AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange; var activeCellsPasteFragment = typeof pasteRange === "string" ? AscCommonExcel.g_oRangeCache.getAscRange(pasteRange) : pasteRange; var tablesMap = null; if (fromBinary && val.TableParts && val.TableParts.length && specialPasteProps.formatTable) { var range, tablePartRange, tables = val.TableParts, diffRow, diffCol, curTable, bIsAddTable; var activeRange = AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange; var refInsertBinary = AscCommonExcel.g_oRangeCache.getAscRange(activeRange); for (var i = 0; i < tables.length; i++) { curTable = tables[i]; tablePartRange = curTable.Ref; diffRow = tablePartRange.r1 - refInsertBinary.r1 + arnToRange.r1; diffCol = tablePartRange.c1 - refInsertBinary.c1 + arnToRange.c1; range = t.model.getRange3(diffRow, diffCol, diffRow + (tablePartRange.r2 - tablePartRange.r1), diffCol + (tablePartRange.c2 - tablePartRange.c1)); //если в активную область при записи попала лишь часть таблицы if(activeCellsPasteFragment && !activeCellsPasteFragment.containsRange(tablePartRange)){ continue; } //если область вставки содержит форматированную таблицу, которая пересекается с вставляемой форматированной таблицей var intersectionRangeWithTableParts = t.model.autoFilters._intersectionRangeWithTableParts(range.bbox); if (intersectionRangeWithTableParts) { continue; } if (curTable.style) { range.cleanFormat(); } //TODO использовать bWithoutFilter из tablePart var bWithoutFilter = false; if (!curTable.AutoFilter) { bWithoutFilter = true; } var offset = { offsetCol: range.bbox.c1 - tablePartRange.c1, offsetRow: range.bbox.r1 - tablePartRange.r1 }; var newDisplayName = this.model.workbook.dependencyFormulas.getNextTableName(); var props = { bWithoutFilter: bWithoutFilter, tablePart: curTable, offset: offset, displayName: newDisplayName }; t.model.autoFilters.addAutoFilter(curTable.TableStyleInfo.Name, range.bbox, true, true, props); if (null === tablesMap) { tablesMap = {}; } tablesMap[curTable.DisplayName] = newDisplayName; } if(bIsAddTable) { t._isLockedDefNames(null, null); } } //делаем unmerge ф/т var intersectionRangeWithTableParts = t.model.autoFilters._intersectionRangeWithTableParts(arnToRange); if (intersectionRangeWithTableParts && intersectionRangeWithTableParts.length) { var tablePart; for (var i = 0; i < intersectionRangeWithTableParts.length; i++) { tablePart = intersectionRangeWithTableParts[i]; this.model.getRange3(tablePart.Ref.r1, tablePart.Ref.c1, tablePart.Ref.r2, tablePart.Ref.c2).unmerge(); } } t.model.workbook.dependencyFormulas.lockRecal(); var selectData; if (fromBinary) { selectData = t._pasteFromBinary(val, null, tablesMap); } else { selectData = t._pasteFromHTML(val, null, specialPasteProps); } t.model.autoFilters.renameTableColumn(t.model.selectionRange.getLast()); if (!selectData) { bIsUpdate = false; t.model.workbook.dependencyFormulas.unlockRecal(); if (callTrigger) { t.handlers.trigger("slowOperation", false); } return; } this.expandColsOnScroll(false, true); this.expandRowsOnScroll(false, true); var arrFormula = selectData[1]; for (var i = 0; i < arrFormula.length; ++i) { var rangeF = arrFormula[i].range; var valF = arrFormula[i].val; if (rangeF.isOneCell()) { rangeF.setValue(valF, null, true); } else { var oBBox = rangeF.getBBox0(); t.model._getCell(oBBox.r1, oBBox.c1, function(cell) { cell.setValue(valF, null, true); }); } } t.model.workbook.dependencyFormulas.unlockRecal(); var arn = selectData[0]; var selectionRange = arn.clone(true); if (bIsUpdate) { if (callTrigger) { t.handlers.trigger("slowOperation", false); } t.isChanged = true; t._updateCellsRange(arn, canChangeColWidth); } var oSelection = History.GetSelection(); if (null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(selectionRange.c1, selectionRange.r1, selectionRange.c2, selectionRange.r2); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } //for special paste if(!window['AscCommon'].g_specialPasteHelper.specialPasteStart) { //var specialPasteShowOptions = new Asc.SpecialPasteShowOptions(); var allowedSpecialPasteProps; var sProps = Asc.c_oSpecialPasteProps; if(fromBinary) { allowedSpecialPasteProps = [sProps.paste, sProps.pasteOnlyFormula, sProps.formulaNumberFormat, sProps.formulaAllFormatting, sProps.formulaWithoutBorders, sProps.formulaColumnWidth, sProps.pasteOnlyValues, sProps.valueNumberFormat, sProps.valueAllFormating, sProps.pasteOnlyFormating/*, sProps.link*/]; if(!(val.TableParts && val.TableParts.length)) { //add transpose property allowedSpecialPasteProps.push(sProps.transpose); } } else { //matchDestinationFormatting - пока не добавляю, так как работает как и values allowedSpecialPasteProps = [sProps.sourceformatting, sProps.destinationFormatting]; } window['AscCommon'].g_specialPasteHelper.CleanButtonInfo(); window['AscCommon'].g_specialPasteHelper.buttonInfo.asc_setOptions(allowedSpecialPasteProps); window['AscCommon'].g_specialPasteHelper.buttonInfo.setRange(selectData[0]); } else { window['AscCommon'].g_specialPasteHelper.buttonInfo.setRange(selectData[0]); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); } }; WorksheetView.prototype._loadDataBeforePaste = function ( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ) { var t = this; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteProps = specialPasteHelper.specialPasteProps; //paste from excel binary if(fromBinary) { t._pasteData(isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth); } else { var callbackLoadFonts = function() { var api = asc["editor"]; var isEndTransaction = false; var imagesFromWord = pasteContent.props.addImagesFromWord; if ( imagesFromWord && imagesFromWord.length != 0 && !(window["Asc"]["editor"] && window["Asc"]["editor"].isChartEditor) && specialPasteProps.images) { var oObjectsForDownload = AscCommon.GetObjectsForImageDownload( pasteContent.props._aPastedImages ); //if already load images on server if ( AscCommonExcel.g_clipboardExcel.pasteProcessor.alreadyLoadImagesOnServer === true ) { var oImageMap = {}; for ( var i = 0, length = oObjectsForDownload.aBuilderImagesByUrl.length; i < length; ++i ) { var url = oObjectsForDownload.aUrls[i]; //get name from array already load on server urls var name = AscCommonExcel.g_clipboardExcel.pasteProcessor.oImages[url]; var aImageElem = oObjectsForDownload.aBuilderImagesByUrl[i]; if ( name ) { if ( Array.isArray( aImageElem ) ) { for ( var j = 0; j < aImageElem.length; ++j ) { var imageElem = aImageElem[j]; if ( null != imageElem ) { imageElem.SetUrl( name ); } } } oImageMap[i] = name; } else { oImageMap[i] = url; } } t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); AscCommonExcel.g_clipboardExcel.pasteProcessor._insertImagesFromBinaryWord( t, pasteContent, oImageMap ); isEndTransaction = true; } else { if(window["NATIVE_EDITOR_ENJINE"]) { var oImageMap = {}; AscCommon.ResetNewUrls( data, oObjectsForDownload.aUrls, oObjectsForDownload.aBuilderImagesByUrl, oImageMap ); t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); AscCommonExcel.g_clipboardExcel.pasteProcessor._insertImagesFromBinaryWord( t, pasteContent, oImageMap ); isEndTransaction = true; } else { AscCommon.sendImgUrls( api, oObjectsForDownload.aUrls, function ( data ) { var oImageMap = {}; AscCommon.ResetNewUrls( data, oObjectsForDownload.aUrls, oObjectsForDownload.aBuilderImagesByUrl, oImageMap ); t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); AscCommonExcel.g_clipboardExcel.pasteProcessor._insertImagesFromBinaryWord( t, pasteContent, oImageMap ); //закрываем транзакцию, поскольку в setSelectionInfo она не закроется History.EndTransaction(); window['AscCommon'].g_specialPasteHelper.Paste_Process_End(); }, true ); } } } else { t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); isEndTransaction = true; } //закрываем транзакцию, поскольку в setSelectionInfo она не закроется if ( isEndTransaction ) { History.EndTransaction(); window['AscCommon'].g_specialPasteHelper.Paste_Process_End(); } }; //загрузка шрифтов, в случае удачи на callback вставляем текст t._loadFonts( pasteContent.props.fontsNew, callbackLoadFonts); } }; WorksheetView.prototype._pasteFromHTML = function (pasteContent, isCheckSelection, specialPasteProps) { var t = this; var wb = window["Asc"]["editor"].wb; var lastSelection = this.model.selectionRange.getLast(); var arn = AscCommonExcel.g_clipboardExcel.pasteProcessor && AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange ? AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange : lastSelection; var arrFormula = []; var numFor = 0; var rMax = pasteContent.content.length + pasteContent.props.rowSpanSpCount + arn.r1; var cMax = pasteContent.props.cellCount + arn.c1; var isMultiple = false; var firstCell = t.model.getRange3(arn.r1, arn.c1, arn.r1, arn.c1); var isMergedFirstCell = firstCell.hasMerged(); var rangeUnMerge = t.model.getRange3(arn.r1, arn.c1, rMax - 1, cMax - 1); var isOneMerge = false; //если вставляем в мерженную ячейку, диапазон которой больше или равен var fPasteCell = pasteContent.content[0][0]; if (arn.c2 >= cMax - 1 && arn.r2 >= rMax - 1 && isMergedFirstCell && isMergedFirstCell.isEqual(arn) && cMax - arn.c1 === fPasteCell.colSpan && rMax - arn.r1 === fPasteCell.rowSpan) { if (!isCheckSelection) { pasteContent.content[0][0].colSpan = isMergedFirstCell.c2 - isMergedFirstCell.c1 + 1; pasteContent.content[0][0].rowSpan = isMergedFirstCell.r2 - isMergedFirstCell.r1 + 1; } isOneMerge = true; } else { //проверка на наличие части объединённой ячейки в области куда осуществляем вставку for (var rFirst = arn.r1; rFirst < rMax; ++rFirst) { for (var cFirst = arn.c1; cFirst < cMax; ++cFirst) { var range = t.model.getRange3(rFirst, cFirst, rFirst, cFirst); var merged = range.hasMerged(); if (merged) { if (merged.r1 < arn.r1 || merged.r2 > rMax - 1 || merged.c1 < arn.c1 || merged.c2 > cMax - 1) { //ошибка в случае если вставка происходит в часть объедененной ячейки if (isCheckSelection) { return arn; } else { this.handlers.trigger("onErrorEvent", c_oAscError.ID.PastInMergeAreaError, c_oAscError.Level.NoCritical); return; } } } } } } var rMax2 = rMax; var cMax2 = cMax; var rMax = pasteContent.content.length; if (isCheckSelection) { var newArr = arn.clone(true); newArr.r2 = rMax2 - 1; newArr.c2 = cMax2 - 1; if (isMultiple || isOneMerge) { newArr.r2 = lastSelection.r2; newArr.c2 = lastSelection.c2; } return newArr; } //если не возникает конфликт, делаем unmerge if(specialPasteProps.format) { rangeUnMerge.unmerge(); //this.cellCommentator.deleteCommentsRange(rangeUnMerge.bbox); } if (!isOneMerge) { arn.r2 = (rMax2 - 1 > 0) ? (rMax2 - 1) : 0; arn.c2 = (cMax2 - 1 > 0) ? (cMax2 - 1) : 0; } if (isMultiple)//случай автозаполнения сложных форм { if(specialPasteProps.format) { t.model.getRange3(lastSelection.r1, lastSelection.c1, lastSelection.r2, lastSelection.c2).unmerge(); } var maxARow = heightArea / heightPasteFr; var maxACol = widthArea / widthPasteFr; var plRow = (rMax2 - arn.r1); var plCol = (arn.c2 - arn.c1) + 1; } else { var maxARow = 1; var maxACol = 1; var plRow = 0; var plCol = 0; } var mergeArr = []; var putInsertedCellIntoRange = function(row, col, currentObj) { var pastedRangeProps = {}; var contentCurrentObj = currentObj.content; var range = t.model.getRange3(row, col, row, col); //value if (contentCurrentObj.length === 1) { var onlyOneChild = contentCurrentObj[0]; var valFormat = onlyOneChild.text; pastedRangeProps.val = valFormat; pastedRangeProps.font = onlyOneChild.format; } else { pastedRangeProps.value2 = contentCurrentObj; pastedRangeProps.alignVertical = currentObj.va; pastedRangeProps.val = currentObj.textVal; } if (contentCurrentObj.length === 1 && contentCurrentObj[0].format) { var fs = contentCurrentObj[0].format.getSize(); if (fs !== '' && fs !== null && fs !== undefined) { pastedRangeProps.fontSize = fs; } } //AlignHorizontal if (!isOneMerge) { pastedRangeProps.alignHorizontal = currentObj.a; } //for merge var isMerged = false; for (var mergeCheck = 0; mergeCheck < mergeArr.length; ++mergeCheck) { if (mergeArr[mergeCheck].contains(col, row)) { isMerged = true; } } if ((currentObj.colSpan > 1 || currentObj.rowSpan > 1) && !isMerged) { var offsetCol = currentObj.colSpan - 1; var offsetRow = currentObj.rowSpan - 1; pastedRangeProps.offsetLast = {offsetCol: offsetCol, offsetRow: offsetRow}; mergeArr.push(new Asc.Range(range.bbox.c1, range.bbox.r1, range.bbox.c2 + offsetCol, range.bbox.r2 + offsetRow)); if (contentCurrentObj[0] == undefined) { pastedRangeProps.val = ''; } pastedRangeProps.merge = c_oAscMergeOptions.Merge; } //borders if (!isOneMerge) { pastedRangeProps.borders = currentObj.borders; } //wrap pastedRangeProps.wrap = currentObj.wrap; //fill if (currentObj.bc && currentObj.bc.rgb) { pastedRangeProps.fill = currentObj.bc; } //hyperlink var link = currentObj.hyperLink; if (link) { pastedRangeProps.hyperLink = currentObj; } //apply props by cell t._setPastedDataByCurrentRange(range, pastedRangeProps, null, specialPasteProps); }; for (var autoR = 0; autoR < maxARow; ++autoR) { for (var autoC = 0; autoC < maxACol; ++autoC) { for (var r = 0; r < rMax; ++r) { for (var c = 0; c < pasteContent.content[r].length; ++c) { if (undefined !== pasteContent.content[r][c]) { var pasteIntoRow = r + autoR * plRow + arn.r1; var pasteIntoCol = c + autoC * plCol + arn.c1; var currentObj = pasteContent.content[r][c]; putInsertedCellIntoRange(pasteIntoRow, pasteIntoCol, currentObj); } } } } } if (isMultiple) { arn.r2 = lastSelection.r2; arn.c2 = lastSelection.c2; } t.isChanged = true; lastSelection.c2 = arn.c2; lastSelection.r2 = arn.r2; var arnFor = [arn, arrFormula]; return arnFor; }; WorksheetView.prototype._pasteFromBinary = function (val, isCheckSelection, tablesMap) { var t = this; var trueActiveRange = t.model.selectionRange.getLast().clone(); var lastSelection = this.model.selectionRange.getLast(); var arn = t.model.selectionRange.getLast().clone(); var arrFormula = []; var pasteRange = AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange; var activeCellsPasteFragment = typeof pasteRange === "string" ? AscCommonExcel.g_oRangeCache.getAscRange(pasteRange) : pasteRange; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteProps = specialPasteHelper.specialPasteProps; var countPasteRow = activeCellsPasteFragment.r2 - activeCellsPasteFragment.r1 + 1; var countPasteCol = activeCellsPasteFragment.c2 - activeCellsPasteFragment.c1 + 1; if(specialPasteProps && specialPasteProps.transpose) { countPasteRow = activeCellsPasteFragment.c2 - activeCellsPasteFragment.c1 + 1; countPasteCol = activeCellsPasteFragment.r2 - activeCellsPasteFragment.r1 + 1; } var rMax = countPasteRow + arn.r1; var cMax = countPasteCol + arn.c1; if (cMax > gc_nMaxCol0) { cMax = gc_nMaxCol0; } if (rMax > gc_nMaxRow0) { rMax = gc_nMaxRow0; } var isMultiple = false; var firstCell = t.model.getRange3(arn.r1, arn.c1, arn.r1, arn.c1); var isMergedFirstCell = firstCell.hasMerged(); var isOneMerge = false; var startCell = val.getCell3(activeCellsPasteFragment.r1, activeCellsPasteFragment.c1); var isMergedStartCell = startCell.hasMerged(); var firstValuesCol; var firstValuesRow; if (isMergedStartCell != null) { firstValuesCol = isMergedStartCell.c2 - isMergedStartCell.c1; firstValuesRow = isMergedStartCell.r2 - isMergedStartCell.r1; } else { firstValuesCol = 0; firstValuesRow = 0; } var rowDiff = arn.r1 - activeCellsPasteFragment.r1; var colDiff = arn.c1 - activeCellsPasteFragment.c1; var newPasteRange = new Asc.Range(arn.c1 - colDiff, arn.r1 - rowDiff, arn.c2 - colDiff, arn.r2 - rowDiff); //если вставляем в мерженную ячейку, диапазон которой больше или меньше, но не равен выделенной области if (isMergedFirstCell && isMergedFirstCell.isEqual(arn) && cMax - arn.c1 === (firstValuesCol + 1) && rMax - arn.r1 === (firstValuesRow + 1) && !newPasteRange.isEqual(activeCellsPasteFragment)) { isOneMerge = true; rMax = arn.r2 + 1; cMax = arn.c2 + 1; } else if (arn.c2 >= cMax - 1 && arn.r2 >= rMax - 1) { //если область кратная куску вставки var widthArea = arn.c2 - arn.c1 + 1; var heightArea = arn.r2 - arn.r1 + 1; var widthPasteFr = cMax - arn.c1; var heightPasteFr = rMax - arn.r1; //если кратны, то обрабатываем if (widthArea % widthPasteFr === 0 && heightArea % heightPasteFr === 0) { isMultiple = true; } else if (firstCell.hasMerged() !== null)//в противном случае ошибка { if (isCheckSelection) { return arn; } else { this.handlers.trigger("onError", c_oAscError.ID.PastInMergeAreaError, c_oAscError.Level.NoCritical); return; } } } else { //проверка на наличие части объединённой ячейки в области куда осуществляем вставку for (var rFirst = arn.r1; rFirst < rMax; ++rFirst) { for (var cFirst = arn.c1; cFirst < cMax; ++cFirst) { var range = t.model.getRange3(rFirst, cFirst, rFirst, cFirst); var merged = range.hasMerged(); if (merged) { if (merged.r1 < arn.r1 || merged.r2 > rMax - 1 || merged.c1 < arn.c1 || merged.c2 > cMax - 1) { //ошибка в случае если вставка происходит в часть объедененной ячейки if (isCheckSelection) { return arn; } else { this.handlers.trigger("onErrorEvent", c_oAscError.ID.PastInMergeAreaError, c_oAscError.Level.NoCritical); return; } } } } } } var rangeUnMerge = t.model.getRange3(arn.r1, arn.c1, rMax - 1, cMax - 1); var rMax2 = rMax; var cMax2 = cMax; //var rMax = values.length; if (isCheckSelection) { var newArr = arn.clone(true); newArr.r2 = rMax2 - 1; newArr.c2 = cMax2 - 1; if (isMultiple || isOneMerge) { newArr.r2 = arn.r2; newArr.c2 = arn.c2; } return newArr; } //если не возникает конфликт, делаем unmerge if(specialPasteProps.format) { rangeUnMerge.unmerge(); this.cellCommentator.deleteCommentsRange(rangeUnMerge.bbox); } if (!isOneMerge) { arn.r2 = rMax2 - 1; arn.c2 = cMax2 - 1; } if (isMultiple)//случай автозаполнения сложных форм { if(specialPasteProps.format) { t.model.getRange3(trueActiveRange.r1, trueActiveRange.c1, trueActiveRange.r2, trueActiveRange.c2).unmerge(); } var maxARow = heightArea / heightPasteFr; var maxACol = widthArea / widthPasteFr; var plRow = (rMax2 - arn.r1); var plCol = (arn.c2 - arn.c1) + 1; } else { var maxARow = 1; var maxACol = 1; var plRow = 0; var plCol = 0; trueActiveRange.r2 = arn.r2; trueActiveRange.c2 = arn.c2; } //необходимо проверить, пересекаемся ли мы с фоматированной таблицей //если да, то подхватывать dxf при вставке не нужно var intersectionAllRangeWithTables = t.model.autoFilters._intersectionRangeWithTableParts(trueActiveRange); var addComments = function(pasteRow, pasteCol, comments) { var comment; for (var i = 0; i < comments.length; i++) { comment = comments[i]; if (comment.nCol == pasteCol && comment.nRow == pasteRow) { var commentData = comment.clone(); //change nRow, nCol commentData.asc_putCol(nCol); commentData.asc_putRow(nRow); t.cellCommentator.addComment(commentData, true); } } }; var mergeArr = []; var checkMerge = function(range, curMerge, nRow, nCol, rowDiff, colDiff, pastedRangeProps) { var isMerged = false; for (var mergeCheck = 0; mergeCheck < mergeArr.length; ++mergeCheck) { if (mergeArr[mergeCheck].contains(nCol, nRow)) { isMerged = true; } } if (!isOneMerge) { if (curMerge != null && !isMerged) { var offsetCol = curMerge.c2 - curMerge.c1; if (offsetCol + nCol >= gc_nMaxCol0) { offsetCol = gc_nMaxCol0 - nCol; } var offsetRow = curMerge.r2 - curMerge.r1; if (offsetRow + nRow >= gc_nMaxRow0) { offsetRow = gc_nMaxRow0 - nRow; } pastedRangeProps.offsetLast = {offsetCol: offsetCol, offsetRow: offsetRow}; if(specialPasteProps.transpose) { mergeArr.push(new Asc.Range( curMerge.c1 + arn.c1 - activeCellsPasteFragment.r1 + colDiff, curMerge.r1 + arn.r1 - activeCellsPasteFragment.c1 + rowDiff, curMerge.c2 + arn.c1 - activeCellsPasteFragment.r1 + colDiff, curMerge.r2 + arn.r1 - activeCellsPasteFragment.c1 + rowDiff )); } else { mergeArr.push(new Asc.Range( curMerge.c1 + arn.c1 - activeCellsPasteFragment.c1 + colDiff, curMerge.r1 + arn.r1 - activeCellsPasteFragment.r1 + rowDiff, curMerge.c2 + arn.c1 - activeCellsPasteFragment.c1 + colDiff, curMerge.r2 + arn.r1 - activeCellsPasteFragment.r1 + rowDiff )); } } } else { if (!isMerged) { pastedRangeProps.offsetLast = {offsetCol: isMergedFirstCell.c2 - isMergedFirstCell.c1, offsetRow: isMergedFirstCell.r2 - isMergedFirstCell.r1}; mergeArr.push(new Asc.Range(isMergedFirstCell.c1, isMergedFirstCell.r1, isMergedFirstCell.c2, isMergedFirstCell.r2)); } } }; var getTableDxf = function (pasteRow, pasteCol, newVal) { var dxf = null; if(false !== intersectionAllRangeWithTables){ return {dxf: null}; } var tables = val.autoFilters._intersectionRangeWithTableParts(newVal.bbox); var blocalArea = true; if (tables && tables[0]) { var table = tables[0]; var styleInfo = table.TableStyleInfo; var styleForCurTable = styleInfo ? t.model.workbook.TableStyles.AllStyles[styleInfo.Name] : null; if (activeCellsPasteFragment.containsRange(table.Ref)) { blocalArea = false; } if (!styleForCurTable) { return null; } var headerRowCount = 1; var totalsRowCount = 0; if (null != table.HeaderRowCount) { headerRowCount = table.HeaderRowCount; } if (null != table.TotalsRowCount) { totalsRowCount = table.TotalsRowCount; } var bbox = new Asc.Range(table.Ref.c1, table.Ref.r1, table.Ref.c2, table.Ref.r2); styleForCurTable.initStyle(val.sheetMergedStyles, bbox, styleInfo, headerRowCount, totalsRowCount); val._getCell(pasteRow, pasteCol, function(cell) { if (cell) { dxf = cell.getCompiledStyle(); } if (null === dxf) { pasteRow = pasteRow - table.Ref.r1; pasteCol = pasteCol - table.Ref.c1; dxf = val.getCompiledStyle(pasteRow, pasteCol); } }); } return {dxf: dxf, blocalArea: blocalArea}; }; var colsWidth = {}; var putInsertedCellIntoRange = function(nRow, nCol, pasteRow, pasteCol, rowDiff, colDiff, range, newVal, curMerge, transposeRange) { var pastedRangeProps = {}; //range может далее изменится в связи с наличием мерженных ячеек, firstRange - не меняется(ему делаем setValue, как первой ячейке в диапазоне мерженных) var firstRange = range.clone(); //****paste comments**** if (specialPasteProps.comment && val.aComments && val.aComments.length) { addComments(pasteRow, pasteCol, val.aComments); } //merge checkMerge(range, curMerge, nRow, nCol, rowDiff, colDiff, pastedRangeProps); //set style if (!isOneMerge) { pastedRangeProps.cellStyle = newVal.getStyleName(); } if (!isOneMerge)//settings for cell(format) { //format var numFormat = newVal.getNumFormat(); var nameFormat; if (numFormat && numFormat.sFormat) { nameFormat = numFormat.sFormat; } pastedRangeProps.numFormat = nameFormat; } if (!isOneMerge)//settings for cell { var align = newVal.getAlign(); //vertical align pastedRangeProps.alignVertical = align.getAlignVertical(); //horizontal align pastedRangeProps.alignHorizontal = align.getAlignHorizontal(); //borders var fullBorders; if(specialPasteProps.transpose) { //TODO сделано для правильного отображения бордеров при транспонирования. возможно стоит использовать эту функцию во всех ситуациях. проверить! fullBorders = newVal.getBorder(newVal.bbox.r1, newVal.bbox.c1).clone(); } else { fullBorders = newVal.getBorderFull(); } if (pastedRangeProps.offsetLast && pastedRangeProps.offsetLast.offsetCol > 0 && curMerge && fullBorders) { //для мерженных ячеек, правая границу var endMergeCell = val.getCell3(pasteRow, curMerge.c2); var fullBordersEndMergeCell = endMergeCell.getBorderFull(); if (fullBordersEndMergeCell && fullBordersEndMergeCell.r) { fullBorders.r = fullBordersEndMergeCell.r; } } pastedRangeProps.bordersFull = fullBorders; //fill pastedRangeProps.fill = newVal.getFill(); //wrap //range.setWrap(newVal.getWrap()); pastedRangeProps.wrap = align.getWrap(); //angle pastedRangeProps.angle = align.getAngle(); //hyperlink pastedRangeProps.hyperlinkObj = newVal.getHyperlink(); } var tableDxf = getTableDxf(pasteRow, pasteCol, newVal); if(tableDxf && tableDxf.blocalArea) { pastedRangeProps.tableDxfLocal = tableDxf.dxf; } else if(tableDxf) { pastedRangeProps.tableDxf = tableDxf.dxf; } if(undefined === colsWidth[nCol]) { colsWidth[nCol] = val._getCol(pasteCol); } pastedRangeProps.colsWidth = colsWidth; //apply props by cell var formulaProps = {firstRange: firstRange, arrFormula: arrFormula, tablesMap: tablesMap, newVal: newVal, isOneMerge: isOneMerge, val: val, activeCellsPasteFragment: activeCellsPasteFragment, transposeRange: transposeRange}; t._setPastedDataByCurrentRange(range, pastedRangeProps, formulaProps, specialPasteProps); }; for (var autoR = 0; autoR < maxARow; ++autoR) { for (var autoC = 0; autoC < maxACol; ++autoC) { for (var r = 0; r < rMax - arn.r1; ++r) { for (var c = 0; c < cMax - arn.c1; ++c) { var pasteRow = r + activeCellsPasteFragment.r1; var pasteCol = c + activeCellsPasteFragment.c1; if(specialPasteProps.transpose) { pasteRow = c + activeCellsPasteFragment.r1; pasteCol = r + activeCellsPasteFragment.c1; } var newVal = val.getCell3(pasteRow, pasteCol); if (undefined !== newVal) { var nRow = r + autoR * plRow + arn.r1; var nCol = c + autoC * plCol + arn.c1; if (nRow > gc_nMaxRow0) { nRow = gc_nMaxRow0; } if (nCol > gc_nMaxCol0) { nCol = gc_nMaxCol0; } var curMerge = newVal.hasMerged(); if(curMerge && specialPasteProps.transpose) { curMerge = curMerge.clone(); var r1 = curMerge.r1; var r2 = curMerge.r2; var c1 = curMerge.c1; var c2 = curMerge.c2; curMerge.r1 = c1; curMerge.r2 = c2; curMerge.c1 = r1; curMerge.c2 = r2; } var range = t.model.getRange3(nRow, nCol, nRow, nCol); var transposeRange = null; if(specialPasteProps.transpose) { transposeRange = t.model.getRange3(c + autoR * plRow + arn.r1, r + autoC * plCol + arn.c1, c + autoR * plRow + arn.r1, r + autoC * plCol + arn.c1); } putInsertedCellIntoRange(nRow, nCol, pasteRow, pasteCol, autoR * plRow, autoC * plCol, range, newVal, curMerge, transposeRange); //если замержили range c = range.bbox.c2 - autoC * plCol - arn.c1; if (c === cMax) { r = range.bbox.r2 - autoC * plCol - arn.r1; } } } } } } t.isChanged = true; var arnFor = [trueActiveRange, arrFormula]; //TODO переделать на setSelection. закомментировал в связи с падением, когда вставляем ниже видимой зоны таблицы //this.setSelection(trueActiveRange); lastSelection.c2 = trueActiveRange.c2; lastSelection.r2 = trueActiveRange.r2; return arnFor; }; WorksheetView.prototype._setPastedDataByCurrentRange = function(range, rangeStyle, formulaProps, specialPasteProps) { var t = this; var firstRange, arrFormula, tablesMap, newVal, isOneMerge, val, activeCellsPasteFragment, transposeRange; if(formulaProps) { //TODO firstRange возможно стоит убрать(добавлено было для правки бага 27745) firstRange = formulaProps.firstRange; arrFormula = formulaProps.arrFormula; tablesMap = formulaProps.tablesMap; newVal = formulaProps.newVal; isOneMerge = formulaProps.isOneMerge; val = formulaProps.val; activeCellsPasteFragment = formulaProps.activeCellsPasteFragment; transposeRange = formulaProps.transposeRange; } var transposeOutStack = function(outStack) { for(var i = 0; i < outStack.length; i++) { if(outStack[i].bbox || "object" === typeof outStack[i].range) { var range = outStack[i].bbox ? outStack[i].bbox : outStack[i].range; var diffCol1 = range.c1 - activeCellsPasteFragment.c1; var diffRow1 = range.r1 - activeCellsPasteFragment.r1; var diffCol2 = range.c2 - activeCellsPasteFragment.c1; var diffRow2 = range.r2 - activeCellsPasteFragment.r1; range.c1 = activeCellsPasteFragment.c1 + diffRow1; range.r1 = activeCellsPasteFragment.r1 + diffCol1; range.c2 = activeCellsPasteFragment.c1 + diffRow2; range.r2 = activeCellsPasteFragment.r1 + diffCol2; } } }; //set formula - for paste from binary var calculateValueAndBinaryFormula = function(newVal, firstRange, range) { var skipFormat = null; var noSkipVal = null; var cellValueData = newVal.getValueData(); if(cellValueData && cellValueData.value) { if(!specialPasteProps.formula) { cellValueData.formula = null; } rangeStyle.cellValueData = cellValueData; } else if(cellValueData && cellValueData.formula && !specialPasteProps.formula) { cellValueData.formula = null; rangeStyle.cellValueData = cellValueData; } else { rangeStyle.val = newVal.getValue(); } var value2 = newVal.getValue2(); var isFromula = false; for (var nF = 0; nF < value2.length; nF++) { if (value2[nF] && value2[nF].sId) { isFromula = true; break; } else if (value2[nF] && value2[nF].format && value2[nF].format.getSkip()) { skipFormat = true; } else if (value2[nF] && value2[nF].format && !value2[nF].format.getSkip()) { noSkipVal = nF; } } //TODO вместо range где возможно использовать cell if (value2.length === 1 || isFromula !== false || (skipFormat != null && noSkipVal != null)) { var numStyle = 0; if (skipFormat != null && noSkipVal != null) { numStyle = noSkipVal; } //formula if (newVal.getFormula() && !isOneMerge) { var offset, callAdress; if(specialPasteProps.transpose && transposeRange) { //для transpose необходимо брать offset перевернутого range callAdress = new AscCommon.CellAddress(value2[0].sId); offset = new AscCommonExcel.CRangeOffset((transposeRange.bbox.c1 - callAdress.col + 1), (transposeRange.bbox.r1 - callAdress.row + 1)); } else { callAdress = new AscCommon.CellAddress(value2[0].sId); offset = new AscCommonExcel.CRangeOffset((range.bbox.c1 - callAdress.col + 1), (range.bbox.r1 - callAdress.row + 1)); } var assemb, _p_ = new AscCommonExcel.parserFormula(value2[0].sFormula, null, t.model); if (_p_.parse()) { if(specialPasteProps.transpose) { //для transpose необходимо перевернуть все дипазоны в формулах transposeOutStack(_p_.outStack); } if(null !== tablesMap) { var renameParams = {}; renameParams.offset = offset; renameParams.tableNameMap = tablesMap; _p_.renameSheetCopy(renameParams); assemb = _p_.assemble(true) } else { assemb = _p_.changeOffset(offset).assemble(true); } rangeStyle.formula = {range: range, val: "=" + assemb}; //arrFormula.push({range: range, val: "=" + assemb}); } } else { newVal.getLeftTopCellNoEmpty(function(cellFrom) { if (cellFrom) { var range; if (isOneMerge && range && range.bbox) { range = t._getCell(range.bbox.c1, range.bbox.r1); } else { range = firstRange; } rangeStyle.cellValueData2 = {valueData: cellFrom.getValueData(), row: range.bbox.r1, col: range.bbox.c1}; } }); } if (!isOneMerge)//settings for text { rangeStyle.font = value2[numStyle].format; //range.setFont(value2[numStyle].format); } } else { rangeStyle.value2 = value2; //firstRange.setValue2(value2); } }; //column width var col = range.bbox.c1; if(specialPasteProps.width && rangeStyle.colsWidth[col]) { var widthProp = rangeStyle.colsWidth[col]; t.model.setColWidth(widthProp.width, col, col); t.model.setColHidden(widthProp.hd, col, col); t.model.setColBestFit(widthProp.BestFit, widthProp.width, col, col); rangeStyle.colsWidth[col] = null; } //offsetLast if(rangeStyle.offsetLast && specialPasteProps.merge) { range.setOffsetLast(rangeStyle.offsetLast); range.merge(rangeStyle.merge); } //for formula if(formulaProps) { calculateValueAndBinaryFormula(newVal, firstRange, range); } //cellStyle if(rangeStyle.cellStyle && specialPasteProps.cellStyle) { //сделал для того, чтобы не перетерались старые бордеры бордерами стиля в случае, если специальная вставка без бордеров var oldBorders = null; if(!specialPasteProps.borders) { oldBorders = range.getBorderFull(); if(oldBorders) { oldBorders = oldBorders.clone(); } } range.setCellStyle(rangeStyle.cellStyle); if(oldBorders) { range.setBorder(null); range.setBorder(oldBorders); } } //если не вставляем форматированную таблицу, но формат необходимо вставить if(specialPasteProps.format && !specialPasteProps.formatTable && rangeStyle.tableDxf) { range.getLeftTopCell(function(firstCell){ if(firstCell) { firstCell.setStyle(rangeStyle.tableDxf); } }); } //numFormat if(rangeStyle.numFormat && specialPasteProps.numFormat) { range.setNumFormat(rangeStyle.numFormat); } //font if(rangeStyle.font && specialPasteProps.font) { var font = rangeStyle.font; //если вставляем форматированную таблицу с параметров values + all formating if(specialPasteProps.format && !specialPasteProps.formatTable && rangeStyle.tableDxf && rangeStyle.tableDxf.font) { font = rangeStyle.tableDxf.font.merge(rangeStyle.font); } range.setFont(font); } //***value*** if(rangeStyle.formula && specialPasteProps.formula) { arrFormula.push(rangeStyle.formula); } else if(rangeStyle.cellValueData2 && specialPasteProps.font && specialPasteProps.val) { t.model._getCell(rangeStyle.cellValueData2.row, rangeStyle.cellValueData2.col, function(cell){ cell.setValueData(rangeStyle.cellValueData2.valueData); }); } else if(rangeStyle.value2 && specialPasteProps.font && specialPasteProps.val) { if(formulaProps) { firstRange.setValue2(rangeStyle.value2); } else { range.setValue2(rangeStyle.value2); } } else if(rangeStyle.cellValueData && specialPasteProps.val) { range.setValueData(rangeStyle.cellValueData); } else if(rangeStyle.val && specialPasteProps.val) { range.setValue(rangeStyle.val); } //alignVertical if(undefined !== rangeStyle.alignVertical && specialPasteProps.alignVertical) { range.setAlignVertical(rangeStyle.alignVertical); } //alignHorizontal if(undefined !== rangeStyle.alignHorizontal && specialPasteProps.alignHorizontal) { range.setAlignHorizontal(rangeStyle.alignHorizontal); } //fontSize if(rangeStyle.fontSize && specialPasteProps.fontSize) { range.setFontsize(rangeStyle.fontSize); } //borders if(rangeStyle.borders && specialPasteProps.borders) { range.setBorderSrc(rangeStyle.borders); } //bordersFull if(rangeStyle.bordersFull && specialPasteProps.borders) { range.setBorder(rangeStyle.bordersFull); } //wrap if(rangeStyle.wrap && specialPasteProps.wrap) { range.setWrap(rangeStyle.wrap); } //fill if(specialPasteProps.fill && undefined !== rangeStyle.fill) { range.setFill(rangeStyle.fill); } //angle if(undefined !== rangeStyle.angle && specialPasteProps.angle) { range.setAngle(rangeStyle.angle); } if(rangeStyle.tableDxfLocal && specialPasteProps.format) { range.getLeftTopCell(function(firstCell) { if (firstCell) { firstCell.setStyle(rangeStyle.tableDxfLocal); } }); } //hyperLink if (rangeStyle.hyperLink && specialPasteProps.hyperlink) { var _link = rangeStyle.hyperLink.hyperLink; var newHyperlink = new AscCommonExcel.Hyperlink(); if (_link.search('#') === 0) { newHyperlink.setLocation(_link.replace('#', '')); } else { newHyperlink.Hyperlink = _link; } newHyperlink.Ref = range; newHyperlink.Tooltip = rangeStyle.hyperLink.toolTip; range.setHyperlink(newHyperlink); } else if (rangeStyle.hyperlinkObj && specialPasteProps.hyperlink) { rangeStyle.hyperlinkObj.Ref = range; range.setHyperlink(rangeStyle.hyperlinkObj, true); } }; WorksheetView.prototype.showSpecialPasteOptions = function(options/*, range, positionShapeContent*/) { var _clipboard = AscCommonExcel.g_clipboardExcel; var specialPasteShowOptions = window['AscCommon'].g_specialPasteHelper.buttonInfo; var positionShapeContent = options.position; var range = options.range; var props = options.options; var cellCoord; if(!positionShapeContent) { window['AscCommon'].g_specialPasteHelper.CleanButtonInfo(); window['AscCommon'].g_specialPasteHelper.buttonInfo.setRange(range); var isVisible = null !== this.getCellVisibleRange(range.c2, range.r2); cellCoord = this.getSpecialPasteCoords(range, isVisible); } else { //var isVisible = null !== this.getCellVisibleRange(range.c2, range.r2); cellCoord = [new AscCommon.asc_CRect( positionShapeContent.x, positionShapeContent.y, 0, 0 )]; } specialPasteShowOptions.asc_setOptions(props); specialPasteShowOptions.asc_setCellCoord(cellCoord); this.handlers.trigger("showSpecialPasteOptions", specialPasteShowOptions); }; WorksheetView.prototype.updateSpecialPasteButton = function() { var specialPasteShowOptions, range; var isIntoShape = this.objectRender.controller.getTargetDocContent(); if(window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton && isIntoShape) { if(window['AscCommon'].g_specialPasteHelper.buttonInfo.shapeId === isIntoShape.Id) { specialPasteShowOptions = window['AscCommon'].g_specialPasteHelper.buttonInfo; range = specialPasteShowOptions.range; specialPasteShowOptions.asc_setOptions(null); var curShape = isIntoShape.Parent.parent; var asc_getcvt = Asc.getCvtRatio; var mmToPx = asc_getcvt(3/*px*/, 0/*pt*/, this._getPPIX()); var ptToPx = asc_getcvt(1/*px*/, 0/*pt*/, this._getPPIX()); var cellsLeft = this.cellsLeft * ptToPx; var cellsTop = this.cellsTop * ptToPx; var cursorPos = range; var offsetX = this.cols[this.visibleRange.c1].left * ptToPx - cellsLeft; var offsetY = this.rows[this.visibleRange.r1].top * ptToPx - cellsTop; var posX = curShape.transformText.TransformPointX(cursorPos.X, cursorPos.Y) * mmToPx - offsetX + cellsLeft; var posY = curShape.transformText.TransformPointY(cursorPos.X, cursorPos.Y) * mmToPx - offsetY + cellsTop; cellCoord = [new AscCommon.asc_CRect( posX, posY, 0, 0 )]; specialPasteShowOptions.asc_setCellCoord(cellCoord); this.handlers.trigger("showSpecialPasteOptions", specialPasteShowOptions); } } else if(window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton) { specialPasteShowOptions = window['AscCommon'].g_specialPasteHelper.buttonInfo; specialPasteShowOptions.asc_setOptions(null); range = specialPasteShowOptions.range; var isVisible = null !== this.getCellVisibleRange(range.c2, range.r2); var cellCoord = this.getSpecialPasteCoords(range, isVisible); specialPasteShowOptions.asc_setCellCoord(cellCoord); this.handlers.trigger("showSpecialPasteOptions", specialPasteShowOptions); } }; WorksheetView.prototype.getSpecialPasteCoords = function(range, isVisible) { var disableCoords = function() { cellCoord._x = -1; cellCoord._y = -1; }; //TODO пересмотреть когда иконка вылезает за пределы области видимости var cellCoord = this.getCellCoord(range.c2, range.r2); if(window['AscCommon'].g_specialPasteHelper.buttonInfo.shapeId) { disableCoords(); cellCoord = [cellCoord]; } else { var visibleRange = this.getVisibleRange(); var intersectionVisibleRange = visibleRange.intersection(range); if(intersectionVisibleRange) { cellCoord = []; cellCoord[0] = this.getCellCoord(intersectionVisibleRange.c2, intersectionVisibleRange.r2); cellCoord[1] = this.getCellCoord(range.c1, range.r1); } else { disableCoords(); cellCoord = [cellCoord]; } } return cellCoord; }; // Залочена ли панель для закрепления WorksheetView.prototype._isLockedFrozenPane = function ( callback ) { var sheetId = this.model.getId(); var lockInfo = this.collaborativeEditing.getLockInfo( c_oAscLockTypeElem.Object, null, sheetId, AscCommonExcel.c_oAscLockNameFrozenPane ); if ( false === this.collaborativeEditing.getCollaborativeEditing() ) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование asc_applyFunction( callback, true ); callback = undefined; } if ( false !== this.collaborativeEditing.getLockIntersection( lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/false ) ) { // Редактируем сами asc_applyFunction( callback, true ); return; } else if ( false !== this.collaborativeEditing.getLockIntersection( lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false ) ) { // Уже ячейку кто-то редактирует asc_applyFunction( callback, false ); return; } this.collaborativeEditing.onStartCheckLock(); this.collaborativeEditing.addCheckLock( lockInfo ); this.collaborativeEditing.onEndCheckLock( callback ); }; WorksheetView.prototype._isLockedDefNames = function ( callback, defNameId ) { var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null /*c_oAscLockTypeElemSubType.DefinedNames*/, -1, defNameId); if ( false === this.collaborativeEditing.getCollaborativeEditing() ) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование asc_applyFunction( callback, true ); callback = undefined; } if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/ false)) { // Редактируем сами asc_applyFunction( callback, true ); return; } else if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже ячейку кто-то редактирует asc_applyFunction( callback, false ); return; } this.collaborativeEditing.onStartCheckLock(); this.collaborativeEditing.addCheckLock( lockInfo ); this.collaborativeEditing.onEndCheckLock( callback ); }; // Залочен ли весь лист WorksheetView.prototype._isLockedAll = function (callback) { var sheetId = this.model.getId(); var subType = c_oAscLockTypeElemSubType.ChangeProperties; var ar = this.model.selectionRange.getLast(); var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/subType, sheetId, new AscCommonExcel.asc_CCollaborativeRange(ar.c1, ar.r1, ar.c2, ar.r2)); if (false === this.collaborativeEditing.getCollaborativeEditing()) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование asc_applyFunction(callback, true); callback = undefined; } if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/ true)) { // Редактируем сами asc_applyFunction(callback, true); return; } else if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/ true)) { // Уже ячейку кто-то редактирует asc_applyFunction(callback, false); return; } this.collaborativeEditing.onStartCheckLock(); this.collaborativeEditing.addCheckLock(lockInfo); this.collaborativeEditing.onEndCheckLock(callback); }; // Пересчет для входящих ячеек в добавленные строки/столбцы WorksheetView.prototype._recalcRangeByInsertRowsAndColumns = function (sheetId, ar) { var isIntersection = false, isIntersectionC1 = true, isIntersectionC2 = true, isIntersectionR1 = true, isIntersectionR2 = true; do { if (isIntersectionC1 && this.collaborativeEditing.isIntersectionInCols(sheetId, ar.c1)) { ar.c1 += 1; } else { isIntersectionC1 = false; } if (isIntersectionR1 && this.collaborativeEditing.isIntersectionInRows(sheetId, ar.r1)) { ar.r1 += 1; } else { isIntersectionR1 = false; } if (isIntersectionC2 && this.collaborativeEditing.isIntersectionInCols(sheetId, ar.c2)) { ar.c2 -= 1; } else { isIntersectionC2 = false; } if (isIntersectionR2 && this.collaborativeEditing.isIntersectionInRows(sheetId, ar.r2)) { ar.r2 -= 1; } else { isIntersectionR2 = false; } if (ar.c1 > ar.c2 || ar.r1 > ar.r2) { isIntersection = true; break; } } while (isIntersectionC1 || isIntersectionC2 || isIntersectionR1 || isIntersectionR2) ; if (false === isIntersection) { ar.c1 = this.collaborativeEditing.getLockMeColumn(sheetId, ar.c1); ar.c2 = this.collaborativeEditing.getLockMeColumn(sheetId, ar.c2); ar.r1 = this.collaborativeEditing.getLockMeRow(sheetId, ar.r1); ar.r2 = this.collaborativeEditing.getLockMeRow(sheetId, ar.r2); } return isIntersection; }; // Функция проверки lock (возвращаемый результат нельзя использовать в качестве ответа, он нужен только для редактирования ячейки) WorksheetView.prototype._isLockedCells = function (range, subType, callback) { var sheetId = this.model.getId(); var isIntersection = false; var newCallback = callback; var t = this; this.collaborativeEditing.onStartCheckLock(); var isArrayRange = Array.isArray(range); var nLength = isArrayRange ? range.length : 1; var nIndex = 0; var ar = null; for (; nIndex < nLength; ++nIndex) { ar = isArrayRange ? range[nIndex].clone(true) : range.clone(true); if (c_oAscLockTypeElemSubType.InsertColumns !== subType && c_oAscLockTypeElemSubType.InsertRows !== subType) { // Пересчет для входящих ячеек в добавленные строки/столбцы isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, ar); } if (false === isIntersection) { var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/subType, sheetId, new AscCommonExcel.asc_CCollaborativeRange(ar.c1, ar.r1, ar.c2, ar.r2)); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже ячейку кто-то редактирует asc_applyFunction(callback, false); return false; } else { if (c_oAscLockTypeElemSubType.InsertColumns === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.addColsRange(sheetId, range.clone(true)); t.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1); } callback(isSuccess); }; } else if (c_oAscLockTypeElemSubType.InsertRows === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1); } callback(isSuccess); }; } else if (c_oAscLockTypeElemSubType.DeleteColumns === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1); } callback(isSuccess); }; } else if (c_oAscLockTypeElemSubType.DeleteRows === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1); } callback(isSuccess); }; } this.collaborativeEditing.addCheckLock(lockInfo); } } else { if (c_oAscLockTypeElemSubType.InsertColumns === subType) { t.collaborativeEditing.addColsRange(sheetId, range.clone(true)); t.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1); } else if (c_oAscLockTypeElemSubType.InsertRows === subType) { t.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1); } else if (c_oAscLockTypeElemSubType.DeleteColumns === subType) { t.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1); } else if (c_oAscLockTypeElemSubType.DeleteRows === subType) { t.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1); } } } if (false === this.collaborativeEditing.getCollaborativeEditing()) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование newCallback(true); newCallback = undefined; } this.collaborativeEditing.onEndCheckLock(newCallback); return true; }; WorksheetView.prototype.changeWorksheet = function (prop, val) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } var t = this; var arn = this.model.selectionRange.getLast().clone(); var checkRange = arn.getAllRange(); var range, count; var oRecalcType = AscCommonExcel.recalcType.recalc; var reinitRanges = false; var updateDrawingObjectsInfo = null; var updateDrawingObjectsInfo2 = null;//{bInsert: false, operType: c_oAscInsertOptions.InsertColumns, updateRange: arn} var isUpdateCols = false, isUpdateRows = false; var isCheckChangeAutoFilter; var functionModelAction = null; var lockDraw = false; // Параметр, при котором не будет отрисовки (т.к. мы просто обновляем информацию на неактивном листе) var lockRange, arrChangedRanges = []; var onChangeWorksheetCallback = function (isSuccess) { if (false === isSuccess) { return; } asc_applyFunction(functionModelAction); t._initCellsArea(oRecalcType); if (oRecalcType) { t.cache.reset(); } t._cleanCellsTextMetricsCache(); t._prepareCellTextMetricsCache(); arrChangedRanges = arrChangedRanges.concat(t.model.hiddenManager.getRecalcHidden()); t.cellCommentator.updateAreaComments(); if (t.objectRender) { if (reinitRanges && t.objectRender.drawingArea) { t.objectRender.drawingArea.reinitRanges(); } if (null !== updateDrawingObjectsInfo) { t.objectRender.updateSizeDrawingObjects(updateDrawingObjectsInfo); } if (null !== updateDrawingObjectsInfo2) { t.objectRender.updateDrawingObject(updateDrawingObjectsInfo2.bInsert, updateDrawingObjectsInfo2.operType, updateDrawingObjectsInfo2.updateRange); } t.model.onUpdateRanges(arrChangedRanges); t.objectRender.rebuildChartGraphicObjects(arrChangedRanges); } t.draw(lockDraw); t.handlers.trigger("reinitializeScroll"); if (isUpdateCols) { t._updateVisibleColsCount(); } if (isUpdateRows) { t._updateVisibleRowsCount(); } t.handlers.trigger("selectionChanged"); t.handlers.trigger("selectionMathInfoChanged", t.getSelectionMathInfo()); }; var checkLocalChange = function(val){ if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = val; } }; var checkDeleteCellsFilteringMode = function () { if (!window['AscCommonExcel'].filteringMode) { if (val === c_oAscDeleteOptions.DeleteCellsAndShiftLeft || val === c_oAscDeleteOptions.DeleteColumns) { //запрещаем в этом режиме удалять столбцы return false; } else if (val === c_oAscDeleteOptions.DeleteCellsAndShiftTop || val === c_oAscDeleteOptions.DeleteRows) { var tempRange = arn; if (val === c_oAscDeleteOptions.DeleteRows) { tempRange = new asc_Range(0, checkRange.r1, gc_nMaxCol0, checkRange.r2); } //запрещаем удалять последнюю строку фильтра и его заголовок + запрещаем удалять ф/т var autoFilter = t.model.AutoFilter; if (autoFilter && autoFilter.Ref) { var ref = autoFilter.Ref; //нельзя удалять целиком а/ф if (tempRange.containsRange(ref)) { return false; } else if (tempRange.containsRange(new asc_Range(ref.c1, ref.r1, ref.c2, ref.r1))) { //нельзя удалять первую строку а/ф return false; } /*else if (ref.r2 === ref.r1 + 1) { //нельзя удалять последнюю строку тела а/ф if (tempRange.containsRange(new asc_Range(ref.c1, ref.r1 + 1, ref.c2, ref.r1 + 1))) { return false; } }*/ } //нельзя целиком удалять ф/т var tableParts = t.model.TableParts; for (var i = 0; i < tableParts.length; i++) { if (tempRange.containsRange(tableParts[i].Ref)) { return false; } } } } return true; }; switch (prop) { case "colWidth": functionModelAction = function () { t.model.setColWidth(val, checkRange.c1, checkRange.c2); isUpdateCols = true; oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.ColumnResize, col: checkRange.c1}; }; this._isLockedAll(onChangeWorksheetCallback); break; case "showCols": functionModelAction = function () { checkLocalChange(true); t.model.setColHidden(false, arn.c1, arn.c2); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.ColumnResize, col: arn.c1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "hideCols": functionModelAction = function () { checkLocalChange(true); t.model.setColHidden(true, arn.c1, arn.c2); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.ColumnResize, col: arn.c1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "rowHeight": functionModelAction = function () { // Приводим к px (чтобы было ровно) val = val / 0.75; val = (val | val) * 0.75; // 0.75 - это размер 1px в pt (можно было 96/72) t.model.setRowHeight(Math.min(val, t.maxRowHeight), checkRange.r1, checkRange.r2, true); isUpdateRows = true; oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.RowResize, row: checkRange.r1}; }; return this._isLockedAll(onChangeWorksheetCallback); case "showRows": functionModelAction = function () { checkLocalChange(true); t.model.setRowHidden(false, arn.r1, arn.r2); t.model.autoFilters.reDrawFilter(arn); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.RowResize, row: arn.r1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "hideRows": functionModelAction = function () { checkLocalChange(true); t.model.setRowHidden(true, arn.r1, arn.r2); t.model.autoFilters.reDrawFilter(arn); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.RowResize, row: arn.r1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "insCell": if (!window['AscCommonExcel'].filteringMode) { if(val === c_oAscInsertOptions.InsertCellsAndShiftRight || val === c_oAscInsertOptions.InsertColumns){ return; } } range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); switch (val) { case c_oAscInsertOptions.InsertCellsAndShiftRight: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscInsertOptions.InsertCellsAndShiftRight, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (range.addCellsShiftRight()) { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.cellCommentator.updateCommentsDependencies(true, val, arn); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; } History.EndTransaction(); }; arrChangedRanges.push(lockRange = new asc_Range(arn.c1, arn.r1, gc_nMaxCol0, arn.r2)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscInsertOptions.InsertCellsAndShiftDown: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscInsertOptions.InsertCellsAndShiftDown, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (range.addCellsShiftBottom()) { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.cellCommentator.updateCommentsDependencies(true, val, arn); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; } History.EndTransaction(); }; arrChangedRanges.push(lockRange = new asc_Range(arn.c1, arn.r1, arn.c2, gc_nMaxRow0)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscInsertOptions.InsertColumns: isCheckChangeAutoFilter = t.model.autoFilters.isRangeIntersectionSeveralTableParts(arn); if (isCheckChangeAutoFilter === true) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); return; } lockRange = new asc_Range(arn.c1, 0, arn.c2, gc_nMaxRow0); count = arn.c2 - arn.c1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(count, 0))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.model.insertColsBefore(arn.c1, count); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; t.cellCommentator.updateCommentsDependencies(true, val, arn); History.EndTransaction(); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.InsertColumns, onChangeWorksheetCallback); break; case c_oAscInsertOptions.InsertRows: lockRange = new asc_Range(0, arn.r1, gc_nMaxCol0, arn.r2); count = arn.r2 - arn.r1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(0, count))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.model.insertRowsBefore(arn.r1, count); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; t.cellCommentator.updateCommentsDependencies(true, val, arn); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.InsertRows, onChangeWorksheetCallback); break; } break; case "delCell": if (!checkDeleteCellsFilteringMode()) { return; } range = t.model.getRange3(checkRange.r1, checkRange.c1, checkRange.r2, checkRange.c2); switch (val) { case c_oAscDeleteOptions.DeleteCellsAndShiftLeft: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscDeleteOptions.DeleteCellsAndShiftLeft, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (isCheckChangeAutoFilter === true) { t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteCellsAndShiftLeft); } if (range.deleteCellsShiftLeft(function () { t._cleanCache(lockRange); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); })) { updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; } History.EndTransaction(); reinitRanges = true; }; arrChangedRanges.push( lockRange = new asc_Range(checkRange.c1, checkRange.r1, gc_nMaxCol0, checkRange.r2)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscDeleteOptions.DeleteCellsAndShiftTop: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscDeleteOptions.DeleteCellsAndShiftTop, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (isCheckChangeAutoFilter === true) { t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteCellsAndShiftTop); } if (range.deleteCellsShiftUp(function () { t._cleanCache(lockRange); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); })) { updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; } History.EndTransaction(); reinitRanges = true; }; arrChangedRanges.push( lockRange = new asc_Range(checkRange.c1, checkRange.r1, checkRange.c2, gc_nMaxRow0)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscDeleteOptions.DeleteColumns: isCheckChangeAutoFilter = t.model.autoFilters.isActiveCellsCrossHalfFTable(checkRange, c_oAscDeleteOptions.DeleteColumns, prop); if (isCheckChangeAutoFilter === false) { return; } lockRange = new asc_Range(checkRange.c1, 0, checkRange.c2, gc_nMaxRow0); count = checkRange.c2 - checkRange.c1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(-count, 0))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; History.Create_NewPoint(); History.StartTransaction(); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteColumns); t.model.removeCols(checkRange.c1, checkRange.c2); updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; History.EndTransaction(); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.DeleteColumns, onChangeWorksheetCallback); break; case c_oAscDeleteOptions.DeleteRows: isCheckChangeAutoFilter = t.model.autoFilters.isActiveCellsCrossHalfFTable(checkRange, c_oAscDeleteOptions.DeleteRows, prop); if (isCheckChangeAutoFilter === false) { return; } lockRange = new asc_Range(0, checkRange.r1, gc_nMaxCol0, checkRange.r2); count = checkRange.r2 - checkRange.r1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(0, -count))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; History.Create_NewPoint(); History.StartTransaction(); checkRange = t.model.autoFilters.checkDeleteAllRowsFormatTable(checkRange, true); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteRows); t.model.removeRows(checkRange.r1, checkRange.r2); updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; History.EndTransaction(); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.DeleteRows, onChangeWorksheetCallback); break; } this.handlers.trigger("selectionNameChanged", t.getSelectionName(/*bRangeText*/false)); break; case "sheetViewSettings": functionModelAction = function () { if (AscCH.historyitem_Worksheet_SetDisplayGridlines === val.type) { t.model.setDisplayGridlines(val.value); } else { t.model.setDisplayHeadings(val.value); } isUpdateCols = true; isUpdateRows = true; oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; }; this._isLockedAll(onChangeWorksheetCallback); break; case "update": if (val !== undefined) { lockDraw = true === val.lockDraw; reinitRanges = !!val.reinitRanges; } onChangeWorksheetCallback(true); break; } }; WorksheetView.prototype.expandColsOnScroll = function (isNotActive, updateColsCount, newColsCount) { var maxColObjects = this.objectRender ? this.objectRender.getMaxColRow().col : -1; var maxc = Math.max(this.model.getColsCount() + 1, this.cols.length, maxColObjects); if (newColsCount) { maxc = Math.max(maxc, newColsCount); } // Сохраняем старое значение var nLastCols = this.nColsCount; if (isNotActive) { this.nColsCount = maxc + 1; } else if (updateColsCount) { this.nColsCount = maxc; if (this.cols.length < this.nColsCount) { nLastCols = this.cols.length; } } // Проверяем ограничения по столбцам if (gc_nMaxCol < this.nColsCount) { this.nColsCount = gc_nMaxCol; } this._calcWidthColumns(AscCommonExcel.recalcType.newLines); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } return nLastCols !== this.nColsCount; }; WorksheetView.prototype.expandRowsOnScroll = function (isNotActive, updateRowsCount, newRowsCount) { var maxRowObjects = this.objectRender ? this.objectRender.getMaxColRow().row : -1; var maxr = Math.max(this.model.getRowsCount() + 1, this.rows.length, maxRowObjects); if (newRowsCount) { maxr = Math.max(maxr, newRowsCount); } // Сохраняем старое значение var nLastRows = this.nRowsCount; if (isNotActive) { this.nRowsCount = maxr + 1; } else if (updateRowsCount) { this.nRowsCount = maxr; if (this.rows.length < this.nRowsCount) { nLastRows = this.rows.length; } } // Проверяем ограничения по строкам if (gc_nMaxRow < this.nRowsCount) { this.nRowsCount = gc_nMaxRow; } this._calcHeightRows(AscCommonExcel.recalcType.newLines); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } return nLastRows !== this.nRowsCount; }; WorksheetView.prototype.onChangeWidthCallback = function (col, r1, r2, onlyIfMore) { var width = null; var row, ct, c, fl, str, maxW, tm, mc, isMerged, oldWidth, oldColWidth; var lastHeight = null; var filterButton = null; if (null == r1) { r1 = 0; } if (null == r2) { r2 = this.rows.length - 1; } oldColWidth = this.cols[col].charCount; this.cols[col].isCustomWidth = false; for (row = r1; row <= r2; ++row) { // пересчет метрик текста this._addCellTextToCache(col, row, /*canChangeColWidth*/c_oAscCanChangeColWidth.all); ct = this._getCellTextCache(col, row); if (ct === undefined) { continue; } fl = ct.flags; isMerged = fl.isMerged(); if (isMerged) { mc = fl.merged; // Для замерженных ячеек (с 2-мя или более колонками) оптимизировать не нужно if (mc.c1 !== mc.c2) { continue; } } if (ct.metrics.height > this.maxRowHeight) { if (isMerged) { continue; } // Запоминаем старую ширину (в случае, если у нас по высоте не уберется) oldWidth = ct.metrics.width; lastHeight = null; // вычисление новой ширины столбца, чтобы высота текста была меньше maxRowHeight c = this._getCell(col, row); str = c.getValue2(); maxW = ct.metrics.width + this.maxDigitWidth; while (1) { tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, maxW)); if (tm.height <= this.maxRowHeight) { break; } if (lastHeight === tm.height) { // Ситуация, когда у нас текст не уберется по высоте (http://bugzilla.onlyoffice.com/show_bug.cgi?id=19974) tm.width = oldWidth; break; } lastHeight = tm.height; maxW += this.maxDigitWidth; } width = Math.max(width, tm.width); } else { filterButton = this.af_getSizeButton(col, row); if (null !== filterButton && CellValueType.String === ct.cellType) { width = Math.max(width, ct.metrics.width + filterButton.width); } else { width = Math.max(width, ct.metrics.width); } } } var pad, cc, cw; if (width > 0) { pad = this.width_padding * 2 + this.width_1px; cc = Math.min(this.model.colWidthToCharCount(width + pad), Asc.c_oAscMaxColumnWidth); } else { cc = this.defaultColWidthChars; } cw = this.model.charCountToModelColWidth(cc); if (cc === oldColWidth || (onlyIfMore && cc < oldColWidth)) { return -1; } History.Create_NewPoint(); if (!onlyIfMore) { var oSelection = History.GetSelection(); if (null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(col, 0, col, gc_nMaxRow0); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } } History.StartTransaction(); // Выставляем, что это bestFit this.model.setColBestFit(true, cw, col, col); History.EndTransaction(); return oldColWidth !== cc ? cw : -1; }; WorksheetView.prototype.autoFitColumnWidth = function (col1, col2) { var t = this; return this._isLockedAll(function (isSuccess) { if (false === isSuccess) { return; } if (null === col1) { var lastSelection = t.model.selectionRange.getLast(); col1 = lastSelection.c1; col2 = lastSelection.c2; } var w, bUpdate = false; History.Create_NewPoint(); History.StartTransaction(); for (var c = col1; c <= col2; ++c) { w = t.onChangeWidthCallback(c, null, null); if (-1 !== w) { t.cols[c] = t._calcColWidth(w); t.cols[c].isCustomWidth = false; bUpdate = true; t._cleanCache(new asc_Range(c, 0, c, t.rows.length - 1)); } } if (bUpdate) { t._updateColumnPositions(); t._updateVisibleColsCount(); t._calcHeightRows(AscCommonExcel.recalcType.recalc); t._updateVisibleRowsCount(); t.objectRender.drawingArea.reinitRanges(); t.changeWorksheet("update"); } History.EndTransaction(); }); }; WorksheetView.prototype.autoFitRowHeight = function (row1, row2) { var t = this; var onChangeHeightCallback = function (isSuccess) { if (false === isSuccess) { return; } if (null === row1) { var lastSelection = t.model.selectionRange.getLast(); row1 = lastSelection.r1; row2 = lastSelection.r2; } History.Create_NewPoint(); var oSelection = History.GetSelection(); if (null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(0, row1, gc_nMaxCol0, row2); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } History.StartTransaction(); var height, col, ct, mc; for (var r = row1; r <= row2; ++r) { height = t.defaultRowHeight; for (col = 0; col < t.cols.length; ++col) { ct = t._getCellTextCache(col, r); if (ct === undefined) { continue; } if (ct.flags.isMerged()) { mc = ct.flags.merged; // Для замерженных ячеек (с 2-мя или более строками) оптимизировать не нужно if (mc.r1 !== mc.r2) { continue; } } height = Math.max(height, ct.metrics.height + t.height_1px); } t.model.setRowBestFit(true, Math.min(height, t.maxRowHeight), r, r); } t.nRowsCount = 0; t._calcHeightRows(AscCommonExcel.recalcType.recalc); t._updateVisibleRowsCount(); t._cleanCache(new asc_Range(0, row1, t.cols.length - 1, row2)); t.objectRender.drawingArea.reinitRanges(); t.changeWorksheet("update"); History.EndTransaction(); }; return this._isLockedAll(onChangeHeightCallback); }; // ----- Search ----- WorksheetView.prototype._isCellEqual = function (c, r, options) { var cell, cellText; // Не пользуемся RegExp, чтобы не возиться со спец.символами var mc = this.model.getMergedByCell(r, c); cell = mc ? this._getVisibleCell(mc.c1, mc.r1) : this._getVisibleCell(c, r); cellText = (options.lookIn === Asc.c_oAscFindLookIn.Formulas) ? cell.getValueForEdit() : cell.getValue(); if (true !== options.isMatchCase) { cellText = cellText.toLowerCase(); } if ((cellText.indexOf(options.findWhat) >= 0) && (true !== options.isWholeCell || options.findWhat.length === cellText.length)) { return (mc ? new asc_Range(mc.c1, mc.r1, mc.c1, mc.r1) : new asc_Range(c, r, c, r)); } return null; }; WorksheetView.prototype.findCellText = function (options) { var self = this; if (true !== options.isMatchCase) { options.findWhat = options.findWhat.toLowerCase(); } var selectionRange = options.selectionRange || this.model.selectionRange; var lastRange = selectionRange.getLast(); var ar = selectionRange.activeCell; var c = ar.col; var r = ar.row; var merge = this.model.getMergedByCell(r, c); options.findInSelection = options.scanOnOnlySheet && !(selectionRange.isSingleRange() && (lastRange.isOneCell() || lastRange.isEqual(merge))); var minC, minR, maxC, maxR; if (options.findInSelection) { minC = lastRange.c1; minR = lastRange.r1; maxC = lastRange.c2; maxR = lastRange.r2; } else { minC = 0; minR = 0; maxC = this.cols.length - 1; maxR = this.rows.length - 1; } var inc = options.scanForward ? +1 : -1; var isEqual; function findNextCell() { var ct = undefined; do { if (options.scanByRows) { c += inc; if (c < minC || c > maxC) { c = options.scanForward ? minC : maxC; r += inc; } } else { r += inc; if (r < minR || r > maxR) { r = options.scanForward ? minR : maxR; c += inc; } } if (c < minC || c > maxC || r < minR || r > maxR) { return undefined; } self.model._getCellNoEmpty(r, c, function(cell){ if (cell && !cell.isNullTextString()) { ct = true; } }); } while (!ct); return ct; } while (findNextCell()) { isEqual = this._isCellEqual(c, r, options); if (null !== isEqual) { return isEqual; } } // Продолжаем циклический поиск if (options.scanForward) { // Идем вперед с первой ячейки if (options.scanByRows) { c = minC - 1; r = minR; maxR = ar.row; } else { c = minC; r = minR - 1; maxC = ar.col; } } else { // Идем назад с последней c = maxC; r = maxR; if (options.scanByRows) { c = maxC + 1; r = maxR; minR = ar.row; } else { c = maxC; r = maxR + 1; minC = ar.col; } } while (findNextCell()) { isEqual = this._isCellEqual(c, r, options); if (null !== isEqual) { return isEqual; } } return null; }; WorksheetView.prototype.replaceCellText = function (options, lockDraw, callback) { if (!options.isMatchCase) { options.findWhat = options.findWhat.toLowerCase(); } // Очищаем результаты options.countFind = 0; options.countReplace = 0; var t = this; var activeCell; var aReplaceCells = []; if (options.isReplaceAll) { var selectionRange = this.model.selectionRange.clone(); activeCell = selectionRange.activeCell; var aReplaceCellsIndex = {}; options.selectionRange = selectionRange; var findResult, index; while (true) { findResult = t.findCellText(options); if (null === findResult) { break; } index = findResult.c1 + '-' + findResult.r1; if (aReplaceCellsIndex[index]) { break; } aReplaceCellsIndex[index] = true; aReplaceCells.push(findResult); activeCell.col = findResult.c1; activeCell.row = findResult.r1; } } else { activeCell = this.model.selectionRange.activeCell; // Попробуем сначала найти var isEqual = this._isCellEqual(activeCell.col, activeCell.row, options); if (isEqual) { aReplaceCells.push(isEqual); } } if (0 > aReplaceCells.length) { return callback(options); } return this._replaceCellsText(aReplaceCells, options, lockDraw, callback); }; WorksheetView.prototype._replaceCellsText = function (aReplaceCells, options, lockDraw, callback) { var t = this; if (this.model.inPivotTable(aReplaceCells)) { options.error = true; return callback(options); } var findFlags = "g"; // Заменяем все вхождения if (true !== options.isMatchCase) { findFlags += "i"; } // Не чувствителен к регистру var valueForSearching = options.findWhat .replace(/(\\)/g, "\\\\").replace(/(\^)/g, "\\^") .replace(/(\()/g, "\\(").replace(/(\))/g, "\\)") .replace(/(\+)/g, "\\+").replace(/(\[)/g, "\\[") .replace(/(\])/g, "\\]").replace(/(\{)/g, "\\{") .replace(/(\})/g, "\\}").replace(/(\$)/g, "\\$") .replace(/(\.)/g, "\\.") .replace(/(~)?\*/g, function ($0, $1) { return $1 ? $0 : '(.*)'; }) .replace(/(~)?\?/g, function ($0, $1) { return $1 ? $0 : '.'; }) .replace(/(~\*)/g, "\\*").replace(/(~\?)/g, "\\?"); valueForSearching = new RegExp(valueForSearching, findFlags); options.indexInArray = 0; options.countFind = aReplaceCells.length; options.countReplace = 0; if (options.isReplaceAll && false === this.collaborativeEditing.getCollaborativeEditing()) { this._isLockedCells(aReplaceCells, /*subType*/null, function () { t._replaceCellText(aReplaceCells, valueForSearching, options, lockDraw, callback, true); }); } else { this._replaceCellText(aReplaceCells, valueForSearching, options, lockDraw, callback, false); } }; WorksheetView.prototype._replaceCellText = function (aReplaceCells, valueForSearching, options, lockDraw, callback, oneUser) { var t = this; if (options.indexInArray >= aReplaceCells.length) { this.draw(lockDraw); return callback(options); } var onReplaceCallback = function (isSuccess) { var cell = aReplaceCells[options.indexInArray]; ++options.indexInArray; if (false !== isSuccess) { ++options.countReplace; var c = t._getVisibleCell(cell.c1, cell.r1); var cellValue = c.getValueForEdit(); cellValue = cellValue.replace(valueForSearching, options.replaceWith); var oCellEdit = new asc_Range(cell.c1, cell.r1, cell.c1, cell.r1); var v, newValue; // get first fragment and change its text v = c.getValueForEdit2().slice(0, 1); // Создаем новый массив, т.к. getValueForEdit2 возвращает ссылку newValue = []; newValue[0] = new AscCommonExcel.Fragment({text: cellValue, format: v[0].format.clone()}); if (!t._saveCellValueAfterEdit(oCellEdit, c, newValue, /*flags*/undefined, /*isNotHistory*/true, /*lockDraw*/true)) { options.error = true; t.draw(lockDraw); return callback(options); } } window.setTimeout(function () { t._replaceCellText(aReplaceCells, valueForSearching, options, lockDraw, callback, oneUser); }, 1); }; return oneUser ? onReplaceCallback(true) : this._isLockedCells(aReplaceCells[options.indexInArray], /*subType*/null, onReplaceCallback); }; WorksheetView.prototype.findCell = function (reference, isViewMode) { var mc, ranges = AscCommonExcel.getRangeByRef(reference, this.model, true); if (0 === ranges.length && !isViewMode) { /*TODO: сделать поиск по названиям автофигур, должен искать до того как вызвать поиск по именованным диапазонам*/ if (this.collaborativeEditing.getGlobalLock() || !this.handlers.trigger("getLockDefNameManagerStatus")) { this.handlers.trigger("onErrorEvent", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); this._updateSelectionNameAndInfo(); return true; } // ToDo multiselect defined names var selectionLast = this.model.selectionRange.getLast(); mc = selectionLast.isOneCell() ? this.model.getMergedByCell(selectionLast.r1, selectionLast.c1) : null; var defName = this.model.workbook.editDefinesNames(null, new Asc.asc_CDefName(reference, parserHelp.get3DRef(this.model.getName(), (mc || selectionLast).getAbsName()))); if (defName) { this._isLockedDefNames(null, defName.getNodeId()); } else { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.InvalidReferenceOrName, c_oAscError.Level.NoCritical); } } return ranges; }; /* Ищет дополнение для ячейки */ WorksheetView.prototype.getCellAutoCompleteValues = function (cell, maxCount) { var merged = this._getVisibleCell(cell.col, cell.row).hasMerged(); if (merged) { cell = new AscCommon.CellBase(merged.r1, merged.c1); } var arrValues = [], objValues = {}; var range = this.findCellAutoComplete(cell, 1, maxCount); this.getColValues(range, cell.col, arrValues, objValues); range = this.findCellAutoComplete(cell, -1, maxCount); this.getColValues(range, cell.col, arrValues, objValues); arrValues.sort(); return arrValues; }; /* Ищет дополнение для ячейки (снизу или сверху) */ WorksheetView.prototype.findCellAutoComplete = function (cellActive, step, maxCount) { var col = cellActive.col, row = cellActive.row; row += step; if (!maxCount) { maxCount = Number.MAX_VALUE; } var count = 0, isBreak = false, end = 0 < step ? this.model.getRowsCount() - 1 : 0, isEnd = true, colsCount = this.model.getColsCount(), range = new asc_Range(col, row, col, row); for (; row * step <= end && count < maxCount; row += step, isEnd = true, ++count) { for (col = range.c1; col <= range.c2; ++col) { this.model._getCellNoEmpty(row, col, function(cell) { if (cell && false === cell.isNullText()) { isEnd = false; isBreak = true; } }); if (isBreak) { isBreak = false; break; } } // Идем влево по колонкам for (col = range.c1 - 1; col >= 0; --col) { this.model._getCellNoEmpty(row, col, function(cell) { isBreak = (null === cell || cell.isNullText()); }); if (isBreak) { isBreak = false; break; } isEnd = false; } range.c1 = col + 1; // Идем вправо по колонкам for (col = range.c2 + 1; col < colsCount; ++col) { this.model._getCellNoEmpty(row, col, function(cell) { isBreak = (null === cell || cell.isNullText()); }); if (isBreak) { isBreak = false; break; } isEnd = false; } range.c2 = col - 1; if (isEnd) { break; } } if (0 < step) { range.r2 = row - 1; } else { range.r1 = row + 1; } return range.r1 <= range.r2 ? range : null; }; /* Формирует уникальный массив */ WorksheetView.prototype.getColValues = function (range, col, arrValues, objValues) { if (null === range) { return; } var row, value, valueLowCase; for (row = range.r1; row <= range.r2; ++row) { this.model._getCellNoEmpty(row, col, function(cell) { if (cell && CellValueType.String === cell.getType()) { value = cell.getValue(); valueLowCase = value.toLowerCase(); if (!objValues.hasOwnProperty(valueLowCase)) { arrValues.push(value); objValues[valueLowCase] = 1; } } }); } }; // ----- Cell Editor ----- WorksheetView.prototype.setCellEditMode = function ( isCellEditMode ) { this.isCellEditMode = isCellEditMode; }; WorksheetView.prototype.setFormulaEditMode = function ( isFormulaEditMode ) { this.isFormulaEditMode = isFormulaEditMode; }; WorksheetView.prototype.setSelectionDialogMode = function (selectionDialogType, selectRange) { if (selectionDialogType === this.selectionDialogType) { return; } var oldSelectionDialogType = this.selectionDialogType; this.selectionDialogType = selectionDialogType; this.isSelectionDialogMode = c_oAscSelectionDialogType.None !== this.selectionDialogType; this.cleanSelection(); if (false === this.isSelectionDialogMode) { if (null !== this.copyActiveRange) { this.model.selectionRange = this.copyActiveRange.clone(); } this.copyActiveRange = null; if (oldSelectionDialogType === c_oAscSelectionDialogType.Chart) { this.objectRender.controller.checkChartForProps(false); } } else { this.copyActiveRange = this.model.selectionRange.clone(); if (selectRange) { if (typeof selectRange === 'string') { selectRange = this.model.getRange2(selectRange); if (selectRange) { selectRange = selectRange.getBBox0(); } } if (null != selectRange) { this.model.selectionRange.assign2(selectRange); } } if (selectionDialogType === c_oAscSelectionDialogType.Chart) { this.objectRender.controller.checkChartForProps(true); } } this._drawSelection(); }; // Получаем свойство: редактируем мы сейчас или нет WorksheetView.prototype.getCellEditMode = function () { return this.isCellEditMode; }; WorksheetView.prototype._isFormula = function ( val ) { return (0 < val.length && 1 < val[0].text.length && '=' === val[0].text.charAt( 0 )); }; WorksheetView.prototype.getActiveCell = function (x, y, isCoord) { var t = this; var col, row; if (isCoord) { x *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIY()); col = t._findColUnderCursor(x, true); row = t._findRowUnderCursor(y, true); if (!col || !row) { return false; } col = col.col; row = row.row; } else { col = t.model.selectionRange.activeCell.col; row = t.model.selectionRange.activeCell.row; } // Проверим замерженность var mergedRange = this.model.getMergedByCell(row, col); return mergedRange ? mergedRange : new asc_Range(col, row, col, row); }; WorksheetView.prototype._saveCellValueAfterEdit = function (oCellEdit, c, val, flags, isNotHistory, lockDraw) { var t = this; var oldMode = this.isFormulaEditMode; this.isFormulaEditMode = false; if (!isNotHistory) { History.Create_NewPoint(); History.StartTransaction(); } var oAutoExpansionTable; var isFormula = this._isFormula(val); if (isFormula) { var ftext = val.reduce(function (pv, cv) { return pv + cv.text; }, ""); var ret = true; // ToDo - при вводе формулы в заголовок автофильтра надо писать "0" c.setValue(ftext, function (r) { ret = r; }); if (!ret) { this.isFormulaEditMode = oldMode; History.EndTransaction(); return false; } isFormula = c.isFormula(); this.model.autoFilters.renameTableColumn(oCellEdit); } else { c.setValue2(val); // Вызываем функцию пересчета для заголовков форматированной таблицы this.model.autoFilters.renameTableColumn(oCellEdit); var api = window["Asc"]["editor"]; var bFast = api.collaborativeEditing.m_bFast; var bIsSingleUser = !api.collaborativeEditing.getCollaborativeEditing(); if (!(bFast && !bIsSingleUser)) { oAutoExpansionTable = this.model.autoFilters.checkTableAutoExpansion(oCellEdit); } } if (!isFormula) { for (var i = 0; i < val.length; ++i) { if (-1 !== val[i].text.indexOf(kNewLine)) { c.setWrap(true); break; } } } this._updateCellsRange(oCellEdit, isNotHistory ? c_oAscCanChangeColWidth.none : c_oAscCanChangeColWidth.numbers, lockDraw); if (!isNotHistory) { History.EndTransaction(); } if (oAutoExpansionTable) { var callback = function () { var options = { props: [Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion], cell: oCellEdit, wsId: t.model.getId() }; t.handlers.trigger("toggleAutoCorrectOptions", true, options); }; t.af_changeTableRange(oAutoExpansionTable.name, oAutoExpansionTable.range, callback); } else { t.handlers.trigger("toggleAutoCorrectOptions"); } // если вернуть false, то редактор не закроется return true; }; WorksheetView.prototype.openCellEditor = function (editor, fragments, cursorPos, isFocus, isClearCell, isHideCursor, isQuickInput, selectionRange) { var t = this, tc = this.cols, tr = this.rows, col, row, c, fl, mc, bg, isMerged; if (selectionRange) { this.model.selectionRange = selectionRange; } if (0 < this.arrActiveFormulaRanges.length) { this.cleanSelection(); this.cleanFormulaRanges(); this._drawSelection(); } var cell = this.model.selectionRange.activeCell; function getVisibleRangeObject() { var vr = t.visibleRange.clone(), offsetX = 0, offsetY = 0; if (t.topLeftFrozenCell) { var cFrozen = t.topLeftFrozenCell.getCol0(); var rFrozen = t.topLeftFrozenCell.getRow0(); if (0 < cFrozen) { if (col >= cFrozen) { offsetX = tc[cFrozen].left - tc[0].left; } else { vr.c1 = 0; vr.c2 = cFrozen - 1; } } if (0 < rFrozen) { if (row >= rFrozen) { offsetY = tr[rFrozen].top - tr[0].top; } else { vr.r1 = 0; vr.r2 = rFrozen - 1; } } } return {vr: vr, offsetX: offsetX, offsetY: offsetY}; } col = cell.col; row = cell.row; // Возможно стоит заменить на ячейку из кеша c = this._getVisibleCell(col, row); fl = this._getCellFlags(c); isMerged = fl.isMerged(); if (isMerged) { mc = fl.merged; c = this._getVisibleCell(mc.c1, mc.r1); fl = this._getCellFlags(c); } // Выставляем режим 'не редактируем' (иначе мы попытаемся переместить редактор, который еще не открыт) this.isCellEditMode = false; this.handlers.trigger("onScroll", this._calcActiveCellOffset()); this.isCellEditMode = true; bg = c.getFill(); this.isFormulaEditMode = false; var font = c.getFont(); // Скрываем окно редактирования комментария this.model.workbook.handlers.trigger("asc_onHideComment"); if (fragments === undefined) { var _fragmentsTmp = c.getValueForEdit2(); fragments = []; for (var i = 0; i < _fragmentsTmp.length; ++i) { fragments.push(_fragmentsTmp[i].clone()); } } var arrAutoComplete = this.getCellAutoCompleteValues(cell, kMaxAutoCompleteCellEdit); var arrAutoCompleteLC = asc.arrayToLowerCase(arrAutoComplete); editor.open({ fragments: fragments, flags: fl, font: new asc.FontProperties(font.getName(), font.getSize()), background: bg || this.settings.cells.defaultState.background, textColor: font.getColor(), cursorPos: cursorPos, zoom: this.getZoom(), focus: isFocus, isClearCell: isClearCell, isHideCursor: isHideCursor, isQuickInput: isQuickInput, isAddPersentFormat: isQuickInput && Asc.c_oAscNumFormatType.Percent === c.getNumFormatType(), autoComplete: arrAutoComplete, autoCompleteLC: arrAutoCompleteLC, cellName: c.getName(), cellNumFormat: c.getNumFormatType(), saveValueCallback: function (val, flags) { var oCellEdit = isMerged ? new asc_Range(mc.c1, mc.r1, mc.c1, mc.r1) : new asc_Range(col, row, col, row); return t._saveCellValueAfterEdit(oCellEdit, c, val, flags, /*isNotHistory*/false, /*lockDraw*/false); }, getSides: function () { var _c1, _r1, _c2, _r2, ri = 0, bi = 0; if (isMerged) { _c1 = mc.c1; _c2 = mc.c2; _r1 = mc.r1; _r2 = mc.r2; } else { _c1 = _c2 = col; _r1 = _r2 = row; } var vro = getVisibleRangeObject(); var i, w, h, arrLeftS = [], arrRightS = [], arrBottomS = []; var offsX = tc[vro.vr.c1].left - tc[0].left - vro.offsetX; var offsY = tr[vro.vr.r1].top - tr[0].top - vro.offsetY; var cellX = tc[_c1].left - offsX, cellY = tr[_r1].top - offsY; for (i = _c1; i >= vro.vr.c1; --i) { if (t.width_1px < tc[i].width) { arrLeftS.push(tc[i].left - offsX); } } if (_c2 > vro.vr.c2) { _c2 = vro.vr.c2; } for (i = _c1; i <= vro.vr.c2; ++i) { w = tc[i].width; if (t.width_1px < w) { arrRightS.push(tc[i].left + w - offsX); } if (_c2 === i) { ri = arrRightS.length - 1; } } w = t.drawingCtx.getWidth(); if (arrRightS[arrRightS.length - 1] > w) { arrRightS[arrRightS.length - 1] = w; } if (_r2 > vro.vr.r2) { _r2 = vro.vr.r2; } for (i = _r1; i <= vro.vr.r2; ++i) { h = tr[i].height; if (t.height_1px < h) { arrBottomS.push(tr[i].top + h - offsY); } if (_r2 === i) { bi = arrBottomS.length - 1; } } h = t.drawingCtx.getHeight(); if (arrBottomS[arrBottomS.length - 1] > h) { arrBottomS[arrBottomS.length - 1] = h; } return {l: arrLeftS, r: arrRightS, b: arrBottomS, cellX: cellX, cellY: cellY, ri: ri, bi: bi}; } }); return true; }; WorksheetView.prototype.openCellEditorWithText = function (editor, text, cursorPos, isFocus, selectionRange) { var t = this; selectionRange = (selectionRange) ? selectionRange : this.model.selectionRange; var activeCell = selectionRange.activeCell; var c = t._getVisibleCell(activeCell.col, activeCell.row); var v, copyValue; // get first fragment and change its text v = c.getValueForEdit2().slice(0, 1); // Создаем новый массив, т.к. getValueForEdit2 возвращает ссылку copyValue = []; copyValue[0] = new AscCommonExcel.Fragment({text: text, format: v[0].format.clone()}); var bSuccess = t.openCellEditor(editor, /*fragments*/undefined, /*cursorPos*/undefined, isFocus, /*isClearCell*/ true, /*isHideCursor*/false, /*isQuickInput*/false, selectionRange); if (bSuccess) { editor.paste(copyValue, cursorPos); } return bSuccess; }; WorksheetView.prototype.getFormulaRanges = function () { return this.arrActiveFormulaRanges; }; /** * * @param {Object} ranges * @param canChangeColWidth * @param lockDraw * @param updateHeight */ WorksheetView.prototype.updateRanges = function (ranges, lockDraw, updateHeight) { var arrRanges = [], range; for (var i in ranges) { range = ranges[i]; this.updateRange(range, range.canChangeColWidth || c_oAscCanChangeColWidth.none, true); arrRanges.push(range); } if (0 < arrRanges.length) { if (updateHeight) { this.isChanged = true; } this._recalculateAfterUpdate(arrRanges, lockDraw); } }; // ToDo избавиться от этой функции!!!!Заглушка для принятия изменений WorksheetView.prototype._checkUpdateRange = function (range) { // Для принятия изменения нужно делать расширение диапазона if (this.model.workbook.bCollaborativeChanges) { var bIsUpdateX = false, bIsUpdateY = false; if (range.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, 0); // Передаем 0, чтобы увеличить размеры // Проверка, вдруг пришел диапазон за пределами существующей области if (range.c2 >= this.nColsCount) { if (range.c1 >= this.nColsCount) { return; } range.c2 = this.nColsCount - 1; } bIsUpdateX = true; } if (range.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, 0); // Передаем 0, чтобы увеличить размеры // Проверка, вдруг пришел диапазон за пределами существующей области if (range.r2 >= this.nRowsCount) { if (range.r1 >= this.nRowsCount) { return; } range.r2 = this.nRowsCount - 1; } bIsUpdateY = true; } if (bIsUpdateX && bIsUpdateY) { this.handlers.trigger("reinitializeScroll"); } else if (bIsUpdateX) { this.handlers.trigger("reinitializeScrollX"); } else if (bIsUpdateY) { this.handlers.trigger("reinitializeScrollY"); } } }; WorksheetView.prototype.updateRange = function (range, canChangeColWidth, lockDraw) { this._checkUpdateRange(range); this._updateCellsRange(range, canChangeColWidth, lockDraw); }; WorksheetView.prototype._updateCellsRange = function (range, canChangeColWidth, lockDraw) { var r, c, h, d, ct, isMerged; var mergedRange, bUpdateRowHeight; if (range === undefined) { range = this.model.selectionRange.getLast().clone(); } else { // ToDo заглушка..пора уже переделать обновление данных if (range.r1 >= this.nRowsCount || range.c1 >= this.nColsCount) { return; } range.r2 = Math.min(range.r2, this.nRowsCount - 1); range.c2 = Math.min(range.c2, this.nColsCount - 1); } if (gc_nMaxCol0 === range.c2 || gc_nMaxRow0 === range.r2) { range = range.clone(); if (gc_nMaxCol0 === range.c2) { range.c2 = this.cols.length - 1; } if (gc_nMaxRow0 === range.r2) { range.r2 = this.rows.length - 1; } } this._cleanCache(range); // Если размер диапазона превышает размер видимой области больше чем в 3 раза, то очищаем весь кэш if (this._isLargeRange(range)) { this.changeWorksheet("update", {lockDraw: lockDraw}); this._updateSelectionNameAndInfo(); return; } var cto; for (r = range.r1; r <= range.r2; ++r) { if (this.height_1px > this.rows[r].height) { continue; } for (c = range.c1; c <= range.c2; ++c) { if (this.width_1px > this.cols[c].width) { continue; } c = this._addCellTextToCache(c, r, canChangeColWidth); // may change member 'this.isChanged' } for (h = this.defaultRowHeight, d = this.defaultRowDescender, c = 0; c < this.cols.length; ++c) { ct = this._getCellTextCache(c, r, true); if (!ct) { continue; } /** * Пробегаемся по строке и смотрим не продолжается ли ячейка на соседние. * С помощью этой правки уйдем от обновления всей строки при каких-либо действиях */ if ((c < range.c1 || c > range.c2) && (0 !== ct.sideL || 0 !== ct.sideR)) { cto = this._calcCellTextOffset(c, r, ct.cellHA, ct.metrics.width); ct.cellW = cto.maxWidth; ct.sideL = cto.leftSide; ct.sideR = cto.rightSide; } // Замерженная ячейка (с 2-мя или более строками) не влияет на высоту строк! isMerged = ct.flags.isMerged(); if (!isMerged) { bUpdateRowHeight = true; } else { mergedRange = ct.flags.merged; // Для замерженных ячеек (с 2-мя или более строками) оптимизировать не нужно bUpdateRowHeight = mergedRange.r1 === mergedRange.r2; } if (bUpdateRowHeight) { h = Math.max(h, ct.metrics.height + this.height_1px); } if (ct.cellVA !== Asc.c_oAscVAlign.Top && ct.cellVA !== Asc.c_oAscVAlign.Center && !isMerged) { d = Math.max(d, ct.metrics.height - ct.metrics.baseline); } } if (Math.abs(h - this.rows[r].height) > 0.000001 && !this.rows[r].isCustomHeight) { this.rows[r].heightReal = this.rows[r].height = Math.min(h, this.maxRowHeight); History.TurnOff(); this.model.setRowHeight(this.rows[r].height, r, r, false); History.TurnOn(); this.isChanged = true; } if (Math.abs(d - this.rows[r].descender) > 0.000001) { this.rows[r].descender = d; this.isChanged = true; } } if (!lockDraw) { this._recalculateAfterUpdate([range]); } }; WorksheetView.prototype._recalculateAfterUpdate = function (arrChanged, lockDraw) { if (this.isChanged) { this.isChanged = false; this._initCellsArea(AscCommonExcel.recalcType.full); this.cache.reset(); this._cleanCellsTextMetricsCache(); this._prepareCellTextMetricsCache(); this.handlers.trigger("reinitializeScroll"); } if (!lockDraw) { this._updateSelectionNameAndInfo(); } arrChanged = arrChanged.concat(this.model.hiddenManager.getRecalcHidden()); this.model.onUpdateRanges(arrChanged); this.objectRender.rebuildChartGraphicObjects(arrChanged); this.cellCommentator.updateActiveComment(); //this.updateSpecialPasteOptionsPosition(); this.handlers.trigger("onDocumentPlaceChanged"); this.draw(lockDraw); }; WorksheetView.prototype.setChartRange = function (range) { this.isChartAreaEditMode = true; this.arrActiveChartRanges[0].assign2(range); }; WorksheetView.prototype.endEditChart = function () { if (this.isChartAreaEditMode) { this.isChartAreaEditMode = false; this.arrActiveChartRanges[0].clean(); } }; WorksheetView.prototype.enterCellRange = function (editor) { if (!this.isFormulaEditMode) { return; } var currentFormula = this.arrActiveFormulaRanges[this.arrActiveFormulaRangesPosition]; var currentRange = currentFormula.getLast().clone(); var activeCellId = currentFormula.activeCellId; var activeCell = currentFormula.activeCell.clone(); // Замерженную ячейку должны отдать только левую верхнюю. var mergedRange = this.model.getMergedByCell(currentRange.r1, currentRange.c1); if (mergedRange && currentRange.isEqual(mergedRange)) { currentRange.r2 = currentRange.r1; currentRange.c2 = currentRange.c1; } /* var defName = this.model.workbook.findDefinesNames(this.model.getName()+"!"+currentRange.getAbsName(),this.model.getId()); console.log("defName #2 " + defName);*/ var sheetName = "", cFEWSO = editor.handlers.trigger("getCellFormulaEnterWSOpen"); if (editor.formulaIsOperator() && cFEWSO && cFEWSO.model.getId() != this.model.getId()) { sheetName = parserHelp.getEscapeSheetName(this.model.getName()) + "!"; } editor.enterCellRange(/*defName || */sheetName + currentRange.getAllRange().getName()); for (var tmpRange, i = 0; i < this.arrActiveFormulaRanges.length; ++i) { tmpRange = this.arrActiveFormulaRanges[i]; if (tmpRange.getLast().isEqual(currentRange)) { tmpRange.activeCellId = activeCellId; tmpRange.activeCell.col = activeCell.col; tmpRange.activeCell.row = activeCell.row; break; } } }; WorksheetView.prototype.addFormulaRange = function (range) { var r = this.model.selectionRange.clone(); if (range) { r.assign2(range); var lastSelection = r.getLast(); lastSelection.cursorePos = range.cursorePos; lastSelection.formulaRangeLength = range.formulaRangeLength; lastSelection.colorRangePos = range.colorRangePos; lastSelection.colorRangeLength = range.colorRangeLength; lastSelection.isName = range.isName; } this.arrActiveFormulaRanges.push(r); this.arrActiveFormulaRangesPosition = this.arrActiveFormulaRanges.length - 1; this._fixSelectionOfMergedCells(); }; WorksheetView.prototype.activeFormulaRange = function (range) { this.arrActiveFormulaRangesPosition = -1; for (var i = 0; i < this.arrActiveFormulaRanges.length; ++i) { if (this.arrActiveFormulaRanges[i].getLast().isEqual(range)) { this.arrActiveFormulaRangesPosition = i; return; } } }; WorksheetView.prototype.removeFormulaRange = function (range) { this.arrActiveFormulaRangesPosition = -1; for (var i = 0; i < this.arrActiveFormulaRanges.length; ++i) { if (this.arrActiveFormulaRanges[i].getLast().isEqual(range)) { this.arrActiveFormulaRanges.splice(i, 1); return; } } }; WorksheetView.prototype.cleanFormulaRanges = function () { // Очищаем массив ячеек для текущей формулы this.arrActiveFormulaRangesPosition = -1; this.arrActiveFormulaRanges = []; }; WorksheetView.prototype.addAutoFilter = function (styleName, addFormatTableOptionsObj) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } if (!this.handlers.trigger("getLockDefNameManagerStatus")) { this.handlers.trigger("onErrorEvent", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); return; } if (!window['AscCommonExcel'].filteringMode) { return; } var t = this; var ar = this.model.selectionRange.getLast().clone(); var isChangeAutoFilterToTablePart = function (addFormatTableOptionsObj) { var res = false; var worksheet = t.model; var activeRange = AscCommonExcel.g_oRangeCache.getAscRange(addFormatTableOptionsObj.asc_getRange()); if (activeRange && worksheet.AutoFilter && activeRange.containsRange(worksheet.AutoFilter.Ref) && activeRange.r1 === worksheet.AutoFilter.Ref.r1) { res = true; } return res; }; var filterRange, bIsChangeFilterToTable, addNameColumn; var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { t.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedAllError, c_oAscError.Level.NoCritical); t.handlers.trigger("selectionChanged"); return; } var addFilterCallBack; if (bIsChangeFilterToTable)//CHANGE FILTER TO TABLEPART { addFilterCallBack = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.changeAutoFilterToTablePart(styleName, ar, addFormatTableOptionsObj); t._onUpdateFormatTable(filterRange, !!(styleName), true); History.EndTransaction(); }; if (addNameColumn) { filterRange.r2 = filterRange.r2 + 1; } t._isLockedCells(filterRange, /*subType*/null, addFilterCallBack); } else//ADD { addFilterCallBack = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); if (null !== styleName) { t.handlers.trigger("slowOperation", true); } //add to model t.model.autoFilters.addAutoFilter(styleName, ar, addFormatTableOptionsObj); //updates if (styleName && addNameColumn) { t.setSelection(filterRange); } t._onUpdateFormatTable(filterRange, !!(styleName), true); if (null !== styleName) { t.handlers.trigger("slowOperation", false); } History.EndTransaction(); }; if (styleName === null) { addFilterCallBack(true); } else { t._isLockedCells(filterRange, null, addFilterCallBack) } } }; //calculate filter range if (addFormatTableOptionsObj && isChangeAutoFilterToTablePart(addFormatTableOptionsObj) === true) { filterRange = t.model.AutoFilter.Ref.clone(); addNameColumn = false; if (addFormatTableOptionsObj === false) { addNameColumn = true; } else if (typeof addFormatTableOptionsObj == 'object') { addNameColumn = !addFormatTableOptionsObj.asc_getIsTitle(); } bIsChangeFilterToTable = true; } else { if (styleName === null) { filterRange = ar; } else { var filterInfo = t.model.autoFilters._getFilterInfoByAddTableProps(ar, addFormatTableOptionsObj, true); filterRange = filterInfo.filterRange; addNameColumn = filterInfo.addNameColumn; } } var checkFilterRange = filterInfo ? filterInfo.rangeWithoutDiff : filterRange; if (t._checkAddAutoFilter(checkFilterRange, styleName, addFormatTableOptionsObj) === true) { this._isLockedAll(onChangeAutoFilterCallback); this._isLockedDefNames(null, null); } else//для того, чтобы в случае ошибки кнопка отжималась! { t.handlers.trigger("selectionChanged"); } }; WorksheetView.prototype.changeAutoFilter = function (tableName, optionType, val) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } if (!window['AscCommonExcel'].filteringMode) { return; } var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { t.handlers.trigger("selectionChanged"); return; } switch (optionType) { case Asc.c_oAscChangeFilterOptions.filter: { //DELETE if (!val) { var filterRange = null; var tablePartsContainsRange = t.model.autoFilters._isTablePartsContainsRange(ar); if (tablePartsContainsRange && tablePartsContainsRange.Ref) { filterRange = tablePartsContainsRange.Ref.clone(); } else if (t.model.AutoFilter) { filterRange = t.model.AutoFilter.Ref; } if (null === filterRange) { return; } var deleteFilterCallBack = function () { t.model.autoFilters.deleteAutoFilter(ar, tableName); t.af_drawButtons(filterRange); t._onUpdateFormatTable(filterRange, false, true); }; t._isLockedCells(filterRange, /*subType*/null, deleteFilterCallBack); } else//ADD ONLY FILTER { var addFilterCallBack = function () { History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.addAutoFilter(null, ar); t._onUpdateFormatTable(filterRange, false, true); History.EndTransaction(); }; var filterInfo = t.model.autoFilters._getFilterInfoByAddTableProps(ar); t._isLockedCells(filterInfo.filterRange, null, addFilterCallBack) } break; } case Asc.c_oAscChangeFilterOptions.style://CHANGE STYLE { var changeStyleFilterCallBack = function () { History.Create_NewPoint(); History.StartTransaction(); //TODO внутри вызывается _isTablePartsContainsRange t.model.autoFilters.changeTableStyleInfo(val, ar, tableName); t._onUpdateFormatTable(filterRange, false, true); History.EndTransaction(); }; var filterRange; //calculate lock range and callback parameters var isTablePartsContainsRange = t.model.autoFilters._isTablePartsContainsRange(ar); if (isTablePartsContainsRange !== null)//if one of the tableParts contains activeRange { filterRange = isTablePartsContainsRange.Ref.clone(); } t._isLockedCells(filterRange, /*subType*/null, changeStyleFilterCallBack); break; } } }; if (Asc.c_oAscChangeFilterOptions.style === optionType) { onChangeAutoFilterCallback(true); } else { this._isLockedAll(onChangeAutoFilterCallback); } }; WorksheetView.prototype.applyAutoFilter = function (autoFilterObject) { var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var applyFilterProps = t.model.autoFilters.applyAutoFilter(autoFilterObject, ar); var minChangeRow = applyFilterProps.minChangeRow; var rangeOldFilter = applyFilterProps.rangeOldFilter; if (null !== rangeOldFilter && !t.model.workbook.bUndoChanges && !t.model.workbook.bRedoChanges) { t._onUpdateFormatTable(rangeOldFilter, false, true); if (applyFilterProps.nOpenRowsCount !== applyFilterProps.nAllRowsCount) { t.handlers.trigger('onFilterInfo', applyFilterProps.nOpenRowsCount, applyFilterProps.nAllRowsCount); } } if (null !== minChangeRow) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: minChangeRow}); } }; if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = true; onChangeAutoFilterCallback(); History.LocalChange = false; } else { this._isLockedAll(onChangeAutoFilterCallback); } }; WorksheetView.prototype.reapplyAutoFilter = function (tableName) { var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } //reApply var applyFilterProps = t.model.autoFilters.reapplyAutoFilter(tableName, ar); //reSort var filter = applyFilterProps.filter; if (filter && filter.SortState && filter.SortState.SortConditions && filter.SortState.SortConditions[0]) { var sortState = filter.SortState; var rangeWithoutHeaderFooter = filter.getRangeWithoutHeaderFooter(); var sortRange = t.model.getRange3(rangeWithoutHeaderFooter.r1, rangeWithoutHeaderFooter.c1, rangeWithoutHeaderFooter.r2, rangeWithoutHeaderFooter.c2); var startCol = sortState.SortConditions[0].Ref.c1; var type; var rgbColor = null; switch (sortState.SortConditions[0].ConditionSortBy) { case Asc.ESortBy.sortbyCellColor: { type = Asc.c_oAscSortOptions.ByColorFill; rgbColor = sortState.SortConditions[0].dxf.fill.bg; break; } case Asc.ESortBy.sortbyFontColor: { type = Asc.c_oAscSortOptions.ByColorFont; rgbColor = sortState.SortConditions[0].dxf.font.getColor(); break; } default: { type = Asc.c_oAscSortOptions.ByColorFont; if (sortState.SortConditions[0].ConditionDescending) { type = Asc.c_oAscSortOptions.Descending; } else { type = Asc.c_oAscSortOptions.Ascending; } } } var sort = sortRange.sort(type, startCol, rgbColor); t.cellCommentator.sortComments(sort); } t.model.autoFilters._resetTablePartStyle(); var minChangeRow = applyFilterProps.minChangeRow; var updateRange = applyFilterProps.updateRange; if (updateRange && !t.model.workbook.bUndoChanges && !t.model.workbook.bRedoChanges) { t._onUpdateFormatTable(updateRange, false, true); } if (null !== minChangeRow) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: minChangeRow}); } }; if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = true; onChangeAutoFilterCallback(); History.LocalChange = false; } else { this._isLockedAll(onChangeAutoFilterCallback); } }; WorksheetView.prototype.applyAutoFilterByType = function (autoFilterObject) { var t = this; var activeCell = this.model.selectionRange.activeCell.clone(); var ar = this.model.selectionRange.getLast().clone(); var isStartRangeIntoFilterOrTable = t.model.autoFilters.isStartRangeContainIntoTableOrFilter(activeCell); var isApplyAutoFilter = null, isAddAutoFilter = null, cellId = null, isFromatTable = null; if (null !== isStartRangeIntoFilterOrTable)//into autofilter or format table { isFromatTable = !(-1 === isStartRangeIntoFilterOrTable); var filterRef = isFromatTable ? t.model.TableParts[isStartRangeIntoFilterOrTable].Ref : t.model.AutoFilter.Ref; cellId = t.model.autoFilters._rangeToId(Asc.Range(ar.c1, filterRef.r1, ar.c1, filterRef.r1)); isApplyAutoFilter = true; if (isFromatTable && !t.model.TableParts[isStartRangeIntoFilterOrTable].AutoFilter)//add autofilter to tablepart { isAddAutoFilter = true; } } else//without filter { isAddAutoFilter = true; isApplyAutoFilter = true; } var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); if (null !== isAddAutoFilter) { //delete old filter if (!isFromatTable && t.model.AutoFilter && t.model.AutoFilter.Ref) { t.model.autoFilters.isEmptyAutoFilters(t.model.AutoFilter.Ref); } //add new filter t.model.autoFilters.addAutoFilter(null, ar, null); //generate cellId if (null === cellId) { cellId = t.model.autoFilters._rangeToId( Asc.Range(activeCell.col, t.model.AutoFilter.Ref.r1, activeCell.col, t.model.AutoFilter.Ref.r1)); } } if (null !== isApplyAutoFilter) { autoFilterObject.asc_setCellId(cellId); var filter = autoFilterObject.filter; if (c_oAscAutoFilterTypes.CustomFilters === filter.type) { t.model._getCell(activeCell.row, activeCell.col, function(cell) { var val = cell.getValueWithoutFormat(); filter.filter.CustomFilters[0].Val = val; }); } else if (c_oAscAutoFilterTypes.ColorFilter === filter.type) { t.model._getCell(activeCell.row, activeCell.col, function(cell) { if (filter.filter && filter.filter.dxf && filter.filter.dxf.fill) { if (false === filter.filter.CellColor) { var fontColor = cell.xfs && cell.xfs.font ? cell.xfs.font.getColor() : null; //TODO добавлять дефолтовый цвет шрифта в случае, если цвет шрифта не указан if (null !== fontColor) { filter.filter.dxf.fill.bg = fontColor; } } else { //TODO просмотерть ситуации без заливки var color = cell.getStyle(); var cellColor = null !== color && color.fill && color.fill.bg ? color.fill.bg : null; filter.filter.dxf.fill.bg = null !== cellColor ? new AscCommonExcel.RgbColor(cellColor.rgb) : new AscCommonExcel.RgbColor(null); } } }); } var applyFilterProps = t.model.autoFilters.applyAutoFilter(autoFilterObject, ar); var minChangeRow = applyFilterProps.minChangeRow; var rangeOldFilter = applyFilterProps.rangeOldFilter; if (null !== rangeOldFilter && !t.model.workbook.bUndoChanges && !t.model.workbook.bRedoChanges) { t._onUpdateFormatTable(rangeOldFilter, false, true); } if (null !== minChangeRow) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: minChangeRow}); } } History.EndTransaction(); }; if (null === isAddAutoFilter)//do not add autoFilter { if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = true; onChangeAutoFilterCallback(); History.LocalChange = false; } else { this._isLockedAll(onChangeAutoFilterCallback); } } else//add autofilter + apply { if (!window['AscCommonExcel'].filteringMode) { return; } if (t._checkAddAutoFilter(ar, null, autoFilterObject, true) === true) { this._isLockedAll(onChangeAutoFilterCallback); this._isLockedDefNames(null, null); } } }; WorksheetView.prototype.sortRange = function (type, cellId, displayName, color, bIsExpandRange) { var t = this; var ar = this.model.selectionRange.getLast().clone(); if (!window['AscCommonExcel'].filteringMode) { return; } var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var sortProps = t.model.autoFilters.getPropForSort(cellId, ar, displayName); var onSortAutoFilterCallBack = function () { History.Create_NewPoint(); History.StartTransaction(); var rgbColor = color ? new AscCommonExcel.RgbColor((color.asc_getR() << 16) + (color.asc_getG() << 8) + color.asc_getB()) : null; var sort = sortProps.sortRange.sort(type, sortProps.startCol, rgbColor); t.cellCommentator.sortComments(sort); t.model.autoFilters.sortColFilter(type, cellId, ar, sortProps, displayName, rgbColor); t._onUpdateFormatTable(sortProps.sortRange.bbox, false); History.EndTransaction(); }; if (null === sortProps) { var rgbColor = color ? new AscCommonExcel.RgbColor((color.asc_getR() << 16) + (color.asc_getG() << 8) + color.asc_getB()) : null; //expand selectionRange if(bIsExpandRange) { var selectionRange = t.model.selectionRange; var activeCell = selectionRange.activeCell.clone(); var activeRange = selectionRange.getLast(); var expandRange = t.model.autoFilters._getAdjacentCellsAF(activeRange, true, true, true); var bIgnoreFirstRow = window['AscCommonExcel'].ignoreFirstRowSort(t.model, expandRange); if(bIgnoreFirstRow) { expandRange.r1++; } //change selection t.setSelection(expandRange); selectionRange.activeCell = activeCell; } //sort t.setSelectionInfo("sort", {type: type, color: rgbColor}); //TODO возможно стоит возвратить selection обратно } else if (false !== sortProps) { t._isLockedCells(sortProps.sortRange.bbox, /*subType*/null, onSortAutoFilterCallBack); } }; this._isLockedAll(onChangeAutoFilterCallback); }; WorksheetView.prototype.getAddFormatTableOptions = function (range) { var selectionRange = this.model.selectionRange.getLast(); //TODO возможно стоит перенести getAddFormatTableOptions во view return this.model.autoFilters.getAddFormatTableOptions(selectionRange, range); }; WorksheetView.prototype.clearFilter = function () { var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var updateRange = t.model.autoFilters.isApplyAutoFilterInCell(ar, true); if (false !== updateRange) { t._onUpdateFormatTable(updateRange, false, true); } }; this._isLockedAll(onChangeAutoFilterCallback); }; WorksheetView.prototype.clearFilterColumn = function (cellId, displayName) { var t = this; var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var updateRange = t.model.autoFilters.clearFilterColumn(cellId, displayName); if (false !== updateRange) { t._onUpdateFormatTable(updateRange, false, true); } }; this._isLockedAll(onChangeAutoFilterCallback); }; /** * Обновление при изменениях форматированной таблицы * @param range - обновляемый диапазон (он же диапазон для выделения) * @param recalc - делать ли автоподбор по названию столбца * @param changeRowsOrMerge - менялись ли строки (скрытие раскрытие) или был unmerge * @private */ WorksheetView.prototype._onUpdateFormatTable = function (range, recalc, changeRowsOrMerge) { //ToDo заглушка, чтобы не падало. Нужно полностью переделывать этот код!!!! (Перенес выше из-за бага http://bugzilla.onlyoffice.com/show_bug.cgi?id=26705) this._checkUpdateRange(range); if (!recalc) { // При скрытии/открытии строк стоит делать update всему if (changeRowsOrMerge) { this.isChanged = true; } // Пока вызовем updateRange, но стоит делать просто draw this._updateCellsRange(range); // ToDo убрать совсем reinitRanges if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } return; } if (!this.model.selectionRange.getLast().isEqual(range)) { this.setSelection(range); } var i, r = range.r1, bIsUpdate = false, w; for (i = range.c1; i <= range.c2; ++i) { w = this.onChangeWidthCallback(i, r, r, /*onlyIfMore*/true); if (-1 !== w) { this.cols[i] = this._calcColWidth(w); this._cleanCache(new asc_Range(i, 0, i, this.rows.length - 1)); bIsUpdate = true; } } if (bIsUpdate) { this._updateColumnPositions(); this._updateVisibleColsCount(); this.changeWorksheet("update"); } else if (changeRowsOrMerge) { // Был merge, нужно обновить (ToDo) this._initCellsArea(AscCommonExcel.recalcType.full); this.cache.reset(); this._cleanCellsTextMetricsCache(); this._prepareCellTextMetricsCache(); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } var arrChanged = [new asc_Range(range.c1, 0, range.c2, gc_nMaxRow0)]; this.model.onUpdateRanges(arrChanged); this.objectRender.rebuildChartGraphicObjects(arrChanged); this.draw(); this.handlers.trigger("reinitializeScroll"); this._updateSelectionNameAndInfo(); } else { // Просто отрисуем this.draw(); this._updateSelectionNameAndInfo(); } }; WorksheetView.prototype._loadFonts = function (fonts, callback) { var api = window["Asc"]["editor"]; api._loadFonts(fonts, callback); }; WorksheetView.prototype.setData = function (oData) { History.Clear(); History.TurnOff(); var oAllRange = new AscCommonExcel.Range(this.model, 0, 0, this.nRowsCount - 1, this.nColsCount - 1); oAllRange.cleanAll(); var row, oCell; for (var r = 0; r < oData.length; ++r) { row = oData[r]; for (var c = 0; c < row.length; ++c) { if (row[c]) { oCell = this._getVisibleCell(c, r); oCell.setValue(row[c]); } } } History.TurnOn(); this._updateCellsRange(oAllRange.bbox); // ToDo Стоит обновить nRowsCount и nColsCount }; WorksheetView.prototype.getData = function () { var arrResult, arrCells = [], c, r, row, lastC = -1, lastR = -1, val; var maxCols = Math.min(this.model.getColsCount(), gc_nMaxCol); var maxRows = Math.min(this.model.getRowsCount(), gc_nMaxRow); for (r = 0; r < maxRows; ++r) { row = []; for (c = 0; c < maxCols; ++c) { this.model._getCellNoEmpty(r, c, function(cell) { if (cell && '' !== (val = cell.getValue())) { lastC = Math.max(lastC, c); lastR = Math.max(lastR, r); } else { val = ''; } }); row.push(val); } arrCells.push(row); } arrResult = arrCells.slice(0, lastR + 1); ++lastC; if (lastC < maxCols) { for (r = 0; r < arrResult.length; ++r) { arrResult[r] = arrResult[r].slice(0, lastC); } } return arrResult; }; WorksheetView.prototype.af_drawButtons = function (updatedRange, offsetX, offsetY) { var i, aWs = this.model; var t = this; if (aWs.workbook.bUndoChanges || aWs.workbook.bRedoChanges) { return false; } var drawCurrentFilterButtons = function (filter) { var autoFilter = filter.isAutoFilter() ? filter : filter.AutoFilter; if(!filter.Ref) { return; } var range = new Asc.Range(filter.Ref.c1, filter.Ref.r1, filter.Ref.c2, filter.Ref.r1); if (range.isIntersect(updatedRange)) { var row = range.r1; var sortCondition = filter.isApplySortConditions() ? filter.SortState.SortConditions[0] : null; for (var col = range.c1; col <= range.c2; col++) { if (col >= updatedRange.c1 && col <= updatedRange.c2) { var isSetFilter = false; var isShowButton = true; var isSortState = null;//true - ascending, false - descending var colId = filter.isAutoFilter() ? t.model.autoFilters._getTrueColId(autoFilter, col - range.c1) : col - range.c1; if (autoFilter.FilterColumns && autoFilter.FilterColumns.length) { var filterColumn = null, filterColumnWithMerge = null; for (var i = 0; i < autoFilter.FilterColumns.length; i++) { if (autoFilter.FilterColumns[i].ColId === col - range.c1) { filterColumn = autoFilter.FilterColumns[i]; } if (colId === col - range.c1 && filterColumn !== null) { filterColumnWithMerge = filterColumn; break; } else if (autoFilter.FilterColumns[i].ColId === colId) { filterColumnWithMerge = autoFilter.FilterColumns[i]; } } if (filterColumnWithMerge && filterColumnWithMerge.isApplyAutoFilter()) { isSetFilter = true; } if (filterColumn && filterColumn.ShowButton === false) { isShowButton = false; } } if(sortCondition && sortCondition.Ref) { if(colId === sortCondition.Ref.c1 - range.c1) { isSortState = !!(sortCondition.ConditionDescending); } } if (isShowButton === false) { continue; } t.af_drawCurrentButton(offsetX, offsetY, {isSortState: isSortState, isSetFilter: isSetFilter, row: row, col: col}); } } } }; if (aWs.AutoFilter) { drawCurrentFilterButtons(aWs.AutoFilter); } if (aWs.TableParts && aWs.TableParts.length) { for (i = 0; i < aWs.TableParts.length; i++) { if (aWs.TableParts[i].AutoFilter && aWs.TableParts[i].HeaderRowCount !== 0) { drawCurrentFilterButtons(aWs.TableParts[i], true); } } } var pivotButtons = this.model.getPivotTableButtons(updatedRange); for (i = 0; i < pivotButtons.length; ++i) { this.af_drawCurrentButton(offsetX, offsetY, {isSortState: null, isSetFilter: false, row: pivotButtons[i].row, col: pivotButtons[i].col}); } return true; }; WorksheetView.prototype.af_drawCurrentButton = function (offsetX, offsetY, props) { var t = this; var ctx = t.drawingCtx; var isMobileRetina = false; //TODO пересмотреть масштабирование!!! var isApplyAutoFilter = props.isSetFilter; var isApplySortState = props.isSortState; var row = props.row; var col = props.col; var widthButtonPx = 17; var heightButtonPx = 17; if (AscBrowser.isRetina) { widthButtonPx = AscCommon.AscBrowser.convertToRetinaValue(widthButtonPx, true); heightButtonPx = AscCommon.AscBrowser.convertToRetinaValue(heightButtonPx, true); } var widthBorder = 1; var scaleIndex = 1; var scaleFactor = ctx.scaleFactor; var width_1px = t.width_1px; var height_1px = t.height_1px; var m_oColor = new CColor(120, 120, 120); var widthWithBorders = widthButtonPx * width_1px; var heightWithBorders = heightButtonPx * height_1px; var width = (widthButtonPx - widthBorder * 2) * width_1px; var height = (heightButtonPx - widthBorder * 2) * height_1px; var colWidth = t.cols[col].width; var rowHeight = t.rows[row].height; if (rowHeight < heightWithBorders) { widthWithBorders = widthWithBorders * (rowHeight / heightWithBorders); heightWithBorders = rowHeight; } //стартовая позиция кнопки var x1 = t.cols[col].left + t.cols[col].width - widthWithBorders - 0.5 - offsetX; var y1 = t.rows[row].top + t.rows[row].height - heightWithBorders - 0.5 - offsetY; var _drawButtonFrame = function(startX, startY, width, height) { ctx.setFillStyle(t.settings.cells.defaultState.background); ctx.setLineWidth(1); ctx.setStrokeStyle(t.settings.cells.defaultState.border); ctx.fillRect(startX, startY, width, height); ctx.strokeRect(startX, startY, width, height); }; var _drawSortArrow = function(startX, startY, isDescending, heightArrow) { //isDescending = true - стрелочка смотрит вниз //рисуем сверху вниз ctx.beginPath(); ctx.lineVer(startX, startY, startY + heightArrow * height_1px * scaleIndex); var x = startX; var y = startY; var heightArrow1 = heightArrow * height_1px * scaleIndex - 1*width_1px/scaleFactor; var height = 3 * scaleIndex * scaleFactor; var x1, x2, y1; if(isDescending) { for(var i = 0; i < height; i++) { x1 = x - (i*width_1px/scaleFactor); x2 = x - (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y - (i*width_1px/scaleFactor) + heightArrow1; ctx.lineHor(x1, y1, x2); x1 = x + (i*width_1px/scaleFactor); x2 = x + (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y - (i*width_1px/scaleFactor) + heightArrow1; ctx.lineHor(x1, y1, x2); } } else { for(var i = 0; i < height; i++) { x1 = x - (i*width_1px/scaleFactor); x2 = x - (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y + (i*width_1px/scaleFactor); ctx.lineHor(x1, y1, x2); x1 = x + (i*width_1px/scaleFactor); x2 = x + (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y + (i*width_1px/scaleFactor); ctx.lineHor(x1, y1, x2); } } if(isMobileRetina) { ctx.setLineWidth(AscBrowser.retinaPixelRatio * 2); } else { ctx.setLineWidth(AscBrowser.retinaPixelRatio * width_1px); } ctx.setStrokeStyle(m_oColor); ctx.stroke(); }; var _drawFilterMark = function (x, y, height) { var heightLine = Math.round(height); var heightCleanLine = heightLine - 2*height_1px; ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x, y - heightCleanLine); if(isMobileRetina) { ctx.setLineWidth(4 * AscBrowser.retinaPixelRatio); } else { ctx.setLineWidth(AscBrowser.retinaPixelRatio * t.width_2px); } ctx.setStrokeStyle(m_oColor); ctx.stroke(); var heightTriangle = 4; y = y - heightLine + 1*width_1px / scaleFactor; _drawFilterDreieck(x, y, heightTriangle, 2); }; var _drawFilterDreieck = function (x, y, height, base) { ctx.beginPath(); x = x + 1*width_1px/scaleFactor; var diffY = (height / 2) * scaleFactor; height = height * scaleIndex*scaleFactor; for(var i = 0; i < height; i++) { ctx.lineHor(x - (i*width_1px/scaleFactor + base*width_1px/scaleFactor) , y + (height*height_1px - i*height_1px/scaleFactor) - diffY, x + i*width_1px/scaleFactor) } if(isMobileRetina) { ctx.setLineWidth(AscBrowser.retinaPixelRatio * 2); } else { ctx.setLineWidth(AscBrowser.retinaPixelRatio * width_1px); } ctx.setStrokeStyle(m_oColor); ctx.stroke(); }; //TODO пересмотреть отрисовку кнопок + отрисовку при масштабировании var _drawButton = function(upLeftXButton, upLeftYButton) { //квадрат кнопки рисуем _drawButtonFrame(upLeftXButton, upLeftYButton, width, height); //координаты центра var centerX = upLeftXButton + (width / 2); var centerY = upLeftYButton + (height / 2); if(null !== isApplySortState && isApplyAutoFilter) { var heigthObj = Math.ceil((height / 2) / height_1px) * height_1px + 1 * height_1px; var marginTop = Math.floor(((height - heigthObj) / 2) / height_1px) * height_1px; centerY = upLeftYButton + heigthObj + marginTop; _drawSortArrow(upLeftXButton + 4 * width_1px * scaleIndex, upLeftYButton + 5 * height_1px * scaleIndex, isApplySortState, 8); _drawFilterMark(centerX + 2 * width_1px, centerY, heigthObj); } else if(null !== isApplySortState) { _drawSortArrow(upLeftXButton + width - 5 * width_1px * scaleIndex, upLeftYButton + 3 * height_1px * scaleIndex, isApplySortState, 10); _drawFilterDreieck(centerX - 4 * width_1px, centerY + 1 * height_1px, 3, 1); } else if (isApplyAutoFilter) { var heigthObj = Math.ceil((height / 2) / height_1px) * height_1px + 1 * height_1px; var marginTop = Math.floor(((height - heigthObj) / 2) / height_1px) * height_1px; centerY = upLeftYButton + heigthObj + marginTop; _drawFilterMark(centerX, centerY, heigthObj); } else { _drawFilterDreieck(centerX, centerY, 4, 1); } }; var diffX = 0; var diffY = 0; if ((colWidth - 2) < width && rowHeight < (height + 2)) { if (rowHeight < colWidth) { scaleIndex = rowHeight / height; width = width * scaleIndex; height = rowHeight; } else { scaleIndex = colWidth / width; diffY = width - colWidth; diffX = width - colWidth; width = colWidth; height = height * scaleIndex; } } else if ((colWidth - 2) < width) { scaleIndex = colWidth / width; //смещения по x и y diffY = width - colWidth; diffX = width - colWidth + 2; width = colWidth; height = height * scaleIndex; } else if (rowHeight < height) { scaleIndex = rowHeight / height; width = width * scaleIndex; height = rowHeight; } if(window['IS_NATIVE_EDITOR']) { isMobileRetina = true; } if(AscBrowser.isRetina) { scaleIndex *= 2; } _drawButton(x1 + diffX, y1 + diffY); }; WorksheetView.prototype.af_checkCursor = function (x, y, _vr, offsetX, offsetY, r, c) { var aWs = this.model; var t = this; var result = null; var _isShowButtonInFilter = function (col, filter) { var result = true; var autoFilter = filter.isAutoFilter() ? filter : filter.AutoFilter; if (filter.HeaderRowCount === 0) { result = null; } else if (autoFilter && autoFilter.FilterColumns)//проверяем скрытые ячейки { var colId = col - autoFilter.Ref.c1; for (var i = 0; i < autoFilter.FilterColumns.length; i++) { if (autoFilter.FilterColumns[i].ColId === colId) { if (autoFilter.FilterColumns[i].ShowButton === false) { result = null; } break; } } } else if (!filter.isAutoFilter() && autoFilter === null)//если форматированная таблица и отсутсвует а/ф { result = null; } return result; }; var checkCurrentFilter = function (filter, num) { var range = new Asc.Range(filter.Ref.c1, filter.Ref.r1, filter.Ref.c2, filter.Ref.r1); if (range.contains(c.col, r.row) && _isShowButtonInFilter(c.col, filter)) { var row = range.r1; for (var col = range.c1; col <= range.c2; col++) { if (col === c.col) { if(t._hitCursorFilterButton(x, y, col, row)){ result = {cursor: kCurAutoFilter, target: c_oTargetType.FilterObject, col: -1, row: -1, idFilter: {id: num, colId: col - range.c1}}; break; } } } } }; if(_vr.contains(c.col, r.row)) { x = x + offsetX; y = y + offsetY; if (aWs.AutoFilter && aWs.AutoFilter.Ref) { checkCurrentFilter(aWs.AutoFilter, null); } if (aWs.TableParts && aWs.TableParts.length && !result) { for (var i = 0; i < aWs.TableParts.length; i++) { if (aWs.TableParts[i].AutoFilter) { checkCurrentFilter(aWs.TableParts[i], i); } } } } return result; }; WorksheetView.prototype._hitCursorFilterButton = function(x, y, col, row) { var ws = this; var width = 13; var height = 13; var rowHeight = ws.rows[row].height; if (rowHeight < height) { width = width * (rowHeight / height); height = rowHeight; } var x1 = ws.cols[col].left + ws.cols[col].width - width - 0.5; var y1 = ws.rows[row].top + ws.rows[row].height - height - 0.5; var x2 = ws.cols[col].left + ws.cols[col].width - 0.5; var y2 = ws.rows[row].top + ws.rows[row].height - 0.5; return (x >= x1 && x <= x2 && y >= y1 && y <= y2); }; WorksheetView.prototype._checkAddAutoFilter = function (activeRange, styleName, addFormatTableOptionsObj, filterByCellContextMenu) { //write error, if not add autoFilter and return false var result = true; var worksheet = this.model; var filter = worksheet.AutoFilter; if (filter && styleName && filter.Ref.isIntersect(activeRange) && !(filter.Ref.containsRange(activeRange) && (activeRange.isOneCell() || (filter.Ref.isEqual(activeRange))) || (filter.Ref.r1 === activeRange.r1 && activeRange.containsRange(filter.Ref)))) { worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (!styleName && activeRange.isOneCell() && worksheet.autoFilters._isEmptyRange(activeRange, 1)) { //add filter to empty range - if select contains 1 cell worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (!styleName && !activeRange.isOneCell() && worksheet.autoFilters._isEmptyRange(activeRange, 0)) { //add filter to empty range worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (!styleName && filterByCellContextMenu && false === worksheet.autoFilters._getAdjacentCellsAF(activeRange, this).isIntersect(activeRange)) { //add filter to empty range worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (styleName && addFormatTableOptionsObj && addFormatTableOptionsObj.isTitle === false && worksheet.autoFilters._isEmptyCellsUnderRange(activeRange) == false && worksheet.autoFilters._isPartTablePartsUnderRange(activeRange)) { //add format table without title if down another format table worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); result = false; } else if (this.model.inPivotTable(activeRange)) { result = false; } return result; }; WorksheetView.prototype.af_getSizeButton = function (c, r) { var ws = this; var result = null; var isCellContainsAutoFilterButton = function (col, row) { var aWs = ws.model; if (aWs.TableParts) { var tablePart; for (var i = 0; i < aWs.TableParts.length; i++) { tablePart = aWs.TableParts[i]; //TODO добавить проверку на isHidden у кнопки if (tablePart.Ref.contains(col, row) && tablePart.Ref.r1 === row) { return true; } } } //TODO добавить проверку на isHidden у кнопки if (aWs.AutoFilter && aWs.AutoFilter.Ref.contains(col, row) && aWs.AutoFilter.Ref.r1 === row) { return true; } return false; }; if (isCellContainsAutoFilterButton(c, r)) { var height = 11; var width = 11; var rowHeight = ws.rows[r].height; var index = 1; if (rowHeight < height) { index = rowHeight / height; width = width * index; height = rowHeight; } result = {width: width, height: height}; } return result; }; WorksheetView.prototype.af_setDialogProp = function (filterProp, isReturnProps) { var ws = this.model; if(!filterProp){ return; } //get filter var filter, autoFilter, displayName = null; if (filterProp.id === null) { autoFilter = ws.AutoFilter; filter = ws.AutoFilter; } else { autoFilter = ws.TableParts[filterProp.id].AutoFilter; filter = ws.TableParts[filterProp.id]; displayName = filter.DisplayName; } //get values var colId = filterProp.colId; var openAndClosedValues = ws.autoFilters.getOpenAndClosedValues(filter, colId); var values = openAndClosedValues.values; var automaticRowCount = openAndClosedValues.automaticRowCount; //для случае когда скрыто только пустое значение не отображаем customfilter var ignoreCustomFilter = openAndClosedValues.ignoreCustomFilter; var filters = autoFilter.getFilterColumn(colId); var rangeButton = Asc.Range(autoFilter.Ref.c1 + colId, autoFilter.Ref.r1, autoFilter.Ref.c1 + colId, autoFilter.Ref.r1); var cellId = ws.autoFilters._rangeToId(rangeButton); var cellCoord = this.getCellCoord(autoFilter.Ref.c1 + colId, autoFilter.Ref.r1); //get filter object var filterObj = new Asc.AutoFilterObj(); if (filters && filters.ColorFilter) { filterObj.type = c_oAscAutoFilterTypes.ColorFilter; filterObj.filter = filters.ColorFilter.clone(); } else if (!ignoreCustomFilter && filters && filters.CustomFiltersObj && filters.CustomFiltersObj.CustomFilters) { filterObj.type = c_oAscAutoFilterTypes.CustomFilters; filterObj.filter = filters.CustomFiltersObj; } else if (filters && filters.DynamicFilter) { filterObj.type = c_oAscAutoFilterTypes.DynamicFilter; filterObj.filter = filters.DynamicFilter.clone(); } else if (filters && filters.Top10) { filterObj.type = c_oAscAutoFilterTypes.Top10; filterObj.filter = filters.Top10.clone(); } else if (filters) { filterObj.type = c_oAscAutoFilterTypes.Filters; } else { filterObj.type = c_oAscAutoFilterTypes.None; } //get sort var sortVal = null; var sortColor = null; if (filter && filter.SortState && filter.SortState.SortConditions && filter.SortState.SortConditions[0]) { var SortConditions = filter.SortState.SortConditions[0]; if (rangeButton.c1 == SortConditions.Ref.c1) { var conditionSortBy = SortConditions.ConditionSortBy; switch (conditionSortBy) { case Asc.ESortBy.sortbyCellColor: { sortVal = Asc.c_oAscSortOptions.ByColorFill; sortColor = SortConditions.dxf && SortConditions.dxf.fill ? SortConditions.dxf.fill.bg : null; break; } case Asc.ESortBy.sortbyFontColor: { sortVal = Asc.c_oAscSortOptions.ByColorFont; sortColor = SortConditions.dxf && SortConditions.dxf.font ? SortConditions.dxf.font.getColor() : null; break; } default: { if (filter.SortState.SortConditions[0].ConditionDescending) { sortVal = Asc.c_oAscSortOptions.Descending; } else { sortVal = Asc.c_oAscSortOptions.Ascending; } break; } } } } var ascColor = null; if (null !== sortColor) { ascColor = new Asc.asc_CColor(); ascColor.asc_putR(sortColor.getR()); ascColor.asc_putG(sortColor.getG()); ascColor.asc_putB(sortColor.getB()); ascColor.asc_putA(sortColor.getA()); } //set menu object var autoFilterObject = new Asc.AutoFiltersOptions(); autoFilterObject.asc_setSortState(sortVal); autoFilterObject.asc_setCellCoord(cellCoord); autoFilterObject.asc_setCellId(cellId); autoFilterObject.asc_setValues(values); autoFilterObject.asc_setFilterObj(filterObj); autoFilterObject.asc_setAutomaticRowCount(automaticRowCount); autoFilterObject.asc_setDiplayName(displayName); autoFilterObject.asc_setSortColor(ascColor); var columnRange = Asc.Range(rangeButton.c1, autoFilter.Ref.r1 + 1, rangeButton.c1, autoFilter.Ref.r2); var filterTypes = this.af_getFilterTypes(columnRange); autoFilterObject.asc_setIsTextFilter(filterTypes.text); autoFilterObject.asc_setColorsFill(filterTypes.colors); autoFilterObject.asc_setColorsFont(filterTypes.fontColors); if (isReturnProps) { return autoFilterObject; } else { this.handlers.trigger("setAutoFiltersDialog", autoFilterObject); } }; WorksheetView.prototype.af_getFilterTypes = function (columnRange) { var t = this; var ws = this.model; var res = {text: true, colors: [], fontColors: []}; var alreadyAddColors = {}, alreadyAddFontColors = {}; var getAscColor = function (color) { var ascColor = new Asc.asc_CColor(); ascColor.asc_putR(color.getR()); ascColor.asc_putG(color.getG()); ascColor.asc_putB(color.getB()); ascColor.asc_putA(color.getA()); return ascColor; }; var addFontColorsToArray = function (fontColor) { var rgb = null === fontColor || fontColor && 0 === fontColor.rgb ? null : fontColor.rgb; var isDefaultFontColor = !!(null === rgb); if (true !== alreadyAddFontColors[rgb]) { if (isDefaultFontColor) { res.fontColors.push(null); alreadyAddFontColors[null] = true; } else { var ascFontColor = getAscColor(fontColor); res.fontColors.push(ascFontColor); alreadyAddFontColors[rgb] = true; } } }; var addCellColorsToArray = function (color) { var rgb = null !== color && color.fill && color.fill.bg ? color.fill.bg.rgb : null; var isDefaultCellColor = !!(null === rgb); if (true !== alreadyAddColors[rgb]) { if (isDefaultCellColor) { res.colors.push(null); alreadyAddColors[null] = true; } else { var ascColor = getAscColor(color.fill.bg); res.colors.push(ascColor); alreadyAddColors[rgb] = true; } } }; var tempText = 0, tempDigit = 0; ws.getRange3(columnRange.r1, columnRange.c1, columnRange.r2, columnRange.c1)._foreachNoEmpty(function(cell) { //добавляем без цвета ячейку if (!cell) { if (true !== alreadyAddColors[null]) { alreadyAddColors[null] = true; res.colors.push(null); } return; } if (false === cell.isNullText()) { var type = cell.getType(); if (type === 0) { tempDigit++; } else { tempText++; } } //font colors var multiText = cell.getValueMultiText(); if (null !== multiText) { for (var j = 0; j < multiText.length; j++) { var fontColor = multiText[j].format ? multiText[j].format.getColor() : null; addFontColorsToArray(fontColor); } } else { var fontColor = cell.xfs && cell.xfs.font ? cell.xfs.font.getColor() : null; addFontColorsToArray(fontColor); } //cell colors addCellColorsToArray(cell.getStyle()); }); //если один элемент в массиве, не отправляем его в меню if (res.colors.length === 1) { res.colors = []; } if (res.fontColors.length === 1) { res.fontColors = []; } res.text = tempDigit > tempText ? false : true; return res; }; WorksheetView.prototype.af_changeSelectionTablePart = function (activeRange) { var t = this; var tableParts = t.model.TableParts; var _changeSelectionToAllTablePart = function () { var tablePart; for (var i = 0; i < tableParts.length; i++) { tablePart = tableParts[i]; if (tablePart.Ref.intersection(activeRange)) { if (t.model.autoFilters._activeRangeContainsTablePart(activeRange, tablePart.Ref)) { var newActiveRange = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2); t.setSelection(newActiveRange); } break; } } }; var _changeSelectionFromCellToColumn = function () { if (tableParts && tableParts.length && activeRange.isOneCell()) { for (var i = 0; i < tableParts.length; i++) { if (tableParts[i].HeaderRowCount !== 0 && tableParts[i].Ref.containsRange(activeRange) && tableParts[i].Ref.r1 === activeRange.r1) { var newActiveRange = new Asc.Range(activeRange.c1, activeRange.r1, activeRange.c1, tableParts[i].Ref.r2); if (!activeRange.isEqual(newActiveRange)) { t.setSelection(newActiveRange); } break; } } } }; if (activeRange.isOneCell()) { _changeSelectionFromCellToColumn(activeRange); } else { _changeSelectionToAllTablePart(activeRange); } }; WorksheetView.prototype.af_isCheckMoveRange = function (arnFrom, arnTo) { var ws = this.model; var tableParts = ws.TableParts; var tablePart; var checkMoveRangeIntoApplyAutoFilter = function (arnTo) { if (ws.AutoFilter && ws.AutoFilter.Ref && arnTo.intersection(ws.AutoFilter.Ref)) { //если затрагиваем скрытые строки а/ф - выдаём ошибку if (ws.autoFilters._searchHiddenRowsByFilter(ws.AutoFilter, arnTo)) { return false; } } return true; }; //1) если выделена часть форматированной таблицы и ещё часть(либо полностью) var counterIntersection = 0; var counterContains = 0; for (var i = 0; i < tableParts.length; i++) { tablePart = tableParts[i]; if (tablePart.Ref.intersection(arnFrom)) { if (arnFrom.containsRange(tablePart.Ref)) { counterContains++; } else { counterIntersection++; } } } if ((counterIntersection > 0 && counterContains > 0) || (counterIntersection > 1)) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); return false; } //2)если затрагиваем перемещаемым диапазоном часть а/ф со скрытыми строчками if (!checkMoveRangeIntoApplyAutoFilter(arnTo)) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterMoveToHiddenRangeError, c_oAscError.Level.NoCritical); return false; } return true; }; WorksheetView.prototype.af_changeSelectionFormatTable = function (tableName, optionType) { var t = this; var ws = this.model; var tablePart = ws.autoFilters._getFilterByDisplayName(tableName); if (!tablePart || (tablePart && !tablePart.Ref)) { return false; } var refTablePart = tablePart.Ref; var lastSelection = this.model.selectionRange.getLast(); var startCol = lastSelection.c1; var endCol = lastSelection.c2; var startRow = lastSelection.r1; var endRow = lastSelection.r2; switch (optionType) { case c_oAscChangeSelectionFormatTable.all: { startCol = refTablePart.c1; endCol = refTablePart.c2; startRow = refTablePart.r1; endRow = refTablePart.r2; break; } case c_oAscChangeSelectionFormatTable.data: { var rangeWithoutHeaderFooter = tablePart.getRangeWithoutHeaderFooter(); startCol = lastSelection.c1 < refTablePart.c1 ? refTablePart.c1 : lastSelection.c1; endCol = lastSelection.c2 > refTablePart.c2 ? refTablePart.c2 : lastSelection.c2; startRow = rangeWithoutHeaderFooter.r1; endRow = rangeWithoutHeaderFooter.r2; break; } case c_oAscChangeSelectionFormatTable.row: { startCol = refTablePart.c1; endCol = refTablePart.c2; startRow = lastSelection.r1 < refTablePart.r1 ? refTablePart.r1 : lastSelection.r1; endRow = lastSelection.r2 > refTablePart.r2 ? refTablePart.r2 : lastSelection.r2; break; } case c_oAscChangeSelectionFormatTable.column: { startCol = lastSelection.c1 < refTablePart.c1 ? refTablePart.c1 : lastSelection.c1; endCol = lastSelection.c2 > refTablePart.c2 ? refTablePart.c2 : lastSelection.c2; startRow = refTablePart.r1; endRow = refTablePart.r2; break; } } t.setSelection(new Asc.Range(startCol, startRow, endCol, endRow)); }; WorksheetView.prototype.af_changeFormatTableInfo = function (tableName, optionType, val) { var tablePart = this.model.autoFilters._getFilterByDisplayName(tableName); var t = this; var ar = this.model.selectionRange.getLast(); if (!tablePart || (tablePart && !tablePart.TableStyleInfo)) { return false; } if (!window['AscCommonExcel'].filteringMode) { return false; } var isChangeTableInfo = this.af_checkChangeTableInfo(tablePart, optionType); if (isChangeTableInfo !== false) { var callback = function (isSuccess) { if (false === isSuccess) { t.handlers.trigger("selectionChanged"); return; } History.Create_NewPoint(); History.StartTransaction(); var newTableRef = t.model.autoFilters.changeFormatTableInfo(tableName, optionType, val); if (newTableRef.r1 > ar.r1 || newTableRef.r2 < ar.r2) { var startRow = newTableRef.r1 > ar.r1 ? newTableRef.r1 : ar.r1; var endRow = newTableRef.r2 < ar.r2 ? newTableRef.r2 : ar.r2; var newActiveRange = new Asc.Range(ar.c1, startRow, ar.c2, endRow); t.setSelection(newActiveRange); History.SetSelectionRedo(newActiveRange); } t._onUpdateFormatTable(isChangeTableInfo, false, true); History.EndTransaction(); }; var lockRange = t.af_getRangeForChangeTableInfo(tablePart, optionType, val); if (lockRange) { t._isLockedCells(lockRange, null, callback); } else { callback(); } } }; WorksheetView.prototype.af_checkChangeTableInfo = function (tablePart, optionType) { var res = tablePart.Ref; var ws = this.model, rangeUpTable; if (optionType === c_oAscChangeTableStyleInfo.rowHeader && tablePart.HeaderRowCount !== null) { //add header row rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, tablePart.Ref.r1 - 1); } else if (optionType === c_oAscChangeTableStyleInfo.rowTotal && tablePart.TotalsRowCount === null) { //add total row rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r2 + 1, tablePart.Ref.c2, tablePart.Ref.r2 + 1); //add total table if down another format table if(ws.autoFilters._isPartTablePartsUnderRange(tablePart.Ref)){ ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); return false; } } if (rangeUpTable && this.model.autoFilters._isEmptyRange(rangeUpTable, 0) && this.model.autoFilters._isPartTablePartsUnderRange(tablePart.Ref) === true) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterMoveToHiddenRangeError, c_oAscError.Level.NoCritical); res = false; } return res; }; WorksheetView.prototype.af_getRangeForChangeTableInfo = function (tablePart, optionType, val) { var res = null; switch (optionType) { case c_oAscChangeTableStyleInfo.columnBanded: case c_oAscChangeTableStyleInfo.columnFirst: case c_oAscChangeTableStyleInfo.columnLast: case c_oAscChangeTableStyleInfo.rowBanded: case c_oAscChangeTableStyleInfo.filterButton: { res = tablePart.Ref; break; } case c_oAscChangeTableStyleInfo.rowTotal: { if (val === false) { res = tablePart.Ref; } else { var rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r2 + 1, tablePart.Ref.c2, tablePart.Ref.r2 + 1); if(this.model.autoFilters._isEmptyRange(rangeUpTable, 0) && this.model.autoFilters.searchRangeInTableParts(rangeUpTable) === -1){ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2 + 1); } else{ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r2 + 1, tablePart.Ref.c2, gc_nMaxRow0); } } break; } case c_oAscChangeTableStyleInfo.rowHeader: { if (val === false) { res = tablePart.Ref; } else { var rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, tablePart.Ref.r1 - 1); if(this.model.autoFilters._isEmptyRange(rangeUpTable, 0) && this.model.autoFilters.searchRangeInTableParts(rangeUpTable) === -1){ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, tablePart.Ref.r2); } else{ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, gc_nMaxRow0); } } break; } } return res; }; WorksheetView.prototype.af_insertCellsInTable = function (tableName, optionType) { var t = this; var ws = this.model; var tablePart = ws.autoFilters._getFilterByDisplayName(tableName); if (!tablePart || (tablePart && !tablePart.Ref)) { return false; } var insertCellsAndShiftDownRight = function (arn, displayName, type) { var range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); var isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, type, "insCell", true); if (isCheckChangeAutoFilter === false) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); var shiftCells = type === c_oAscInsertOptions.InsertCellsAndShiftRight ? range.addCellsShiftRight(displayName) : range.addCellsShiftBottom(displayName); if (shiftCells) { t.cellCommentator.updateCommentsDependencies(true, type, arn); t.objectRender.updateDrawingObject(true, type, arn); t._onUpdateFormatTable(range, false, true); } History.EndTransaction(); }; var changedRange = new asc_Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2); t._isLockedCells(changedRange, null, callback); }; var newActiveRange = this.model.selectionRange.getLast().clone(); var displayName = null; var type = null; switch (optionType) { case c_oAscInsertOptions.InsertTableRowAbove: { newActiveRange.c1 = tablePart.Ref.c1; newActiveRange.c2 = tablePart.Ref.c2; type = c_oAscInsertOptions.InsertCellsAndShiftDown; break; } case c_oAscInsertOptions.InsertTableRowBelow: { newActiveRange.c1 = tablePart.Ref.c1; newActiveRange.c2 = tablePart.Ref.c2; newActiveRange.r1 = tablePart.Ref.r2 + 1; newActiveRange.r2 = tablePart.Ref.r2 + 1; displayName = tableName; type = c_oAscInsertOptions.InsertCellsAndShiftDown; break; } case c_oAscInsertOptions.InsertTableColLeft: { newActiveRange.r1 = tablePart.Ref.r1; newActiveRange.r2 = tablePart.Ref.r2; type = c_oAscInsertOptions.InsertCellsAndShiftRight; break; } case c_oAscInsertOptions.InsertTableColRight: { newActiveRange.c1 = tablePart.Ref.c2 + 1; newActiveRange.c2 = tablePart.Ref.c2 + 1; newActiveRange.r1 = tablePart.Ref.r1; newActiveRange.r2 = tablePart.Ref.r2; displayName = tableName; type = c_oAscInsertOptions.InsertCellsAndShiftRight; break; } } insertCellsAndShiftDownRight(newActiveRange, displayName, type) }; WorksheetView.prototype.af_deleteCellsInTable = function (tableName, optionType) { var t = this; var ws = this.model; var tablePart = ws.autoFilters._getFilterByDisplayName(tableName); if (!tablePart || (tablePart && !tablePart.Ref)) { return false; } var deleteCellsAndShiftLeftTop = function (arn, type) { var isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, type, "delCell", true); if (isCheckChangeAutoFilter === false) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); if (isCheckChangeAutoFilter === true) { t.model.autoFilters.isEmptyAutoFilters(arn, type); } var preDeleteAction = function () { t.cellCommentator.updateCommentsDependencies(false, type, arn); }; var res; var range; if (type === c_oAscInsertOptions.InsertCellsAndShiftRight) { range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); res = range.deleteCellsShiftLeft(preDeleteAction); } else { arn = t.model.autoFilters.checkDeleteAllRowsFormatTable(arn, true); range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); res = range.deleteCellsShiftUp(preDeleteAction); } if (res) { t.objectRender.updateDrawingObject(true, type, arn); t._onUpdateFormatTable(range, false, true); } History.EndTransaction(); }; var changedRange = new asc_Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2); t._isLockedCells(changedRange, null, callback); }; var deleteTableCallback = function (ref) { if (!window['AscCommonExcel'].filteringMode) { return false; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.isEmptyAutoFilters(ref); var cleanRange = t.model.getRange3(ref.r1, ref.c1, ref.r2, ref.c2); cleanRange.cleanAll(); t.cellCommentator.deleteCommentsRange(cleanRange.bbox); t._onUpdateFormatTable(ref, false, true); History.EndTransaction(); }; t._isLockedCells(ref, null, callback); }; var newActiveRange = this.model.selectionRange.getLast().clone(); var val = null; switch (optionType) { case c_oAscDeleteOptions.DeleteColumns: { newActiveRange.r1 = tablePart.Ref.r1; newActiveRange.r2 = tablePart.Ref.r2; val = c_oAscDeleteOptions.DeleteCellsAndShiftLeft; break; } case c_oAscDeleteOptions.DeleteRows: { newActiveRange.c1 = tablePart.Ref.c1; newActiveRange.c2 = tablePart.Ref.c2; val = c_oAscDeleteOptions.DeleteCellsAndShiftTop; break; } case c_oAscDeleteOptions.DeleteTable: { deleteTableCallback(tablePart.Ref.clone()); break; } } if (val !== null) { deleteCellsAndShiftLeftTop(newActiveRange, val); } }; WorksheetView.prototype.af_changeDisplayNameTable = function (tableName, newName) { this.model.autoFilters.changeDisplayNameTable(tableName, newName); }; WorksheetView.prototype.af_checkInsDelCells = function (activeRange, val, prop, isFromFormatTable) { var ws = this.model; var res = true; if (!window['AscCommonExcel'].filteringMode) { if(val === c_oAscInsertOptions.InsertCellsAndShiftRight || val === c_oAscInsertOptions.InsertColumns){ return false; }else if(val === c_oAscDeleteOptions.DeleteCellsAndShiftLeft || val === c_oAscDeleteOptions.DeleteColumns){ return false; } } var intersectionTableParts = ws.autoFilters.getTableIntersectionRange(activeRange); var isPartTablePartsUnderRange = ws.autoFilters._isPartTablePartsUnderRange(activeRange); var isPartTablePartsRightRange = ws.autoFilters.isPartTablePartsRightRange(activeRange); var isOneTableIntersection = intersectionTableParts && intersectionTableParts.length === 1 ? intersectionTableParts[0] : null; var checkInsCells = function () { switch (val) { case c_oAscInsertOptions.InsertCellsAndShiftDown: { if (isFromFormatTable) { //если внизу находится часть форматированной таблицы или это часть форматированной таблицы if (isPartTablePartsUnderRange) { res = false; } else if (isOneTableIntersection !== null && !(isOneTableIntersection.Ref.c1 === activeRange.c1 && isOneTableIntersection.Ref.c2 === activeRange.c2)) { res = false; } } else { if (isPartTablePartsUnderRange) { res = false; } else if (intersectionTableParts && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscInsertOptions.InsertCellsAndShiftRight: { //если справа находится часть форматированной таблицы или это часть форматированной таблицы if (isFromFormatTable) { if (isPartTablePartsRightRange) { res = false; } } else { if (isPartTablePartsRightRange) { res = false; } else if (intersectionTableParts && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscInsertOptions.InsertColumns: { break; } case c_oAscInsertOptions.InsertRows: { break; } } }; var checkDelCells = function () { switch (val) { case c_oAscDeleteOptions.DeleteCellsAndShiftTop: { if (isFromFormatTable) { if (isPartTablePartsUnderRange) { res = false; } } else { if (isPartTablePartsUnderRange) { res = false; } else if (!isOneTableIntersection && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscDeleteOptions.DeleteCellsAndShiftLeft: { if (isFromFormatTable) { if (isPartTablePartsRightRange) { res = false; } } else { if (isPartTablePartsRightRange) { res = false; } else if (!isOneTableIntersection && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscDeleteOptions.DeleteColumns: { break; } case c_oAscDeleteOptions.DeleteRows: { break; } } }; prop === "insCell" ? checkInsCells() : checkDelCells(); if (res === false) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); } return res; }; WorksheetView.prototype.af_setDisableProps = function (tablePart, formatTableInfo) { var selectionRange = this.model.selectionRange; var lastRange = selectionRange.getLast(); var activeCell = selectionRange.activeCell; if (!tablePart) { return false; } var refTable = tablePart.Ref; var refTableContainsActiveRange = selectionRange.isSingleRange() && refTable.containsRange(lastRange); //если курсор стоит в нижней строке, то разрешаем добавление нижней строки formatTableInfo.isInsertRowBelow = (refTableContainsActiveRange && ((tablePart.TotalsRowCount === null && activeCell.row === refTable.r2) || (tablePart.TotalsRowCount !== null && activeCell.row === refTable.r2 - 1))); //если курсор стоит в правом столбце, то разрешаем добавление одного столбца правее formatTableInfo.isInsertColumnRight = (refTableContainsActiveRange && activeCell.col === refTable.c2); //если внутри находится вся активная область или если выходит активная область за границу справа formatTableInfo.isInsertColumnLeft = refTableContainsActiveRange; //если внутри находится вся активная область(кроме строки заголовков) или если выходит активная область за границу снизу formatTableInfo.isInsertRowAbove = (refTableContainsActiveRange && ((lastRange.r1 > refTable.r1 && tablePart.HeaderRowCount === null) || (lastRange.r1 >= refTable.r1 && tablePart.HeaderRowCount !== null))); //если есть заголовок, и в данных всего одна строка //todo пределать все проверки HeaderRowCount на вызов функции isHeaderRow var dataRange = tablePart.getRangeWithoutHeaderFooter(); if((tablePart.isHeaderRow() || tablePart.isTotalsRow()) && dataRange.r1 === dataRange.r2 && lastRange.r1 === lastRange.r2 && dataRange.r1 === lastRange.r1) { formatTableInfo.isDeleteRow = false; } else { formatTableInfo.isDeleteRow = refTableContainsActiveRange && !(lastRange.r1 <= refTable.r1 && lastRange.r2 >= refTable.r1 && null === tablePart.HeaderRowCount); } formatTableInfo.isDeleteColumn = true; formatTableInfo.isDeleteTable = true; if (!window['AscCommonExcel'].filteringMode) { formatTableInfo.isDeleteColumn = false; formatTableInfo.isInsertColumnRight = false; formatTableInfo.isInsertColumnLeft = false; } }; WorksheetView.prototype.af_convertTableToRange = function (tableName) { var t = this; if (!window['AscCommonExcel'].filteringMode) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.workbook.dependencyFormulas.lockRecal(); t.model.autoFilters.convertTableToRange(tableName); t._onUpdateFormatTable(tableRange, false, true); t.model.workbook.dependencyFormulas.unlockRecal(); History.EndTransaction(); }; var table = t.model.autoFilters._getFilterByDisplayName(tableName); var tableRange = null !== table ? table.Ref : null; var lockRange = tableRange; var callBackLockedDefNames = function (isSuccess) { if (false === isSuccess) { return; } t._isLockedCells(lockRange, null, callback); }; //лочим данный именованный диапазон var defNameId = t.model.workbook.dependencyFormulas.getDefNameByName(tableName, t.model.getId()); defNameId = defNameId ? defNameId.getNodeId() : null; t._isLockedDefNames(callBackLockedDefNames, defNameId); }; WorksheetView.prototype.af_changeTableRange = function (tableName, range, callbackAfterChange) { var t = this; if(typeof range === "string"){ range = AscCommonExcel.g_oRangeCache.getAscRange(range); } if (!window['AscCommonExcel'].filteringMode) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.changeTableRange(tableName, range); t._onUpdateFormatTable(range, false, true); //TODO добавить перерисовку таблицы и перерисовку шаблонов History.EndTransaction(); if(callbackAfterChange){ callbackAfterChange(); } }; //TODO возможно не стоит лочить весь диапазон. проверить: когда один ползователь меняет диапазон, другой снимает а/ф с ф/т. в этом случае в deleteAutoFilter передавать не range а имя ф/т var table = t.model.autoFilters._getFilterByDisplayName(tableName); var tableRange = null !== table ? table.Ref : null; var lockRange = range; if (null !== tableRange) { var r1 = tableRange.r1 < range.r1 ? tableRange.r1 : range.r1; var r2 = tableRange.r2 > range.r2 ? tableRange.r2 : range.r2; var c1 = tableRange.c1 < range.c1 ? tableRange.c1 : range.c1; var c2 = tableRange.c2 > range.c2 ? tableRange.c2 : range.c2; lockRange = new Asc.Range(c1, r1, c2, r2); } var callBackLockedDefNames = function (isSuccess) { if (false === isSuccess) { return; } t._isLockedCells(lockRange, null, callback); }; //лочим данный именованный диапазон при смене размера ф/т var defNameId = t.model.workbook.dependencyFormulas.getDefNameByName(tableName, t.model.getId()); defNameId = defNameId ? defNameId.getNodeId() : null; t._isLockedDefNames(callBackLockedDefNames, defNameId); }; WorksheetView.prototype.af_checkChangeRange = function (range) { var res = null; var intersectionTables = this.model.autoFilters.getTableIntersectionRange(range); if (0 < intersectionTables.length) { var tablePart = intersectionTables[0]; if (range.isOneCell()) { res = c_oAscError.ID.FTChangeTableRangeError } else if (range.r1 !== tablePart.Ref.r1)//первая строка таблицы не равна первой строке выделенного диапазона { res = c_oAscError.ID.FTChangeTableRangeError; } else if (intersectionTables.length !== 1)//выделено несколько таблиц { res = c_oAscError.ID.FTRangeIncludedOtherTables; } else if (this.model.AutoFilter && this.model.AutoFilter.Ref && this.model.AutoFilter.Ref.isIntersect(range)) { res = c_oAscError.ID.FTChangeTableRangeError; } } else { res = c_oAscError.ID.FTChangeTableRangeError; } return res; }; // Convert coordinates methods WorksheetView.prototype.ConvertXYToLogic = function (x, y) { x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var c = this.visibleRange.c1, cFrozen, widthDiff; var r = this.visibleRange.r1, rFrozen, heightDiff; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; if (x < this.cellsLeft + widthDiff && 0 !== widthDiff) { c = 0; } rFrozen = this.topLeftFrozenCell.getRow0(); heightDiff = this.rows[rFrozen].top - this.rows[0].top; if (y < this.cellsTop + heightDiff && 0 !== heightDiff) { r = 0; } } x += this.cols[c].left - this.cellsLeft - this.cellsLeft; y += this.rows[r].top - this.cellsTop - this.cellsTop; x *= asc_getcvt(1/*pt*/, 3/*mm*/, this._getPPIX()); y *= asc_getcvt(1/*pt*/, 3/*mm*/, this._getPPIY()); return {X: x, Y: y}; }; WorksheetView.prototype.ConvertLogicToXY = function (xL, yL) { xL *= asc_getcvt(3/*mm*/, 1/*pt*/, this._getPPIX()); yL *= asc_getcvt(3/*mm*/, 1/*pt*/, this._getPPIY()); var c = this.visibleRange.c1, cFrozen, widthDiff = 0; var r = this.visibleRange.r1, rFrozen, heightDiff = 0; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; if (xL < widthDiff && 0 !== widthDiff) { c = 0; widthDiff = 0; } rFrozen = this.topLeftFrozenCell.getRow0(); heightDiff = this.rows[rFrozen].top - this.rows[0].top; if (yL < heightDiff && 0 !== heightDiff) { r = 0; heightDiff = 0; } } xL -= (this.cols[c].left - widthDiff - this.cellsLeft - this.cellsLeft); yL -= (this.rows[r].top - heightDiff - this.cellsTop - this.cellsTop); xL *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); yL *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); return {X: xL, Y: yL}; }; //------------------------------------------------------------export--------------------------------------------------- window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window["AscCommonExcel"].CellFlags = CellFlags; window["AscCommonExcel"].WorksheetView = WorksheetView; })(window);
cell/view/WorksheetView.js
/* * (c) Copyright Ascensio System SIA 2010-2017 * * This program is a free software product. You can redistribute it and/or * modify it under the terms of the GNU Affero General Public License (AGPL) * version 3 as published by the Free Software Foundation. In accordance with * Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect * that Ascensio System SIA expressly excludes the warranty of non-infringement * of any third-party rights. * * This program is distributed WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For * details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html * * You can contact Ascensio System SIA at Lubanas st. 125a-25, Riga, Latvia, * EU, LV-1021. * * The interactive user interfaces in modified source and object code versions * of the Program must display Appropriate Legal Notices, as required under * Section 5 of the GNU AGPL version 3. * * Pursuant to Section 7(b) of the License you must retain the original Product * logo when distributing the program. Pursuant to Section 7(e) we decline to * grant you any rights under trademark law for use of our trademarks. * * All the Product's GUI elements, including illustrations and icon sets, as * well as technical writing content are licensed under the terms of the * Creative Commons Attribution-ShareAlike 4.0 International. See the License * terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode * */ "use strict"; (/** * @param {Window} window * @param {undefined} undefined */ function (window, undefined) { /* * Import * ----------------------------------------------------------------------------- */ var CellValueType = AscCommon.CellValueType; var c_oAscBorderStyles = AscCommon.c_oAscBorderStyles; var c_oAscBorderType = AscCommon.c_oAscBorderType; var c_oAscLockTypes = AscCommon.c_oAscLockTypes; var c_oAscFormatPainterState = AscCommon.c_oAscFormatPainterState; var c_oAscPrintDefaultSettings = AscCommon.c_oAscPrintDefaultSettings; var AscBrowser = AscCommon.AscBrowser; var CColor = AscCommon.CColor; var fSortAscending = AscCommon.fSortAscending; var parserHelp = AscCommon.parserHelp; var gc_nMaxDigCountView = AscCommon.gc_nMaxDigCountView; var gc_nMaxRow0 = AscCommon.gc_nMaxRow0; var gc_nMaxCol0 = AscCommon.gc_nMaxCol0; var gc_nMaxRow = AscCommon.gc_nMaxRow; var gc_nMaxCol = AscCommon.gc_nMaxCol; var History = AscCommon.History; var asc = window["Asc"]; var asc_applyFunction = AscCommonExcel.applyFunction; var asc_calcnpt = asc.calcNearestPt; var asc_getcvt = asc.getCvtRatio; var asc_floor = asc.floor; var asc_ceil = asc.ceil; var asc_obj2Color = asc.colorObjToAscColor; var asc_typeof = asc.typeOf; var asc_incDecFonSize = asc.incDecFonSize; var asc_debug = asc.outputDebugStr; var asc_Range = asc.Range; var asc_CMM = AscCommonExcel.asc_CMouseMoveData; var asc_VR = AscCommonExcel.VisibleRange; var asc_CFont = AscCommonExcel.asc_CFont; var asc_CFill = AscCommonExcel.asc_CFill; var asc_CCellInfo = AscCommonExcel.asc_CCellInfo; var asc_CHyperlink = asc.asc_CHyperlink; var asc_CPageOptions = asc.asc_CPageOptions; var asc_CPageSetup = asc.asc_CPageSetup; var asc_CPageMargins = asc.asc_CPageMargins; var asc_CPagePrint = AscCommonExcel.CPagePrint; var asc_CAutoFilterInfo = AscCommonExcel.asc_CAutoFilterInfo; var c_oTargetType = AscCommonExcel.c_oTargetType; var c_oAscCanChangeColWidth = AscCommonExcel.c_oAscCanChangeColWidth; var c_oAscLockTypeElemSubType = AscCommonExcel.c_oAscLockTypeElemSubType; var c_oAscLockTypeElem = AscCommonExcel.c_oAscLockTypeElem; var c_oAscGraphicOption = AscCommonExcel.c_oAscGraphicOption; var c_oAscError = asc.c_oAscError; var c_oAscMergeOptions = asc.c_oAscMergeOptions; var c_oAscInsertOptions = asc.c_oAscInsertOptions; var c_oAscDeleteOptions = asc.c_oAscDeleteOptions; var c_oAscBorderOptions = asc.c_oAscBorderOptions; var c_oAscCleanOptions = asc.c_oAscCleanOptions; var c_oAscSelectionType = asc.c_oAscSelectionType; var c_oAscSelectionDialogType = asc.c_oAscSelectionDialogType; var c_oAscAutoFilterTypes = asc.c_oAscAutoFilterTypes; var c_oAscChangeTableStyleInfo = asc.c_oAscChangeTableStyleInfo; var c_oAscChangeSelectionFormatTable = asc.c_oAscChangeSelectionFormatTable; var asc_CSelectionMathInfo = AscCommonExcel.asc_CSelectionMathInfo; var vector_koef = AscCommonExcel.vector_koef; /* * Constants * ----------------------------------------------------------------------------- */ /** * header styles * @const */ var kHeaderDefault = 0; var kHeaderActive = 1; var kHeaderHighlighted = 2; /** * cursor styles * @const */ var kCurDefault = "default"; var kCurCorner = "pointer"; var kCurColSelect = "pointer"; var kCurColResize = "col-resize"; var kCurRowSelect = "pointer"; var kCurRowResize = "row-resize"; // Курсор для автозаполнения var kCurFillHandle = "crosshair"; // Курсор для гиперссылки var kCurHyperlink = "pointer"; // Курсор для перемещения области выделения var kCurMove = "move"; var kCurSEResize = "se-resize"; var kCurNEResize = "ne-resize"; var kCurAutoFilter = "pointer"; var kCurCells = ''; var kCurFormatPainterExcel = ''; if (AscBrowser.isIE) { // Пути указаны относительно html в меню, не надо их исправлять // и коммитить на пути относительно тестового меню var cursorRetina = AscBrowser.isRetina ? '_2x' : ''; cursorRetina = ''; // ToDo 2x cursors kCurCells = 'url(../../../../sdkjs/common/Images/plus' + cursorRetina + '.cur), pointer'; kCurFormatPainterExcel = 'url(../../../../sdkjs/common/Images/plus_copy' + cursorRetina + '.cur), pointer'; } else if (AscBrowser.isOpera) { kCurCells = 'cell'; kCurFormatPainterExcel = 'pointer'; } else { // ToDo 2x cursors /*if (AscBrowser.isRetina) { kCurCells = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAcCAYAAAByDd+UAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAGtJREFUeNpidHFxYSAS/Ccgz0iMIUwMdAYspGrYvXs3Ct/V1ZUk/XT34aiFoxYOfgtZiChBqFUSDXBJg16CkFvy4AKwEmk0ldIuDokt9YdcbcFCbE09ZGv8UQtHLRxCJQ2xgNSSZcB9CBBgAA9FEd4uFbt8AAAAAElFTkSuQmCC') 12 12, pointer"; kCurFormatPainterExcel = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACoAAAAqCAYAAADFw8lbAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAASFJREFUeNrsmU0SgyAMhQnD0eDUcre4KU5EwMQpf0pW2kX7zePlJVpARDVD6YHZcAZQjGH1qJDW2tO9HhmSwpre3ouLwCnvfbgEPQOkUkqZjt7LVoC01kK4hkY5KoYMSoYyPSAJTPLYewQ+C5JTphUkBUx9NswIjbNRqixwDM6Jltj827Zlm6jk0Vwz1VYUOOpxxBJ79KfUUc45Dix670/HT7LyNppaehRSDcWFrAqaOM6sDegkGmVxvsBSJUtergZa+NEDlqNkM0VjLyZ8CJxMrTaZQhoAwOmepAZIvm/kh7uLov/a81DSUG96XE57NJ44TyfVnWff+AJigbbxKNdDD7an7ynKzTXRhr+aaYEu0AX6tckk3dyXorlpMssfYvsAnpmCy8p26IoAAAAASUVORK5CYII=') 12 25, pointer"; } else {*/ kCurCells = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAYAAAAfSC3RAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAFJJREFUeNpidHFxYcAC/qPxGdEVMDHgALt37wZjXACnRkKA/hpZsAQEMYHFwAAM1f+kApAeipzK4OrqijU6cMnBNDJSNQEMznjECnAFCgwABBgAcX1BU/hbd0sAAAAASUVORK5CYII=') 6 6, pointer"; kCurFormatPainterExcel = "url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAUCAYAAABiS3YzAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAK1JREFUeNrUk+ESxBAMhG3Hm+GpeTfF0Eld0uLcj9uZTP3xdZMsxBjVRhXYsRNora2n5HSxbjLGtKPSX7uqCiHkD1adUlcfLnMdKw6zq94plXbOiVskKm1575GAF1iS6DQBSjECdUp+gFcoJ9LyBe6B09BuluCA09A8fwCK7AHsopiljCxOBLY5xVnVO2KWd779W/uKy2qLk5DjVyhGwz+qn7T/P1D9FPRVnQIMABDnBAmTp4GtAAAAAElFTkSuQmCC') 6 12, pointer"; //} } var kNewLine = "\n"; var kMaxAutoCompleteCellEdit = 20000; function CacheElement() { if (!(this instanceof CacheElement)) { return new CacheElement(); } this.columnsWithText = {}; // Колонки, в которых есть текст this.columns = {}; this.erased = {}; return this; } function Cache() { if (!(this instanceof Cache)) { return new Cache(); } this.rows = {}; this.sectors = []; this.reset = function () { this.rows = {}; this.sectors = []; }; // Structure of cache // // cache : { // // rows : { // 0 : { // columns : { // 0 : { // text : { // cellHA : String, // cellVA : String, // cellW : Number, // color : String, // metrics : TextMetrics, // sideL : Number, // sideR : Number, // state : StringRenderInternalState // } // } // }, // erased : { // 1 : true, 2 : true // } // } // }, // // sectors: [ // 0 : Range // ] // // } } function CellFlags() { this.wrapText = false; this.shrinkToFit = false; this.merged = null; this.textAlign = null; } CellFlags.prototype.clone = function () { var oRes = new CellFlags(); oRes.wrapText = this.wrapText; oRes.shrinkToFit = this.shrinkToFit; oRes.merged = this.merged ? this.merged.clone() : null; oRes.textAlign = this.textAlign; return oRes; }; CellFlags.prototype.isMerged = function () { return null !== this.merged; }; function CellBorderObject(borders, mergeInfo, col, row) { this.borders = borders; this.mergeInfo = mergeInfo; this.col = col; this.row = row; } CellBorderObject.prototype.isMerge = function () { return null != this.mergeInfo; }; CellBorderObject.prototype.getLeftBorder = function () { if (!this.borders || (this.isMerge() && (this.col !== this.mergeInfo.c1 || this.col - 1 !== this.mergeInfo.c2))) { return null; } return this.borders.l; }; CellBorderObject.prototype.getRightBorder = function () { if (!this.borders || (this.isMerge() && (this.col - 1 !== this.mergeInfo.c1 || this.col !== this.mergeInfo.c2))) { return null; } return this.borders.r; }; CellBorderObject.prototype.getTopBorder = function () { if (!this.borders || (this.isMerge() && (this.row !== this.mergeInfo.r1 || this.row - 1 !== this.mergeInfo.r2))) { return null; } return this.borders.t; }; CellBorderObject.prototype.getBottomBorder = function () { if (!this.borders || (this.isMerge() && (this.row - 1 !== this.mergeInfo.r1 || this.row !== this.mergeInfo.r2))) { return null; } return this.borders.b; }; /** * Widget for displaying and editing Worksheet object * ----------------------------------------------------------------------------- * @param {Worksheet} model Worksheet * @param {AscCommonExcel.asc_CHandlersList} handlers Event handlers * @param {Object} buffers DrawingContext + Overlay * @param {AscCommonExcel.StringRender} stringRender StringRender * @param {Number} maxDigitWidth Максимальный размер цифры * @param {CCollaborativeEditing} collaborativeEditing * @param {Object} settings Settings * * @constructor * @memberOf Asc */ function WorksheetView(model, handlers, buffers, stringRender, maxDigitWidth, collaborativeEditing, settings) { this.settings = settings; this.vspRatio = 1.275; this.handlers = handlers; this.model = model; this.buffers = buffers; this.drawingCtx = this.buffers.main; this.overlayCtx = this.buffers.overlay; this.drawingGraphicCtx = this.buffers.mainGraphic; this.overlayGraphicCtx = this.buffers.overlayGraphic; this.shapeCtx = this.buffers.shapeCtx; this.shapeOverlayCtx = this.buffers.shapeOverlayCtx; this.stringRender = stringRender; // Флаг, сигнализирует о том, что мы сделали resize, но это не активный лист (поэтому как только будем показывать, нужно перерисовать и пересчитать кеш) this.updateResize = false; // Флаг, сигнализирует о том, что мы сменили zoom, но это не активный лист (поэтому как только будем показывать, нужно перерисовать и пересчитать кеш) this.updateZoom = false; // ToDo Флаг-заглушка, для того, чтобы на mobile не было изменения высоты строк при zoom (по правильному высота просто не должна меняться) this.notUpdateRowHeight = false; this.cache = new Cache(); //---member declaration--- // Максимальная ширина числа из 0,1,2...,9, померенная в нормальном шрифте(дефалтовый для книги) в px(целое) // Ecma-376 Office Open XML Part 1, пункт 18.3.1.13 this.maxDigitWidth = maxDigitWidth; this.defaultColWidthChars = 0; this.defaultColWidth = 0; this.defaultRowHeight = 0; this.defaultRowDescender = 0; this.headersLeft = 0; this.headersTop = 0; this.headersWidth = 0; this.headersHeight = 0; this.headersHeightByFont = 0; // Размер по шрифту (размер без скрытия заголовков) this.cellsLeft = 0; this.cellsTop = 0; this.cols = []; this.rows = []; this.width_1px = 0; this.width_2px = 0; this.width_3px = 0; this.width_4px = 0; this.width_padding = 0; this.height_1px = 0; this.height_2px = 0; this.height_3px = 0; this.height_4px = 0; this.highlightedCol = -1; this.highlightedRow = -1; this.topLeftFrozenCell = null; // Верхняя ячейка для закрепления диапазона this.visibleRange = new asc_Range(0, 0, 0, 0); this.isChanged = false; this.isCellEditMode = false; this.isFormulaEditMode = false; this.isChartAreaEditMode = false; this.lockDraw = false; this.isSelectOnShape = false; // Выделен shape this.stateFormatPainter = c_oAscFormatPainterState.kOff; this.selectionDialogType = c_oAscSelectionDialogType.None; this.isSelectionDialogMode = false; this.copyActiveRange = null; this.startCellMoveResizeRange = null; this.startCellMoveResizeRange2 = null; this.moveRangeDrawingObjectTo = null; // Координаты ячейки начала перемещения диапазона this.startCellMoveRange = null; // Дипазон перемещения this.activeMoveRange = null; // Range fillHandle this.activeFillHandle = null; // Горизонтальное (0) или вертикальное (1) направление автозаполнения this.fillHandleDirection = -1; // Зона автозаполнения this.fillHandleArea = -1; this.nRowsCount = 0; this.nColsCount = 0; // Массив ячеек для текущей формулы this.arrActiveFormulaRanges = []; this.arrActiveFormulaRangesPosition = -1; this.arrActiveChartRanges = [new AscCommonExcel.SelectionRange(this.model)]; //------------------------ this.collaborativeEditing = collaborativeEditing; this.drawingArea = new AscFormat.DrawingArea(this); this.cellCommentator = new AscCommonExcel.CCellCommentator(this); this.objectRender = null; this._init(); return this; } WorksheetView.prototype.getCellVisibleRange = function (col, row) { var vr, offsetX = 0, offsetY = 0, cFrozen, rFrozen; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0() - 1; rFrozen = this.topLeftFrozenCell.getRow0() - 1; if (col <= cFrozen && row <= rFrozen) { vr = new asc_Range(0, 0, cFrozen, rFrozen); } else if (col <= cFrozen) { vr = new asc_Range(0, this.visibleRange.r1, cFrozen, this.visibleRange.r2); offsetY -= this.rows[rFrozen + 1].top - this.cellsTop; } else if (row <= rFrozen) { vr = new asc_Range(this.visibleRange.c1, 0, this.visibleRange.c2, rFrozen); offsetX -= this.cols[cFrozen + 1].left - this.cellsLeft; } else { vr = this.visibleRange; offsetX -= this.cols[cFrozen + 1].left - this.cellsLeft; offsetY -= this.rows[rFrozen + 1].top - this.cellsTop; } } else { vr = this.visibleRange; } offsetX += this.cols[vr.c1].left - this.cellsLeft; offsetY += this.rows[vr.r1].top - this.cellsTop; return vr.contains(col, row) ? new asc_VR(vr, offsetX, offsetY) : null; }; WorksheetView.prototype.getCellMetrics = function (col, row) { var vr, nColSize, nRowSize; if (vr = this.getCellVisibleRange(col, row)) { nColSize = this.getColSize(col); nRowSize = this.getRowSize(row); if (nColSize && nRowSize) { return { left: nColSize.left - vr.offsetX, top: nRowSize.top - vr.offsetY, width: nColSize.width, height: nRowSize.height }; } } return null; }; WorksheetView.prototype.getColSize = function (col) { return (col >= 0 && col < this.cols.length) ? this.cols[col] : null; }; WorksheetView.prototype.getRowSize = function (row) { return (row >= 0 && row < this.rows.length) ? this.rows[row] : null; }; WorksheetView.prototype.getFrozenCell = function () { return this.topLeftFrozenCell; }; WorksheetView.prototype.getVisibleRange = function () { return this.visibleRange; }; WorksheetView.prototype.updateVisibleRange = function () { return this._updateCellsRange(this.getVisibleRange()); }; WorksheetView.prototype.getFirstVisibleCol = function (allowPane) { var tmp = 0; if (allowPane && this.topLeftFrozenCell) { tmp = this.topLeftFrozenCell.getCol0(); } return this.visibleRange.c1 - tmp; }; WorksheetView.prototype.getLastVisibleCol = function () { return this.visibleRange.c2; }; WorksheetView.prototype.getFirstVisibleRow = function (allowPane) { var tmp = 0; if (allowPane && this.topLeftFrozenCell) { tmp = this.topLeftFrozenCell.getRow0(); } return this.visibleRange.r1 - tmp; }; WorksheetView.prototype.getLastVisibleRow = function () { return this.visibleRange.r2; }; WorksheetView.prototype.getHorizontalScrollRange = function () { var ctxW = this.drawingCtx.getWidth() - this.cellsLeft; for (var w = 0, i = this.cols.length - 1; i >= 0; --i) { w += this.cols[i].width; if (w > ctxW) { break; } } return i; // Диапазон скрола должен быть меньше количества столбцов, чтобы не было прибавления столбцов при перетаскивании бегунка }; WorksheetView.prototype.getVerticalScrollRange = function () { var ctxH = this.drawingCtx.getHeight() - this.cellsTop; for (var h = 0, i = this.rows.length - 1; i >= 0; --i) { h += this.rows[i].height; if (h > ctxH) { break; } } return i; // Диапазон скрола должен быть меньше количества строк, чтобы не было прибавления строк при перетаскивании бегунка }; WorksheetView.prototype.getCellsOffset = function (units) { var u = units >= 0 && units <= 3 ? units : 0; return { left: this.cellsLeft * asc_getcvt(1/*pt*/, u, this._getPPIX()), top: this.cellsTop * asc_getcvt(1/*pt*/, u, this._getPPIY()) }; }; WorksheetView.prototype.getCellLeft = function (column, units) { if (column >= 0 && column < this.cols.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.cols[column].left * asc_getcvt(1/*pt*/, u, this._getPPIX()); } return null; }; WorksheetView.prototype.getCellTop = function (row, units) { if (row >= 0 && row < this.rows.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.rows[row].top * asc_getcvt(1/*pt*/, u, this._getPPIY()); } return null; }; WorksheetView.prototype.getCellLeftRelative = function (col, units) { if (col < 0 || col >= this.cols.length) { return null; } // С учетом видимой области var offsetX = 0; if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0(); offsetX = (col < cFrozen) ? 0 : this.cols[this.visibleRange.c1].left - this.cols[cFrozen].left; } else { offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; } var u = units >= 0 && units <= 3 ? units : 0; return (this.cols[col].left - offsetX) * asc_getcvt(1/*pt*/, u, this._getPPIX()); }; WorksheetView.prototype.getCellTopRelative = function (row, units) { if (row < 0 || row >= this.rows.length) { return null; } // С учетом видимой области var offsetY = 0; if (this.topLeftFrozenCell) { var rFrozen = this.topLeftFrozenCell.getRow0(); offsetY = (row < rFrozen) ? 0 : this.rows[this.visibleRange.r1].top - this.rows[rFrozen].top; } else { offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; } var u = units >= 0 && units <= 3 ? units : 0; return (this.rows[row].top - offsetY) * asc_getcvt(1/*pt*/, u, this._getPPIY()); }; WorksheetView.prototype.getColumnWidth = function (index, units) { if (index >= 0 && index < this.cols.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.cols[index].width * asc_getcvt(1/*pt*/, u, this._getPPIX()); } return null; }; WorksheetView.prototype.getSelectedColumnWidthInSymbols = function () { var c, res = null; var range = this.model.selectionRange.getLast(); for (c = range.c1; c <= range.c2 && c < this.cols.length; ++c) { if (null === res) { res = this.cols[c].charCount; } else if (res !== this.cols[c].charCount) { return null; } } // ToDo сравнить с default для проверки выделения всего return res; }; WorksheetView.prototype.getSelectedRowHeight = function () { var r, res = null; var range = this.model.selectionRange.getLast(); for (r = range.r1; r <= range.r2 && r < this.rows.length; ++r) { if (null === res) { res = this.rows[r].heightReal; } else if (res !== this.rows[r].heightReal) { return null; } } // ToDo сравнить с default для проверки выделения всего return res; }; WorksheetView.prototype.getRowHeight = function (index, units) { if (index >= 0 && index < this.rows.length) { var u = units >= 0 && units <= 3 ? units : 0; return this.rows[index].height * asc_getcvt(1/*pt*/, u, this._getPPIY()); } return null; }; WorksheetView.prototype.getSelectedRange = function () { // ToDo multiselect ? var lastRange = this.model.selectionRange.getLast(); return this._getRange(lastRange.c1, lastRange.r1, lastRange.c2, lastRange.r2); }; WorksheetView.prototype.resize = function (isUpdate) { if (isUpdate) { this._initCellsArea(AscCommonExcel.recalcType.newLines); this._normalizeViewRange(); this._prepareCellTextMetricsCache(); this.updateResize = false; this.objectRender.resizeCanvas(); } else { this.updateResize = true; } return this; }; WorksheetView.prototype.getZoom = function () { return this.drawingCtx.getZoom(); }; WorksheetView.prototype.changeZoom = function (isUpdate) { if (isUpdate) { this.notUpdateRowHeight = true; this.cleanSelection(); this._initCellsArea(AscCommonExcel.recalcType.recalc); this._normalizeViewRange(); this._cleanCellsTextMetricsCache(); // ToDo fix with sheetView->topLeftCell on open var ar = this._getSelection().getLast(); if (ar.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, ar.c2 + 1); } if (ar.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, ar.r2 + 1); } var d = this._calcActiveRangeOffset(); if (d.deltaX) { this.scrollHorizontal(d.deltaX); } if (d.deltaY) { this.scrollVertical(d.deltaY); } this._prepareCellTextMetricsCache(); this.cellCommentator.updateActiveComment(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("toggleAutoCorrectOptions", null, true); this.handlers.trigger("onDocumentPlaceChanged"); this.objectRender.drawingArea.reinitRanges(); this.updateZoom = false; this.notUpdateRowHeight = false; } else { this.updateZoom = true; } return this; }; WorksheetView.prototype.changeZoomResize = function () { this.cleanSelection(); this._initCellsArea(AscCommonExcel.recalcType.full); this._normalizeViewRange(); this._cleanCellsTextMetricsCache(); // ToDo fix with sheetView->topLeftCell on open var ar = this._getSelection().getLast(); if (ar.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, ar.c2 + 1); } if (ar.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, ar.r2 + 1); } var d = this._calcActiveRangeOffset(); if (d.deltaX) { this.scrollHorizontal(d.deltaX); } if (d.deltaY) { this.scrollVertical(d.deltaY); } this._prepareCellTextMetricsCache(); this.cellCommentator.updateActiveComment(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("onDocumentPlaceChanged"); this.objectRender.drawingArea.reinitRanges(); this.updateResize = false; this.updateZoom = false; }; WorksheetView.prototype.getSheetViewSettings = function () { return this.model.getSheetViewSettings(); }; WorksheetView.prototype.getFrozenPaneOffset = function (noX, noY) { var offsetX = 0, offsetY = 0, c = this.cols, r = this.rows; if (this.topLeftFrozenCell) { if (!noX) { var cFrozen = this.topLeftFrozenCell.getCol0(); offsetX = c[cFrozen].left - c[0].left; } if (!noY) { var rFrozen = this.topLeftFrozenCell.getRow0(); offsetY = r[rFrozen].top - r[0].top; } } return {offsetX: offsetX, offsetY: offsetY}; }; // mouseX - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.changeColumnWidth = function (col, x2, mouseX) { var t = this; x2 *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIX()); // Учитываем координаты точки, где мы начали изменение размера x2 += mouseX; var offsetFrozenX = 0; var c1 = t.visibleRange.c1; if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0() - 1; if (0 <= cFrozen) { if (col < c1) { c1 = 0; } else { offsetFrozenX = t.cols[cFrozen].left + t.cols[cFrozen].width - t.cols[0].left; } } } var offsetX = t.cols[c1].left - t.cellsLeft; offsetX -= offsetFrozenX; var x1 = t.cols[col].left - offsetX - this.width_1px; var w = Math.max(x2 - x1, 0); if (w === t.cols[col].width) { return; } var cc = Math.min(this.model.colWidthToCharCount(w), Asc.c_oAscMaxColumnWidth); var onChangeWidthCallback = function (isSuccess) { if (false === isSuccess) { return; } t.model.setColWidth(cc, col, col); t._cleanCache(new asc_Range(0, 0, t.cols.length - 1, t.rows.length - 1)); t.changeWorksheet("update", {reinitRanges: true}); t._updateVisibleColsCount(); t.cellCommentator.updateActiveComment(); t.cellCommentator.updateAreaComments(); if (t.objectRender) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.ColumnResize, col: col}); t.objectRender.rebuildChartGraphicObjects([new asc_Range(col, 0, col, gc_nMaxRow0)]); } }; this._isLockedAll(onChangeWidthCallback); }; // mouseY - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.changeRowHeight = function (row, y2, mouseY) { var t = this; y2 *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIY()); // Учитываем координаты точки, где мы начали изменение размера y2 += mouseY; var offsetFrozenY = 0; var r1 = t.visibleRange.r1; if (this.topLeftFrozenCell) { var rFrozen = this.topLeftFrozenCell.getRow0() - 1; if (0 <= rFrozen) { if (row < r1) { r1 = 0; } else { offsetFrozenY = t.rows[rFrozen].top + t.rows[rFrozen].height - t.rows[0].top; } } } var offsetY = t.rows[r1].top - t.cellsTop; offsetY -= offsetFrozenY; var y1 = t.rows[row].top - offsetY - this.height_1px; var newHeight = Math.min(t.maxRowHeight, Math.max(y2 - y1, 0)); if (newHeight === t.rows[row].height) { return; } var onChangeHeightCallback = function (isSuccess) { if (false === isSuccess) { return; } t.model.setRowHeight(newHeight, row, row, true); t.model.autoFilters.reDrawFilter(null, row); t._cleanCache(new asc_Range(0, row, t.cols.length - 1, row)); t.changeWorksheet("update", {reinitRanges: true}); t._updateVisibleRowsCount(); t.cellCommentator.updateActiveComment(); t.cellCommentator.updateAreaComments(); if (t.objectRender) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: row}); t.objectRender.rebuildChartGraphicObjects([new asc_Range(0, row, gc_nMaxCol0, row)]); } }; this._isLockedAll(onChangeHeightCallback); }; // Проверяет, есть ли числовые значения в диапазоне WorksheetView.prototype._hasNumberValueInActiveRange = function () { var cell, cellType, isNumberFormat, arrCols = [], arrRows = []; // ToDo multiselect var selectionRange = this.model.selectionRange.getLast(); if (selectionRange.isOneCell()) { // Для одной ячейки не стоит ничего делать return null; } var mergedRange = this.model.getMergedByCell(selectionRange.r1, selectionRange.c1); if (mergedRange && mergedRange.isEqual(selectionRange)) { // Для одной ячейки не стоит ничего делать return null; } for (var c = selectionRange.c1; c <= selectionRange.c2; ++c) { for (var r = selectionRange.r1; r <= selectionRange.r2; ++r) { cell = this._getCellTextCache(c, r); if (cell) { // Нашли не пустую ячейку, проверим формат cellType = cell.cellType; isNumberFormat = (null == cellType || CellValueType.Number === cellType); if (isNumberFormat) { arrCols.push(c); arrRows.push(r); } } } } if (0 !== arrCols.length) { // Делаем массивы уникальными и сортируем arrCols = arrCols.filter(AscCommon.fOnlyUnique); arrRows = arrRows.filter(AscCommon.fOnlyUnique); return {arrCols: arrCols.sort(fSortAscending), arrRows: arrRows.sort(fSortAscending)}; } else { return null; } }; // Автодополняет формулу диапазоном, если это возможно WorksheetView.prototype.autoCompleteFormula = function (functionName) { var t = this; // ToDo autoComplete with multiselect var activeCell = this.model.selectionRange.activeCell; var ar = this.model.selectionRange.getLast(); var arCopy = null; var arHistorySelect = ar.clone(true); var vr = this.visibleRange; // Первая верхняя не числовая ячейка var topCell = null; // Первая левая не числовая ячейка var leftCell = null; var r = activeCell.row - 1; var c = activeCell.col - 1; var cell, cellType, isNumberFormat; var result = {}; // Проверим, есть ли числовые значения в диапазоне var hasNumber = this._hasNumberValueInActiveRange(); var val, text; if (hasNumber) { var i; // Есть ли значения в последней строке и столбце var hasNumberInLastColumn = (ar.c2 === hasNumber.arrCols[hasNumber.arrCols.length - 1]); var hasNumberInLastRow = (ar.r2 === hasNumber.arrRows[hasNumber.arrRows.length - 1]); // Нужно уменьшить зону выделения (если она реально уменьшилась) var startCol = hasNumber.arrCols[0]; var startRow = hasNumber.arrRows[0]; // Старые границы диапазона var startColOld = ar.c1; var startRowOld = ar.r1; // Нужно ли перерисовывать var bIsUpdate = false; if (startColOld !== startCol || startRowOld !== startRow) { bIsUpdate = true; } if (true === hasNumberInLastRow && true === hasNumberInLastColumn) { bIsUpdate = true; } if (bIsUpdate) { this.cleanSelection(); ar.c1 = startCol; ar.r1 = startRow; if (false === ar.contains(activeCell.col, activeCell.row)) { // Передвинуть первую ячейку в выделении activeCell.col = startCol; activeCell.row = startRow; } if (true === hasNumberInLastRow && true === hasNumberInLastColumn) { // Мы расширяем диапазон if (1 === hasNumber.arrRows.length) { // Одна строка или только в последней строке есть значения... (увеличиваем вправо) ar.c2 += 1; } else { // Иначе вводим в строку вниз ar.r2 += 1; } } this._drawSelection(); } arCopy = ar.clone(true); var functionAction = null; var changedRange = null; if (false === hasNumberInLastColumn && false === hasNumberInLastRow) { // Значений нет ни в последней строке ни в последнем столбце (значит нужно сделать формулы в каждой последней ячейке) changedRange = [new asc_Range(hasNumber.arrCols[0], arCopy.r2, hasNumber.arrCols[hasNumber.arrCols.length - 1], arCopy.r2), new asc_Range(arCopy.c2, hasNumber.arrRows[0], arCopy.c2, hasNumber.arrRows[hasNumber.arrRows.length - 1])]; functionAction = function () { // Пройдемся по последней строке for (i = 0; i < hasNumber.arrCols.length; ++i) { c = hasNumber.arrCols[i]; cell = t._getVisibleCell(c, arCopy.r2); text = t._getCellTitle(c, arCopy.r1) + ":" + t._getCellTitle(c, arCopy.r2 - 1); val = "=" + functionName + "(" + text + ")"; // ToDo - при вводе формулы в заголовок автофильтра надо писать "0" cell.setValue(val); } // Пройдемся по последнему столбцу for (i = 0; i < hasNumber.arrRows.length; ++i) { r = hasNumber.arrRows[i]; cell = t._getVisibleCell(arCopy.c2, r); text = t._getCellTitle(arCopy.c1, r) + ":" + t._getCellTitle(arCopy.c2 - 1, r); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } // Значение в правой нижней ячейке cell = t._getVisibleCell(arCopy.c2, arCopy.r2); text = t._getCellTitle(arCopy.c1, arCopy.r2) + ":" + t._getCellTitle(arCopy.c2 - 1, arCopy.r2); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); }; } else if (true === hasNumberInLastRow && false === hasNumberInLastColumn) { // Есть значения только в последней строке (значит нужно заполнить только последнюю колонку) changedRange = new asc_Range(arCopy.c2, hasNumber.arrRows[0], arCopy.c2, hasNumber.arrRows[hasNumber.arrRows.length - 1]); functionAction = function () { // Пройдемся по последнему столбцу for (i = 0; i < hasNumber.arrRows.length; ++i) { r = hasNumber.arrRows[i]; cell = t._getVisibleCell(arCopy.c2, r); text = t._getCellTitle(arCopy.c1, r) + ":" + t._getCellTitle(arCopy.c2 - 1, r); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } }; } else if (false === hasNumberInLastRow && true === hasNumberInLastColumn) { // Есть значения только в последнем столбце (значит нужно заполнить только последнюю строчку) changedRange = new asc_Range(hasNumber.arrCols[0], arCopy.r2, hasNumber.arrCols[hasNumber.arrCols.length - 1], arCopy.r2); functionAction = function () { // Пройдемся по последней строке for (i = 0; i < hasNumber.arrCols.length; ++i) { c = hasNumber.arrCols[i]; cell = t._getVisibleCell(c, arCopy.r2); text = t._getCellTitle(c, arCopy.r1) + ":" + t._getCellTitle(c, arCopy.r2 - 1); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } }; } else { // Есть значения и в последнем столбце, и в последней строке if (1 === hasNumber.arrRows.length) { changedRange = new asc_Range(arCopy.c2, arCopy.r2, arCopy.c2, arCopy.r2); functionAction = function () { // Одна строка или только в последней строке есть значения... cell = t._getVisibleCell(arCopy.c2, arCopy.r2); // ToDo вводить в первое свободное место, а не сразу за диапазоном text = t._getCellTitle(arCopy.c1, arCopy.r2) + ":" + t._getCellTitle(arCopy.c2 - 1, arCopy.r2); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); }; } else { changedRange = new asc_Range(hasNumber.arrCols[0], arCopy.r2, hasNumber.arrCols[hasNumber.arrCols.length - 1], arCopy.r2); functionAction = function () { // Иначе вводим в строку вниз for (i = 0; i < hasNumber.arrCols.length; ++i) { c = hasNumber.arrCols[i]; cell = t._getVisibleCell(c, arCopy.r2); // ToDo вводить в первое свободное место, а не сразу за диапазоном text = t._getCellTitle(c, arCopy.r1) + ":" + t._getCellTitle(c, arCopy.r2 - 1); val = "=" + functionName + "(" + text + ")"; cell.setValue(val); } }; } } var onAutoCompleteFormula = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.SetSelection(arHistorySelect.clone()); History.SetSelectionRedo(arCopy.clone()); History.StartTransaction(); asc_applyFunction(functionAction); t.handlers.trigger("selectionMathInfoChanged", t.getSelectionMathInfo()); History.EndTransaction(); }; // Можно ли применять автоформулу this._isLockedCells(changedRange, /*subType*/null, onAutoCompleteFormula); result.notEditCell = true; return result; } // Ищем первую ячейку с числом for (; r >= vr.r1; --r) { cell = this._getCellTextCache(activeCell.col, r); if (cell) { // Нашли не пустую ячейку, проверим формат cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (isNumberFormat) { // Это число, мы нашли то, что искали topCell = { c: activeCell.col, r: r, isFormula: cell.isFormula }; // смотрим вторую ячейку if (topCell.isFormula && r - 1 >= vr.r1) { cell = this._getCellTextCache(activeCell.col, r - 1); if (cell && cell.isFormula) { topCell.isFormulaSeq = true; } } break; } } } // Проверим, первой все равно должна быть колонка if (null === topCell || topCell.r !== activeCell.row - 1 || topCell.isFormula && !topCell.isFormulaSeq) { for (; c >= vr.c1; --c) { cell = this._getCellTextCache(c, activeCell.row); if (cell) { // Нашли не пустую ячейку, проверим формат cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (isNumberFormat) { // Это число, мы нашли то, что искали leftCell = { r: activeCell.row, c: c }; break; } } if (null !== topCell) { // Если это не первая ячейка слева от текущей и мы нашли верхнюю, то дальше не стоит искать break; } } } if (leftCell) { // Идем влево до первой не числовой ячейки --c; for (; c >= 0; --c) { cell = this._getCellTextCache(c, activeCell.row); if (!cell) { // Могут быть еще не закешированные данные this._addCellTextToCache(c, activeCell.row); cell = this._getCellTextCache(c, activeCell.row); if (!cell) { break; } } cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (!isNumberFormat) { break; } } // Мы ушли чуть дальше ++c; // Диапазон или только 1 ячейка if (activeCell.col - 1 !== c) { // Диапазон result = new asc_Range(c, leftCell.r, activeCell.col - 1, leftCell.r); } else { // Одна ячейка result = new asc_Range(c, leftCell.r, c, leftCell.r); } this._fixSelectionOfMergedCells(result); if (result.c1 === result.c2 && result.r1 === result.r2) { result.text = this._getCellTitle(result.c1, result.r1); } else { result.text = this._getCellTitle(result.c1, result.r1) + ":" + this._getCellTitle(result.c2, result.r2); } return result; } if (topCell) { // Идем вверх до первой не числовой ячейки --r; for (; r >= 0; --r) { cell = this._getCellTextCache(activeCell.col, r); if (!cell) { // Могут быть еще не закешированные данные this._addCellTextToCache(activeCell.col, r); cell = this._getCellTextCache(activeCell.col, r); if (!cell) { break; } } cellType = cell.cellType; isNumberFormat = (null === cellType || CellValueType.Number === cellType); if (!isNumberFormat) { break; } } // Мы ушли чуть дальше ++r; // Диапазон или только 1 ячейка if (activeCell.row - 1 !== r) { // Диапазон result = new asc_Range(topCell.c, r, topCell.c, activeCell.row - 1); } else { // Одна ячейка result = new asc_Range(topCell.c, r, topCell.c, r); } this._fixSelectionOfMergedCells(result); if (result.c1 === result.c2 && result.r1 === result.r2) { result.text = this._getCellTitle(result.c1, result.r1); } else { result.text = this._getCellTitle(result.c1, result.r1) + ":" + this._getCellTitle(result.c2, result.r2); } return result; } }; // ----- Initialization ----- WorksheetView.prototype._init = function () { this._initConstValues(); this._initWorksheetDefaultWidth(); this._initPane(); this._initCellsArea(AscCommonExcel.recalcType.full); this.model.setTableStyleAfterOpen(); this.model.setDirtyConditionalFormatting(null); this.model.initPivotTables(); this.model.updatePivotTablesStyle(null); this._cleanCellsTextMetricsCache(); this._prepareCellTextMetricsCache(); // initializing is completed this.handlers.trigger("initialized"); }; WorksheetView.prototype._prepareComments = function () { // ToDo возможно не нужно это делать именно тут.. if (0 < this.model.aComments.length) { this.model.workbook.handlers.trigger("asc_onAddComments", this.model.aComments); } }; WorksheetView.prototype._prepareDrawingObjects = function () { this.objectRender = new AscFormat.DrawingObjects(); if (!window["NATIVE_EDITOR_ENJINE"] || window['IS_NATIVE_EDITOR'] || window['DoctRendererMode']) { this.objectRender.init(this); } }; WorksheetView.prototype._initWorksheetDefaultWidth = function () { // Теперь рассчитываем число px var defaultColWidthChars = this.model.charCountToModelColWidth(this.model.getBaseColWidth()); var defaultColWidthPx = this.model.modelColWidthToColWidth(defaultColWidthChars) * asc_getcvt(1/*pt*/, 0/*px*/, 96); // Делаем кратным 8 (http://support.microsoft.com/kb/214123) defaultColWidthPx = asc_ceil(defaultColWidthPx / 8) * 8; this.defaultColWidthChars = this.model.colWidthToCharCount(defaultColWidthPx * asc_getcvt(0/*px*/, 1/*pt*/, 96)); AscCommonExcel.oDefaultMetrics.ColWidthChars = this.model.charCountToModelColWidth(this.defaultColWidthChars); this.defaultColWidth = this.model.modelColWidthToColWidth(AscCommonExcel.oDefaultMetrics.ColWidthChars); var defaultFontSize = this.model.getDefaultFontSize(); // ToDo разобраться со значениями this._setFont(undefined, this.model.getDefaultFontName(), defaultFontSize); var tm = this._roundTextMetrics(this.stringRender.measureString("A")); this.headersHeightByFont = tm.height + this.height_1px; this.maxRowHeight = asc_calcnpt(Asc.c_oAscMaxRowHeight, this._getPPIY()); this.defaultRowDescender = this._calcRowDescender(defaultFontSize); AscCommonExcel.oDefaultMetrics.RowHeight = this.defaultRowHeight = Math.min(this.maxRowHeight, this.model.getDefaultHeight() || this.headersHeightByFont); // Инициализируем число колонок и строк (при открытии). Причем нужно поставить на 1 больше, // чтобы могли показать последнюю строку/столбец (http://bugzilla.onlyoffice.com/show_bug.cgi?id=23513) this.nColsCount = Math.min(this.model.getColsCount() + 1, gc_nMaxCol); this.nRowsCount = Math.min(this.model.getRowsCount() + 1, gc_nMaxRow); }; WorksheetView.prototype._initConstValues = function () { var ppiX = this._getPPIX(); var ppiY = this._getPPIY(); this.width_1px = asc_calcnpt(0, ppiX, 1/*px*/); this.width_2px = asc_calcnpt(0, ppiX, 2/*px*/); this.width_3px = asc_calcnpt(0, ppiX, 3/*px*/); this.width_4px = asc_calcnpt(0, ppiX, 4/*px*/); this.width_padding = asc_calcnpt(0, ppiX, this.settings.cells.padding/*px*/); this.height_1px = asc_calcnpt(0, ppiY, 1/*px*/); this.height_2px = asc_calcnpt(0, ppiY, 2/*px*/); this.height_3px = asc_calcnpt(0, ppiY, 3/*px*/); this.height_4px = asc_calcnpt(0, ppiY, 4/*px*/); }; WorksheetView.prototype._initCellsArea = function (type) { // calculate rows heights and visible rows if (!(window["NATIVE_EDITOR_ENJINE"] && this.notUpdateRowHeight)) { this._calcHeaderRowHeight(); this._calcHeightRows(type); } this.visibleRange.r2 = 0; this._calcVisibleRows(); this._updateVisibleRowsCount(/*skipScrolReinit*/true); // calculate columns widths and visible columns if (!(window["NATIVE_EDITOR_ENJINE"] && this.notUpdateRowHeight)) { this._calcHeaderColumnWidth(); this._calcWidthColumns(type); } this.visibleRange.c2 = 0; this._calcVisibleColumns(); this._updateVisibleColsCount(/*skipScrolReinit*/true); }; WorksheetView.prototype._initPane = function () { var pane = this.model.sheetViews[0].pane; if ( null !== pane && pane.isInit() ) { this.topLeftFrozenCell = pane.topLeftFrozenCell; this.visibleRange.r1 = this.topLeftFrozenCell.getRow0(); this.visibleRange.c1 = this.topLeftFrozenCell.getCol0(); } }; WorksheetView.prototype._getSelection = function () { return (this.isFormulaEditMode) ? this.arrActiveFormulaRanges[this.arrActiveFormulaRangesPosition] : this.model.selectionRange; }; WorksheetView.prototype._fixVisibleRange = function ( range ) { var tmp; if ( null !== this.topLeftFrozenCell ) { tmp = this.topLeftFrozenCell.getRow0(); if ( range.r1 < tmp ) { range.r1 = tmp; tmp = this._findVisibleRow( range.r1, +1 ); if ( 0 < tmp ) { range.r1 = tmp; } } tmp = this.topLeftFrozenCell.getCol0(); if ( range.c1 < tmp ) { range.c1 = tmp; tmp = this._findVisibleCol( range.c1, +1 ); if ( 0 < tmp ) { range.c1 = tmp; } } } }; /** * Вычисляет ширину столбца для отрисовки * @param {Number} w Ширина столбца в символах * @returns {Number} Ширина столбца в пунктах (pt) */ WorksheetView.prototype._calcColWidth = function ( w ) { var t = this; var res = {}; var useDefault = w === undefined || w === null || w === -1; var width; res.width = useDefault ? t.defaultColWidth : (width = t.model.modelColWidthToColWidth(w), (width < t.width_1px ? 0 : width)); res.innerWidth = Math.max( res.width - this.width_padding * 2 - this.width_1px, 0 ); res.charCount = this.model.colWidthToCharCount(res.width); return res; }; /** * Вычисляет Descender строки * @param {Number} fontSize * @returns {Number} */ WorksheetView.prototype._calcRowDescender = function ( fontSize ) { return asc_calcnpt( fontSize * (this.vspRatio - 1), this._getPPIY() ); // ToDo возможно стоит тоже использовать 96 }; /** Вычисляет ширину колонки заголовков (в pt) */ WorksheetView.prototype._calcHeaderColumnWidth = function () { if (false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { this.headersWidth = 0; } else { // Ширина колонки заголовков считается - max число знаков в строке - перевести в символы - перевести в пикселы var numDigit = Math.max(AscCommonExcel.calcDecades(this.visibleRange.r2 + 1), 3); var nCharCount = this.model.charCountToModelColWidth(numDigit); this.headersWidth = this.model.modelColWidthToColWidth(nCharCount); } this.cellsLeft = this.headersLeft + this.headersWidth; }; /** Вычисляет высоту строки заголовков (в pt) */ WorksheetView.prototype._calcHeaderRowHeight = function () { if ( false === this.model.sheetViews[0].asc_getShowRowColHeaders() ) { this.headersHeight = 0; } else //this.headersHeight = this.model.getDefaultHeight() || this.defaultRowHeight; { this.headersHeight = this.headersHeightByFont; } //this.headersHeight = asc_calcnpt( this.settings.header.fontSize * this.vspRatio, this._getPPIY() ); this.cellsTop = this.headersTop + this.headersHeight; }; /** * Вычисляет ширину и позицию колонок (в pt) * @param {AscCommonExcel.recalcType} type */ WorksheetView.prototype._calcWidthColumns = function (type) { var x = this.cellsLeft; var visibleW = this.drawingCtx.getWidth(); var maxColObjects = this.objectRender ? this.objectRender.getMaxColRow().col : -1; var l = Math.max(this.model.getColsCount() + 1, this.nColsCount, maxColObjects); var i = 0, w, column, isBestFit, hiddenW = 0; // Берем дефалтовую ширину документа var defaultWidth = this.model.getDefaultWidth(); defaultWidth = (typeof defaultWidth === "number" && defaultWidth >= 0) ? defaultWidth : -1; if (AscCommonExcel.recalcType.full === type) { this.cols = []; } else if (AscCommonExcel.recalcType.newLines === type) { i = this.cols.length; x = this.cols[i - 1].left + this.cols[i - 1].width; } for (; ((AscCommonExcel.recalcType.recalc !== type) ? i < l || x + hiddenW < visibleW : i < this.cols.length) && i < gc_nMaxCol; ++i) { // Получаем свойства колонки column = this.model._getColNoEmptyWithAll(i); if (!column) { w = defaultWidth; // Используем дефолтное значение isBestFit = true; // Это уже оптимальная ширина } else if (column.getHidden()) { w = 0; // Если столбец скрытый, ширину выставляем 0 isBestFit = false; hiddenW += this._calcColWidth(column.width).width; } else { w = column.width || defaultWidth; isBestFit = !!(column.BestFit || (null === column.BestFit && null === column.CustomWidth)); } this.cols[i] = this._calcColWidth(w); this.cols[i].isCustomWidth = !isBestFit; this.cols[i].left = x; x += this.cols[i].width; } this.nColsCount = Math.min(Math.max(this.nColsCount, i), gc_nMaxCol); }; /** * Вычисляет высоту и позицию строк (в pt) * @param {AscCommonExcel.recalcType} type */ WorksheetView.prototype._calcHeightRows = function (type) { var t = this; var y = this.cellsTop; var visibleH = this.drawingCtx.getHeight(); var maxRowObjects = this.objectRender ? this.objectRender.getMaxColRow().row : -1; var l = Math.max(this.model.getRowsCount() + 1, this.nRowsCount, maxRowObjects); var defaultH = this.defaultRowHeight; var i = 0, h, hR, isCustomHeight, row, hiddenH = 0; if (AscCommonExcel.recalcType.full === type) { this.rows = []; } else if (AscCommonExcel.recalcType.newLines === type) { i = this.rows.length; y = this.rows[i - 1].top + this.rows[i - 1].height; } // ToDo calc all rows (not visible) for (; ((AscCommonExcel.recalcType.recalc !== type) ? i < l || y + hiddenH < visibleH : i < this.rows.length) && i < gc_nMaxRow; ++i) { this.model._getRowNoEmptyWithAll(i, function(row){ if (!row) { h = -1; // Будет использоваться дефолтная высота строки isCustomHeight = false; } else if (row.getHidden()) { hR = h = 0; // Скрытая строка, высоту выставляем 0 isCustomHeight = true; hiddenH += row.h > 0 ? row.h - t.height_1px : defaultH; } else { isCustomHeight = row.getCustomHeight(); // Берем высоту из модели, если она custom(баг 15618), либо дефолтную if (row.h > 0 && (isCustomHeight || row.getCalcHeight())) { hR = row.h; h = hR / 0.75; h = (h | h) * 0.75; // 0.75 - это размер 1px в pt (можно было 96/72) } else { h = -1; } } }); h = h < 0 ? (hR = defaultH) : h; this.rows[i] = { top: y, height: h, // Высота с точностью до 1 px heightReal: hR, // Реальная высота из файла (может быть не кратна 1 px, в Excel можно выставить через меню строки) descender: this.defaultRowDescender, isCustomHeight: isCustomHeight }; y += this.rows[i].height; } this.nRowsCount = Math.min(Math.max(this.nRowsCount, i), gc_nMaxRow); }; /** Вычисляет диапазон индексов видимых колонок */ WorksheetView.prototype._calcVisibleColumns = function () { var l = this.cols.length; var w = this.drawingCtx.getWidth(); var sumW = this.topLeftFrozenCell ? this.cols[this.topLeftFrozenCell.getCol0()].left : this.cellsLeft; for (var i = this.visibleRange.c1, f = false; i < l && sumW < w; ++i) { sumW += this.cols[i].width; f = true; } this.visibleRange.c2 = i - (f ? 1 : 0); }; /** Вычисляет диапазон индексов видимых строк */ WorksheetView.prototype._calcVisibleRows = function () { var l = this.rows.length; var h = this.drawingCtx.getHeight(); var sumH = this.topLeftFrozenCell ? this.rows[this.topLeftFrozenCell.getRow0()].top : this.cellsTop; for (var i = this.visibleRange.r1, f = false; i < l && sumH < h; ++i) { sumH += this.rows[i].height; f = true; } this.visibleRange.r2 = i - (f ? 1 : 0); }; /** Обновляет позицию колонок (в pt) */ WorksheetView.prototype._updateColumnPositions = function () { var x = this.cellsLeft; for (var l = this.cols.length, i = 0; i < l; ++i) { this.cols[i].left = x; x += this.cols[i].width; } }; /** Обновляет позицию строк (в pt) */ WorksheetView.prototype._updateRowPositions = function () { var y = this.cellsTop; for (var l = this.rows.length, i = 0; i < l; ++i) { this.rows[i].top = y; y += this.rows[i].height; } }; /** * Добавляет колонки, пока общая ширина листа не превысит rightSide * @param {Number} rightSide Правая граница */ WorksheetView.prototype._appendColumns = function (rightSide) { var i = this.cols.length; var lc = this.cols[i - 1]; var done = false; for (var x = lc.left + lc.width; i < gc_nMaxCol && (x < rightSide || !done); ++i) { if (x >= rightSide) { // add +1 column at the end and exit cycle done = true; } this.cols[i] = this._calcColWidth(this.model.getColWidth(i)); this.cols[i].left = x; x += this.cols[i].width; this.isChanged = true; } this.nColsCount = Math.min(Math.max(this.nColsCount, i), gc_nMaxCol); }; /** Устанаваливает видимый диапазон ячеек максимально возможным */ WorksheetView.prototype._normalizeViewRange = function () { var t = this; var vr = t.visibleRange; var w = t.drawingCtx.getWidth() - t.cellsLeft; var h = t.drawingCtx.getHeight() - t.cellsTop; var c = t.cols; var r = t.rows; var vw = c[vr.c2].left + c[vr.c2].width - c[vr.c1].left; var vh = r[vr.r2].top + r[vr.r2].height - r[vr.r1].top; var i; var offsetFrozen = t.getFrozenPaneOffset(); vw += offsetFrozen.offsetX; vh += offsetFrozen.offsetY; if ( vw < w ) { for ( i = vr.c1 - 1; i >= 0; --i ) { vw += c[i].width; if ( vw > w ) { break; } } vr.c1 = i + 1; if ( vr.c1 >= vr.c2 ) { vr.c1 = vr.c2 - 1; } if ( vr.c1 < 0 ) { vr.c1 = 0; } } if ( vh < h ) { for ( i = vr.r1 - 1; i >= 0; --i ) { vh += r[i].height; if ( vh > h ) { break; } } vr.r1 = i + 1; if ( vr.r1 >= vr.r2 ) { vr.r1 = vr.r2 - 1; } if ( vr.r1 < 0 ) { vr.r1 = 0; } } }; // ----- Drawing for print ----- WorksheetView.prototype.calcPagesPrint = function(pageOptions, printOnlySelection, indexWorksheet, arrPages) { var t = this; var range; var maxCols = this.model.getColsCount(); var maxRows = this.model.getRowsCount(); var lastC = -1, lastR = -1; // ToDo print each range on new page (now only last) var selectionRange = printOnlySelection ? this.model.selectionRange.getLast() : null; var bFitToWidth = false; var bFitToHeight = false; if (null === selectionRange) { range = new asc_Range(0, 0, maxCols, maxRows); this._prepareCellTextMetricsCache(range); var rowCache, rightSide, curRow = -1, skipRow = false; this.model._forEachCell(function(cell) { var c = cell.nCol; var r = cell.nRow; if (curRow !== r) { curRow = r; skipRow = t.height_1px > t.rows[r].height; rowCache = t._getRowCache(r); } if(!skipRow && !(t.width_1px > t.cols[c].width)){ var style = cell.getStyle(); if (style && ((style.fill && style.fill.notEmpty()) || (style.border && style.border.notEmpty()))) { lastC = Math.max(lastC, c); lastR = Math.max(lastR, r); } if (rowCache && rowCache.columnsWithText[c]) { rightSide = 0; var ct = t._getCellTextCache(c, r); if (ct !== undefined) { if (!ct.flags.isMerged() && !ct.flags.wrapText) { rightSide = ct.sideR; } lastC = Math.max(lastC, c + rightSide); lastR = Math.max(lastR, r); } } } }); var maxCell = this.model.autoFilters.getMaxColRow(); lastC = Math.max(lastC, maxCell.col); lastR = Math.max(lastR, maxCell.row); maxCols = lastC + 1; maxRows = lastR + 1; // Получаем максимальную колонку/строку для изображений/чатов maxCell = this.objectRender.getMaxColRow(); maxCols = Math.max(maxCols, maxCell.col); maxRows = Math.max(maxRows, maxCell.row); } else { maxCols = selectionRange.c2 + 1; maxRows = selectionRange.r2 + 1; range = new asc_Range(0, 0, maxCols, maxRows); this._prepareCellTextMetricsCache(range); } var pageMargins, pageSetup, pageGridLines, pageHeadings; if (pageOptions instanceof asc_CPageOptions) { pageMargins = pageOptions.asc_getPageMargins(); pageSetup = pageOptions.asc_getPageSetup(); pageGridLines = pageOptions.asc_getGridLines(); pageHeadings = pageOptions.asc_getHeadings(); } var pageWidth, pageHeight, pageOrientation; if (pageSetup instanceof asc_CPageSetup) { pageWidth = pageSetup.asc_getWidth(); pageHeight = pageSetup.asc_getHeight(); pageOrientation = pageSetup.asc_getOrientation(); bFitToWidth = pageSetup.asc_getFitToWidth(); bFitToHeight = pageSetup.asc_getFitToHeight(); } var pageLeftField, pageRightField, pageTopField, pageBottomField; if (pageMargins instanceof asc_CPageMargins) { pageLeftField = Math.max(pageMargins.asc_getLeft(), c_oAscPrintDefaultSettings.MinPageLeftField); pageRightField = Math.max(pageMargins.asc_getRight(), c_oAscPrintDefaultSettings.MinPageRightField); pageTopField = Math.max(pageMargins.asc_getTop(), c_oAscPrintDefaultSettings.MinPageTopField); pageBottomField = Math.max(pageMargins.asc_getBottom(), c_oAscPrintDefaultSettings.MinPageBottomField); } if (null == pageGridLines) { pageGridLines = c_oAscPrintDefaultSettings.PageGridLines; } if (null == pageHeadings) { pageHeadings = c_oAscPrintDefaultSettings.PageHeadings; } if (null == pageWidth) { pageWidth = c_oAscPrintDefaultSettings.PageWidth; } if (null == pageHeight) { pageHeight = c_oAscPrintDefaultSettings.PageHeight; } if (null == pageOrientation) { pageOrientation = c_oAscPrintDefaultSettings.PageOrientation; } if (null == pageLeftField) { pageLeftField = c_oAscPrintDefaultSettings.PageLeftField; } if (null == pageRightField) { pageRightField = c_oAscPrintDefaultSettings.PageRightField; } if (null == pageTopField) { pageTopField = c_oAscPrintDefaultSettings.PageTopField; } if (null == pageBottomField) { pageBottomField = c_oAscPrintDefaultSettings.PageBottomField; } if (Asc.c_oAscPageOrientation.PageLandscape === pageOrientation) { var tmp = pageWidth; pageWidth = pageHeight; pageHeight = tmp; } if (0 === maxCols || 0 === maxRows) { // Ничего нет, возвращаем пустой массив return null; } else { var pageWidthWithFields = pageWidth - pageLeftField - pageRightField; var pageHeightWithFields = pageHeight - pageTopField - pageBottomField; // 1px offset for borders var leftFieldInPt = pageLeftField / vector_koef + this.width_1px; var topFieldInPt = pageTopField / vector_koef + this.height_1px; var rightFieldInPt = pageRightField / vector_koef + this.width_1px; var bottomFieldInPt = pageBottomField / vector_koef + this.height_1px; if (pageHeadings) { // Рисуем заголовки, нужно чуть сдвинуться leftFieldInPt += this.cellsLeft; topFieldInPt += this.cellsTop; } var pageWidthWithFieldsHeadings = (pageWidth - pageRightField) / vector_koef - leftFieldInPt; var pageHeightWithFieldsHeadings = (pageHeight - pageBottomField) / vector_koef - topFieldInPt; var currentColIndex = (null !== selectionRange) ? selectionRange.c1 : 0; var currentWidth = 0; var currentRowIndex = (null !== selectionRange) ? selectionRange.r1 : 0; var currentHeight = 0; var isCalcColumnsWidth = true; var bIsAddOffset = false; var nCountOffset = 0; while (AscCommonExcel.c_kMaxPrintPages > arrPages.length) { if (currentColIndex === maxCols && currentRowIndex === maxRows) { break; } var newPagePrint = new asc_CPagePrint(); var colIndex = currentColIndex, rowIndex = currentRowIndex; newPagePrint.indexWorksheet = indexWorksheet; newPagePrint.pageWidth = pageWidth; newPagePrint.pageHeight = pageHeight; newPagePrint.pageClipRectLeft = pageLeftField / vector_koef; newPagePrint.pageClipRectTop = pageTopField / vector_koef; newPagePrint.pageClipRectWidth = pageWidthWithFields / vector_koef; newPagePrint.pageClipRectHeight = pageHeightWithFields / vector_koef; newPagePrint.leftFieldInPt = leftFieldInPt; newPagePrint.topFieldInPt = topFieldInPt; newPagePrint.rightFieldInPt = rightFieldInPt; newPagePrint.bottomFieldInPt = bottomFieldInPt; for (rowIndex = currentRowIndex; rowIndex < maxRows; ++rowIndex) { var currentRowHeight = this.rows[rowIndex].height; if (!bFitToHeight && currentHeight + currentRowHeight > pageHeightWithFieldsHeadings) { // Закончили рисовать страницу break; } if (isCalcColumnsWidth) { for (colIndex = currentColIndex; colIndex < maxCols; ++colIndex) { var currentColWidth = this.cols[colIndex].width; if (bIsAddOffset) { newPagePrint.startOffset = ++nCountOffset; newPagePrint.startOffsetPt = (pageWidthWithFieldsHeadings * newPagePrint.startOffset); currentColWidth -= newPagePrint.startOffsetPt; } if (!bFitToWidth && currentWidth + currentColWidth > pageWidthWithFieldsHeadings && colIndex !== currentColIndex) { break; } currentWidth += currentColWidth; if (!bFitToWidth && currentWidth > pageWidthWithFieldsHeadings && colIndex === currentColIndex) { // Смещаем в селедующий раз ячейку bIsAddOffset = true; ++colIndex; break; } else { bIsAddOffset = false; } } isCalcColumnsWidth = false; if (pageHeadings) { currentWidth += this.cellsLeft; } if (bFitToWidth) { newPagePrint.pageClipRectWidth = Math.max(currentWidth, newPagePrint.pageClipRectWidth); newPagePrint.pageWidth = newPagePrint.pageClipRectWidth * vector_koef + (pageLeftField + pageRightField); } else { newPagePrint.pageClipRectWidth = Math.min(currentWidth, newPagePrint.pageClipRectWidth); } } currentHeight += currentRowHeight; currentWidth = 0; } if (bFitToHeight) { newPagePrint.pageClipRectHeight = Math.max(currentHeight, newPagePrint.pageClipRectHeight); newPagePrint.pageHeight = newPagePrint.pageClipRectHeight * vector_koef + (pageTopField + pageBottomField); } else { newPagePrint.pageClipRectHeight = Math.min(currentHeight, newPagePrint.pageClipRectHeight); } // Нужно будет пересчитывать колонки isCalcColumnsWidth = true; // Рисуем сетку if (pageGridLines) { newPagePrint.pageGridLines = true; } if (pageHeadings) { // Нужно отрисовать заголовки newPagePrint.pageHeadings = true; } newPagePrint.pageRange = new asc_Range(currentColIndex, currentRowIndex, colIndex - 1, rowIndex - 1); if (bIsAddOffset) { // Мы еще не дорисовали колонку colIndex -= 1; } else { nCountOffset = 0; } if (colIndex < maxCols) { // Мы еще не все колонки отрисовали currentColIndex = colIndex; currentHeight = 0; } else { // Мы дорисовали все колонки, нужна новая строка и стартовая колонка currentColIndex = (null !== selectionRange) ? selectionRange.c1 : 0; currentRowIndex = rowIndex; currentHeight = 0; } if (rowIndex === maxRows) { // Мы вышли, т.к. дошли до конца отрисовки по строкам if (colIndex < maxCols) { currentColIndex = colIndex; currentHeight = 0; } else { // Мы дошли до конца отрисовки currentColIndex = colIndex; currentRowIndex = rowIndex; } } arrPages.push(newPagePrint); } } }; WorksheetView.prototype.drawForPrint = function(drawingCtx, printPagesData) { if (null === printPagesData) { // Напечатаем пустую страницу drawingCtx.BeginPage(c_oAscPrintDefaultSettings.PageWidth, c_oAscPrintDefaultSettings.PageHeight); drawingCtx.EndPage(); } else { drawingCtx.BeginPage(printPagesData.pageWidth, printPagesData.pageHeight); drawingCtx.AddClipRect(printPagesData.pageClipRectLeft, printPagesData.pageClipRectTop, printPagesData.pageClipRectWidth, printPagesData.pageClipRectHeight); var offsetCols = printPagesData.startOffsetPt; var range = printPagesData.pageRange; var offsetX = this.cols[range.c1].left - printPagesData.leftFieldInPt + offsetCols; var offsetY = this.rows[range.r1].top - printPagesData.topFieldInPt; var tmpVisibleRange = this.visibleRange; // Сменим visibleRange для прохождения проверок отрисовки this.visibleRange = range; // Нужно отрисовать заголовки if (printPagesData.pageHeadings) { this._drawColumnHeaders(drawingCtx, range.c1, range.c2, /*style*/ undefined, offsetX, printPagesData.topFieldInPt - this.cellsTop); this._drawRowHeaders(drawingCtx, range.r1, range.r2, /*style*/ undefined, printPagesData.leftFieldInPt - this.cellsLeft, offsetY); } // Рисуем сетку if (printPagesData.pageGridLines) { this._drawGrid(drawingCtx, range, offsetX, offsetY, printPagesData.pageWidth / vector_koef, printPagesData.pageHeight / vector_koef); } // Отрисовываем ячейки и бордеры this._drawCellsAndBorders(drawingCtx, range, offsetX, offsetY); var drawingPrintOptions = { ctx: drawingCtx, printPagesData: printPagesData }; this.objectRender.showDrawingObjectsEx(false, null, drawingPrintOptions); this.visibleRange = tmpVisibleRange; drawingCtx.RemoveClipRect(); drawingCtx.EndPage(); } }; // ----- Drawing ----- WorksheetView.prototype.draw = function (lockDraw) { if (lockDraw || this.model.workbook.bCollaborativeChanges || window['IS_NATIVE_EDITOR']) { return this; } this.handlers.trigger("checkLastWork"); this._clean(); this._drawCorner(); this._drawColumnHeaders(null); this._drawRowHeaders(null); this._drawGrid(null); this._drawCellsAndBorders(null); this._drawFrozenPane(); this._drawFrozenPaneLines(); this._fixSelectionOfMergedCells(); this._drawElements(this.af_drawButtons); this.cellCommentator.drawCommentCells(); this.objectRender.showDrawingObjectsEx(true); if (this.overlayCtx) { this._drawSelection(); } return this; }; WorksheetView.prototype._clean = function () { this.drawingCtx .setFillStyle( this.settings.cells.defaultState.background ) .fillRect( 0, 0, this.drawingCtx.getWidth(), this.drawingCtx.getHeight() ); if ( this.overlayCtx ) { this.overlayCtx.clear(); } }; WorksheetView.prototype.drawHighlightedHeaders = function (col, row) { this._activateOverlayCtx(); if (col >= 0 && col !== this.highlightedCol) { this._doCleanHighlightedHeaders(); this.highlightedCol = col; this._drawColumnHeaders(null, col, col, kHeaderHighlighted); } else if (row >= 0 && row !== this.highlightedRow) { this._doCleanHighlightedHeaders(); this.highlightedRow = row; this._drawRowHeaders(null, row, row, kHeaderHighlighted); } this._deactivateOverlayCtx(); return this; }; WorksheetView.prototype.cleanHighlightedHeaders = function () { this._activateOverlayCtx(); this._doCleanHighlightedHeaders(); this._deactivateOverlayCtx(); return this; }; WorksheetView.prototype._activateOverlayCtx = function () { this.drawingCtx = this.buffers.overlay; }; WorksheetView.prototype._deactivateOverlayCtx = function () { this.drawingCtx = this.buffers.main; }; WorksheetView.prototype._doCleanHighlightedHeaders = function () { // ToDo highlighted! var hlc = this.highlightedCol, hlr = this.highlightedRow, arn = this.model.selectionRange.getLast(); var hStyle = this.objectRender.selectedGraphicObjectsExists() ? kHeaderDefault : kHeaderActive; if (hlc >= 0) { if (hlc >= arn.c1 && hlc <= arn.c2) { this._drawColumnHeaders(null, hlc, hlc, hStyle); } else { this._cleanColumnHeaders(hlc); if (hlc + 1 === arn.c1) { this._drawColumnHeaders(null, hlc + 1, hlc + 1, kHeaderActive); } else if (hlc - 1 === arn.c2) { this._drawColumnHeaders(null, hlc - 1, hlc - 1, hStyle); } } this.highlightedCol = -1; } if (hlr >= 0) { if (hlr >= arn.r1 && hlr <= arn.r2) { this._drawRowHeaders(null, hlr, hlr, hStyle); } else { this._cleanRowHeaders(hlr); if (hlr + 1 === arn.r1) { this._drawRowHeaders(null, hlr + 1, hlr + 1, kHeaderActive); } else if (hlr - 1 === arn.r2) { this._drawRowHeaders(null, hlr - 1, hlr - 1, hStyle); } } this.highlightedRow = -1; } }; WorksheetView.prototype._drawActiveHeaders = function () { var vr = this.visibleRange; var range, c1, c2, r1, r2; this._activateOverlayCtx(); for (var i = 0; i < this.model.selectionRange.ranges.length; ++i) { range = this.model.selectionRange.ranges[i]; c1 = Math.max(vr.c1, range.c1); c2 = Math.min(vr.c2, range.c2); r1 = Math.max(vr.r1, range.r1); r2 = Math.min(vr.r2, range.r2); this._drawColumnHeaders(null, c1, c2, kHeaderActive); this._drawRowHeaders(null, r1, r2, kHeaderActive); if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0() - 1; var rFrozen = this.topLeftFrozenCell.getRow0() - 1; if (0 <= cFrozen) { c1 = Math.max(0, range.c1); c2 = Math.min(cFrozen, range.c2); this._drawColumnHeaders(null, c1, c2, kHeaderActive); } if (0 <= rFrozen) { r1 = Math.max(0, range.r1); r2 = Math.min(rFrozen, range.r2); this._drawRowHeaders(null, r1, r2, kHeaderActive); } } } this._deactivateOverlayCtx(); }; WorksheetView.prototype._drawCorner = function () { if (false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { return; } var x2 = this.headersLeft + this.headersWidth; var x1 = x2 - this.headersHeight; var y2 = this.headersTop + this.headersHeight; var y1 = this.headersTop; var dx = 4 * this.width_1px; var dy = 4 * this.height_1px; this._drawHeader(null, this.headersLeft, this.headersTop, this.headersWidth, this.headersHeight, kHeaderDefault, true, -1); this.drawingCtx.beginPath() .moveTo(x2 - dx, y1 + dy) .lineTo(x2 - dx, y2 - dy) .lineTo(x1 + dx, y2 - dy) .lineTo(x2 - dx, y1 + dy) .setFillStyle(this.settings.header.cornerColor) .fill(); }; /** Рисует заголовки видимых колонок */ WorksheetView.prototype._drawColumnHeaders = function (drawingCtx, start, end, style, offsetXForDraw, offsetYForDraw) { if (null === drawingCtx && false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { return; } var vr = this.visibleRange; var c = this.cols; var offsetX = (undefined !== offsetXForDraw) ? offsetXForDraw : c[vr.c1].left - this.cellsLeft; var offsetY = (undefined !== offsetYForDraw) ? offsetYForDraw : this.headersTop; if (null === drawingCtx && this.topLeftFrozenCell && undefined === offsetXForDraw) { var cFrozen = this.topLeftFrozenCell.getCol0(); if (start < vr.c1) { offsetX = c[0].left - this.cellsLeft; } else { offsetX -= c[cFrozen].left - c[0].left; } } if (asc_typeof(start) !== "number") { start = vr.c1; } if (asc_typeof(end) !== "number") { end = vr.c2; } if (style === undefined) { style = kHeaderDefault; } this._setFont(drawingCtx, this.model.getDefaultFontName(), this.model.getDefaultFontSize()); // draw column headers for (var i = start; i <= end; ++i) { this._drawHeader(drawingCtx, c[i].left - offsetX, offsetY, c[i].width, this.headersHeight, style, true, i); } }; /** Рисует заголовки видимых строк */ WorksheetView.prototype._drawRowHeaders = function (drawingCtx, start, end, style, offsetXForDraw, offsetYForDraw) { if (null === drawingCtx && false === this.model.sheetViews[0].asc_getShowRowColHeaders()) { return; } var vr = this.visibleRange; var r = this.rows; var offsetX = (undefined !== offsetXForDraw) ? offsetXForDraw : this.headersLeft; var offsetY = (undefined !== offsetYForDraw) ? offsetYForDraw : r[vr.r1].top - this.cellsTop; if (null === drawingCtx && this.topLeftFrozenCell && undefined === offsetYForDraw) { var rFrozen = this.topLeftFrozenCell.getRow0(); if (start < vr.r1) { offsetY = r[0].top - this.cellsTop; } else { offsetY -= r[rFrozen].top - r[0].top; } } if (asc_typeof(start) !== "number") { start = vr.r1; } if (asc_typeof(end) !== "number") { end = vr.r2; } if (style === undefined) { style = kHeaderDefault; } this._setFont(drawingCtx, this.model.getDefaultFontName(), this.model.getDefaultFontSize()); // draw row headers for (var i = start; i <= end; ++i) { this._drawHeader(drawingCtx, offsetX, r[i].top - offsetY, this.headersWidth, r[i].height, style, false, i); } }; /** * Рисует заголовок, принимает координаты и размеры в pt * @param {DrawingContext} drawingCtx * @param {Number} x Координата левого угла в pt * @param {Number} y Координата левого угла в pt * @param {Number} w Ширина в pt * @param {Number} h Высота в pt * @param {Number} style Стиль заголовка (kHeaderDefault, kHeaderActive, kHeaderHighlighted) * @param {Boolean} isColHeader Тип заголовка: true - колонка, false - строка * @param {Number} index Индекс столбца/строки или -1 */ WorksheetView.prototype._drawHeader = function (drawingCtx, x, y, w, h, style, isColHeader, index) { // Для отрисовки невидимого столбца/строки var isZeroHeader = false; if (-1 !== index) { if (isColHeader) { if (w < this.width_1px) { if (style !== kHeaderDefault) { return; } // Это невидимый столбец isZeroHeader = true; // Отрисуем только границу w = this.width_1px; // Возможно мы уже рисовали границу невидимого столбца (для последовательности невидимых) if (0 < index && 0 === this.cols[index - 1].width) { // Мы уже нарисовали border для невидимой границы return; } } else if (0 < index && 0 === this.cols[index - 1].width) { // Мы уже нарисовали border для невидимой границы (поэтому нужно чуть меньше рисовать для соседнего столбца) w -= this.width_1px; x += this.width_1px; } } else { if (h < this.height_1px) { if (style !== kHeaderDefault) { return; } // Это невидимая строка isZeroHeader = true; // Отрисуем только границу h = this.height_1px; // Возможно мы уже рисовали границу невидимой строки (для последовательности невидимых) if (0 < index && 0 === this.rows[index - 1].height) { // Мы уже нарисовали border для невидимой границы return; } } else if (0 < index && 0 === this.rows[index - 1].height) { // Мы уже нарисовали border для невидимой границы (поэтому нужно чуть меньше рисовать для соседней строки) h -= this.height_1px; y += this.height_1px; } } } var ctx = drawingCtx || this.drawingCtx; var st = this.settings.header.style[style]; var x2 = x + w; var y2 = y + h; var x2WithoutBorder = x2 - this.width_1px; var y2WithoutBorder = y2 - this.height_1px; // background только для видимых if (!isZeroHeader) { // draw background ctx.setFillStyle(st.background) .fillRect(x, y, w, h); } // draw border ctx.setStrokeStyle(st.border) .setLineWidth(1) .beginPath(); if (style !== kHeaderDefault && !isColHeader) { // Select row (top border) ctx.lineHorPrevPx(x, y, x2); } // Right border ctx.lineVerPrevPx(x2, y, y2); // Bottom border ctx.lineHorPrevPx(x, y2, x2); if (style !== kHeaderDefault && isColHeader) { // Select col (left border) ctx.lineVerPrevPx(x, y, y2); } ctx.stroke(); // Для невидимых кроме border-а ничего не рисуем if (isZeroHeader || -1 === index) { return; } // draw text var text = isColHeader ? this._getColumnTitle(index) : this._getRowTitle(index); var sr = this.stringRender; var tm = this._roundTextMetrics(sr.measureString(text)); var bl = y2WithoutBorder - (isColHeader ? this.defaultRowDescender : this.rows[index].descender); var textX = this._calcTextHorizPos(x, x2WithoutBorder, tm, tm.width < w ? AscCommon.align_Center : AscCommon.align_Left); var textY = this._calcTextVertPos(y, y2WithoutBorder, bl, tm, Asc.c_oAscVAlign.Bottom); ctx.AddClipRect(x, y, w, h); ctx.setFillStyle(st.color).fillText(text, textX, textY + tm.baseline, undefined, sr.charWidths); ctx.RemoveClipRect(); }; WorksheetView.prototype._cleanColumnHeaders = function (colStart, colEnd) { var offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; var i, cFrozen = 0; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); offsetX -= this.cols[cFrozen].left - this.cols[0].left; } if (colEnd === undefined) { colEnd = colStart; } var colStartTmp = Math.max(this.visibleRange.c1, colStart); var colEndTmp = Math.min(this.visibleRange.c2, colEnd); for (i = colStartTmp; i <= colEndTmp; ++i) { this.drawingCtx.clearRectByX(this.cols[i].left - offsetX, this.headersTop, this.cols[i].width, this.headersHeight); } if (0 !== cFrozen) { offsetX = this.cols[0].left - this.cellsLeft; // Почистим для pane colStart = Math.max(0, colStart); colEnd = Math.min(cFrozen, colEnd); for (i = colStart; i <= colEnd; ++i) { this.drawingCtx.clearRectByX(this.cols[i].left - offsetX, this.headersTop, this.cols[i].width, this.headersHeight); } } }; WorksheetView.prototype._cleanRowHeaders = function (rowStart, rowEnd) { var offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; var i, rFrozen = 0; if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); offsetY -= this.rows[rFrozen].top - this.rows[0].top; } if (rowEnd === undefined) { rowEnd = rowStart; } var rowStartTmp = Math.max(this.visibleRange.r1, rowStart); var rowEndTmp = Math.min(this.visibleRange.r2, rowEnd); for (i = rowStartTmp; i <= rowEndTmp; ++i) { if (this.height_1px > this.rows[i].height) { continue; } this.drawingCtx.clearRectByY(this.headersLeft, this.rows[i].top - offsetY, this.headersWidth, this.rows[i].height); } if (0 !== rFrozen) { offsetY = this.rows[0].top - this.cellsTop; // Почистим для pane rowStart = Math.max(0, rowStart); rowEnd = Math.min(rFrozen, rowEnd); for (i = rowStart; i <= rowEnd; ++i) { if (this.height_1px > this.rows[i].height) { continue; } this.drawingCtx.clearRectByY(this.headersLeft, this.rows[i].top - offsetY, this.headersWidth, this.rows[i].height); } } }; WorksheetView.prototype._cleanColumnHeadersRect = function () { this.drawingCtx.clearRect(this.cellsLeft, this.headersTop, this.drawingCtx.getWidth() - this.cellsLeft, this.headersHeight); }; /** Рисует сетку таблицы */ WorksheetView.prototype._drawGrid = function (drawingCtx, range, leftFieldInPt, topFieldInPt, width, height) { // Возможно сетку не нужно рисовать (при печати свои проверки) if (null === drawingCtx && false === this.model.sheetViews[0].asc_getShowGridLines()) { return; } if (range === undefined) { range = this.visibleRange; } var ctx = drawingCtx || this.drawingCtx; var c = this.cols; var r = this.rows; var widthCtx = (width) ? width : ctx.getWidth(); var heightCtx = (height) ? height : ctx.getHeight(); var offsetX = (undefined !== leftFieldInPt) ? leftFieldInPt : c[this.visibleRange.c1].left - this.cellsLeft; var offsetY = (undefined !== topFieldInPt) ? topFieldInPt : r[this.visibleRange.r1].top - this.cellsTop; if (null === drawingCtx && this.topLeftFrozenCell) { if (undefined === leftFieldInPt) { var cFrozen = this.topLeftFrozenCell.getCol0(); offsetX -= c[cFrozen].left - c[0].left; } if (undefined === topFieldInPt) { var rFrozen = this.topLeftFrozenCell.getRow0(); offsetY -= r[rFrozen].top - r[0].top; } } var x1 = c[range.c1].left - offsetX; var y1 = r[range.r1].top - offsetY; var x2 = Math.min(c[range.c2].left - offsetX + c[range.c2].width, widthCtx); var y2 = Math.min(r[range.r2].top - offsetY + r[range.r2].height, heightCtx); ctx.setFillStyle(this.settings.cells.defaultState.background) .fillRect(x1, y1, x2 - x1, y2 - y1) .setStrokeStyle(this.settings.cells.defaultState.border) .setLineWidth(1).beginPath(); var i, d, l; for (i = range.c1, d = x1; i <= range.c2 && d <= x2; ++i) { l = c[i].width; d += l; if (l >= this.width_1px) { ctx.lineVerPrevPx(d, y1, y2); } } for (i = range.r1, d = y1; i <= range.r2 && d <= y2; ++i) { l = r[i].height; d += l; if (l >= this.height_1px) { ctx.lineHorPrevPx(x1, d, x2); } } ctx.stroke(); // Clear grid for pivot tables with classic and outline layout var clearRange, pivotRange, clearRanges = this.model.getPivotTablesClearRanges(range); ctx.setFillStyle(this.settings.cells.defaultState.background); for (i = 0; i < clearRanges.length; i += 2) { clearRange = clearRanges[i]; pivotRange = clearRanges[i + 1]; x1 = c[clearRange.c1].left - offsetX + (clearRange.c1 === pivotRange.c1 ? this.width_1px : 0); y1 = r[clearRange.r1].top - offsetY + (clearRange.r1 === pivotRange.r1 ? this.height_1px : 0); x2 = Math.min(c[clearRange.c2].left - offsetX + c[clearRange.c2].width - (clearRange.c2 === pivotRange.c2 ? this.width_1px : 0), widthCtx); y2 = Math.min(r[clearRange.r2].top - offsetY + r[clearRange.r2].height - (clearRange.r2 === pivotRange.r2 ? this.height_1px : 0), heightCtx); ctx.fillRect(x1, y1, x2 - x1, y2 - y1); } }; WorksheetView.prototype._drawCellsAndBorders = function ( drawingCtx, range, offsetXForDraw, offsetYForDraw ) { if ( range === undefined ) { range = this.visibleRange; } var left, top, cFrozen, rFrozen; var offsetX = (undefined === offsetXForDraw) ? this.cols[this.visibleRange.c1].left - this.cellsLeft : offsetXForDraw; var offsetY = (undefined === offsetYForDraw) ? this.rows[this.visibleRange.r1].top - this.cellsTop : offsetYForDraw; if ( null === drawingCtx && this.topLeftFrozenCell ) { if ( undefined === offsetXForDraw ) { cFrozen = this.topLeftFrozenCell.getCol0(); offsetX -= this.cols[cFrozen].left - this.cols[0].left; } if ( undefined === offsetYForDraw ) { rFrozen = this.topLeftFrozenCell.getRow0(); offsetY -= this.rows[rFrozen].top - this.rows[0].top; } } if ( !drawingCtx && !window['IS_NATIVE_EDITOR'] ) { left = this.cols[range.c1].left; top = this.rows[range.r1].top; // set clipping rect to cells area this.drawingCtx.save() .beginPath() .rect( left - offsetX, top - offsetY, Math.min( this.cols[range.c2].left - left + this.cols[range.c2].width, this.drawingCtx.getWidth() - this.cellsLeft ), Math.min( this.rows[range.r2].top - top + this.rows[range.r2].height, this.drawingCtx.getHeight() - this.cellsTop ) ) .clip(); } var mergedCells = this._drawCells( drawingCtx, range, offsetX, offsetY ); this._drawCellsBorders( drawingCtx, range, offsetX, offsetY, mergedCells ); if ( !drawingCtx && !window['IS_NATIVE_EDITOR'] ) { // restore canvas' original clipping range this.drawingCtx.restore(); } }; /** Рисует спарклайны */ WorksheetView.prototype._drawSparklines = function(drawingCtx, range, offsetX, offsetY) { this.objectRender.drawSparkLineGroups(drawingCtx || this.drawingCtx, this.model.aSparklineGroups, range, offsetX, offsetY); }; /** Рисует ячейки таблицы */ WorksheetView.prototype._drawCells = function ( drawingCtx, range, offsetX, offsetY ) { this._prepareCellTextMetricsCache( range ); var mergedCells = [], mc, i; for ( var row = range.r1; row <= range.r2; ++row ) { mergedCells = mergedCells.concat(this._drawRowBG(drawingCtx, row, range.c1, range.c2, offsetX, offsetY, null), this._drawRowText(drawingCtx, row, range.c1, range.c2, offsetX, offsetY)); } // draw merged cells at last stage to fix cells background issue for (i = 0; i < mergedCells.length; ++i) { if (i === mergedCells.indexOf(mergedCells[i])) { mc = mergedCells[i]; this._drawRowBG(drawingCtx, mc.r1, mc.c1, mc.c1, offsetX, offsetY, mc); this._drawCellText(drawingCtx, mc.c1, mc.r1, range.c1, range.c2, offsetX, offsetY, true); } } this._drawSparklines(drawingCtx, range, offsetX, offsetY); return mergedCells; }; /** Рисует фон ячеек в строке */ WorksheetView.prototype._drawRowBG = function ( drawingCtx, row, colStart, colEnd, offsetX, offsetY, oMergedCell ) { var mergedCells = []; if ( this.rows[row].height < this.height_1px && null === oMergedCell ) { return mergedCells; } var ctx = drawingCtx || this.drawingCtx; for ( var col = colStart; col <= colEnd; ++col ) { if ( this.cols[col].width < this.width_1px && null === oMergedCell ) { continue; } // ToDo подумать, может стоит не брать ячейку из модели (а брать из кеш-а) var c = this._getVisibleCell( col, row ); var findFillColor = this.handlers.trigger('selectSearchingResults') && this.model.inFindResults(row, col) ? this.settings.findFillColor : null; var fillColor = c.getFill(); var bg = fillColor || findFillColor; var mc = null; var mwidth = 0, mheight = 0; if ( null === oMergedCell ) { mc = this.model.getMergedByCell( row, col ); if ( null !== mc ) { mergedCells.push(mc); col = mc.c2; continue; } } else { mc = oMergedCell; } if ( null !== mc ) { if ( col !== mc.c1 || row !== mc.r1 ) { continue; } for ( var i = mc.c1 + 1; i <= mc.c2 && i < this.cols.length; ++i ) { mwidth += this.cols[i].width; } for ( var j = mc.r1 + 1; j <= mc.r2 && j < this.rows.length; ++j ) { mheight += this.rows[j].height; } } else { if ( bg === null ) { if ( col === colEnd && col < this.cols.length - 1 && row < this.rows.length - 1 ) { var c2 = this._getVisibleCell( col + 1, row ); var bg2 = c2.getFill(); if ( bg2 !== null ) { ctx.setFillStyle( bg2 ) .fillRect( this.cols[col + 1].left - offsetX - this.width_1px, this.rows[row].top - offsetY - this.height_1px, this.width_1px, this.rows[row].height + this.height_1px ); } var c3 = this._getVisibleCell( col, row + 1 ); var bg3 = c3.getFill(); if ( bg3 !== null ) { ctx.setFillStyle( bg3 ) .fillRect( this.cols[col].left - offsetX - this.width_1px, this.rows[row + 1].top - offsetY - this.height_1px, this.cols[col].width + this.width_1px, this.height_1px ); } } continue; } } var x = this.cols[col].left - (bg !== null ? this.width_1px : 0); var y = this.rows[row].top - (bg !== null ? this.height_1px : 0); var w = this.cols[col].width + this.width_1px * (bg !== null ? +1 : -1) + mwidth; var h = this.rows[row].height + this.height_1px * (bg !== null ? +1 : -1) + mheight; var color = bg !== null ? bg : this.settings.cells.defaultState.background; ctx.setFillStyle( color ).fillRect( x - offsetX, y - offsetY, w, h ); if (fillColor && findFillColor) { ctx.setFillStyle(findFillColor).fillRect(x - offsetX, y - offsetY, w, h); } } return mergedCells; }; /** Рисует текст ячеек в строке */ WorksheetView.prototype._drawRowText = function ( drawingCtx, row, colStart, colEnd, offsetX, offsetY ) { var mergedCells = []; if ( this.rows[row].height < this.height_1px ) { return mergedCells; } var dependentCells = {}, i, mc, col; // draw cells' text for ( col = colStart; col <= colEnd; ++col ) { if ( this.cols[col].width < this.width_1px ) { continue; } mc = this._drawCellText( drawingCtx, col, row, colStart, colEnd, offsetX, offsetY, false ); if ( mc !== null ) { mergedCells.push(mc); } // check if long text overlaps this cell i = this._findSourceOfCellText( col, row ); if ( i >= 0 ) { dependentCells[i] = (dependentCells[i] || []); dependentCells[i].push( col ); } } // draw long text that overlaps own cell's borders for ( i in dependentCells ) { var arr = dependentCells[i], j = arr.length - 1; col = i >> 0; // if source cell belongs to cells range then skip it (text has been drawn already) if ( col >= arr[0] && col <= arr[j] ) { continue; } // draw long text fragment this._drawCellText( drawingCtx, col, row, arr[0], arr[j], offsetX, offsetY, false ); } return mergedCells; }; /** Рисует текст ячейки */ WorksheetView.prototype._drawCellText = function (drawingCtx, col, row, colStart, colEnd, offsetX, offsetY, drawMergedCells) { var c = this._getVisibleCell(col, row); var color = c.getFont().getColor(); var ct = this._getCellTextCache(col, row); if (!ct) { return null; } var isMerged = ct.flags.isMerged(), range = undefined, isWrapped = ct.flags.wrapText; var ctx = drawingCtx || this.drawingCtx; if (isMerged) { range = ct.flags.merged; if (!drawMergedCells) { return range; } if (col !== range.c1 || row !== range.r1) { return null; } } var colL = isMerged ? range.c1 : Math.max(colStart, col - ct.sideL); var colR = isMerged ? Math.min(range.c2, this.nColsCount - 1) : Math.min(colEnd, col + ct.sideR); var rowT = isMerged ? range.r1 : row; var rowB = isMerged ? Math.min(range.r2, this.nRowsCount - 1) : row; var isTrimmedR = !isMerged && colR !== col + ct.sideR; if (!(ct.angle || 0)) { if (!isMerged && !isWrapped) { this._eraseCellRightBorder(drawingCtx, colL, colR + (isTrimmedR ? 1 : 0), row, offsetX, offsetY); } } var x1 = this.cols[colL].left - offsetX; var y1 = this.rows[rowT].top - offsetY; var w = this.cols[colR].left + this.cols[colR].width - offsetX - x1; var h = this.rows[rowB].top + this.rows[rowB].height - offsetY - y1; var x2 = x1 + w - (isTrimmedR ? 0 : this.width_1px); var y2 = y1 + h - this.height_1px; var bl = !isMerged ? (y2 - this.rows[rowB].descender) : (y2 - ct.metrics.height + ct.metrics.baseline - this.height_1px); var x1ct = isMerged ? x1 : this.cols[col].left - offsetX; var x2ct = isMerged ? x2 : x1ct + this.cols[col].width - this.width_1px; var textX = this._calcTextHorizPos(x1ct, x2ct, ct.metrics, ct.cellHA); var textY = this._calcTextVertPos(y1, y2, bl, ct.metrics, ct.cellVA); var textW = this._calcTextWidth(x1ct, x2ct, ct.metrics, ct.cellHA); var xb1, yb1, wb, hb, colLeft, colRight, i; var txtRotX, txtRotW, clipUse = false; if (ct.angle || 0) { xb1 = this.cols[col].left - offsetX; yb1 = this.rows[row].top - offsetY; wb = this.cols[col].width; hb = this.rows[row].height; txtRotX = xb1 - ct.textBound.offsetX; txtRotW = ct.textBound.width + xb1 - ct.textBound.offsetX; if (isMerged) { wb = 0; for (i = colL; i <= colR && i < this.nColsCount; ++i) { wb += this.cols[i].width; } hb = 0; for (i = rowT; i <= rowB && i < this.nRowsCount; ++i) { hb += this.rows[i].height; } ctx.AddClipRect(xb1, yb1, wb, hb); clipUse = true; } this.stringRender.angle = ct.angle; this.stringRender.fontNeedUpdate = true; if (90 === ct.angle || -90 === ct.angle) { // клип по ячейке if (!isMerged) { ctx.AddClipRect(xb1, yb1, wb, hb); clipUse = true; } } else { // клип по строке if (!isMerged) { ctx.AddClipRect(0, y1, this.drawingCtx.getWidth(), h); clipUse = true; } if (!isMerged && !isWrapped) { colLeft = col; if (0 !== txtRotX) { while (true) { if (0 == colLeft) { break; } if (txtRotX >= this.cols[colLeft].left) { break; } --colLeft; } } colRight = Math.min(col, this.nColsCount - 1); if (0 !== txtRotW) { while (true) { ++colRight; if (colRight >= this.nColsCount) { --colRight; break; } if (txtRotW <= this.cols[colRight].left) { --colRight; break; } } } colLeft = isMerged ? range.c1 : colLeft; colRight = isMerged ? Math.min(range.c2, this.nColsCount - 1) : colRight; this._eraseCellRightBorder(drawingCtx, colLeft, colRight + (isTrimmedR ? 1 : 0), row, offsetX, offsetY); } } this.stringRender.rotateAtPoint(drawingCtx, ct.angle, xb1, yb1, ct.textBound.dx, ct.textBound.dy); this.stringRender.restoreInternalState(ct.state); if (isWrapped) { if (ct.angle < 0) { if (Asc.c_oAscVAlign.Top === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Left; } else if (Asc.c_oAscVAlign.Center === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Center; } else if (Asc.c_oAscVAlign.Bottom === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Right; } } else { if (Asc.c_oAscVAlign.Top === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Right; } else if (Asc.c_oAscVAlign.Center === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Center; } else if (Asc.c_oAscVAlign.Bottom === ct.cellVA) { this.stringRender.flags.textAlign = AscCommon.align_Left; } } } this.stringRender.render(drawingCtx, 0, 0, textW, color); this.stringRender.resetTransform(drawingCtx); if (clipUse) { ctx.RemoveClipRect(); } } else { ctx.AddClipRect(x1, y1, w, h); this.stringRender.restoreInternalState(ct.state).render(drawingCtx, textX, textY, textW, color); ctx.RemoveClipRect(); } return null; }; /** Удаляет вертикальные границы ячейки, если текст выходит за границы и соседние ячейки пусты */ WorksheetView.prototype._eraseCellRightBorder = function ( drawingCtx, colBeg, colEnd, row, offsetX, offsetY ) { if ( colBeg >= colEnd ) { return; } var nextCell = -1; var ctx = drawingCtx || this.drawingCtx; ctx.setFillStyle( this.settings.cells.defaultState.background ); for ( var col = colBeg; col < colEnd; ++col ) { var c = -1 !== nextCell ? nextCell : this._getCell( col, row ); var bg = null !== c ? c.getFill() : null; if ( bg !== null ) { continue; } nextCell = this._getCell( col + 1, row ); bg = null !== nextCell ? nextCell.getFill() : null; if ( bg !== null ) { continue; } ctx.fillRect( this.cols[col].left + this.cols[col].width - offsetX - this.width_1px, this.rows[row].top - offsetY, this.width_1px, this.rows[row].height - this.height_1px ); } }; /** Рисует рамки для ячеек */ WorksheetView.prototype._drawCellsBorders = function (drawingCtx, range, offsetX, offsetY, mergedCells) { //TODO: использовать стили линий при рисовании границ var t = this; var ctx = drawingCtx || this.drawingCtx; var c = this.cols; var r = this.rows; var objectMergedCells = {}; // Двумерный map вида строка-колонка {1: {1: range, 4: range}} var i, mergeCellInfo, startCol, endRow, endCol, col, row; for (i in mergedCells) { mergeCellInfo = mergedCells[i]; startCol = Math.max(range.c1, mergeCellInfo.c1); endRow = Math.min(mergeCellInfo.r2, range.r2, this.nRowsCount); endCol = Math.min(mergeCellInfo.c2, range.c2, this.nColsCount); for (row = Math.max(range.r1, mergeCellInfo.r1); row <= endRow; ++row) { if (!objectMergedCells.hasOwnProperty(row)) { objectMergedCells[row] = {}; } for (col = startCol; col <= endCol; ++col) { objectMergedCells[row][col] = mergeCellInfo; } } } var bc = null, bs = c_oAscBorderStyles.None, isNotFirst = false; // cached border color function drawBorder(type, border, x1, y1, x2, y2) { var isStroke = false, isNewColor = !AscCommonExcel.g_oColorManager.isEqual(bc, border.c), isNewStyle = bs !== border.s; if (isNotFirst && (isNewColor || isNewStyle)) { ctx.stroke(); isStroke = true; } if (isNewColor) { bc = border.c; ctx.setStrokeStyle(bc); } if (isNewStyle) { bs = border.s; ctx.setLineWidth(border.w); ctx.setLineDash(border.getDashSegments()); } if (isStroke || false === isNotFirst) { isNotFirst = true; ctx.beginPath(); } switch (type) { case c_oAscBorderType.Hor: ctx.lineHor(x1, y1, x2); break; case c_oAscBorderType.Ver: ctx.lineVer(x1, y1, y2); break; case c_oAscBorderType.Diag: ctx.lineDiag(x1, y1, x2, y2); break; } } function drawVerticalBorder(borderLeftObject, borderRightObject, x, y1, y2) { var borderLeft = borderLeftObject ? borderLeftObject.borders : null, borderRight = borderRightObject ? borderRightObject.borders : null; var border = AscCommonExcel.getMatchingBorder(borderLeft && borderLeft.r, borderRight && borderRight.l); if (!border || border.w < 1) { return; } // ToDo переделать рассчет var tbw = t._calcMaxBorderWidth(borderLeftObject && borderLeftObject.getTopBorder(), borderRightObject && borderRightObject.getTopBorder()); // top border width var bbw = t._calcMaxBorderWidth(borderLeftObject && borderLeftObject.getBottomBorder(), borderRightObject && borderRightObject.getBottomBorder()); // bottom border width var dy1 = tbw > border.w ? tbw - 1 : (tbw > 1 ? -1 : 0); var dy2 = bbw > border.w ? -2 : (bbw > 2 ? 1 : 0); drawBorder(c_oAscBorderType.Ver, border, x, y1 + (-1 + dy1) * t.height_1px, x, y2 + (1 + dy2) * t.height_1px); } function drawHorizontalBorder(borderTopObject, borderBottomObject, x1, y, x2) { var borderTop = borderTopObject ? borderTopObject.borders : null, borderBottom = borderBottomObject ? borderBottomObject.borders : null; var border = AscCommonExcel.getMatchingBorder(borderTop && borderTop.b, borderBottom && borderBottom.t); if (border && border.w > 0) { // ToDo переделать рассчет var lbw = t._calcMaxBorderWidth(borderTopObject && borderTopObject.getLeftBorder(), borderBottomObject && borderBottomObject.getLeftBorder()); var rbw = t._calcMaxBorderWidth(borderTopObject && borderTopObject.getRightBorder(), borderTopObject && borderTopObject.getRightBorder()); var dx1 = border.w > lbw ? (lbw > 1 ? -1 : 0) : (lbw > 2 ? 2 : 1); var dx2 = border.w > rbw ? (rbw > 2 ? 1 : 0) : (rbw > 1 ? -2 : -1); drawBorder(c_oAscBorderType.Hor, border, x1 + (-1 + dx1) * t.width_1px, y, x2 + (1 + dx2) * t.width_1px, y); } } var arrPrevRow = [], arrCurrRow = [], arrNextRow = []; var objMCPrevRow = null, objMCRow = null, objMCNextRow = null; var bCur, bPrev, bNext, bTopCur, bTopPrev, bTopNext, bBotCur, bBotPrev, bBotNext; bCur = bPrev = bNext = bTopCur = bTopNext = bBotCur = bBotNext = null; row = range.r1 - 1; var prevCol = range.c1 - 1; // Определим первую колонку (т.к. могут быть скрытые колонки) while (0 <= prevCol && c[prevCol].width < t.width_1px) --prevCol; // Сначала пройдемся по верхней строке (над отрисовываемым диапазоном) while (0 <= row) { if (r[row].height >= t.height_1px) { objMCPrevRow = objectMergedCells[row]; for (col = prevCol; col <= range.c2 && col < t.nColsCount; ++col) { if (0 > col || c[col].width < t.width_1px) { continue; } arrPrevRow[col] = new CellBorderObject(t._getVisibleCell(col, row).getBorder(), objMCPrevRow ? objMCPrevRow[col] : null, col, row); } break; } --row; } var mc = null, nextRow, isFirstRow = true; var isPrevColExist = (0 <= prevCol); for (row = range.r1; row <= range.r2 && row < t.nRowsCount; row = nextRow) { nextRow = row + 1; if (r[row].height < t.height_1px) { continue; } // Нужно отсеять пустые снизу for (; nextRow <= range.r2 && nextRow < t.nRowsCount; ++nextRow) { if (r[nextRow].height >= t.height_1px) { break; } } var isFirstRowTmp = isFirstRow, isLastRow = nextRow > range.r2 || nextRow >= t.nRowsCount; isFirstRow = false; // Это уже не первая строка (определяем не по совпадению с range.r1, а по видимости) objMCRow = isFirstRowTmp ? objectMergedCells[row] : objMCNextRow; objMCNextRow = objectMergedCells[nextRow]; var rowCache = t._fetchRowCache(row); var y1 = r[row].top - offsetY; var y2 = y1 + r[row].height - t.height_1px; var nextCol, isFirstCol = true; for (col = range.c1; col <= range.c2 && col < t.nColsCount; col = nextCol) { nextCol = col + 1; if (c[col].width < t.width_1px) { continue; } // Нужно отсеять пустые справа for (; nextCol <= range.c2 && nextCol < t.nColsCount; ++nextCol) { if (c[nextCol].width >= t.width_1px) { break; } } var isFirstColTmp = isFirstCol, isLastCol = nextCol > range.c2 || nextCol >= t.nColsCount; isFirstCol = false; // Это уже не первая колонка (определяем не по совпадению с range.c1, а по видимости) mc = objMCRow ? objMCRow[col] : null; var x1 = c[col].left - offsetX; var x2 = x1 + c[col].width - this.width_1px; if (row === t.nRowsCount) { bBotPrev = bBotCur = bBotNext = null; } else { if (isFirstColTmp) { bBotPrev = arrNextRow[prevCol] = new CellBorderObject(isPrevColExist ? t._getVisibleCell(prevCol, nextRow).getBorder() : null, objMCNextRow ? objMCNextRow[prevCol] : null, prevCol, nextRow); bBotCur = arrNextRow[col] = new CellBorderObject(t._getVisibleCell(col, nextRow).getBorder(), objMCNextRow ? objMCNextRow[col] : null, col, nextRow); } else { bBotPrev = bBotCur; bBotCur = bBotNext; } } if (isFirstColTmp) { bPrev = arrCurrRow[prevCol] = new CellBorderObject(isPrevColExist ? t._getVisibleCell(prevCol, row).getBorder() : null, objMCRow ? objMCRow[prevCol] : null, prevCol, row); bCur = arrCurrRow[col] = new CellBorderObject(t._getVisibleCell(col, row).getBorder(), mc, col, row); bTopPrev = arrPrevRow[prevCol]; bTopCur = arrPrevRow[col]; } else { bPrev = bCur; bCur = bNext; bTopPrev = bTopCur; bTopCur = bTopNext; } if (col === t.nColsCount) { bNext = null; bTopNext = null; } else { bNext = arrCurrRow[nextCol] = new CellBorderObject(t._getVisibleCell(nextCol, row).getBorder(), objMCRow ? objMCRow[nextCol] : null, nextCol, row); bTopNext = arrPrevRow[nextCol]; if (row === t.nRowsCount) { bBotNext = null; } else { bBotNext = arrNextRow[nextCol] = new CellBorderObject(t._getVisibleCell(nextCol, nextRow).getBorder(), objMCNextRow ? objMCNextRow[nextCol] : null, nextCol, nextRow); } } if (mc && row !== mc.r1 && row !== mc.r2 && col !== mc.c1 && col !== mc.c2) { continue; } // draw diagonal borders if ((bCur.borders.dd || bCur.borders.du) && (!mc || (row === mc.r1 && col === mc.c1))) { var x2Diagonal = x2; var y2Diagonal = y2; if (mc) { // Merge cells x2Diagonal = c[mc.c2].left + c[mc.c2].width - offsetX - t.width_1px; y2Diagonal = r[mc.r2].top + r[mc.r2].height - offsetY - t.height_1px; } // ToDo Clip diagonal borders /*ctx.save() .beginPath() .rect(x1 + this.width_1px * (lb.w < 1 ? -1 : (lb.w < 3 ? 0 : +1)), y1 + this.width_1px * (tb.w < 1 ? -1 : (tb.w < 3 ? 0 : +1)), c[col].width + this.width_1px * ( -1 + (lb.w < 1 ? +1 : (lb.w < 3 ? 0 : -1)) + (rb.w < 1 ? +1 : (rb.w < 2 ? 0 : -1)) ), r[row].height + this.height_1px * ( -1 + (tb.w < 1 ? +1 : (tb.w < 3 ? 0 : -1)) + (bb.w < 1 ? +1 : (bb.w < 2 ? 0 : -1)) )) .clip(); */ if (bCur.borders.dd) { // draw diagonal line l,t - r,b drawBorder(c_oAscBorderType.Diag, bCur.borders.d, x1 - t.width_1px, y1 - t.height_1px, x2Diagonal, y2Diagonal); } if (bCur.borders.du) { // draw diagonal line l,b - r,t drawBorder(c_oAscBorderType.Diag, bCur.borders.d, x1 - t.width_1px, y2Diagonal, x2Diagonal, y1 - t.height_1px); } // ToDo Clip diagonal borders //ctx.restore(); // canvas context has just been restored, so destroy border color cache //bc = undefined; } // draw left border if (isFirstColTmp && !t._isLeftBorderErased(col, rowCache)) { drawVerticalBorder(bPrev, bCur, x1 - t.width_1px, y1, y2); // Если мы в печати и печатаем первый столбец, то нужно напечатать бордеры // if (lb.w >= 1 && drawingCtx && 0 === col) { // Иначе они будут не такой ширины // ToDo посмотреть что с этим ? в печати будет обрезка // drawVerticalBorder(lb, tb, tbPrev, bb, bbPrev, x1, y1, y2); // } } // draw right border if ((!mc || col === mc.c2) && !t._isRightBorderErased(col, rowCache)) { drawVerticalBorder(bCur, bNext, x2, y1, y2); } // draw top border if (isFirstRowTmp) { drawHorizontalBorder(bTopCur, bCur, x1, y1 - t.height_1px, x2); // Если мы в печати и печатаем первую строку, то нужно напечатать бордеры // if (tb.w > 0 && drawingCtx && 0 === row) { // ToDo посмотреть что с этим ? в печати будет обрезка // drawHorizontalBorder.call(this, tb, lb, lbPrev, rb, rbPrev, x1, y1, x2); // } } if (!mc || row === mc.r2) { // draw bottom border drawHorizontalBorder(bCur, bBotCur, x1, y2, x2); } } arrPrevRow = arrCurrRow; arrCurrRow = arrNextRow; arrNextRow = []; } if (isNotFirst) { ctx.stroke(); } }; /** Рисует закрепленные области областей */ WorksheetView.prototype._drawFrozenPane = function ( noCells ) { if ( this.topLeftFrozenCell ) { var row = this.topLeftFrozenCell.getRow0(); var col = this.topLeftFrozenCell.getCol0(); var tmpRange, offsetX, offsetY; if ( 0 < row && 0 < col ) { offsetX = this.cols[0].left - this.cellsLeft; offsetY = this.rows[0].top - this.cellsTop; tmpRange = new asc_Range( 0, 0, col - 1, row - 1 ); if ( !noCells ) { this._drawGrid( null, tmpRange, offsetX, offsetY ); this._drawCellsAndBorders(null, tmpRange, offsetX, offsetY ); } } if ( 0 < row ) { row -= 1; offsetX = undefined; offsetY = this.rows[0].top - this.cellsTop; tmpRange = new asc_Range( this.visibleRange.c1, 0, this.visibleRange.c2, row ); this._drawRowHeaders( null, 0, row, kHeaderDefault, offsetX, offsetY ); if ( !noCells ) { this._drawGrid( null, tmpRange, offsetX, offsetY ); this._drawCellsAndBorders(null, tmpRange, offsetX, offsetY ); } } if ( 0 < col ) { col -= 1; offsetX = this.cols[0].left - this.cellsLeft; offsetY = undefined; tmpRange = new asc_Range( 0, this.visibleRange.r1, col, this.visibleRange.r2 ); this._drawColumnHeaders( null, 0, col, kHeaderDefault, offsetX, offsetY ); if ( !noCells ) { this._drawGrid( null, tmpRange, offsetX, offsetY ); this._drawCellsAndBorders(null, tmpRange, offsetX, offsetY ); } } } }; /** Рисует закрепление областей */ WorksheetView.prototype._drawFrozenPaneLines = function (drawingCtx) { // Возможно стоит отрисовывать на overlay, а не на основной канве var ctx = drawingCtx || this.drawingCtx; var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, this.model.getId(), AscCommonExcel.c_oAscLockNameFrozenPane); var isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false); var color = isLocked ? AscCommonExcel.c_oAscCoAuthoringOtherBorderColor : this.settings.frozenColor; ctx.setLineWidth(1).setStrokeStyle(color).beginPath(); var fHorLine, fVerLine; if (isLocked) { fHorLine = ctx.dashLineCleverHor; fVerLine = ctx.dashLineCleverVer; } else { fHorLine = ctx.lineHorPrevPx; fVerLine = ctx.lineVerPrevPx; } if (this.topLeftFrozenCell) { var row = this.topLeftFrozenCell.getRow0(); var col = this.topLeftFrozenCell.getCol0(); if (0 < row) { fHorLine.apply(ctx, [0, this.rows[row].top, ctx.getWidth()]); } else { fHorLine.apply(ctx, [0, this.headersHeight, this.headersWidth]); } if (0 < col) { fVerLine.apply(ctx, [this.cols[col].left, 0, ctx.getHeight()]); } else { fVerLine.apply(ctx, [this.headersWidth, 0, this.headersHeight]); } ctx.stroke(); } else if (this.model.sheetViews[0].asc_getShowRowColHeaders()) { fHorLine.apply(ctx, [0, this.headersHeight, this.headersWidth]); fVerLine.apply(ctx, [this.headersWidth, 0, this.headersHeight]); ctx.stroke(); } }; WorksheetView.prototype.drawFrozenGuides = function ( x, y, target ) { var data, offsetFrozen; var ctx = this.overlayCtx; ctx.clear(); this._drawSelection(); switch ( target ) { case c_oTargetType.FrozenAnchorV: x *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIX() ); data = this._findColUnderCursor( x, true, true ); if ( data ) { data.col += 1; if ( 0 <= data.col && data.col < this.cols.length ) { var h = ctx.getHeight(); var offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; offsetFrozen = this.getFrozenPaneOffset( false, true ); offsetX -= offsetFrozen.offsetX; ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( this.cols[data.col].left - offsetX - this.width_1px, 0, this.width_1px, h ); } } break; case c_oTargetType.FrozenAnchorH: y *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIY() ); data = this._findRowUnderCursor( y, true, true ); if ( data ) { data.row += 1; if ( 0 <= data.row && data.row < this.rows.length ) { var w = ctx.getWidth(); var offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; offsetFrozen = this.getFrozenPaneOffset( true, false ); offsetY -= offsetFrozen.offsetY; ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( 0, this.rows[data.row].top - offsetY - this.height_1px, w, this.height_1px ); } } break; } }; WorksheetView.prototype._isFrozenAnchor = function ( x, y ) { var result = {result: false, cursor: "move", name: ""}; if ( false === this.model.sheetViews[0].asc_getShowRowColHeaders() ) { return result; } var _this = this; var frozenCell = this.topLeftFrozenCell ? this.topLeftFrozenCell : new AscCommon.CellAddress( 0, 0, 0 ); x *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIX() ); y *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIY() ); function isPointInAnchor( x, y, rectX, rectY, rectW, rectH ) { var delta = 2 * asc_getcvt( 0/*px*/, 1/*pt*/, _this._getPPIX() ); return (x >= rectX - delta) && (x <= rectX + rectW + delta) && (y >= rectY - delta) && (y <= rectY + rectH + delta); } // vertical var _x = this.getCellLeft( frozenCell.getCol0(), 1 ) - 0.5; var _y = _this.headersTop; var w = 0; var h = _this.headersHeight; if ( isPointInAnchor( x, y, _x, _y, w, h ) ) { result.result = true; result.name = c_oTargetType.FrozenAnchorV; } // horizontal _x = _this.headersLeft; _y = this.getCellTop( frozenCell.getRow0(), 1 ) - 0.5; w = _this.headersWidth - 0.5; h = 0; if ( isPointInAnchor( x, y, _x, _y, w, h ) ) { result.result = true; result.name = c_oTargetType.FrozenAnchorH; } return result; }; WorksheetView.prototype.applyFrozenAnchor = function ( x, y, target ) { var t = this; var onChangeFrozenCallback = function ( isSuccess ) { if ( false === isSuccess ) { t.overlayCtx.clear(); t._drawSelection(); return; } var lastCol = 0, lastRow = 0, data; if ( t.topLeftFrozenCell ) { lastCol = t.topLeftFrozenCell.getCol0(); lastRow = t.topLeftFrozenCell.getRow0(); } switch ( target ) { case c_oTargetType.FrozenAnchorV: x *= asc_getcvt( 0/*px*/, 1/*pt*/, t._getPPIX() ); data = t._findColUnderCursor( x, true, true ); if ( data ) { data.col += 1; if ( 0 <= data.col && data.col < t.cols.length ) { lastCol = data.col; } } break; case c_oTargetType.FrozenAnchorH: y *= asc_getcvt( 0/*px*/, 1/*pt*/, t._getPPIY() ); data = t._findRowUnderCursor( y, true, true ); if ( data ) { data.row += 1; if ( 0 <= data.row && data.row < t.rows.length ) { lastRow = data.row; } } break; } t._updateFreezePane( lastCol, lastRow ); }; this._isLockedFrozenPane( onChangeFrozenCallback ); }; /** Для api закрепленных областей */ WorksheetView.prototype.freezePane = function () { var t = this; var activeCell = this.model.selectionRange.activeCell.clone(); var onChangeFreezePane = function (isSuccess) { if (false === isSuccess) { return; } var col, row, mc; if (null !== t.topLeftFrozenCell) { col = row = 0; } else { col = activeCell.col; row = activeCell.row; if (0 !== row || 0 !== col) { mc = t.model.getMergedByCell(row, col); if (mc) { col = mc.c1; row = mc.r1; } } if (0 === col && 0 === row) { col = ((t.visibleRange.c2 - t.visibleRange.c1) / 2) >> 0; row = ((t.visibleRange.r2 - t.visibleRange.r1) / 2) >> 0; } } t._updateFreezePane(col, row); }; return this._isLockedFrozenPane(onChangeFreezePane); }; WorksheetView.prototype._updateFreezePane = function (col, row, lockDraw) { var lastCol = 0, lastRow = 0; if (this.topLeftFrozenCell) { lastCol = this.topLeftFrozenCell.getCol0(); lastRow = this.topLeftFrozenCell.getRow0(); } History.Create_NewPoint(); var oData = new AscCommonExcel.UndoRedoData_FromTo(new AscCommonExcel.UndoRedoData_BBox(new asc_Range(lastCol, lastRow, lastCol, lastRow)), new AscCommonExcel.UndoRedoData_BBox(new asc_Range(col, row, col, row)), null); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeFrozenCell, this.model.getId(), null, oData); var isUpdate = false; if (0 === col && 0 === row) { // Очистка if (null !== this.topLeftFrozenCell) { isUpdate = true; } this.topLeftFrozenCell = this.model.sheetViews[0].pane = null; } else { // Создание if (null === this.topLeftFrozenCell) { isUpdate = true; } var pane = this.model.sheetViews[0].pane = new AscCommonExcel.asc_CPane(); this.topLeftFrozenCell = pane.topLeftFrozenCell = new AscCommon.CellAddress(row, col, 0); } this.visibleRange.c1 = col; this.visibleRange.r1 = row; if (col >= this.nColsCount) { this.expandColsOnScroll(false, true); } if (row >= this.nRowsCount) { this.expandRowsOnScroll(false, true); } this.visibleRange.r2 = 0; this._calcVisibleRows(); this.visibleRange.c2 = 0; this._calcVisibleColumns(); this.handlers.trigger("reinitializeScroll"); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.init(); } if (!lockDraw) { this.draw(); } // Эвент на обновление if (isUpdate && !this.model.workbook.bUndoChanges && !this.model.workbook.bRedoChanges) { this.handlers.trigger("updateSheetViewSettings"); } }; /** */ WorksheetView.prototype._drawSelectionElement = function (visibleRange, offsetX, offsetY, args) { var range = args[0]; var selectionLineType = args[1]; var strokeColor = args[2]; var isAllRange = args[3]; var colorN = this.settings.activeCellBorderColor2; var ctx = this.overlayCtx; var c = this.cols; var r = this.rows; var oIntersection = range.intersectionSimple(visibleRange); var ppiX = this._getPPIX(), ppiY = this._getPPIY(); if (!oIntersection) { return true; } var width_1px = asc_calcnpt(0, ppiX, 1/*px*/), width_2px = asc_calcnpt(0, ppiX, 2 /*px*/), width_3px = asc_calcnpt(0, ppiX, 3/*px*/), width_4px = asc_calcnpt(0, ppiX, 4 /*px*/), width_5px = asc_calcnpt(0, ppiX, 5/*px*/), width_7px = asc_calcnpt(0, ppiX, 7/*px*/), height_1px = asc_calcnpt(0, ppiY, 1/*px*/), height_2px = asc_calcnpt(0, ppiY, 2 /*px*/), height_3px = asc_calcnpt(0, ppiY, 3/*px*/), height_4px = asc_calcnpt(0, ppiY, 4 /*px*/), height_5px = asc_calcnpt(0, ppiY, 5/*px*/), height_7px = asc_calcnpt(0, ppiY, 7/*px*/); var fHorLine, fVerLine; var canFill = AscCommonExcel.selectionLineType.Selection & selectionLineType; var isDashLine = AscCommonExcel.selectionLineType.Dash & selectionLineType; if (isDashLine) { fHorLine = ctx.dashLineCleverHor; fVerLine = ctx.dashLineCleverVer; } else { fHorLine = ctx.lineHorPrevPx; fVerLine = ctx.lineVerPrevPx; } var firstCol = oIntersection.c1 === visibleRange.c1 && !isAllRange; var firstRow = oIntersection.r1 === visibleRange.r1 && !isAllRange; var drawLeftSide = oIntersection.c1 === range.c1; var drawRightSide = oIntersection.c2 === range.c2; var drawTopSide = oIntersection.r1 === range.r1; var drawBottomSide = oIntersection.r2 === range.r2; var x1 = c[oIntersection.c1].left - offsetX; var x2 = c[oIntersection.c2].left + c[oIntersection.c2].width - offsetX; var y1 = r[oIntersection.r1].top - offsetY; var y2 = r[oIntersection.r2].top + r[oIntersection.r2].height - offsetY; if (canFill) { var fillColor = strokeColor.Copy(); fillColor.a = 0.15; ctx.setFillStyle(fillColor).fillRect(x1, y1, x2 - x1, y2 - y1); } ctx.setLineWidth(isDashLine ? 1 : 2).setStrokeStyle(strokeColor); ctx.beginPath(); if (drawTopSide && !firstRow) { fHorLine.apply(ctx, [x1 - !isDashLine * width_2px, y1, x2 + !isDashLine * width_1px]); } if (drawBottomSide) { fHorLine.apply(ctx, [x1, y2 + !isDashLine * height_1px, x2]); } if (drawLeftSide && !firstCol) { fVerLine.apply(ctx, [x1, y1, y2 + !isDashLine * height_1px]); } if (drawRightSide) { fVerLine.apply(ctx, [x2 + !isDashLine * width_1px, y1, y2 + !isDashLine * height_1px]); } ctx.closePath().stroke(); // draw active cell in selection var isActive = AscCommonExcel.selectionLineType.ActiveCell & selectionLineType; if (isActive) { var cell = (this.isSelectionDialogMode ? this.copyActiveRange : this.model.selectionRange).activeCell; var fs = this.model.getMergedByCell(cell.row, cell.col); fs = range.intersectionSimple( fs ? fs : new asc_Range(cell.col, cell.row, cell.col, cell.row)); if (fs) { var _x1 = c[fs.c1].left - offsetX + width_1px; var _y1 = r[fs.r1].top - offsetY + height_1px; var _w = c[fs.c2].left - c[fs.c1].left + c[fs.c2].width - width_2px; var _h = r[fs.r2].top - r[fs.r1].top + r[fs.r2].height - height_2px; if (0 < _w && 0 < _h) { ctx.clearRect(_x1, _y1, _w, _h); } } } if (canFill) {/*Отрисовка светлой полосы при выборе ячеек для формулы*/ ctx.setLineWidth(1); ctx.setStrokeStyle(colorN); ctx.beginPath(); if (drawTopSide) { fHorLine.apply(ctx, [x1, y1 + height_1px, x2 - width_1px]); } if (drawBottomSide) { fHorLine.apply(ctx, [x1, y2 - height_1px, x2 - width_1px]); } if (drawLeftSide) { fVerLine.apply(ctx, [x1 + width_1px, y1, y2 - height_2px]); } if (drawRightSide) { fVerLine.apply(ctx, [x2 - width_1px, y1, y2 - height_2px]); } ctx.closePath().stroke(); } // Отрисовка квадратов для move/resize var isResize = AscCommonExcel.selectionLineType.Resize & selectionLineType; var isPromote = AscCommonExcel.selectionLineType.Promote & selectionLineType; if (isResize || isPromote) { ctx.setFillStyle(colorN); if (drawRightSide && drawBottomSide) { ctx.fillRect(x2 - width_4px, y2 - height_4px, width_7px, height_7px); } ctx.setFillStyle(strokeColor); if (drawRightSide && drawBottomSide) { ctx.fillRect(x2 - width_3px, y2 - height_3px, width_5px, height_5px); } if (isResize) { ctx.setFillStyle(colorN); if (drawLeftSide && drawTopSide) { ctx.fillRect(x1 - width_4px, y1 - height_4px, width_7px, height_7px); } if (drawRightSide && drawTopSide) { ctx.fillRect(x2 - width_4px, y1 - height_4px, width_7px, height_7px); } if (drawLeftSide && drawBottomSide) { ctx.fillRect(x1 - width_4px, y2 - height_4px, width_7px, height_7px); } ctx.setFillStyle(strokeColor); if (drawLeftSide && drawTopSide) { ctx.fillRect(x1 - width_3px, y1 - height_3px, width_5px, height_5px); } if (drawRightSide && drawTopSide) { ctx.fillRect(x2 - width_3px, y1 - height_3px, width_5px, height_5px); } if (drawLeftSide && drawBottomSide) { ctx.fillRect(x1 - width_3px, y2 - height_3px, width_5px, height_5px); } } } return true; }; /**Отрисовывает диапазон с заданными параметрами*/ WorksheetView.prototype._drawElements = function (drawFunction) { var cFrozen = 0, rFrozen = 0, args = Array.prototype.slice.call(arguments, 1), c = this.cols, r = this.rows, offsetX = c[this.visibleRange.c1].left - this.cellsLeft, offsetY = r[this.visibleRange.r1].top - this.cellsTop, res; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); rFrozen = this.topLeftFrozenCell.getRow0(); offsetX -= this.cols[cFrozen].left - this.cols[0].left; offsetY -= this.rows[rFrozen].top - this.rows[0].top; var oFrozenRange; cFrozen -= 1; rFrozen -= 1; if (0 <= cFrozen && 0 <= rFrozen) { oFrozenRange = new asc_Range(0, 0, cFrozen, rFrozen); res = drawFunction.call(this, oFrozenRange, c[0].left - this.cellsLeft, r[0].top - this.cellsTop, args); if (!res) { return; } } if (0 <= cFrozen) { oFrozenRange = new asc_Range(0, this.visibleRange.r1, cFrozen, this.visibleRange.r2); res = drawFunction.call(this, oFrozenRange, c[0].left - this.cellsLeft, offsetY, args); if (!res) { return; } } if (0 <= rFrozen) { oFrozenRange = new asc_Range(this.visibleRange.c1, 0, this.visibleRange.c2, rFrozen); res = drawFunction.call(this, oFrozenRange, offsetX, r[0].top - this.cellsTop, args); if (!res) { return; } } } // Можно вместо call попользовать apply, но тогда нужно каждый раз соединять массив аргументов и 3 объекта drawFunction.call(this, this.visibleRange, offsetX, offsetY, args); }; /** * Рисует выделение вокруг ячеек */ WorksheetView.prototype._drawSelection = function () { var isShapeSelect = false; if (window['IS_NATIVE_EDITOR']) { return; } this.handlers.trigger("checkLastWork"); // set clipping rect to cells area var ctx = this.overlayCtx; ctx.save().beginPath() .rect(this.cellsLeft, this.cellsTop, ctx.getWidth() - this.cellsLeft, ctx.getHeight() - this.cellsTop) .clip(); if (!this.isSelectionDialogMode) { this._drawCollaborativeElements(); } var isOtherSelectionMode = this.isSelectionDialogMode || this.isFormulaEditMode; if (isOtherSelectionMode && !this.handlers.trigger('isActive')) { if (this.isSelectionDialogMode) { this._drawSelectRange(); } else if (this.isFormulaEditMode) { this._drawFormulaRanges(this.arrActiveFormulaRanges); } } else { isShapeSelect = (asc["editor"].isStartAddShape || this.objectRender.selectedGraphicObjectsExists()); if (isShapeSelect) { if (this.isChartAreaEditMode) { this._drawFormulaRanges(this.arrActiveChartRanges); } } else { this._drawFormulaRanges(this.arrActiveFormulaRanges); if (this.isChartAreaEditMode) { this._drawFormulaRanges(this.arrActiveChartRanges); } this._drawSelectionRange(); if (this.activeFillHandle) { this._drawElements(this._drawSelectionElement, this.activeFillHandle.clone(true), AscCommonExcel.selectionLineType.None, this.settings.activeCellBorderColor); } if (this.isSelectionDialogMode) { this._drawSelectRange(); } if (this.stateFormatPainter && this.handlers.trigger('isActive')) { this._drawFormatPainterRange(); } if (null !== this.activeMoveRange) { this._drawElements(this._drawSelectionElement, this.activeMoveRange, AscCommonExcel.selectionLineType.None, new CColor(0, 0, 0)); } } } // restore canvas' original clipping range ctx.restore(); if (!isOtherSelectionMode && !isShapeSelect) { this._drawActiveHeaders(); } }; WorksheetView.prototype._drawSelectionRange = function () { var type, ranges = (this.isSelectionDialogMode ? this.copyActiveRange : this.model.selectionRange).ranges; var range, selectionLineType; for (var i = 0, l = ranges.length; i < l; ++i) { range = ranges[i].clone(); type = range.getType(); if (c_oAscSelectionType.RangeMax === type) { range.c2 = this.cols.length - 1; range.r2 = this.rows.length - 1; } else if (c_oAscSelectionType.RangeCol === type) { range.r2 = this.rows.length - 1; } else if (c_oAscSelectionType.RangeRow === type) { range.c2 = this.cols.length - 1; } selectionLineType = AscCommonExcel.selectionLineType.Selection; if (1 === l) { selectionLineType |= AscCommonExcel.selectionLineType.ActiveCell | AscCommonExcel.selectionLineType.Promote; } else if (i === this.model.selectionRange.activeCellId) { selectionLineType |= AscCommonExcel.selectionLineType.ActiveCell; } this._drawElements(this._drawSelectionElement, range, selectionLineType, this.settings.activeCellBorderColor); } this.handlers.trigger("drawMobileSelection", this.settings.activeCellBorderColor); }; WorksheetView.prototype._drawFormatPainterRange = function () { var t = this, color = new CColor(0, 0, 0); this.copyActiveRange.ranges.forEach(function (item) { t._drawElements(t._drawSelectionElement, item, AscCommonExcel.selectionLineType.Dash, color); }); }; WorksheetView.prototype._drawFormulaRanges = function (arrRanges) { var i, ranges, length = AscCommonExcel.c_oAscFormulaRangeBorderColor.length; var strokeColor, colorIndex, uniqueColorIndex = 0, tmpColors = []; for (i = 0; i < arrRanges.length; ++i) { ranges = arrRanges[i].ranges; for (var j = 0, l = ranges.length; j < l; ++j) { colorIndex = asc.getUniqueRangeColor(ranges, j, tmpColors); if (null == colorIndex) { colorIndex = uniqueColorIndex++; } tmpColors.push(colorIndex); if (ranges[j].noColor) { colorIndex = 0; } strokeColor = AscCommonExcel.c_oAscFormulaRangeBorderColor[colorIndex % length]; this._drawElements(this._drawSelectionElement, ranges[j], AscCommonExcel.selectionLineType.Selection | (ranges[j].isName ? AscCommonExcel.selectionLineType.None : AscCommonExcel.selectionLineType.Resize), strokeColor); } } }; WorksheetView.prototype._drawSelectRange = function () { var ranges = this.model.selectionRange.ranges; for (var i = 0, l = ranges.length; i < l; ++i) { this._drawElements(this._drawSelectionElement, ranges[i], AscCommonExcel.selectionLineType.Dash, AscCommonExcel.c_oAscCoAuthoringOtherBorderColor); } }; WorksheetView.prototype._drawCollaborativeElements = function () { if ( this.collaborativeEditing.getCollaborativeEditing() ) { this._drawCollaborativeElementsMeOther(c_oAscLockTypes.kLockTypeMine); this._drawCollaborativeElementsMeOther(c_oAscLockTypes.kLockTypeOther); this._drawCollaborativeElementsAllLock(); } }; WorksheetView.prototype._drawCollaborativeElementsAllLock = function () { var currentSheetId = this.model.getId(); var nLockAllType = this.collaborativeEditing.isLockAllOther(currentSheetId); if (Asc.c_oAscMouseMoveLockedObjectType.None !== nLockAllType) { var isAllRange = true, strokeColor = (Asc.c_oAscMouseMoveLockedObjectType.TableProperties === nLockAllType) ? AscCommonExcel.c_oAscCoAuthoringLockTablePropertiesBorderColor : AscCommonExcel.c_oAscCoAuthoringOtherBorderColor, oAllRange = new asc_Range(0, 0, gc_nMaxCol0, gc_nMaxRow0); this._drawElements(this._drawSelectionElement, oAllRange, AscCommonExcel.selectionLineType.Dash, strokeColor, isAllRange); } }; WorksheetView.prototype._drawCollaborativeElementsMeOther = function (type) { var currentSheetId = this.model.getId(), i, strokeColor, arrayCells, oCellTmp; if (c_oAscLockTypes.kLockTypeMine === type) { strokeColor = AscCommonExcel.c_oAscCoAuthoringMeBorderColor; arrayCells = this.collaborativeEditing.getLockCellsMe(currentSheetId); arrayCells = arrayCells.concat(this.collaborativeEditing.getArrayInsertColumnsBySheetId(currentSheetId)); arrayCells = arrayCells.concat(this.collaborativeEditing.getArrayInsertRowsBySheetId(currentSheetId)); } else { strokeColor = AscCommonExcel.c_oAscCoAuthoringOtherBorderColor; arrayCells = this.collaborativeEditing.getLockCellsOther(currentSheetId); } for (i = 0; i < arrayCells.length; ++i) { oCellTmp = new asc_Range(arrayCells[i].c1, arrayCells[i].r1, arrayCells[i].c2, arrayCells[i].r2); this._drawElements(this._drawSelectionElement, oCellTmp, AscCommonExcel.selectionLineType.Dash, strokeColor); } }; WorksheetView.prototype.cleanSelection = function (range, isFrozen) { if (window['IS_NATIVE_EDITOR']) { return; } isFrozen = !!isFrozen; if (range === undefined) { range = this.visibleRange; } var ctx = this.overlayCtx; var width = ctx.getWidth(); var height = ctx.getHeight(); var offsetX, offsetY, diffWidth = 0, diffHeight = 0; var x1 = Number.MAX_VALUE; var x2 = -Number.MAX_VALUE; var y1 = Number.MAX_VALUE; var y2 = -Number.MAX_VALUE; var _x1, _x2, _y1, _y2; var i; if (this.topLeftFrozenCell) { var cFrozen = this.topLeftFrozenCell.getCol0(); var rFrozen = this.topLeftFrozenCell.getRow0(); diffWidth = this.cols[cFrozen].left - this.cols[0].left; diffHeight = this.rows[rFrozen].top - this.rows[0].top; if (!isFrozen) { var oFrozenRange; cFrozen -= 1; rFrozen -= 1; if (0 <= cFrozen && 0 <= rFrozen) { oFrozenRange = new asc_Range(0, 0, cFrozen, rFrozen); this.cleanSelection(oFrozenRange, true); } if (0 <= cFrozen) { oFrozenRange = new asc_Range(0, this.visibleRange.r1, cFrozen, this.visibleRange.r2); this.cleanSelection(oFrozenRange, true); } if (0 <= rFrozen) { oFrozenRange = new asc_Range(this.visibleRange.c1, 0, this.visibleRange.c2, rFrozen); this.cleanSelection(oFrozenRange, true); } } } if (isFrozen) { if (range.c1 !== this.visibleRange.c1) { diffWidth = 0; } if (range.r1 !== this.visibleRange.r1) { diffHeight = 0; } offsetX = this.cols[range.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[range.r1].top - this.cellsTop - diffHeight; } else { offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop - diffHeight; } this._activateOverlayCtx(); var t = this; this.model.selectionRange.ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_2px; _x2 = t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + /* Это ширина "квадрата" для автофильтра от границы ячейки */t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_2px; _y2 = t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + /* Это высота "квадрата" для автофильтра от границы ячейки */t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } if (!isFrozen) { t._cleanColumnHeaders(item.c1, item.c2); t._cleanRowHeaders(item.r1, item.r2); } }); this._deactivateOverlayCtx(); // Если есть активное автозаполнения, то нужно его тоже очистить if (this.activeFillHandle !== null) { var activeFillClone = this.activeFillHandle.clone(true); // Координаты для автозаполнения _x1 = this.cols[activeFillClone.c1].left - offsetX - this.width_2px; _x2 = this.cols[activeFillClone.c2].left + this.cols[activeFillClone.c2].width - offsetX + this.width_1px + this.width_2px; _y1 = this.rows[activeFillClone.r1].top - offsetY - this.height_2px; _y2 = this.rows[activeFillClone.r2].top + this.rows[activeFillClone.r2].height - offsetY + this.height_1px + this.height_2px; // Выбираем наибольший range для очистки x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } if (this.collaborativeEditing.getCollaborativeEditing()) { var currentSheetId = this.model.getId(); var nLockAllType = this.collaborativeEditing.isLockAllOther(currentSheetId); if (Asc.c_oAscMouseMoveLockedObjectType.None !== nLockAllType) { this.overlayCtx.clear(); } else { var arrayElementsMe = this.collaborativeEditing.getLockCellsMe(currentSheetId); var arrayElementsOther = this.collaborativeEditing.getLockCellsOther(currentSheetId); var arrayElements = arrayElementsMe.concat(arrayElementsOther); arrayElements = arrayElements.concat(this.collaborativeEditing.getArrayInsertColumnsBySheetId(currentSheetId)); arrayElements = arrayElements.concat(this.collaborativeEditing.getArrayInsertRowsBySheetId(currentSheetId)); for (i = 0; i < arrayElements.length; ++i) { var arFormulaTmp = new asc_Range(arrayElements[i].c1, arrayElements[i].r1, arrayElements[i].c2, arrayElements[i].r2); var aFormulaIntersection = arFormulaTmp.intersection(range); if (aFormulaIntersection) { // Координаты для автозаполнения _x1 = this.cols[aFormulaIntersection.c1].left - offsetX - this.width_2px; _x2 = this.cols[aFormulaIntersection.c2].left + this.cols[aFormulaIntersection.c2].width - offsetX + this.width_1px + this.width_2px; _y1 = this.rows[aFormulaIntersection.r1].top - offsetY - this.height_2px; _y2 = this.rows[aFormulaIntersection.r2].top + this.rows[aFormulaIntersection.r2].height - offsetY + this.height_1px + this.height_2px; // Выбираем наибольший range для очистки x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } } } } for (i = 0; i < this.arrActiveFormulaRanges.length; ++i) { this.arrActiveFormulaRanges[i].ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_3px; _x2 = arnIntersection.c2 > t.cols.length ? width : t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_3px; _y2 = arnIntersection.r2 > t.rows.length ? height : t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } }); } for (i = 0; i < this.arrActiveChartRanges.length; ++i) { this.arrActiveChartRanges[i].ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_3px; _x2 = arnIntersection.c2 > t.cols.length ? width : t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_3px; _y2 = arnIntersection.r2 > t.rows.length ? height : t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } }); } if (null !== this.activeMoveRange) { var activeMoveRangeClone = this.activeMoveRange.clone(true); // Увеличиваем, если выходим за область видимости // Critical Bug 17413 while (!this.cols[activeMoveRangeClone.c2]) { this.expandColsOnScroll(true); this.handlers.trigger("reinitializeScrollX"); } while (!this.rows[activeMoveRangeClone.r2]) { this.expandRowsOnScroll(true); this.handlers.trigger("reinitializeScrollY"); } // Координаты для перемещения диапазона _x1 = this.cols[activeMoveRangeClone.c1].left - offsetX - this.width_2px; _x2 = this.cols[activeMoveRangeClone.c2].left + this.cols[activeMoveRangeClone.c2].width - offsetX + this.width_1px + this.width_2px; _y1 = this.rows[activeMoveRangeClone.r1].top - offsetY - this.height_2px; _y2 = this.rows[activeMoveRangeClone.r2].top + this.rows[activeMoveRangeClone.r2].height - offsetY + this.height_1px + this.height_2px; // Выбираем наибольший range для очистки x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } if (null !== this.copyActiveRange) { this.copyActiveRange.ranges.forEach(function (item) { var arnIntersection = item.intersectionSimple(range); if (arnIntersection) { _x1 = t.cols[arnIntersection.c1].left - offsetX - t.width_2px; _x2 = t.cols[arnIntersection.c2].left + t.cols[arnIntersection.c2].width - offsetX + t.width_1px + /* Это ширина "квадрата" для автофильтра от границы ячейки */t.width_2px; _y1 = t.rows[arnIntersection.r1].top - offsetY - t.height_2px; _y2 = t.rows[arnIntersection.r2].top + t.rows[arnIntersection.r2].height - offsetY + t.height_1px + /* Это высота "квадрата" для автофильтра от границы ячейки */t.height_2px; x1 = Math.min(x1, _x1); x2 = Math.max(x2, _x2); y1 = Math.min(y1, _y1); y2 = Math.max(y2, _y2); } }); } if (!(Number.MAX_VALUE === x1 && -Number.MAX_VALUE === x2 && Number.MAX_VALUE === y1 && -Number.MAX_VALUE === y2)) { ctx.save() .beginPath() .rect(this.cellsLeft, this.cellsTop, ctx.getWidth() - this.cellsLeft, ctx.getHeight() - this.cellsTop) .clip() .clearRect(x1, y1, x2 - x1, y2 - y1) .restore(); } return this; }; WorksheetView.prototype.updateSelection = function () { this.cleanSelection(); this._drawSelection(); }; WorksheetView.prototype.updateSelectionWithSparklines = function () { if (!this.checkSelectionSparkline()) { this._drawSelection(); } }; // mouseX - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.drawColumnGuides = function ( col, x, y, mouseX ) { x *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIX() ); // Учитываем координаты точки, где мы начали изменение размера x += mouseX; var ctx = this.overlayCtx; var offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; var offsetFrozen = this.getFrozenPaneOffset( false, true ); offsetX -= offsetFrozen.offsetX; var x1 = this.cols[col].left - offsetX - this.width_1px; var h = ctx.getHeight(); var widthPt = (x - x1); if ( 0 > widthPt ) { widthPt = 0; } ctx.clear(); this._drawSelection(); ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( x1, 0, this.width_1px, h ) .fillRect( x, 0, this.width_1px, h ); return new asc_CMM( { type : Asc.c_oAscMouseMoveType.ResizeColumn, sizeCCOrPt: this.model.colWidthToCharCount(widthPt), sizePx : widthPt * 96 / 72, x : (x1 + this.cols[col].width) * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIX() ), y : this.cellsTop * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIY() ) } ); }; // mouseY - это разница стартовых координат от мыши при нажатии и границы WorksheetView.prototype.drawRowGuides = function ( row, x, y, mouseY ) { y *= asc_getcvt( 0/*px*/, 1/*pt*/, this._getPPIY() ); // Учитываем координаты точки, где мы начали изменение размера y += mouseY; var ctx = this.overlayCtx; var offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; var offsetFrozen = this.getFrozenPaneOffset( true, false ); offsetY -= offsetFrozen.offsetY; var y1 = this.rows[row].top - offsetY - this.height_1px; var w = ctx.getWidth(); var heightPt = (y - y1); if ( 0 > heightPt ) { heightPt = 0; } ctx.clear(); this._drawSelection(); ctx.setFillPattern( this.settings.ptrnLineDotted1 ) .fillRect( 0, y1, w, this.height_1px ) .fillRect( 0, y, w, this.height_1px ); return new asc_CMM( { type : Asc.c_oAscMouseMoveType.ResizeRow, sizeCCOrPt: heightPt, sizePx : heightPt * 96 / 72, x : this.cellsLeft * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIX() ), y : (y1 + this.rows[row].height) * asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIY() ) } ); }; // --- Cache --- WorksheetView.prototype._cleanCache = function (range) { var r, c, row; if (range === undefined) { range = this.model.selectionRange.getLast(); } for (r = range.r1; r <= range.r2; ++r) { row = this.cache.rows[r]; if (row !== undefined) { // Должны еще крайнюю удалить c = range.c1; if (row.erased[c - 1]) { delete row.erased[c - 1]; } for (; c <= range.c2; ++c) { if (row.columns[c]) { delete row.columns[c]; } if (row.columnsWithText[c]) { delete row.columnsWithText[c]; } if (row.erased[c]) { delete row.erased[c]; } } } } }; // ----- Cell text cache ----- /** Очищает кэш метрик текста ячеек */ WorksheetView.prototype._cleanCellsTextMetricsCache = function () { var s = this.cache.sectors = []; var vr = this.visibleRange; var h = vr.r2 + 1 - vr.r1; var rl = this.rows.length; var rc = asc_floor(rl / h) + (rl % h > 0 ? 1 : 0); var range = new asc_Range(0, 0, this.cols.length - 1, h - 1); var j; for (j = rc; j > 0; --j, range.r1 += h, range.r2 += h) { if (j === 1 && rl % h > 0) { range.r2 = rl - 1; } s.push(range.clone()); } }; /** * Обновляет общий кэш и кэширует метрики текста ячеек для указанного диапазона * @param {Asc.Range} [range] Диапазон кэширования текта */ WorksheetView.prototype._prepareCellTextMetricsCache = function (range) { var firstUpdateRow = null; if (!range) { range = this.visibleRange; if (this.topLeftFrozenCell) { var row = this.topLeftFrozenCell.getRow0(); var col = this.topLeftFrozenCell.getCol0(); if (0 < row && 0 < col) { firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2(new Asc.Range(0, 0, col - 1, row - 1))); } if (0 < row) { firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2( new Asc.Range(this.visibleRange.c1, 0, this.visibleRange.c2, row - 1))); } if (0 < col) { firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2( new Asc.Range(0, this.visibleRange.r1, col - 1, this.visibleRange.r2))); } } } firstUpdateRow = asc.getMinValueOrNull(firstUpdateRow, this._prepareCellTextMetricsCache2(range)); if (null !== firstUpdateRow || this.isChanged) { // Убрал это из _calcCellsTextMetrics, т.к. вызов был для каждого сектора(добавляло тормоза: баг 20388) // Код нужен для бага http://bugzilla.onlyoffice.com/show_bug.cgi?id=13875 this._updateRowPositions(); this._calcVisibleRows(); if (this.objectRender) { this.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: firstUpdateRow}, true); } } }; /** * Обновляет общий кэш и кэширует метрики текста ячеек для указанного диапазона (сама реализация, напрямую не вызывать, только из _prepareCellTextMetricsCache) * @param {Asc.Range} [range] Диапазон кэширования текта */ WorksheetView.prototype._prepareCellTextMetricsCache2 = function (range) { var firstUpdateRow = null; var s = this.cache.sectors; for (var i = 0; i < s.length;) { if (s[i].isIntersect(range)) { this._calcCellsTextMetrics(s[i]); s.splice(i, 1); firstUpdateRow = null !== firstUpdateRow ? Math.min(range.r1, firstUpdateRow) : range.r1; continue; } ++i; } return firstUpdateRow; }; /** * Кэширует метрики текста для диапазона ячеек * @param {Asc.Range} range description */ WorksheetView.prototype._calcCellsTextMetrics = function (range) { var colsLength = this.cols.length; if (range === undefined) { range = new Asc.Range(0, 0, colsLength - 1, this.rows.length - 1); } var t = this; var curRow = -1, skipRow = false; this.model.getRange3(range.r1, 0, range.r2, range.c2)._foreachNoEmpty(function(cell, row, col) { if (curRow !== row) { curRow = row; skipRow = t.height_1px > t.rows[row].height; } if(!skipRow && !(colsLength <= col || t.width_1px > t.cols[col].width)) { t._addCellTextToCache(col, row); } }); this.isChanged = false; }; WorksheetView.prototype._fetchRowCache = function (row) { return (this.cache.rows[row] = ( this.cache.rows[row] || new CacheElement() )); }; WorksheetView.prototype._fetchCellCache = function (col, row) { var r = this._fetchRowCache(row); return (r.columns[col] = ( r.columns[col] || {} )); }; WorksheetView.prototype._fetchCellCacheText = function (col, row) { var r = this._fetchRowCache(row); return (r.columnsWithText[col] = ( r.columnsWithText[col] || {} )); }; WorksheetView.prototype._getRowCache = function (row) { return this.cache.rows[row]; }; WorksheetView.prototype._getCellCache = function (col, row) { var r = this.cache.rows[row]; return r ? r.columns[col] : undefined; }; WorksheetView.prototype._getCellTextCache = function (col, row, dontLookupMergedCells) { var r = this.cache.rows[row], c = r ? r.columns[col] : undefined; if (c && c.text) { return c.text; } else if (!dontLookupMergedCells) { // ToDo проверить это условие, возможно оно избыточно var range = this.model.getMergedByCell(row, col); return null !== range ? this._getCellTextCache(range.c1, range.r1, true) : undefined; } return undefined; }; WorksheetView.prototype._changeColWidth = function (col, width, pad) { var cc = Math.min(this.model.colWidthToCharCount(width + pad), Asc.c_oAscMaxColumnWidth); var modelw = this.model.charCountToModelColWidth(cc); var colw = this._calcColWidth(modelw); if (colw.width > this.cols[col].width) { this.cols[col].width = colw.width; this.cols[col].innerWidth = colw.innerWidth; this.cols[col].charCount = colw.charCount; History.Create_NewPoint(); History.StartTransaction(); // Выставляем, что это bestFit this.model.setColBestFit(true, modelw, col, col); History.EndTransaction(); this._updateColumnPositions(); this.isChanged = true; } }; WorksheetView.prototype._addCellTextToCache = function (col, row, canChangeColWidth) { var self = this; function makeFnIsGoodNumFormat(flags, width) { return function (str) { return self.stringRender.measureString(str, flags, width).width <= width; }; } var c = this._getCell(col, row); if (null === c) { return col; } var bUpdateScrollX = false; var bUpdateScrollY = false; // Проверка на увеличение колличества столбцов if (col >= this.cols.length) { bUpdateScrollX = this.expandColsOnScroll(/*isNotActive*/ false, /*updateColsCount*/ true); } // Проверка на увеличение колличества строк if (row >= this.rows.length) { bUpdateScrollY = this.expandRowsOnScroll(/*isNotActive*/ false, /*updateRowsCount*/ true); } if (bUpdateScrollX && bUpdateScrollY) { this.handlers.trigger("reinitializeScroll"); } else if (bUpdateScrollX) { this.handlers.trigger("reinitializeScrollX"); } else if (bUpdateScrollY) { this.handlers.trigger("reinitializeScrollY"); } var str, tm, isMerged = false, strCopy; // Range для замерженной ячейки var fl = this._getCellFlags(c); var mc = fl.merged; var fMergedColumns = false; // Замержены ли колонки (если да, то автоподбор ширины не должен работать) var fMergedRows = false; // Замержены ли строки (если да, то автоподбор высоты не должен работать) if (null !== mc) { if (col !== mc.c1 || row !== mc.r1) { // Проверим внесена ли первая ячейка в cache (иначе если была скрыта первая строка или первый столбец, то мы не внесем) if (undefined === this._getCellTextCache(mc.c1, mc.r1, true)) { return this._addCellTextToCache(mc.c1, mc.r1, canChangeColWidth); } return mc.c2; } // skip other merged cell from range if (mc.c1 !== mc.c2) { fMergedColumns = true; } if (mc.r1 !== mc.r2) { fMergedRows = true; } isMerged = true; } var align = c.getAlign(); var angle = align.getAngle(); var va = align.getAlignVertical(); if (c.isEmptyTextString()) { if (!angle && c.isNotDefaultFont()) { // Пустая ячейка с измененной гарнитурой или размером, учитвается в высоте str = c.getValue2(); if (0 < str.length) { strCopy = str[0]; if (!(tm = AscCommonExcel.g_oCacheMeasureEmpty.get(strCopy.format))) { // Без текста не будет толка strCopy = strCopy.clone(); strCopy.text = 'A'; tm = this._roundTextMetrics(this.stringRender.measureString([strCopy], fl)); AscCommonExcel.g_oCacheMeasureEmpty.add(strCopy.format, tm); } this._updateRowHeight(tm, col, row, fl, isMerged, fMergedRows, va); } } return mc ? mc.c2 : col; } var dDigitsCount = 0; var colWidth = 0; var cellType = c.getType(); fl.isNumberFormat = (null === cellType || CellValueType.String !== cellType); // Автоподбор делается по любому типу (кроме строки) var numFormatStr = c.getNumFormatStr(); var pad = this.width_padding * 2 + this.width_1px; var sstr, sfl, stm; if (!this.cols[col].isCustomWidth && fl.isNumberFormat && !fMergedColumns && (c_oAscCanChangeColWidth.numbers === canChangeColWidth || c_oAscCanChangeColWidth.all === canChangeColWidth)) { colWidth = this.cols[col].innerWidth; // Измеряем целую часть числа sstr = c.getValue2(gc_nMaxDigCountView, function () { return true; }); if ("General" === numFormatStr && c_oAscCanChangeColWidth.all !== canChangeColWidth) { // asc.truncFracPart изменяет исходный массив, поэтому клонируем var fragmentsTmp = []; for (var k = 0; k < sstr.length; ++k) { fragmentsTmp.push(sstr[k].clone()); } sstr = asc.truncFracPart(fragmentsTmp); } sfl = fl.clone(); sfl.wrapText = false; stm = this._roundTextMetrics(this.stringRender.measureString(sstr, sfl, colWidth)); // Если целая часть числа не убирается в ячейку, то расширяем столбец if (stm.width > colWidth) { this._changeColWidth(col, stm.width, pad); } // Обновленная ячейка dDigitsCount = this.cols[col].charCount; colWidth = this.cols[col].innerWidth; } else if (null === mc) { // Обычная ячейка dDigitsCount = this.cols[col].charCount; colWidth = this.cols[col].innerWidth; // подбираем ширину if (!this.cols[col].isCustomWidth && !fMergedColumns && !fl.wrapText && c_oAscCanChangeColWidth.all === canChangeColWidth) { sstr = c.getValue2(gc_nMaxDigCountView, function () { return true; }); stm = this._roundTextMetrics(this.stringRender.measureString(sstr, fl, colWidth)); if (stm.width > colWidth) { this._changeColWidth(col, stm.width, pad); // Обновленная ячейка dDigitsCount = this.cols[col].charCount; colWidth = this.cols[col].innerWidth; } } } else { // Замерженная ячейка, нужна сумма столбцов for (var i = mc.c1; i <= mc.c2 && i < this.cols.length; ++i) { colWidth += this.cols[i].width; dDigitsCount += this.cols[i].charCount; } colWidth -= pad; } var rowHeight = this.rows[row].height; // ToDo dDigitsCount нужно рассчитывать исходя не из дефалтового шрифта и размера, а исходя из текущего шрифта и размера ячейки str = c.getValue2(dDigitsCount, makeFnIsGoodNumFormat(fl, colWidth)); var ha = c.getAlignHorizontalByValue(align.getAlignHorizontal()); var maxW = fl.wrapText || fl.shrinkToFit || isMerged || asc.isFixedWidthCell(str) ? this._calcMaxWidth(col, row, mc) : undefined; tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, maxW)); var cto = (isMerged || fl.wrapText || fl.shrinkToFit) ? { maxWidth: maxW - this.cols[col].innerWidth + this.cols[col].width, leftSide: 0, rightSide: 0 } : this._calcCellTextOffset(col, row, ha, tm.width); // check right side of cell text and append columns if it exceeds existing cells borders if (!isMerged) { var rside = this.cols[col - cto.leftSide].left + tm.width; var lc = this.cols[this.cols.length - 1]; if (rside > lc.left + lc.width) { this._appendColumns(rside); cto = this._calcCellTextOffset(col, row, ha, tm.width); } } var textBound = {}; if (angle) { // повернутый текст учитывает мерж ячеек по строкам if (fMergedRows) { rowHeight = 0; for (var j = mc.r1; j <= mc.r2 && j < this.nRowsCount; ++j) { rowHeight += this.rows[j].height; } } var textW = tm.width; if (fl.wrapText) { if (this.rows[row].isCustomHeight) { tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, rowHeight)); textBound = this.stringRender.getTransformBound(angle, colWidth, rowHeight, tm.width, ha, va, rowHeight); } else { if (!fMergedRows) { rowHeight = tm.height; } tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, rowHeight)); textBound = this.stringRender.getTransformBound(angle, colWidth, rowHeight, tm.width, ha, va, tm.width); } } else { textBound = this.stringRender.getTransformBound(angle, colWidth, rowHeight, textW, ha, va, maxW); } // NOTE: если проекция строчки на Y больше высоты ячейки подставлять # и рисовать все по центру // if (fl.isNumberFormat) { // var prj = Math.abs(Math.sin(angle * Math.PI / 180.0) * tm.width); // if (prj > rowHeight) { // //if (maxW === undefined) {} // maxW = rowHeight / Math.abs(Math.cos(angle * Math.PI / 180.0)); // str = c.getValue2(gc_nMaxDigCountView, makeFnIsGoodNumFormat(fl, maxW)); // // for (i = 0; i < str.length; ++i) { // var f = str[i].format; // if (f) f.repeat = true; // } // // tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, maxW)); // } // } } this._fetchCellCache(col, row).text = { state: this.stringRender.getInternalState(), flags: fl, metrics: tm, cellW: cto.maxWidth, cellHA: ha, cellVA: va, sideL: cto.leftSide, sideR: cto.rightSide, cellType: cellType, isFormula: c.isFormula(), angle: angle, textBound: textBound }; this._fetchCellCacheText(col, row).hasText = true; if (!angle && (cto.leftSide !== 0 || cto.rightSide !== 0)) { this._addErasedBordersToCache(col - cto.leftSide, col + cto.rightSide, row); } fMergedRows = fMergedRows || (isMerged && fl.wrapText); this._updateRowHeight(tm, col, row, fl, isMerged, fMergedRows, va, ha, angle, maxW, colWidth, textBound); return mc ? mc.c2 : col; }; WorksheetView.prototype._updateRowHeight = function (tm, col, row, flags, isMerged, fMergedRows, va, ha, angle, maxW, colWidth, textBound) { var rowInfo = this.rows[row]; // update row's descender if (va !== Asc.c_oAscVAlign.Top && va !== Asc.c_oAscVAlign.Center && !isMerged) { rowInfo.descender = Math.max(rowInfo.descender, tm.height - tm.baseline); } // update row's height // Замерженная ячейка (с 2-мя или более строками) не влияет на высоту строк! if (!rowInfo.isCustomHeight && !(window["NATIVE_EDITOR_ENJINE"] && this.notUpdateRowHeight) && !fMergedRows) { var newHeight = tm.height + this.height_1px; if (angle && textBound) { newHeight = Math.max(rowInfo.height, textBound.height); } newHeight = Math.min(this.maxRowHeight, Math.max(rowInfo.height, newHeight)); if (newHeight !== rowInfo.height) { rowInfo.heightReal = rowInfo.height = newHeight; History.TurnOff(); this.model.setRowHeight(rowInfo.height, row, row, false); History.TurnOn(); if (angle) { if (flags.wrapText && !rowInfo.isCustomHeight) { maxW = tm.width; } textBound = this.stringRender.getTransformBound(angle, colWidth, rowInfo.height, tm.width, ha, va, maxW); this._fetchCellCache(col, row).text.textBound = textBound; } this.isChanged = true; } } }; WorksheetView.prototype._calcMaxWidth = function (col, row, mc) { if (null === mc) { return this.cols[col].innerWidth; } var width = this.cols[mc.c1].innerWidth; for (var c = mc.c1 + 1; c <= mc.c2 && c < this.cols.length; ++c) { width += this.cols[c].width; } return width; }; WorksheetView.prototype._calcCellTextOffset = function (col, row, textAlign, textWidth) { var sideL = [0], sideR = [0], i; var maxWidth = this.cols[col].width; var ls = 0, rs = 0; var pad = this.settings.cells.padding * asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); var textW = textAlign === AscCommon.align_Center ? (textWidth + maxWidth) * 0.5 : textWidth + pad; if (textAlign === AscCommon.align_Right || textAlign === AscCommon.align_Center) { sideL = this._calcCellsWidth(col, 0, row); // condition (sideL.lenght >= 1) is always true for (i = 0; i < sideL.length && textW > sideL[i]; ++i) {/* do nothing */ } ls = i !== sideL.length ? i : i - 1; } if (textAlign !== AscCommon.align_Right) { sideR = this._calcCellsWidth(col, this.cols.length - 1, row); // condition (sideR.lenght >= 1) is always true for (i = 0; i < sideR.length && textW > sideR[i]; ++i) {/* do nothing */ } rs = i !== sideR.length ? i : i - 1; } if (textAlign === AscCommon.align_Center) { maxWidth = (sideL[ls] - sideL[0]) + sideR[rs]; } else { maxWidth = textAlign === AscCommon.align_Right ? sideL[ls] : sideR[rs]; } return { maxWidth: maxWidth, leftSide: ls, rightSide: rs }; }; WorksheetView.prototype._calcCellsWidth = function (colBeg, colEnd, row) { var inc = colBeg <= colEnd ? 1 : -1, res = []; for (var i = colBeg; (colEnd - i) * inc >= 0; i += inc) { if (i !== colBeg && !this._isCellEmptyOrMerged(i, row)) { break; } res.push(this.cols[i].width); if (res.length > 1) { res[res.length - 1] += res[res.length - 2]; } } return res; }; // Ищет текст в строке (columnsWithText - это колонки, в которых есть текст) WorksheetView.prototype._findSourceOfCellText = function (col, row) { var r = this._getRowCache(row); if (r) { for (var i in r.columnsWithText) { if (!r.columns[i] || 0 === this.cols[i].width) { continue; } var ct = r.columns[i].text; if (!ct) { continue; } i >>= 0; var lc = i - ct.sideL, rc = i + ct.sideR; if (col >= lc && col <= rc) { return i; } } } return -1; }; // ----- Merged cells cache ----- WorksheetView.prototype._isMergedCells = function (range) { return range.isEqual(this.model.getMergedByCell(range.r1, range.c1)); }; // ----- Cell borders cache ----- WorksheetView.prototype._addErasedBordersToCache = function (colBeg, colEnd, row) { var rc = this._fetchRowCache(row); for (var col = colBeg; col < colEnd; ++col) { rc.erased[col] = true; } }; WorksheetView.prototype._isLeftBorderErased = function (col, rowCache) { return rowCache.erased[col - 1] === true; }; WorksheetView.prototype._isRightBorderErased = function (col, rowCache) { return rowCache.erased[col] === true; }; WorksheetView.prototype._calcMaxBorderWidth = function (b1, b2) { // ToDo пересмотреть return Math.max(b1 && b1.w, b2 && b2.w); }; // ----- Cells utilities ----- /** * Возвращает заголовок колонки по индексу * @param {Number} col Индекс колонки * @return {String} */ WorksheetView.prototype._getColumnTitle = function (col) { return AscCommon.g_oCellAddressUtils.colnumToColstrFromWsView(col + 1); }; /** * Возвращает заголовок строки по индексу * @param {Number} row Индекс строки * @return {String} */ WorksheetView.prototype._getRowTitle = function (row) { return "" + (row + 1); }; /** * Возвращает заголовок ячейки по индексу * @param {Number} col Индекс колонки * @param {Number} row Индекс строки * @return {String} */ WorksheetView.prototype._getCellTitle = function (col, row) { return this._getColumnTitle(col) + this._getRowTitle(row); }; /** * Возвращает ячейку таблицы (из Worksheet) * @param {Number} col Индекс колонки * @param {Number} row Индекс строки * @return {Range} */ WorksheetView.prototype._getCell = function (col, row) { if (this.nRowsCount < this.model.getRowsCount() + 1) { this.expandRowsOnScroll(false, true, 0); } // Передаем 0, чтобы увеличить размеры if (this.nColsCount < this.model.getColsCount() + 1) { this.expandColsOnScroll(false, true, 0); } // Передаем 0, чтобы увеличить размеры if (col < 0 || col >= this.nColsCount || row < 0 || row >= this.nRowsCount) { return null; } return this.model.getCell3(row, col); }; WorksheetView.prototype._getVisibleCell = function (col, row) { return this.model.getCell3(row, col); }; WorksheetView.prototype._getCellFlags = function (col, row) { var c = row !== undefined ? this._getCell(col, row) : col; var fl = new CellFlags(); if (null !== c) { var align = c.getAlign(); fl.wrapText = align.getWrap(); fl.shrinkToFit = fl.wrapText ? false : align.getShrinkToFit(); fl.merged = c.hasMerged(); fl.textAlign = c.getAlignHorizontalByValue(align.getAlignHorizontal()); } return fl; }; WorksheetView.prototype._isCellNullText = function (col, row) { var c = row !== undefined ? this._getCell(col, row) : col; return null === c || c.isNullText(); }; WorksheetView.prototype._isCellEmptyOrMerged = function (col, row) { var c = row !== undefined ? this._getCell(col, row) : col; return null === c || (c.isNullText() && null === c.hasMerged()); }; WorksheetView.prototype._getRange = function (c1, r1, c2, r2) { return this.model.getRange3(r1, c1, r2, c2); }; WorksheetView.prototype._selectColumnsByRange = function () { var ar = this.model.selectionRange.getLast(); var type = ar.getType(); if (c_oAscSelectionType.RangeMax !== type) { this.cleanSelection(); if (c_oAscSelectionType.RangeRow === type) { ar.assign(0, 0, gc_nMaxCol0, gc_nMaxRow0); } else { ar.assign(ar.c1, 0, ar.c2, gc_nMaxRow0); } this._drawSelection(); this._updateSelectionNameAndInfo(); } }; WorksheetView.prototype._selectRowsByRange = function () { var ar = this.model.selectionRange.getLast(); var type = ar.getType(); if (c_oAscSelectionType.RangeMax !== type) { this.cleanSelection(); if (c_oAscSelectionType.RangeCol === type) { ar.assign(0, 0, gc_nMaxCol0, gc_nMaxRow0); } else { ar.assign(0, ar.r1, gc_nMaxCol0, ar.r2); } this._drawSelection(); this._updateSelectionNameAndInfo(); } }; /** * Возвращает true, если диапазон больше видимой области, и операции над ним могут привести к задержкам * @param {Asc.Range} range Диапазон для проверки * @returns {Boolean} */ WorksheetView.prototype._isLargeRange = function (range) { var vr = this.visibleRange; return range.c2 - range.c1 + 1 > (vr.c2 - vr.c1 + 1) * 3 || range.r2 - range.r1 + 1 > (vr.r2 - vr.r1 + 1) * 3; }; WorksheetView.prototype.drawDepCells = function () { var ctx = this.overlayCtx, _cc = this.cellCommentator, c, node, that = this; ctx.clear(); this._drawSelection(); var color = new CColor(0, 0, 255); function draw_arrow(context, fromx, fromy, tox, toy) { var headlen = 9, showArrow = tox > that.getCellLeft(0, 0) && toy > that.getCellTop(0, 0), dx = tox - fromx, dy = toy - fromy, tox = tox > that.getCellLeft(0, 0) ? tox : that.getCellLeft(0, 0), toy = toy > that.getCellTop(0, 0) ? toy : that.getCellTop(0, 0), angle = Math.atan2(dy, dx), _a = Math.PI / 18; // ToDo посмотреть на четкость moveTo, lineTo context.save() .setLineWidth(1) .beginPath() .lineDiag .moveTo(_cc.pxToPt(fromx), _cc.pxToPt(fromy)) .lineTo(_cc.pxToPt(tox), _cc.pxToPt(toy)); // .dashLine(_cc.pxToPt(fromx-.5), _cc.pxToPt(fromy-.5), _cc.pxToPt(tox-.5), _cc.pxToPt(toy-.5), 15, 5) if (showArrow) { context .moveTo(_cc.pxToPt(tox - headlen * Math.cos(angle - _a)), _cc.pxToPt(toy - headlen * Math.sin(angle - _a))) .lineTo(_cc.pxToPt(tox), _cc.pxToPt(toy)) .lineTo(_cc.pxToPt(tox - headlen * Math.cos(angle + _a)), _cc.pxToPt(toy - headlen * Math.sin(angle + _a))) .lineTo(_cc.pxToPt(tox - headlen * Math.cos(angle - _a)), _cc.pxToPt(toy - headlen * Math.sin(angle - _a))); } context .setStrokeStyle(color) .setFillStyle(color) .stroke() .fill() .closePath() .restore(); } function gCM(_this, col, row) { var metrics = {top: 0, left: 0, width: 0, height: 0, result: false}; // px var fvr = _this.getFirstVisibleRow(); var fvc = _this.getFirstVisibleCol(); var mergedRange = _this.model.getMergedByCell(row, col); if (mergedRange && (fvc < mergedRange.c2) && (fvr < mergedRange.r2)) { var startCol = (mergedRange.c1 > fvc) ? mergedRange.c1 : fvc; var startRow = (mergedRange.r1 > fvr) ? mergedRange.r1 : fvr; metrics.top = _this.getCellTop(startRow, 0) - _this.getCellTop(fvr, 0) + _this.getCellTop(0, 0); metrics.left = _this.getCellLeft(startCol, 0) - _this.getCellLeft(fvc, 0) + _this.getCellLeft(0, 0); for (var i = startCol; i <= mergedRange.c2; i++) { metrics.width += _this.getColumnWidth(i, 0) } for (var i = startRow; i <= mergedRange.r2; i++) { metrics.height += _this.getRowHeight(i, 0) } metrics.result = true; } else { metrics.top = _this.getCellTop(row, 0) - _this.getCellTop(fvr, 0) + _this.getCellTop(0, 0); metrics.left = _this.getCellLeft(col, 0) - _this.getCellLeft(fvc, 0) + _this.getCellLeft(0, 0); metrics.width = _this.getColumnWidth(col, 0); metrics.height = _this.getRowHeight(row, 0); metrics.result = true; } return metrics } for (var id in this.depDrawCells) { c = this.depDrawCells[id].from; node = this.depDrawCells[id].to; var mainCellMetrics = gCM(this, c.nCol, c.nRow), nodeCellMetrics, _t1, _t2; for (var id in node) { if (!node[id].isArea) { _t1 = gCM(this, node[id].returnCell().nCol, node[id].returnCell().nRow) nodeCellMetrics = { t: _t1.top, l: _t1.left, w: _t1.width, h: _t1.height, apt: _t1.top + _t1.height / 2, apl: _t1.left + _t1.width / 4 }; } else { var _t1 = gCM(_wsV, me[id].getBBox0().c1, me[id].getBBox0().r1), _t2 = gCM(_wsV, me[id].getBBox0().c2, me[id].getBBox0().r2); nodeCellMetrics = { t: _t1.top, l: _t1.left, w: _t2.left + _t2.width - _t1.left, h: _t2.top + _t2.height - _t1.top, apt: _t1.top + _t1.height / 2, apl: _t1.left + _t1.width / 4 }; } var x1 = Math.floor(nodeCellMetrics.apl), y1 = Math.floor(nodeCellMetrics.apt), x2 = Math.floor( mainCellMetrics.left + mainCellMetrics.width / 4), y2 = Math.floor( mainCellMetrics.top + mainCellMetrics.height / 2); if (x1 < 0 && x2 < 0 || y1 < 0 && y2 < 0) { continue; } if (y1 < this.getCellTop(0, 0)) { y1 -= this.getCellTop(0, 0); } if (y1 < 0 && y2 > 0) { var _x1 = Math.floor(Math.sqrt((x1 - x2) * (x1 - x2) * y1 * y1 / ((y2 - y1) * (y2 - y1)))); // x1 -= (x1-x2>0?1:-1)*_x1; if (x1 > x2) { x1 -= _x1; } else if (x1 < x2) { x1 += _x1; } } else if (y1 > 0 && y2 < 0) { var _x2 = Math.floor(Math.sqrt((x1 - x2) * (x1 - x2) * y2 * y2 / ((y2 - y1) * (y2 - y1)))); // x2 -= (x2-x1>0?1:-1)*_x2; if (x2 > x1) { x2 -= _x2; } else if (x2 < x1) { x2 += _x2; } } if (x1 < 0 && x2 > 0) { var _y1 = Math.floor(Math.sqrt((y1 - y2) * (y1 - y2) * x1 * x1 / ((x2 - x1) * (x2 - x1)))) // y1 -= (y1-y2>0?1:-1)*_y1; if (y1 > y2) { y1 -= _y1; } else if (y1 < y2) { y1 += _y1; } } else if (x1 > 0 && x2 < 0) { var _y2 = Math.floor(Math.sqrt((y1 - y2) * (y1 - y2) * x2 * x2 / ((x2 - x1) * (x2 - x1)))) // y2 -= (y2-y1>0?1:-1)*_y2; if (y2 > y1) { y2 -= _y2; } else if (y2 < y1) { y2 += _y2; } } draw_arrow(ctx, x1 < this.getCellLeft(0, 0) ? this.getCellLeft(0, 0) : x1, y1 < this.getCellTop(0, 0) ? this.getCellTop(0, 0) : y1, x2, y2); // draw_arrow(ctx, x1, y1, x2, y2); // ToDo посмотреть на четкость rect if (nodeCellMetrics.apl > this.getCellLeft(0, 0) && nodeCellMetrics.apt > this.getCellTop(0, 0)) { ctx.save() .beginPath() .arc(_cc.pxToPt(Math.floor(nodeCellMetrics.apl)), _cc.pxToPt(Math.floor(nodeCellMetrics.apt)), 3, 0, 2 * Math.PI, false, -0.5, -0.5) .setFillStyle(color) .fill() .closePath() .setLineWidth(1) .setStrokeStyle(color) .rect(_cc.pxToPt(nodeCellMetrics.l), _cc.pxToPt(nodeCellMetrics.t), _cc.pxToPt(nodeCellMetrics.w - 1), _cc.pxToPt(nodeCellMetrics.h - 1)) .stroke() .restore(); } } } }; WorksheetView.prototype.prepareDepCells = function (se) { this.drawDepCells(); }; WorksheetView.prototype.cleanDepCells = function () { this.depDrawCells = null; this.drawDepCells(); }; // ----- Text drawing ----- WorksheetView.prototype._getPPIX = function () { return this.drawingCtx.getPPIX(); }; WorksheetView.prototype._getPPIY = function () { return this.drawingCtx.getPPIY(); }; WorksheetView.prototype._setFont = function (drawingCtx, name, size) { var ctx = drawingCtx || this.drawingCtx; ctx.setFont(new asc.FontProperties(name, size)); }; /** * @param {Asc.TextMetrics} tm * @return {Asc.TextMetrics} */ WorksheetView.prototype._roundTextMetrics = function (tm) { tm.width = asc_calcnpt(tm.width, this._getPPIX()); tm.height = asc_calcnpt(tm.height, 96); tm.baseline = asc_calcnpt(tm.baseline, 96); if (tm.centerline !== undefined) { tm.centerline = asc_calcnpt(tm.centerline, 96); } return tm; }; WorksheetView.prototype._calcTextHorizPos = function (x1, x2, tm, halign) { switch (halign) { case AscCommon.align_Center: return asc_calcnpt(0.5 * (x1 + x2 + this.width_1px - tm.width), this._getPPIX()); case AscCommon.align_Right: return x2 + this.width_1px - this.width_padding - tm.width; case AscCommon.align_Justify: default: return x1 + this.width_padding; } }; WorksheetView.prototype._calcTextVertPos = function (y1, y2, baseline, tm, valign) { switch (valign) { case Asc.c_oAscVAlign.Center: return asc_calcnpt(0.5 * (y1 + y2 - tm.height), this._getPPIY()) - this.height_1px; // ToDo возможно стоит тоже использовать 96 case Asc.c_oAscVAlign.Top: return y1 - this.height_1px; default: return baseline - tm.baseline; } }; WorksheetView.prototype._calcTextWidth = function (x1, x2, tm, halign) { switch (halign) { case AscCommon.align_Justify: return x2 + this.width_1px - this.width_padding * 2 - x1; default: return tm.width; } }; // ----- Scrolling ----- WorksheetView.prototype._calcCellPosition = function (c, r, dc, dr) { var t = this; var vr = t.visibleRange; function findNextCell(col, row, dx, dy) { var state = t._isCellNullText(col, row); var i = col + dx; var j = row + dy; while (i >= 0 && i < t.cols.length && j >= 0 && j < t.rows.length) { var newState = t._isCellNullText(i, j); if (newState !== state) { var ret = {}; ret.col = state ? i : i - dx; ret.row = state ? j : j - dy; if (ret.col !== col || ret.row !== row || state) { return ret; } state = newState; } i += dx; j += dy; } // Проверки для перехода в самый конец (ToDo пока убрал, чтобы не добавлять тормозов) /*if (i === t.cols.length && state) i = gc_nMaxCol; if (j === t.rows.length && state) j = gc_nMaxRow;*/ return {col: i - dx, row: j - dy}; } function findEOT() { var obr = t.objectRender ? t.objectRender.getMaxColRow() : new AscCommon.CellBase(-1, -1); var maxCols = t.model.getColsCount(); var maxRows = t.model.getRowsCount(); var lastC = -1, lastR = -1; for (var col = 0; col < maxCols; ++col) { for (var row = 0; row < maxRows; ++row) { if (!t._isCellNullText(col, row)) { lastC = Math.max(lastC, col); lastR = Math.max(lastR, row); } } } return {col: Math.max(lastC, obr.col), row: Math.max(lastR, obr.row)}; } var eot = dc > +2.0001 && dc < +2.9999 && dr > +2.0001 && dr < +2.9999 ? findEOT() : null; var newCol = (function () { if (dc > +0.0001 && dc < +0.9999) { return c + (vr.c2 - vr.c1 + 1); } // PageDown if (dc < -0.0001 && dc > -0.9999) { return c - (vr.c2 - vr.c1 + 1); } // PageUp if (dc > +1.0001 && dc < +1.9999) { return findNextCell(c, r, +1, 0).col; } // Ctrl + -> if (dc < -1.0001 && dc > -1.9999) { return findNextCell(c, r, -1, 0).col; } // Ctrl + <- if (dc > +2.0001 && dc < +2.9999) { return (eot || findNextCell(c, r, +1, 0)).col; } // End if (dc < -2.0001 && dc > -2.9999) { return 0; } // Home return c + dc; })(); var newRow = (function () { if (dr > +0.0001 && dr < +0.9999) { return r + (vr.r2 - vr.r1 + 1); } if (dr < -0.0001 && dr > -0.9999) { return r - (vr.r2 - vr.r1 + 1); } if (dr > +1.0001 && dr < +1.9999) { return findNextCell(c, r, 0, +1).row; } if (dr < -1.0001 && dr > -1.9999) { return findNextCell(c, r, 0, -1).row; } if (dr > +2.0001 && dr < +2.9999) { return !eot ? 0 : eot.row; } if (dr < -2.0001 && dr > -2.9999) { return 0; } return r + dr; })(); if (newCol >= t.cols.length && newCol <= gc_nMaxCol0) { t.nColsCount = newCol + 1; t._calcWidthColumns(AscCommonExcel.recalcType.newLines); } if (newRow >= t.rows.length && newRow <= gc_nMaxRow0) { t.nRowsCount = newRow + 1; t._calcHeightRows(AscCommonExcel.recalcType.newLines); } return { col: newCol < 0 ? 0 : Math.min(newCol, t.cols.length - 1), row: newRow < 0 ? 0 : Math.min(newRow, t.rows.length - 1) }; }; WorksheetView.prototype._isColDrawnPartially = function (col, leftCol, diffWidth) { if (col <= leftCol || col >= this.nColsCount) { return false; } diffWidth = diffWidth ? diffWidth : 0; var c = this.cols; return c[col].left + c[col].width - c[leftCol].left + this.cellsLeft + diffWidth > this.drawingCtx.getWidth(); }; WorksheetView.prototype._isRowDrawnPartially = function (row, topRow, diffHeight) { if (row <= topRow || row >= this.nRowsCount) { return false; } diffHeight = diffHeight ? diffHeight : 0; var r = this.rows; return r[row].top + r[row].height - r[topRow].top + this.cellsTop + diffHeight > this.drawingCtx.getHeight(); }; WorksheetView.prototype._isVisibleX = function () { var vr = this.visibleRange; var c = this.cols; var x = c[vr.c2].left + c[vr.c2].width; var offsetFrozen = this.getFrozenPaneOffset(false, true); x += offsetFrozen.offsetX; return x - c[vr.c1].left + this.cellsLeft < this.drawingCtx.getWidth(); }; WorksheetView.prototype._isVisibleY = function () { var vr = this.visibleRange; var r = this.rows; var y = r[vr.r2].top + r[vr.r2].height; var offsetFrozen = this.getFrozenPaneOffset(true, false); y += offsetFrozen.offsetY; return y - r[vr.r1].top + this.cellsTop < this.drawingCtx.getHeight(); }; WorksheetView.prototype._updateVisibleRowsCount = function (skipScrollReinit) { var isUpdate = false; this._calcVisibleRows(); while (this._isVisibleY() && !this.isMaxRow()) { // Добавим еще строки, чтоб не было видно фон под таблицей this.expandRowsOnScroll(true); this._calcVisibleRows(); isUpdate = true; } if (!skipScrollReinit && isUpdate) { this.handlers.trigger("reinitializeScrollY"); } }; WorksheetView.prototype._updateVisibleColsCount = function (skipScrollReinit) { var isUpdate = false; this._calcVisibleColumns(); while (this._isVisibleX() && !this.isMaxCol()) { // Добавим еще столбцы, чтоб не было видно фон под таблицей this.expandColsOnScroll(true); this._calcVisibleColumns(); isUpdate = true; } if (!skipScrollReinit && isUpdate) { this.handlers.trigger("reinitializeScrollX"); } }; WorksheetView.prototype.isMaxRow = function () { var rowsCountCurrent = this.rows.length; if (gc_nMaxRow === rowsCountCurrent) { return true; } var rowsCount = this.model.getRowsCount() + 1; return rowsCount <= rowsCountCurrent && this.model.isDefaultHeightHidden(); }; WorksheetView.prototype.isMaxCol = function () { var colsCountCurrent = this.cols.length; if (gc_nMaxCol === colsCountCurrent) { return true; } var colsCount = this.model.getColsCount() + 1; return colsCount <= colsCountCurrent && this.model.isDefaultWidthHidden(); }; WorksheetView.prototype.scrollVertical = function (delta, editor) { var vr = this.visibleRange; var fixStartRow = new asc_Range(vr.c1, vr.r1, vr.c2, vr.r1); this._fixSelectionOfHiddenCells(0, delta >= 0 ? +1 : -1, fixStartRow); var start = this._calcCellPosition(vr.c1, fixStartRow.r1, 0, delta).row; fixStartRow.assign(vr.c1, start, vr.c2, start); this._fixSelectionOfHiddenCells(0, delta >= 0 ? +1 : -1, fixStartRow); this._fixVisibleRange(fixStartRow); var reinitScrollY = start !== fixStartRow.r1; // Для скролла вверх обычный сдвиг + дорисовка if (reinitScrollY && 0 > delta) { delta += fixStartRow.r1 - start; } start = fixStartRow.r1; if (start === vr.r1) { if (reinitScrollY) { this.handlers.trigger("reinitializeScrollY"); } return this; } if (!this.notUpdateRowHeight) { this.cleanSelection(); this.cellCommentator.cleanSelectedComment(); } var ctx = this.drawingCtx; var ctxW = ctx.getWidth(); var ctxH = ctx.getHeight(); var offsetX, offsetY, diffWidth = 0, diffHeight = 0, cFrozen = 0, rFrozen = 0; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); rFrozen = this.topLeftFrozenCell.getRow0(); diffWidth = this.cols[cFrozen].left - this.cols[0].left; diffHeight = this.rows[rFrozen].top - this.rows[0].top; } var oldVRE_isPartial = this._isRowDrawnPartially(vr.r2, vr.r1, diffHeight); var oldVR = vr.clone(); var oldStart = vr.r1; var oldEnd = vr.r2; // ToDo стоит тут переделать весь scroll vr.r1 = start; this._updateVisibleRowsCount(); // Это необходимо для того, чтобы строки, у которых высота по тексту, рассчитались if (!oldVR.intersectionSimple(vr)) { // Полностью обновилась область this._prepareCellTextMetricsCache(vr); } else { if (0 > delta) { // Идем вверх this._prepareCellTextMetricsCache(new asc_Range(vr.c1, start, vr.c2, oldStart - 1)); } else { // Идем вниз this._prepareCellTextMetricsCache(new asc_Range(vr.c1, oldEnd + 1, vr.c2, vr.r2)); } } if (this.notUpdateRowHeight) { return this; } var oldDec = Math.max(AscCommonExcel.calcDecades(oldEnd + 1), 3); var oldW, x, dx; var dy = this.rows[start].top - this.rows[oldStart].top; var oldH = ctxH - this.cellsTop - Math.abs(dy) - diffHeight; var scrollDown = (dy > 0 && oldH > 0); var y = this.cellsTop + (scrollDown ? dy : 0) + diffHeight; var lastRowHeight = (scrollDown && oldVRE_isPartial) ? ctxH - (this.rows[oldEnd].top - this.rows[oldStart].top + this.cellsTop + diffHeight) : 0; if (this.isCellEditMode && editor && this.model.selectionRange.activeCell.row >= rFrozen) { editor.move(this.cellsLeft + (this.model.selectionRange.activeCell.col >= cFrozen ? diffWidth : 0), this.cellsTop + diffHeight, ctxW, ctxH); } var widthChanged = Math.max(AscCommonExcel.calcDecades(vr.r2 + 1), 3) !== oldDec; if (widthChanged) { x = this.cellsLeft; this._calcHeaderColumnWidth(); this._updateColumnPositions(); this._calcVisibleColumns(); this._drawCorner(); this._cleanColumnHeadersRect(); this._drawColumnHeaders(null); dx = this.cellsLeft - x; oldW = ctxW - x - Math.abs(dx); if (rFrozen) { ctx.drawImage(ctx.getCanvas(), x, this.cellsTop, oldW, diffHeight, x + dx, this.cellsTop, oldW, diffHeight); // ToDo Посмотреть с объектами!!! } this._drawFrozenPane(true); } else { dx = 0; x = this.headersLeft; oldW = ctxW; } // Перемещаем область var moveHeight = oldH - lastRowHeight; if (moveHeight > 0) { ctx.drawImage(ctx.getCanvas(), x, y, oldW, moveHeight, x + dx, y - dy, oldW, moveHeight); // Заглушка для safari (http://bugzilla.onlyoffice.com/show_bug.cgi?id=25546). Режим 'copy' сначала затирает, а // потом рисует (а т.к. мы рисуем сами на себе, то уже картинка будет пустой) if (AscBrowser.isSafari) { this.drawingGraphicCtx.moveImageDataSafari(x, y, oldW, moveHeight, x + dx, y - dy); } else { this.drawingGraphicCtx.moveImageData(x, y, oldW, moveHeight, x + dx, y - dy); } } // Очищаем область var clearTop = this.cellsTop + diffHeight + (scrollDown && moveHeight > 0 ? moveHeight : 0); var clearHeight = (moveHeight > 0) ? Math.abs(dy) + lastRowHeight : ctxH - (this.cellsTop + diffHeight); ctx.setFillStyle(this.settings.cells.defaultState.background) .fillRect(this.headersLeft, clearTop, ctxW, clearHeight); this.drawingGraphicCtx.clearRect(this.headersLeft, clearTop, ctxW, clearHeight); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } // Дорисовываем необходимое if (dy < 0 || vr.r2 !== oldEnd || oldVRE_isPartial || dx !== 0) { var r1, r2; if (moveHeight > 0) { if (scrollDown) { r1 = oldEnd + (oldVRE_isPartial ? 0 : 1); r2 = vr.r2; } else { r1 = vr.r1; r2 = vr.r1 - 1 - delta; } } else { r1 = vr.r1; r2 = vr.r2; } var range = new asc_Range(vr.c1, r1, vr.c2, r2); if (dx === 0) { this._drawRowHeaders(null, r1, r2); } else { // redraw all headres, because number of decades in row index has been changed this._drawRowHeaders(null); if (dx < 0) { // draw last column var r_; var r1_ = r2 + 1; var r2_ = vr.r2; if (r2_ >= r1_) { r_ = new asc_Range(vr.c2, r1_, vr.c2, r2_); this._drawGrid(null, r_); this._drawCellsAndBorders(null, r_); } if (0 < rFrozen) { r_ = new asc_Range(vr.c2, 0, vr.c2, rFrozen - 1); offsetY = this.rows[0].top - this.cellsTop; this._drawGrid(null, r_, /*offsetXForDraw*/undefined, offsetY); this._drawCellsAndBorders(null, r_, /*offsetXForDraw*/undefined, offsetY); } } } offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop - diffHeight; this._drawGrid(null, range); this._drawCellsAndBorders(null, range); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollVertical, range, { offsetX: offsetX, offsetY: offsetY })); if (0 < cFrozen) { range.c1 = 0; range.c2 = cFrozen - 1; offsetX = this.cols[0].left - this.cellsLeft; this._drawGrid(null, range, offsetX); this._drawCellsAndBorders(null, range, offsetX); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollVertical, range, { offsetX: offsetX, offsetY: offsetY })); } } // Отрисовывать нужно всегда, вдруг бордеры this._drawFrozenPaneLines(); this._fixSelectionOfMergedCells(); this._drawSelection(); if (widthChanged) { this.handlers.trigger("reinitializeScrollX"); } if (reinitScrollY) { this.handlers.trigger("reinitializeScrollY"); } this.handlers.trigger("onDocumentPlaceChanged"); //ToDo this.drawDepCells(); this.cellCommentator.updateActiveComment(); this.cellCommentator.drawCommentCells(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("toggleAutoCorrectOptions", true); return this; }; WorksheetView.prototype.scrollHorizontal = function (delta, editor) { var vr = this.visibleRange; var fixStartCol = new asc_Range(vr.c1, vr.r1, vr.c1, vr.r2); this._fixSelectionOfHiddenCells(delta >= 0 ? +1 : -1, 0, fixStartCol); var start = this._calcCellPosition(fixStartCol.c1, vr.r1, delta, 0).col; fixStartCol.assign(start, vr.r1, start, vr.r2); this._fixSelectionOfHiddenCells(delta >= 0 ? +1 : -1, 0, fixStartCol); this._fixVisibleRange(fixStartCol); var reinitScrollX = start !== fixStartCol.c1; // Для скролла влево обычный сдвиг + дорисовка if (reinitScrollX && 0 > delta) { delta += fixStartCol.c1 - start; } start = fixStartCol.c1; if (start === vr.c1) { if (reinitScrollX) { this.handlers.trigger("reinitializeScrollX"); } return this; } if (!this.notUpdateRowHeight) { this.cleanSelection(); this.cellCommentator.cleanSelectedComment(); } var ctx = this.drawingCtx; var ctxW = ctx.getWidth(); var ctxH = ctx.getHeight(); var dx = this.cols[start].left - this.cols[vr.c1].left; var oldStart = vr.c1; var oldEnd = vr.c2; var offsetX, offsetY, diffWidth = 0, diffHeight = 0; var oldW = ctxW - this.cellsLeft - Math.abs(dx); var scrollRight = (dx > 0 && oldW > 0); var x = this.cellsLeft + (scrollRight ? dx : 0); var y = this.headersTop; var cFrozen = 0, rFrozen = 0; if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); cFrozen = this.topLeftFrozenCell.getCol0(); diffWidth = this.cols[cFrozen].left - this.cols[0].left; diffHeight = this.rows[rFrozen].top - this.rows[0].top; x += diffWidth; oldW -= diffWidth; } var oldVCE_isPartial = this._isColDrawnPartially(vr.c2, vr.c1, diffWidth); var oldVR = vr.clone(); // ToDo стоит тут переделать весь scroll vr.c1 = start; this._updateVisibleColsCount(); // Это необходимо для того, чтобы строки, у которых высота по тексту, рассчитались if (!oldVR.intersectionSimple(vr)) { // Полностью обновилась область this._prepareCellTextMetricsCache(vr); } else { if (0 > delta) { // Идем влево this._prepareCellTextMetricsCache(new asc_Range(start, vr.r1, oldStart - 1, vr.r2)); } else { // Идем вправо this._prepareCellTextMetricsCache(new asc_Range(oldEnd + 1, vr.r1, vr.c2, vr.r2)); } } if (this.notUpdateRowHeight) { return this; } var lastColWidth = (scrollRight && oldVCE_isPartial) ? ctxW - (this.cols[oldEnd].left - this.cols[oldStart].left + this.cellsLeft + diffWidth) : 0; if (this.isCellEditMode && editor && this.model.selectionRange.activeCell.col >= cFrozen) { editor.move(this.cellsLeft + diffWidth, this.cellsTop + (this.model.selectionRange.activeCell.row >= rFrozen ? diffHeight : 0), ctxW, ctxH); } // Перемещаем область var moveWidth = oldW - lastColWidth; if (moveWidth > 0) { ctx.drawImage(ctx.getCanvas(), x, y, moveWidth, ctxH, x - dx, y, moveWidth, ctxH); // Заглушка для safari (http://bugzilla.onlyoffice.com/show_bug.cgi?id=25546). Режим 'copy' сначала затирает, а // потом рисует (а т.к. мы рисуем сами на себе, то уже картинка будет пустой) if (AscBrowser.isSafari) { this.drawingGraphicCtx.moveImageDataSafari(x, y, moveWidth, ctxH, x - dx, y); } else { this.drawingGraphicCtx.moveImageData(x, y, moveWidth, ctxH, x - dx, y); } } // Очищаем область var clearLeft = this.cellsLeft + diffWidth + (scrollRight && moveWidth > 0 ? moveWidth : 0); var clearWidth = (moveWidth > 0) ? Math.abs(dx) + lastColWidth : ctxW - (this.cellsLeft + diffWidth); ctx.setFillStyle(this.settings.cells.defaultState.background) .fillRect(clearLeft, y, clearWidth, ctxH); this.drawingGraphicCtx.clearRect(clearLeft, y, clearWidth, ctxH); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } // Дорисовываем необходимое if (dx < 0 || vr.c2 !== oldEnd || oldVCE_isPartial) { var c1, c2; if (moveWidth > 0) { if (scrollRight) { c1 = oldEnd + (oldVCE_isPartial ? 0 : 1); c2 = vr.c2; } else { c1 = vr.c1; c2 = vr.c1 - 1 - delta; } } else { c1 = vr.c1; c2 = vr.c2; } var range = new asc_Range(c1, vr.r1, c2, vr.r2); offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft - diffWidth; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop - diffHeight; this._drawColumnHeaders(null, c1, c2); this._drawGrid(null, range); this._drawCellsAndBorders(null, range); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollHorizontal, range, { offsetX: offsetX, offsetY: offsetY })); if (rFrozen) { range.r1 = 0; range.r2 = rFrozen - 1; offsetY = this.rows[0].top - this.cellsTop; this._drawGrid(null, range, undefined, offsetY); this._drawCellsAndBorders(null, range, undefined, offsetY); this.af_drawButtons(range, offsetX, offsetY); this.objectRender.showDrawingObjectsEx(false, new AscFormat.GraphicOption(this, c_oAscGraphicOption.ScrollHorizontal, range, { offsetX: offsetX, offsetY: offsetY })); } } // Отрисовывать нужно всегда, вдруг бордеры this._drawFrozenPaneLines(); this._fixSelectionOfMergedCells(); this._drawSelection(); if (reinitScrollX) { this.handlers.trigger("reinitializeScrollX"); } this.handlers.trigger("onDocumentPlaceChanged"); //ToDo this.drawDepCells(); this.cellCommentator.updateActiveComment(); this.cellCommentator.drawCommentCells(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); this.handlers.trigger("toggleAutoCorrectOptions", true); return this; }; // ----- Selection ----- // x,y - абсолютные координаты относительно листа (без учета заголовков) WorksheetView.prototype.findCellByXY = function (x, y, canReturnNull, skipCol, skipRow) { var r = 0, c = 0, tmpRow, tmpCol, result = new AscFormat.CCellObjectInfo(); if (canReturnNull) { result.col = result.row = null; } x += this.cellsLeft; y += this.cellsTop; if (!skipCol) { while (c < this.cols.length) { tmpCol = this.cols[c]; if (x <= tmpCol.left + tmpCol.width) { result.col = c; break; } ++c; } if (null !== result.col) { result.colOff = x - this.cols[result.col].left; } } if (!skipRow) { while (r < this.rows.length) { tmpRow = this.rows[r]; if (y <= tmpRow.top + tmpRow.height) { result.row = r; break; } ++r; } if (null !== result.row) { result.rowOff = y - this.rows[result.row].top; } } return result; }; /** * * @param x * @param canReturnNull * @param half - считать с половиной следующей ячейки * @returns {*} * @private */ WorksheetView.prototype._findColUnderCursor = function (x, canReturnNull, half) { var activeCellCol = half ? this._getSelection().activeCell.col : -1; var dx = 0; var c = this.visibleRange.c1; var offset = this.cols[c].left - this.cellsLeft; var c2, x1, x2, cFrozen, widthDiff = 0; if (x >= this.cellsLeft) { if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; if (x < this.cellsLeft + widthDiff && 0 !== widthDiff) { c = 0; widthDiff = 0; } } for (x1 = this.cellsLeft + widthDiff, c2 = this.cols.length - 1; c <= c2; ++c, x1 = x2) { x2 = x1 + this.cols[c].width; dx = half ? this.cols[c].width / 2.0 * Math.sign(c - activeCellCol) : 0; if (x1 + dx > x) { if (c !== this.visibleRange.c1) { if (dx) { c -= 1; x2 = x1; x1 -= this.cols[c].width; } return {col: c, left: x1, right: x2}; } else { c = c2; break; } } else if (x <= x2 + dx) { return {col: c, left: x1, right: x2}; } } if (!canReturnNull) { x1 = this.cols[c2].left - offset; return {col: c2, left: x1, right: x1 + this.cols[c2].width}; } } else { if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); if (0 !== cFrozen) { c = 0; offset = this.cols[c].left - this.cellsLeft; } } for (x2 = this.cellsLeft + this.cols[c].width, c2 = 0; c >= c2; --c, x2 = x1) { x1 = this.cols[c].left - offset; if (x1 <= x && x < x2) { return {col: c, left: x1, right: x2}; } } if (!canReturnNull) { return {col: c2, left: x1, right: x1 + this.cols[c2].width}; } } return null; }; /** * * @param y * @param canReturnNull * @param half - считать с половиной следующей ячейки * @returns {*} * @private */ WorksheetView.prototype._findRowUnderCursor = function (y, canReturnNull, half) { var activeCellRow = half ? this._getSelection().activeCell.row : -1; var dy = 0; var r = this.visibleRange.r1; var offset = this.rows[r].top - this.cellsTop; var r2, y1, y2, rFrozen, heightDiff = 0; if (y >= this.cellsTop) { if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); heightDiff = this.rows[rFrozen].top - this.rows[0].top; if (y < this.cellsTop + heightDiff && 0 !== heightDiff) { r = 0; heightDiff = 0; } } for (y1 = this.cellsTop + heightDiff, r2 = this.rows.length - 1; r <= r2; ++r, y1 = y2) { y2 = y1 + this.rows[r].height; dy = half ? this.rows[r].height / 2.0 * Math.sign(r - activeCellRow) : 0; if (y1 + dy > y) { if (r !== this.visibleRange.r1) { if (dy) { r -= 1; y2 = y1; y1 -= this.rows[r].height; } return {row: r, top: y1, bottom: y2}; } else { r = r2; break; } } else if (y <= y2 + dy) { return {row: r, top: y1, bottom: y2}; } } if (!canReturnNull) { y1 = this.rows[r2].top - offset; return {row: r2, top: y1, bottom: y1 + this.rows[r2].height}; } } else { if (this.topLeftFrozenCell) { rFrozen = this.topLeftFrozenCell.getRow0(); if (0 !== rFrozen) { r = 0; offset = this.rows[r].top - this.cellsTop; } } for (y2 = this.cellsTop + this.rows[r].height, r2 = 0; r >= r2; --r, y2 = y1) { y1 = this.rows[r].top - offset; if (y1 <= y && y < y2) { return {row: r, top: y1, bottom: y2}; } } if (!canReturnNull) { return {row: r2, top: y1, bottom: y1 + this.rows[r2].height}; } } return null; }; WorksheetView.prototype._hitResizeCorner = function (x1, y1, x2, y2) { var wEps = this.width_1px * AscCommon.global_mouseEvent.KoefPixToMM, hEps = this.height_1px * AscCommon.global_mouseEvent.KoefPixToMM; return Math.abs(x2 - x1) <= wEps + this.width_2px && Math.abs(y2 - y1) <= hEps + this.height_2px; }; WorksheetView.prototype._hitInRange = function (range, rangeType, vr, x, y, offsetX, offsetY) { var wEps = this.width_2px * AscCommon.global_mouseEvent.KoefPixToMM, hEps = this.height_2px * AscCommon.global_mouseEvent.KoefPixToMM; var cursor, x1, x2, y1, y2, isResize; var col = -1, row = -1; var oFormulaRangeIn = range.intersectionSimple(vr); if (oFormulaRangeIn) { x1 = this.cols[oFormulaRangeIn.c1].left - offsetX; x2 = this.cols[oFormulaRangeIn.c2].left + this.cols[oFormulaRangeIn.c2].width - offsetX; y1 = this.rows[oFormulaRangeIn.r1].top - offsetY; y2 = this.rows[oFormulaRangeIn.r2].top + this.rows[oFormulaRangeIn.r2].height - offsetY; isResize = AscCommonExcel.selectionLineType.Resize & rangeType; if (isResize && this._hitResizeCorner(x1 - this.width_1px, y1 - this.height_1px, x, y)) { /*TOP-LEFT*/ cursor = kCurSEResize; col = range.c2; row = range.r2; } else if (isResize && this._hitResizeCorner(x2, y1 - this.height_1px, x, y)) { /*TOP-RIGHT*/ cursor = kCurNEResize; col = range.c1; row = range.r2; } else if (isResize && this._hitResizeCorner(x1 - this.width_1px, y2, x, y)) { /*BOTTOM-LEFT*/ cursor = kCurNEResize; col = range.c2; row = range.r1; } else if (this._hitResizeCorner(x2, y2, x, y)) { /*BOTTOM-RIGHT*/ cursor = kCurSEResize; col = range.c1; row = range.r1; } else if ((((range.c1 === oFormulaRangeIn.c1 && Math.abs(x - x1) <= wEps) || (range.c2 === oFormulaRangeIn.c2 && Math.abs(x - x2) <= wEps)) && hEps <= y - y1 && y - y2 <= hEps) || (((range.r1 === oFormulaRangeIn.r1 && Math.abs(y - y1) <= hEps) || (range.r2 === oFormulaRangeIn.r2 && Math.abs(y - y2) <= hEps)) && wEps <= x - x1 && x - x2 <= wEps)) { cursor = kCurMove; } } return cursor ? { cursor: cursor, col: col, row: row } : null; }; WorksheetView.prototype._hitCursorSelectionRange = function (vr, x, y, offsetX, offsetY) { var res = this._hitInRange(this.model.selectionRange.getLast(), AscCommonExcel.selectionLineType.Selection | AscCommonExcel.selectionLineType.ActiveCell | AscCommonExcel.selectionLineType.Promote, vr, x, y, offsetX, offsetY); return res ? { cursor: kCurMove === res.cursor ? kCurMove : kCurFillHandle, target: kCurMove === res.cursor ? c_oTargetType.MoveRange : c_oTargetType.FillHandle, col: -1, row: -1 } : null; }; WorksheetView.prototype._hitCursorFormulaOrChart = function (vr, x, y, offsetX, offsetY) { var i, l, res; var oFormulaRange; var arrRanges = this.isFormulaEditMode ? this.arrActiveFormulaRanges : this.arrActiveChartRanges; var targetArr = this.isFormulaEditMode ? 0 : -1; for (i = 0, l = arrRanges.length; i < l; ++i) { oFormulaRange = arrRanges[i].getLast(); res = !oFormulaRange.isName && this._hitInRange(oFormulaRange, AscCommonExcel.selectionLineType.Resize, vr, x, y, offsetX, offsetY); if (res) { break; } } return res ? { cursor: res.cursor, target: c_oTargetType.MoveResizeRange, col: res.col, row: res.row, formulaRange: oFormulaRange, indexFormulaRange: i, targetArr: targetArr } : null; }; WorksheetView.prototype.getCursorTypeFromXY = function (x, y, isViewerMode) { this.handlers.trigger("checkLastWork"); var res, c, r, f, i, offsetX, offsetY, cellCursor; var sheetId = this.model.getId(), userId, lockRangePosLeft, lockRangePosTop, lockInfo, oHyperlink; var widthDiff = 0, heightDiff = 0, isLocked = false, target = c_oTargetType.Cells, row = -1, col = -1, isSelGraphicObject, isNotFirst; if (c_oAscSelectionDialogType.None === this.selectionDialogType) { var frozenCursor = this._isFrozenAnchor(x, y); if (!isViewerMode && frozenCursor.result) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, sheetId, AscCommonExcel.c_oAscLockNameFrozenPane); isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false); if (false !== isLocked) { // Кто-то сделал lock var frozenCell = this.topLeftFrozenCell ? this.topLeftFrozenCell : new AscCommon.CellAddress(0, 0, 0); userId = isLocked.UserId; lockRangePosLeft = this.getCellLeft(frozenCell.getCol0(), 0); lockRangePosTop = this.getCellTop(frozenCell.getRow0(), 0); } return { cursor: frozenCursor.cursor, target: frozenCursor.name, col: -1, row: -1, userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop }; } var drawingInfo = this.objectRender.checkCursorDrawingObject(x, y); if (asc["editor"].isStartAddShape && AscCommonExcel.CheckIdSatetShapeAdd(this.objectRender.controller.curState)) { return {cursor: kCurFillHandle, target: c_oTargetType.Shape, col: -1, row: -1}; } if (drawingInfo && drawingInfo.id) { // Возможно картинка с lock lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null, sheetId, drawingInfo.id); isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, false); if (false !== isLocked) { // Кто-то сделал lock userId = isLocked.UserId; lockRangePosLeft = drawingInfo.object.getVisibleLeftOffset(true); lockRangePosTop = drawingInfo.object.getVisibleTopOffset(true); } if (drawingInfo.hyperlink instanceof ParaHyperlink) { oHyperlink = new AscCommonExcel.Hyperlink(); oHyperlink.Tooltip = drawingInfo.hyperlink.ToolTip; var spl = drawingInfo.hyperlink.Value.split("!"); if (spl.length === 2) { oHyperlink.setLocation(drawingInfo.hyperlink.Value); } else { oHyperlink.Hyperlink = drawingInfo.hyperlink.Value; } cellCursor = {cursor: drawingInfo.cursor, target: c_oTargetType.Cells, col: -1, row: -1, userId: userId}; return { cursor: kCurHyperlink, target: c_oTargetType.Hyperlink, hyperlink: new asc_CHyperlink(oHyperlink), cellCursor: cellCursor, userId: userId }; } return { cursor: drawingInfo.cursor, target: c_oTargetType.Shape, drawingId: drawingInfo.id, col: -1, row: -1, userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop }; } } x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var oResDefault = {cursor: kCurDefault, target: c_oTargetType.None, col: -1, row: -1}; if (x < this.cellsLeft && y < this.cellsTop) { return {cursor: kCurCorner, target: c_oTargetType.Corner, col: -1, row: -1}; } var cFrozen = -1, rFrozen = -1; offsetX = this.cols[this.visibleRange.c1].left - this.cellsLeft; offsetY = this.rows[this.visibleRange.r1].top - this.cellsTop; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); rFrozen = this.topLeftFrozenCell.getRow0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; heightDiff = this.rows[rFrozen].top - this.rows[0].top; offsetX = (x < this.cellsLeft + widthDiff) ? 0 : offsetX - widthDiff; offsetY = (y < this.cellsTop + heightDiff) ? 0 : offsetY - heightDiff; } var epsChangeSize = 3 * AscCommon.global_mouseEvent.KoefPixToMM; if (x <= this.cellsLeft && y >= this.cellsTop) { r = this._findRowUnderCursor(y, true); if (r === null) { return oResDefault; } isNotFirst = (r.row !== (-1 !== rFrozen ? 0 : this.visibleRange.r1)); f = !isViewerMode && (isNotFirst && y < r.top + epsChangeSize || y >= r.bottom - epsChangeSize); // ToDo В Excel зависимость epsilon от размера ячейки (у нас фиксированный 3) return { cursor: f ? kCurRowResize : kCurRowSelect, target: f ? c_oTargetType.RowResize : c_oTargetType.RowHeader, col: -1, row: r.row + (isNotFirst && f && y < r.top + 3 ? -1 : 0), mouseY: f ? ((y < r.top + 3) ? (r.top - y - this.height_1px) : (r.bottom - y - this.height_1px)) : null }; } if (y <= this.cellsTop && x >= this.cellsLeft) { c = this._findColUnderCursor(x, true); if (c === null) { return oResDefault; } isNotFirst = c.col !== (-1 !== cFrozen ? 0 : this.visibleRange.c1); f = !isViewerMode && (isNotFirst && x < c.left + epsChangeSize || x >= c.right - epsChangeSize); // ToDo В Excel зависимость epsilon от размера ячейки (у нас фиксированный 3) return { cursor: f ? kCurColResize : kCurColSelect, target: f ? c_oTargetType.ColumnResize : c_oTargetType.ColumnHeader, col: c.col + (isNotFirst && f && x < c.left + 3 ? -1 : 0), row: -1, mouseX: f ? ((x < c.left + 3) ? (c.left - x - this.width_1px) : (c.right - x - this.width_1px)) : null }; } if (this.stateFormatPainter) { if (x <= this.cellsLeft && y >= this.cellsTop) { r = this._findRowUnderCursor(y, true); if (r !== null) { target = c_oTargetType.RowHeader; row = r.row; } } if (y <= this.cellsTop && x >= this.cellsLeft) { c = this._findColUnderCursor(x, true); if (c !== null) { target = c_oTargetType.ColumnHeader; col = c.col; } } return {cursor: kCurFormatPainterExcel, target: target, col: col, row: row}; } if (this.isFormulaEditMode || this.isChartAreaEditMode) { this._drawElements(function (_vr, _offsetX, _offsetY) { return (null === (res = this._hitCursorFormulaOrChart(_vr, x, y, _offsetX, _offsetY))); }); if (res) { return res; } } isSelGraphicObject = this.objectRender.selectedGraphicObjectsExists(); if (!isViewerMode && !isSelGraphicObject && this.model.selectionRange.isSingleRange() && c_oAscSelectionDialogType.None === this.selectionDialogType) { this._drawElements(function (_vr, _offsetX, _offsetY) { return (null === (res = this._hitCursorSelectionRange(_vr, x, y, _offsetX, _offsetY))); }); if (res) { return res; } } if (x > this.cellsLeft && y > this.cellsTop) { c = this._findColUnderCursor(x, true); r = this._findRowUnderCursor(y, true); if (c === null || r === null) { return oResDefault; } // Проверка на совместное редактирование var lockRange = undefined; var lockAllPosLeft = undefined; var lockAllPosTop = undefined; var userIdAllProps = undefined; var userIdAllSheet = undefined; if (!isViewerMode && this.collaborativeEditing.getCollaborativeEditing()) { var c1Recalc = null, r1Recalc = null; var selectRangeRecalc = new asc_Range(c.col, r.row, c.col, r.row); // Пересчет для входящих ячеек в добавленные строки/столбцы var isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, selectRangeRecalc); if (false === isIntersection) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, new AscCommonExcel.asc_CCollaborativeRange(selectRangeRecalc.c1, selectRangeRecalc.r1, selectRangeRecalc.c2, selectRangeRecalc.r2)); isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false); if (false !== isLocked) { // Кто-то сделал lock userId = isLocked.UserId; lockRange = isLocked.Element["rangeOrObjectId"]; c1Recalc = this.collaborativeEditing.m_oRecalcIndexColumns[sheetId].getLockOther(lockRange["c1"], c_oAscLockTypes.kLockTypeOther); r1Recalc = this.collaborativeEditing.m_oRecalcIndexRows[sheetId].getLockOther(lockRange["r1"], c_oAscLockTypes.kLockTypeOther); if (null !== c1Recalc && null !== r1Recalc) { lockRangePosLeft = this.getCellLeft(c1Recalc, /*pt*/1); lockRangePosTop = this.getCellTop(r1Recalc, /*pt*/1); // Пересчитываем X и Y относительно видимой области lockRangePosLeft -= offsetX; lockRangePosTop -= offsetY; lockRangePosLeft = this.cellsLeft > lockRangePosLeft ? this.cellsLeft : lockRangePosLeft; lockRangePosTop = this.cellsTop > lockRangePosTop ? this.cellsTop : lockRangePosTop; // Пересчитываем в px lockRangePosLeft *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); lockRangePosTop *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); } } } else { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, null); } // Проверим не удален ли весь лист (именно удален, т.к. если просто залочен, то не рисуем рамку вокруг) lockInfo["type"] = c_oAscLockTypeElem.Sheet; isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/true); if (false !== isLocked) { // Кто-то сделал lock userIdAllSheet = isLocked.UserId; lockAllPosLeft = this.cellsLeft * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); lockAllPosTop = this.cellsTop * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); } // Проверим не залочены ли все свойства листа (только если не удален весь лист) if (undefined === userIdAllSheet) { lockInfo["type"] = c_oAscLockTypeElem.Range; lockInfo["subType"] = c_oAscLockTypeElemSubType.InsertRows; isLocked = this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/true); if (false !== isLocked) { // Кто-то сделал lock userIdAllProps = isLocked.UserId; lockAllPosLeft = this.cellsLeft * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); lockAllPosTop = this.cellsTop * asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); } } } if (!isViewerMode) { var pivotButtons = this.model.getPivotTableButtons(new asc_Range(c.col, r.row, c.col, r.row)); var isPivot = pivotButtons.some(function (element) { return element.row === r.row && element.col === c.col; }); this._drawElements(function (_vr, _offsetX, _offsetY) { if (isPivot) { if (_vr.contains(c.col, r.row) && this._hitCursorFilterButton(x + _offsetX, y + _offsetY, c.col, r.row)) { res = {cursor: kCurAutoFilter, target: c_oTargetType.FilterObject, col: -1, row: -1}; } } else { res = this.af_checkCursor(x, y, _vr, _offsetX, _offsetY, r, c); } return (null === res); }); if (res) { return res; } } // Проверим есть ли комменты var comment = this.cellCommentator.getComment(c.col, r.row); var coords = null; var indexes = null; if (comment) { indexes = [comment.asc_getId()]; coords = this.cellCommentator.getCommentTooltipPosition(comment); } // Проверим, может мы в гиперлинке oHyperlink = this.model.getHyperlinkByCell(r.row, c.col); cellCursor = { cursor: kCurCells, target: c_oTargetType.Cells, col: (c ? c.col : -1), row: (r ? r.row : -1), userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop, userIdAllProps: userIdAllProps, lockAllPosLeft: lockAllPosLeft, lockAllPosTop: lockAllPosTop, userIdAllSheet: userIdAllSheet, commentIndexes: indexes, commentCoords: coords }; if (null !== oHyperlink) { return { cursor: kCurHyperlink, target: c_oTargetType.Hyperlink, hyperlink: new asc_CHyperlink(oHyperlink), cellCursor: cellCursor, userId: userId, lockRangePosLeft: lockRangePosLeft, lockRangePosTop: lockRangePosTop, userIdAllProps: userIdAllProps, userIdAllSheet: userIdAllSheet, lockAllPosLeft: lockAllPosLeft, lockAllPosTop: lockAllPosTop, commentIndexes: indexes, commentCoords: coords }; } return cellCursor; } return oResDefault; }; WorksheetView.prototype._fixSelectionOfMergedCells = function (fixedRange) { var selection; var ar = fixedRange ? fixedRange : ((selection = this._getSelection()) ? selection.getLast() : null); if (!ar || c_oAscSelectionType.RangeCells !== ar.getType()) { return; } // ToDo - переделать этот момент!!!! var res = this.model.expandRangeByMerged(ar.clone(true)); if (ar.c1 !== res.c1 && ar.c1 !== res.c2) { ar.c1 = ar.c1 <= ar.c2 ? res.c1 : res.c2; } ar.c2 = ar.c1 === res.c1 ? res.c2 : (res.c1); if (ar.r1 !== res.r1 && ar.r1 !== res.r2) { ar.r1 = ar.r1 <= ar.r2 ? res.r1 : res.r2; } ar.r2 = ar.r1 === res.r1 ? res.r2 : res.r1; ar.normalize(); if (!fixedRange) { selection.update(); } }; WorksheetView.prototype._findVisibleCol = function (from, dc, flag) { var to = dc < 0 ? -1 : this.cols.length, c; for (c = from; c !== to; c += dc) { if (this.cols[c].width > this.width_1px) { return c; } } return flag ? -1 : this._findVisibleCol(from, dc * -1, true); }; WorksheetView.prototype._findVisibleRow = function (from, dr, flag) { var to = dr < 0 ? -1 : this.rows.length, r; for (r = from; r !== to; r += dr) { if (this.rows[r].height > this.height_1px) { return r; } } return flag ? -1 : this._findVisibleRow(from, dr * -1, true); }; WorksheetView.prototype._fixSelectionOfHiddenCells = function (dc, dr, range) { var ar = (range) ? range : this.model.selectionRange.getLast(), c1, c2, r1, r2, mc, i, arn = ar.clone(true); if (dc === undefined) { dc = +1; } if (dr === undefined) { dr = +1; } if (ar.c2 === ar.c1) { if (this.cols[ar.c1].width < this.width_1px) { c1 = c2 = this._findVisibleCol(ar.c1, dc); } } else { if (0 !== dc && this.nColsCount > ar.c2 && this.cols[ar.c2].width < this.width_1px) { // Проверка для одновременно замерженных и скрытых ячеек (A1:C1 merge, B:C hidden) for (mc = null, i = arn.r1; i <= arn.r2; ++i) { mc = this.model.getMergedByCell(i, ar.c2); if (mc) { break; } } if (!mc) { c2 = this._findVisibleCol(ar.c2, dc); } } } if (c1 < 0 || c2 < 0) { throw "Error: all columns are hidden"; } if (ar.r2 === ar.r1) { if (this.rows[ar.r1].height < this.height_1px) { r1 = r2 = this._findVisibleRow(ar.r1, dr); } } else { if (0 !== dr && this.nRowsCount > ar.r2 && this.rows[ar.r2].height < this.height_1px) { //Проверка для одновременно замерженных и скрытых ячеек (A1:A3 merge, 2:3 hidden) for (mc = null, i = arn.c1; i <= arn.c2; ++i) { mc = this.model.getMergedByCell(ar.r2, i); if (mc) { break; } } if (!mc) { r2 = this._findVisibleRow(ar.r2, dr); } } } if (r1 < 0 || r2 < 0) { throw "Error: all rows are hidden"; } ar.assign(c1 !== undefined ? c1 : ar.c1, r1 !== undefined ? r1 : ar.r1, c2 !== undefined ? c2 : ar.c2, r2 !== undefined ? r2 : ar.r2); }; WorksheetView.prototype._getCellByXY = function (x, y) { var c1, r1, c2, r2; x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); if (x < this.cellsLeft && y < this.cellsTop) { c1 = r1 = 0; c2 = gc_nMaxCol0; r2 = gc_nMaxRow0; } else if (x < this.cellsLeft) { r1 = r2 = this._findRowUnderCursor(y).row; c1 = 0; c2 = gc_nMaxCol0; } else if (y < this.cellsTop) { c1 = c2 = this._findColUnderCursor(x).col; r1 = 0; r2 = gc_nMaxRow0; } else { c1 = c2 = this._findColUnderCursor(x).col; r1 = r2 = this._findRowUnderCursor(y).row; } return new asc_Range(c1, r1, c2, r2); }; WorksheetView.prototype._moveActiveCellToXY = function (x, y) { var selection = this._getSelection(); var ar = selection.getLast(); var range = this._getCellByXY(x, y); ar.assign(range.c1, range.r1, range.c2, range.r2); selection.setCell(range.r1, range.c1); if (c_oAscSelectionType.RangeCells !== ar.getType()) { this._fixSelectionOfHiddenCells(); } this._fixSelectionOfMergedCells(); }; WorksheetView.prototype._moveActiveCellToOffset = function (dc, dr) { var selection = this._getSelection(); var ar = selection.getLast(); var activeCell = selection.activeCell; var mc = this.model.getMergedByCell(activeCell.row, activeCell.col); var c = mc ? (dc < 0 ? mc.c1 : dc > 0 ? Math.min(mc.c2, this.nColsCount - 1 - dc) : activeCell.col) : activeCell.col; var r = mc ? (dr < 0 ? mc.r1 : dr > 0 ? Math.min(mc.r2, this.nRowsCount - 1 - dr) : activeCell.row) : activeCell.row; var p = this._calcCellPosition(c, r, dc, dr); ar.assign(p.col, p.row, p.col, p.row); this.model.selectionRange.setCell(p.row, p.col); this._fixSelectionOfHiddenCells(dc >= 0 ? +1 : -1, dr >= 0 ? +1 : -1); this._fixSelectionOfMergedCells(); }; // Движение активной ячейки в выделенной области WorksheetView.prototype._moveActivePointInSelection = function (dc, dr) { var t = this, cell = this.model.selectionRange.activeCell; // Если мы на скрытой строке или ячейке, то двигаться в выделении нельзя (так делает и Excel) if (this.width_1px > this.cols[cell.col].width || this.height_1px > this.rows[cell.row].height) { return; } return this.model.selectionRange.offsetCell(dr, dc, function (row, col) { return (0 <= row) ? (t.rows[row].height < t.height_1px) : (t.cols[col].width < t.width_1px); }); }; WorksheetView.prototype._calcSelectionEndPointByXY = function (x, y, keepType) { var activeCell = this._getSelection().activeCell; var range = this._getCellByXY(x, y); var res = (keepType ? this._getSelection().getLast() : range).clone(); var type = res.getType(); if (c_oAscSelectionType.RangeRow === type) { res.r1 = Math.min(range.r1, activeCell.row); res.r2 = Math.max(range.r1, activeCell.row); } else if (c_oAscSelectionType.RangeCol === type) { res.c1 = Math.min(range.c1, activeCell.col); res.c2 = Math.max(range.c1, activeCell.col); } else if (c_oAscSelectionType.RangeCells === type) { res.assign(activeCell.col, activeCell.row, range.c1, range.r1, true); } this._fixSelectionOfMergedCells(res); return res; }; WorksheetView.prototype._calcSelectionEndPointByOffset = function (dc, dr) { var selection = this._getSelection(); var ar = selection.getLast(); var c1, r1, c2, r2, tmp; tmp = asc.getEndValueRange(dc, selection.activeCell.col, ar.c1, ar.c2); c1 = tmp.x1; c2 = tmp.x2; tmp = asc.getEndValueRange(dr, selection.activeCell.row, ar.r1, ar.r2); r1 = tmp.x1; r2 = tmp.x2; var p1 = this._calcCellPosition(c2, r2, dc, dr), p2; var res = new asc_Range(c1, r1, c2 = p1.col, r2 = p1.row, true); dc = Math.sign(dc); dr = Math.sign(dr); if (c_oAscSelectionType.RangeCells === ar.getType()) { this._fixSelectionOfMergedCells(res); while (ar.isEqual(res)) { p2 = this._calcCellPosition(c2, r2, dc, dr); res.assign(c1, r1, c2 = p2.col, r2 = p2.row, true); this._fixSelectionOfMergedCells(res); if (p1.c2 === p2.c2 && p1.r2 === p2.r2) { break; } p1 = p2; } } var bIsHidden = false; if (0 !== dc && this.cols[c2].width < this.width_1px) { c2 = this._findVisibleCol(c2, dc); bIsHidden = true; } if (0 !== dr && this.rows[r2].height < this.height_1px) { r2 = this._findVisibleRow(r2, dr); bIsHidden = true; } if (bIsHidden) { res.assign(c1, r1, c2, r2, true); } return res; }; WorksheetView.prototype._calcActiveRangeOffsetIsCoord = function (x, y) { var ar = this._getSelection().getLast(); if (this.isFormulaEditMode) { // Для формул нужно сделать ограничение по range (у нас хранится полный диапазон) if (ar.c2 >= this.nColsCount || ar.r2 >= this.nRowsCount) { ar = ar.clone(true); ar.c2 = (ar.c2 >= this.nColsCount) ? this.nColsCount - 1 : ar.c2; ar.r2 = (ar.r2 >= this.nRowsCount) ? this.nRowsCount - 1 : ar.r2; } } x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var d = {}; if (y <= this.cellsTop + this.height_2px /*+ offsetFrozen.offsetY*/) { d.deltaY = -1; } else if (y >= this.drawingCtx.getHeight() - this.height_2px) { d.deltaY = 1; } if (x <= this.cellsLeft + this.width_2px /*+ offsetFrozen.offsetX*/) { d.deltaX = -1; } else if (x >= this.drawingCtx.getWidth() - this.width_2px) { d.deltaX = 1; } var type = ar.getType(); if (type === c_oAscSelectionType.RangeRow) { d.deltaX = 0; } else if (type === c_oAscSelectionType.RangeCol) { d.deltaY = 0; } else if (type === c_oAscSelectionType.RangeMax) { d.deltaX = 0; d.deltaY = 0; } return d; }; WorksheetView.prototype._calcActiveRangeOffset = function () { var vr = this.visibleRange; var ar = this._getSelection().getLast(); if (this.isFormulaEditMode) { // Для формул нужно сделать ограничение по range (у нас хранится полный диапазон) if (ar.c2 >= this.nColsCount || ar.r2 >= this.nRowsCount) { ar = ar.clone(true); ar.c2 = (ar.c2 >= this.nColsCount) ? this.nColsCount - 1 : ar.c2; ar.r2 = (ar.r2 >= this.nRowsCount) ? this.nRowsCount - 1 : ar.r2; } } var arn = ar.clone(true); var isMC = this._isMergedCells(arn); var adjustRight = ar.c2 >= vr.c2 || ar.c1 >= vr.c2 && isMC; var adjustBottom = ar.r2 >= vr.r2 || ar.r1 >= vr.r2 && isMC; var incX = ar.c1 < vr.c1 && isMC ? arn.c1 - vr.c1 : ar.c2 < vr.c1 ? ar.c2 - vr.c1 : 0; var incY = ar.r1 < vr.r1 && isMC ? arn.r1 - vr.r1 : ar.r2 < vr.r1 ? ar.r2 - vr.r1 : 0; var type = ar.getType(); var offsetFrozen = this.getFrozenPaneOffset(); if (adjustRight) { while (this._isColDrawnPartially(isMC ? arn.c2 : ar.c2, vr.c1 + incX, offsetFrozen.offsetX)) { ++incX; } } if (adjustBottom) { while (this._isRowDrawnPartially(isMC ? arn.r2 : ar.r2, vr.r1 + incY, offsetFrozen.offsetY)) { ++incY; } } return { deltaX: type === c_oAscSelectionType.RangeCol || type === c_oAscSelectionType.RangeCells ? incX : 0, deltaY: type === c_oAscSelectionType.RangeRow || type === c_oAscSelectionType.RangeCells ? incY : 0 }; }; /** * @param {Range} [range] * @returns {{deltaX: number, deltaY: number}} */ WorksheetView.prototype._calcActiveCellOffset = function (range) { var vr = this.visibleRange; var activeCell = this.model.selectionRange.activeCell; var ar = range ? range : this.model.selectionRange.getLast(); var mc = this.model.getMergedByCell(activeCell.row, activeCell.col); var startCol = mc ? mc.c1 : activeCell.col; var startRow = mc ? mc.r1 : activeCell.row; var incX = startCol < vr.c1 ? startCol - vr.c1 : 0; var incY = startRow < vr.r1 ? startRow - vr.r1 : 0; var type = ar.getType(); var offsetFrozen = this.getFrozenPaneOffset(); // adjustRight if (startCol >= vr.c2) { while (this._isColDrawnPartially(startCol, vr.c1 + incX, offsetFrozen.offsetX)) { ++incX; } } // adjustBottom if (startRow >= vr.r2) { while (this._isRowDrawnPartially(startRow, vr.r1 + incY, offsetFrozen.offsetY)) { ++incY; } } return { deltaX: type === c_oAscSelectionType.RangeCol || type === c_oAscSelectionType.RangeCells ? incX : 0, deltaY: type === c_oAscSelectionType.RangeRow || type === c_oAscSelectionType.RangeCells ? incY : 0 }; }; WorksheetView.prototype._calcFillHandleOffset = function (range) { var vr = this.visibleRange; var ar = range ? range : this.activeFillHandle; var arn = ar.clone(true); var isMC = this._isMergedCells(arn); var adjustRight = ar.c2 >= vr.c2 || ar.c1 >= vr.c2 && isMC; var adjustBottom = ar.r2 >= vr.r2 || ar.r1 >= vr.r2 && isMC; var incX = ar.c1 < vr.c1 && isMC ? arn.c1 - vr.c1 : ar.c2 < vr.c1 ? ar.c2 - vr.c1 : 0; var incY = ar.r1 < vr.r1 && isMC ? arn.r1 - vr.r1 : ar.r2 < vr.r1 ? ar.r2 - vr.r1 : 0; var offsetFrozen = this.getFrozenPaneOffset(); if (adjustRight) { try { while (this._isColDrawnPartially(isMC ? arn.c2 : ar.c2, vr.c1 + incX, offsetFrozen.offsetX)) { ++incX; } } catch (e) { this.expandColsOnScroll(true); this.handlers.trigger("reinitializeScrollX"); } } if (adjustBottom) { try { while (this._isRowDrawnPartially(isMC ? arn.r2 : ar.r2, vr.r1 + incY, offsetFrozen.offsetY)) { ++incY; } } catch (e) { this.expandRowsOnScroll(true); this.handlers.trigger("reinitializeScrollY"); } } return { deltaX: incX, deltaY: incY }; }; // Потеряем ли мы что-то при merge ячеек WorksheetView.prototype.getSelectionMergeInfo = function (options) { // ToDo now check only last selection range var arn = this.model.selectionRange.getLast().clone(true); var notEmpty = false; var r, c; if (this.cellCommentator.isMissComments(arn)) { return true; } switch (options) { case c_oAscMergeOptions.Merge: case c_oAscMergeOptions.MergeCenter: for (r = arn.r1; r <= arn.r2; ++r) { for (c = arn.c1; c <= arn.c2; ++c) { if (false === this._isCellNullText(c, r)) { if (notEmpty) { return true; } notEmpty = true; } } } break; case c_oAscMergeOptions.MergeAcross: for (r = arn.r1; r <= arn.r2; ++r) { notEmpty = false; for (c = arn.c1; c <= arn.c2; ++c) { if (false === this._isCellNullText(c, r)) { if (notEmpty) { return true; } notEmpty = true; } } } break; } return false; }; //нужно ли спрашивать пользователя о расширении диапазона WorksheetView.prototype.getSelectionSortInfo = function () { //в случае попытки сортировать мультиселект, необходимо выдавать ошибку var arn = this.model.selectionRange.getLast().clone(true); //null - не выдавать сообщение и не расширять, false - не выдавать сообщение и расширЯть, true - выдавать сообщение var bResult = false; //если внутри форматированной таблиц, никогда не выдаем сообщение if(this.model.autoFilters._isTablePartsContainsRange(arn)) { bResult = null; } else if(!arn.isOneCell())//в случае одной выделенной ячейки - всегда не выдаём сообщение и автоматически расширяем { var colCount = arn.c2 - arn.c1 + 1; var rowCount = arn.r2 - arn.r1 + 1; //если выделено более одного столбца и более одной строки - не выдаем сообщение и не расширяем if(colCount > 1 && rowCount > 1) { bResult = null; } else { //далее проверяем есть ли смежные ячейки у startCol/startRow var activeCell = this.model.selectionRange.activeCell; var activeCellRange = new Asc.Range(activeCell.col, activeCell.row, activeCell.col, activeCell.row); var expandRange = this.model.autoFilters._getAdjacentCellsAF(activeCellRange); //если диапазон не расширяется за счет близлежащих ячеек - не выдаем сообщение и не расширяем if(arn.isEqual(expandRange) || activeCellRange.isEqual(expandRange)) { bResult = null; } else if(arn.c1 === expandRange.c1 && arn.c2 === expandRange.c2) { bResult = null; } else { bResult = true; } } } return bResult; }; WorksheetView.prototype.getSelectionMathInfo = function () { var oSelectionMathInfo = new asc_CSelectionMathInfo(); var sum = 0; var oExistCells = {}; if (window["NATIVE_EDITOR_ENJINE"]) { return oSelectionMathInfo; } var t = this; this.model.selectionRange.ranges.forEach(function (item) { var cellValue; var range = t.model.getRange3(item.r1, item.c1, item.r2, item.c2); range._setPropertyNoEmpty(null, null, function (cell, r) { var idCell = cell.nCol + '-' + cell.nRow; if (!oExistCells[idCell] && !cell.isNullTextString() && t.height_1px <= t.rows[r].height) { oExistCells[idCell] = true; ++oSelectionMathInfo.count; if (CellValueType.Number === cell.getType()) { cellValue = cell.getNumberValue(); if (0 === oSelectionMathInfo.countNumbers) { oSelectionMathInfo.min = oSelectionMathInfo.max = cellValue; } else { oSelectionMathInfo.min = Math.min(oSelectionMathInfo.min, cellValue); oSelectionMathInfo.max = Math.max(oSelectionMathInfo.max, cellValue); } ++oSelectionMathInfo.countNumbers; sum += cellValue; } } }); }); // Показываем только данные для 2-х или более ячеек (http://bugzilla.onlyoffice.com/show_bug.cgi?id=24115) if (1 < oSelectionMathInfo.count && 0 < oSelectionMathInfo.countNumbers) { // Мы должны отдавать в формате активной ячейки var activeCell = this.model.selectionRange.activeCell; var numFormat = this.model.getRange3(activeCell.row, activeCell.col, activeCell.row, activeCell.col).getNumFormat(); if (Asc.c_oAscNumFormatType.Time === numFormat.getType()) { // Для времени нужно отдавать в формате [h]:mm:ss (http://bugzilla.onlyoffice.com/show_bug.cgi?id=26271) numFormat = AscCommon.oNumFormatCache.get('[h]:mm:ss'); } oSelectionMathInfo.sum = numFormat.formatToMathInfo(sum, CellValueType.Number, this.settings.mathMaxDigCount); oSelectionMathInfo.average = numFormat.formatToMathInfo(sum / oSelectionMathInfo.countNumbers, CellValueType.Number, this.settings.mathMaxDigCount); oSelectionMathInfo.min = numFormat.formatToMathInfo(oSelectionMathInfo.min, CellValueType.Number, this.settings.mathMaxDigCount); oSelectionMathInfo.max = numFormat.formatToMathInfo(oSelectionMathInfo.max, CellValueType.Number, this.settings.mathMaxDigCount); } return oSelectionMathInfo; }; WorksheetView.prototype.getSelectionName = function (bRangeText) { if (this.isSelectOnShape) { return " "; } // Пока отправим пустое имя(с пробелом, пустое не воспринимаем в меню..) ToDo var ar = this.model.selectionRange.getLast(); var cell = this.model.selectionRange.activeCell; var mc = this.model.getMergedByCell(cell.row, cell.col); var c1 = mc ? mc.c1 : cell.col, r1 = mc ? mc.r1 : cell.row, ar_norm = ar.normalize(), mc_norm = mc ? mc.normalize() : null, c2 = mc_norm ? mc_norm.isEqual(ar_norm) ? mc_norm.c1 : ar_norm.c2 : ar_norm.c2, r2 = mc_norm ? mc_norm.isEqual(ar_norm) ? mc_norm.r1 : ar_norm.r2 : ar_norm.r2, selectionSize = !bRangeText ? "" : (function (r) { var rc = Math.abs(r.r2 - r.r1) + 1; var cc = Math.abs(r.c2 - r.c1) + 1; switch (r.getType()) { case c_oAscSelectionType.RangeCells: return rc + "R x " + cc + "C"; case c_oAscSelectionType.RangeCol: return cc + "C"; case c_oAscSelectionType.RangeRow: return rc + "R"; case c_oAscSelectionType.RangeMax: return gc_nMaxRow + "R x " + gc_nMaxCol + "C"; } return ""; })(ar); if (selectionSize) { return selectionSize; } var dN = new Asc.Range(ar_norm.c1, ar_norm.r1, c2, r2, true); var defName = parserHelp.get3DRef(this.model.getName(), dN.getAbsName()); defName = this.model.workbook.findDefinesNames(defName, this.model.getId()); if (defName) { return defName; } return this._getColumnTitle(c1) + this._getRowTitle(r1); }; WorksheetView.prototype.getSelectionRangeValue = function () { // ToDo проблема с выбором целого столбца/строки var ar = this.model.selectionRange.getLast().clone(true); var sAbsName = ar.getAbsName(); var sName = (c_oAscSelectionDialogType.FormatTable === this.selectionDialogType) ? sAbsName : parserHelp.get3DRef(this.model.getName(), sAbsName); var type = ar.type; var selectionRangeValueObj = new AscCommonExcel.asc_CSelectionRangeValue(); selectionRangeValueObj.asc_setName(sName); selectionRangeValueObj.asc_setType(type); return selectionRangeValueObj; }; WorksheetView.prototype.getSelectionInfo = function () { return this.objectRender.selectedGraphicObjectsExists() ? this._getSelectionInfoObject() : this._getSelectionInfoCell(); }; WorksheetView.prototype._getSelectionInfoCell = function () { var selectionRange = this.model.selectionRange; var cell = selectionRange.activeCell; var mc = this.model.getMergedByCell(cell.row, cell.col); var c1 = mc ? mc.c1 : cell.col; var r1 = mc ? mc.r1 : cell.row; var c = this._getVisibleCell(c1, r1); var font = c.getFont(true); var fa = font.getVerticalAlign(); var bg = c.getFill(); var align = c.getAlign(); var cellType = c.getType(); var isNumberFormat = (!cellType || CellValueType.Number === cellType); var cell_info = new asc_CCellInfo(); cell_info.name = this._getColumnTitle(c1) + this._getRowTitle(r1); cell_info.formula = c.getFormula(); cell_info.text = c.getValueForEdit(); cell_info.halign = align.getAlignHorizontal(); cell_info.valign = align.getAlignVertical(); var tablePartsOptions = selectionRange.isSingleRange() ? this.model.autoFilters.searchRangeInTableParts(selectionRange.getLast()) : -2; var curTablePart = tablePartsOptions >= 0 ? this.model.TableParts[tablePartsOptions] : null; var tableStyleInfo = curTablePart && curTablePart.TableStyleInfo ? curTablePart.TableStyleInfo : null; cell_info.autoFilterInfo = new asc_CAutoFilterInfo(); if (-2 === tablePartsOptions || this.model.inPivotTable(selectionRange.getLast())) { cell_info.autoFilterInfo.isAutoFilter = null; cell_info.autoFilterInfo.isApplyAutoFilter = false; } else { var checkApplyFilterOrSort = this.model.autoFilters.checkApplyFilterOrSort(tablePartsOptions); cell_info.autoFilterInfo.isAutoFilter = checkApplyFilterOrSort.isAutoFilter; cell_info.autoFilterInfo.isApplyAutoFilter = checkApplyFilterOrSort.isFilterColumns; } if (curTablePart !== null) { cell_info.formatTableInfo = new AscCommonExcel.asc_CFormatTableInfo(); cell_info.formatTableInfo.tableName = curTablePart.DisplayName; if (tableStyleInfo) { cell_info.formatTableInfo.tableStyleName = tableStyleInfo.Name; cell_info.formatTableInfo.bandVer = tableStyleInfo.ShowColumnStripes; cell_info.formatTableInfo.firstCol = tableStyleInfo.ShowFirstColumn; cell_info.formatTableInfo.lastCol = tableStyleInfo.ShowLastColumn; cell_info.formatTableInfo.bandHor = tableStyleInfo.ShowRowStripes; } cell_info.formatTableInfo.lastRow = curTablePart.TotalsRowCount !== null; cell_info.formatTableInfo.firstRow = curTablePart.HeaderRowCount === null; cell_info.formatTableInfo.tableRange = curTablePart.Ref.getAbsName(); cell_info.formatTableInfo.filterButton = curTablePart.isShowButton(); cell_info.formatTableInfo.altText = curTablePart.altText; cell_info.formatTableInfo.altTextSummary = curTablePart.altTextSummary; this.af_setDisableProps(curTablePart, cell_info.formatTableInfo); } cell_info.styleName = c.getStyleName(); cell_info.angle = align.getAngle(); cell_info.flags = new AscCommonExcel.asc_CCellFlag(); cell_info.flags.shrinkToFit = align.getShrinkToFit(); cell_info.flags.wrapText = align.getWrap(); // ToDo activeRange type cell_info.flags.selectionType = selectionRange.getLast().getType(); cell_info.flags.multiselect = !selectionRange.isSingleRange(); cell_info.flags.lockText = ("" !== cell_info.text && (isNumberFormat || "" !== cell_info.formula)); cell_info.font = new asc_CFont(); cell_info.font.name = font.getName(); cell_info.font.size = font.getSize(); cell_info.font.bold = font.getBold(); cell_info.font.italic = font.getItalic(); // ToDo убрать, когда будет реализовано двойное подчеркивание cell_info.font.underline = (Asc.EUnderline.underlineNone !== font.getUnderline()); cell_info.font.strikeout = font.getStrikeout(); cell_info.font.subscript = fa === AscCommon.vertalign_SubScript; cell_info.font.superscript = fa === AscCommon.vertalign_SuperScript; cell_info.font.color = asc_obj2Color(font.getColor()); cell_info.fill = new asc_CFill((null != bg) ? asc_obj2Color(bg) : bg); cell_info.numFormat = c.getNumFormatStr(); cell_info.numFormatInfo = c.getNumFormatTypeInfo(); // Получаем гиперссылку (//ToDo) var ar = selectionRange.getLast().clone(); var range = this.model.getRange3(ar.r1, ar.c1, ar.r2, ar.c2); var hyperlink = range.getHyperlink(); var oHyperlink; if (null !== hyperlink) { // Гиперлинк oHyperlink = new asc_CHyperlink(hyperlink); oHyperlink.asc_setText(cell_info.text); cell_info.hyperlink = oHyperlink; } else { cell_info.hyperlink = null; } cell_info.comment = this.cellCommentator.getComment(ar.c1, ar.r1); cell_info.flags.merge = range.isOneCell() ? Asc.c_oAscMergeOptions.Disabled : null !== range.hasMerged() ? Asc.c_oAscMergeOptions.Merge : Asc.c_oAscMergeOptions.None; var sheetId = this.model.getId(); var lockInfo; // Пересчет для входящих ячеек в добавленные строки/столбцы var isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, ar); if (false === isIntersection) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, new AscCommonExcel.asc_CCollaborativeRange(ar.c1, ar.r1, ar.c2, ar.r2)); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже ячейку кто-то редактирует cell_info.isLocked = true; } } if (null !== curTablePart) { var tableAr = curTablePart.Ref.clone(); isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, tableAr); if (false === isIntersection) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/null, sheetId, new AscCommonExcel.asc_CCollaborativeRange(tableAr.c1, tableAr.r1, tableAr.c2, tableAr.r2)); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже таблицу кто-то редактирует cell_info.isLockedTable = true; } } } cell_info.sparklineInfo = this.model.getSparklineGroup(c1, r1); if (cell_info.sparklineInfo) { lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, /*subType*/null, sheetId, cell_info.sparklineInfo.Get_Id()); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { cell_info.isLockedSparkline = true; } } cell_info.pivotTableInfo = this.model.getPivotTable(c1, r1); return cell_info; }; WorksheetView.prototype._getSelectionInfoObject = function () { var objectInfo = new asc_CCellInfo(); objectInfo.flags = new AscCommonExcel.asc_CCellFlag(); var graphicObjects = this.objectRender.getSelectedGraphicObjects(); if (graphicObjects.length) { objectInfo.flags.selectionType = this.objectRender.getGraphicSelectionType(graphicObjects[0].Id); } var textPr = this.objectRender.controller.getParagraphTextPr(); var theme = this.objectRender.controller.getTheme(); if (textPr && theme && theme.themeElements && theme.themeElements.fontScheme) { if (textPr.FontFamily) { textPr.FontFamily.Name = theme.themeElements.fontScheme.checkFont(textPr.FontFamily.Name); } if (textPr.RFonts) { if (textPr.RFonts.Ascii) { textPr.RFonts.Ascii.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.Ascii.Name); } if (textPr.RFonts.EastAsia) { textPr.RFonts.EastAsia.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.EastAsia.Name); } if (textPr.RFonts.HAnsi) { textPr.RFonts.HAnsi.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.HAnsi.Name); } if (textPr.RFonts.CS) { textPr.RFonts.CS.Name = theme.themeElements.fontScheme.checkFont(textPr.RFonts.CS.Name); } } } var paraPr = this.objectRender.controller.getParagraphParaPr(); if (!paraPr && textPr) { paraPr = new CParaPr(); } if (textPr && paraPr) { objectInfo.text = this.objectRender.controller.GetSelectedText(true); var horAlign = paraPr.Jc; var vertAlign = Asc.c_oAscVAlign.Center; var shape_props = this.objectRender.controller.getDrawingProps().shapeProps; var angle = null; if (shape_props) { switch (shape_props.verticalTextAlign) { case AscFormat.VERTICAL_ANCHOR_TYPE_BOTTOM: vertAlign = Asc.c_oAscVAlign.Bottom; break; case AscFormat.VERTICAL_ANCHOR_TYPE_CENTER: vertAlign = Asc.c_oAscVAlign.Center; break; case AscFormat.VERTICAL_ANCHOR_TYPE_TOP: case AscFormat.VERTICAL_ANCHOR_TYPE_DISTRIBUTED: case AscFormat.VERTICAL_ANCHOR_TYPE_JUSTIFIED: vertAlign = Asc.c_oAscVAlign.Top; break; } switch (shape_props.vert) { case AscFormat.nVertTTvert: angle = 90; break; case AscFormat.nVertTTvert270: angle = 270; break; default: angle = 0; break; } } objectInfo.halign = horAlign; objectInfo.valign = vertAlign; objectInfo.angle = angle; objectInfo.font = new asc_CFont(); objectInfo.font.name = textPr.FontFamily ? textPr.FontFamily.Name : null; objectInfo.font.size = textPr.FontSize; objectInfo.font.bold = textPr.Bold; objectInfo.font.italic = textPr.Italic; objectInfo.font.underline = textPr.Underline; objectInfo.font.strikeout = textPr.Strikeout; objectInfo.font.subscript = textPr.VertAlign == AscCommon.vertalign_SubScript; objectInfo.font.superscript = textPr.VertAlign == AscCommon.vertalign_SuperScript; if(textPr.Unifill){ if(theme){ textPr.Unifill.check(theme, this.objectRender.controller.getColorMap()); } var oColor = textPr.Unifill.getRGBAColor(); objectInfo.font.color = AscCommon.CreateAscColorCustom(oColor.R, oColor.G, oColor.B); } else if (textPr.Color) { objectInfo.font.color = AscCommon.CreateAscColorCustom(textPr.Color.r, textPr.Color.g, textPr.Color.b); } var shapeHyperlink = this.objectRender.controller.getHyperlinkInfo(); if (shapeHyperlink && (shapeHyperlink instanceof ParaHyperlink)) { var hyperlink = new AscCommonExcel.Hyperlink(); hyperlink.Tooltip = shapeHyperlink.ToolTip; var spl = shapeHyperlink.Value.split("!"); if (spl.length === 2) { hyperlink.setLocation(shapeHyperlink.Value); } else { hyperlink.Hyperlink = shapeHyperlink.Value; } objectInfo.hyperlink = new asc_CHyperlink(hyperlink); objectInfo.hyperlink.asc_setText(shapeHyperlink.GetSelectedText(true, true)); } } else { // Может быть не задано текста, поэтому выставим по умолчанию objectInfo.font = new asc_CFont(); objectInfo.font.name = null; objectInfo.font.size = null; } // Заливка не нужна как таковая objectInfo.fill = new asc_CFill(null); // ToDo locks return objectInfo; }; // Получаем координаты активной ячейки WorksheetView.prototype.getActiveCellCoord = function () { return this.getCellCoord(this.model.selectionRange.activeCell.col, this.model.selectionRange.activeCell.row); }; WorksheetView.prototype.getCellCoord = function (col, row) { var offsetX = 0, offsetY = 0; var vrCol = this.visibleRange.c1, vrRow = this.visibleRange.r1; if ( this.topLeftFrozenCell ) { var offsetFrozen = this.getFrozenPaneOffset(); var cFrozen = this.topLeftFrozenCell.getCol0(); var rFrozen = this.topLeftFrozenCell.getRow0(); if ( col >= cFrozen ) { offsetX = offsetFrozen.offsetX; } else { vrCol = 0; } if ( row >= rFrozen ) { offsetY = offsetFrozen.offsetY; } else { vrRow = 0; } } var xL = this.getCellLeft( col, /*pt*/1 ); var yL = this.getCellTop( row, /*pt*/1 ); // Пересчитываем X и Y относительно видимой области xL -= (this.cols[vrCol].left - this.cellsLeft); yL -= (this.rows[vrRow].top - this.cellsTop); // Пересчитываем X и Y относительно закрепленной области xL += offsetX; yL += offsetY; // Пересчитываем в px xL *= asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIX() ); yL *= asc_getcvt( 1/*pt*/, 0/*px*/, this._getPPIY() ); var width = this.getColumnWidth( col, /*px*/0 ); var height = this.getRowHeight( row, /*px*/0 ); if ( AscBrowser.isRetina ) { xL = AscCommon.AscBrowser.convertToRetinaValue(xL); yL = AscCommon.AscBrowser.convertToRetinaValue(yL); width = AscCommon.AscBrowser.convertToRetinaValue(width); height = AscCommon.AscBrowser.convertToRetinaValue(height); } return new AscCommon.asc_CRect( xL, yL, width, height ); }; WorksheetView.prototype._endSelectionShape = function () { var isSelectOnShape = this.isSelectOnShape; if (this.isSelectOnShape) { this.isSelectOnShape = false; this.objectRender.unselectDrawingObjects(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); } return isSelectOnShape; }; WorksheetView.prototype._updateSelectionNameAndInfo = function () { this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/false)); this.handlers.trigger("selectionChanged"); this.handlers.trigger("selectionMathInfoChanged", this.getSelectionMathInfo()); }; WorksheetView.prototype.getSelectionShape = function () { return this.isSelectOnShape; }; WorksheetView.prototype.setSelectionShape = function ( isSelectOnShape ) { this.isSelectOnShape = isSelectOnShape; // отправляем евент для получения свойств картинки, шейпа или группы this.model.workbook.handlers.trigger( "asc_onHideComment" ); this._updateSelectionNameAndInfo(); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); }; WorksheetView.prototype.setSelection = function (range, validRange) { // Проверка на валидность range. if (validRange && (range.c2 >= this.nColsCount || range.r2 >= this.nRowsCount)) { if (range.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, range.c2 + 1); } if (range.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, range.r2 + 1); } } var oRes = null; var type = range.getType(); if (type === c_oAscSelectionType.RangeCells || type === c_oAscSelectionType.RangeCol || type === c_oAscSelectionType.RangeRow || type === c_oAscSelectionType.RangeMax) { this.cleanSelection(); this.model.selectionRange.assign2(range); this._fixSelectionOfMergedCells(); this.updateSelectionWithSparklines(); this._updateSelectionNameAndInfo(); oRes = this._calcActiveCellOffset(); } return oRes; }; WorksheetView.prototype.changeSelectionStartPoint = function (x, y, isCoord, isCtrl) { this.cleanSelection(); if (!this.isFormulaEditMode) { this.cleanFormulaRanges(); if (isCtrl) { this.model.selectionRange.addRange(); } else { this.model.selectionRange.clean(); } } var ar = this._getSelection().getLast().clone(); var ret = {}; var isChangeSelectionShape = false; var comment; if (isCoord) { comment = this.cellCommentator.getCommentByXY(x, y); // move active range to coordinates x,y this._moveActiveCellToXY(x, y); isChangeSelectionShape = this._endSelectionShape(); } else { comment = this.cellCommentator.getComment(x, y); // move active range to offset x,y this._moveActiveCellToOffset(x, y); ret = this._calcActiveRangeOffset(); } if (!comment) { this.cellCommentator.resetLastSelectedId(); } if (this.isSelectionDialogMode) { if (!this.model.selectionRange.isEqual(ar)) { // Смена диапазона this.handlers.trigger("selectionRangeChanged", this.getSelectionRangeValue()); } } else if (!this.isCellEditMode) { if (isChangeSelectionShape || !this.model.selectionRange.isEqual(ar)) { this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/false)); if (!isCoord) { this.handlers.trigger("selectionChanged"); this.handlers.trigger("selectionMathInfoChanged", this.getSelectionMathInfo()); } } } if (!isChangeSelectionShape) { if (!isCoord) { this.updateSelectionWithSparklines(); } else { this._drawSelection(); } } //ToDo this.drawDepCells(); return ret; }; // Смена селекта по нажатию правой кнопки мыши WorksheetView.prototype.changeSelectionStartPointRightClick = function (x, y) { var isSelectOnShape = this._endSelectionShape(); this.model.workbook.handlers.trigger("asc_onHideComment"); var _x = x * asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); var _y = y * asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var val, c1, c2, r1, r2; val = this._findColUnderCursor(_x, true); if (val) { c1 = c2 = val.col; } else { c1 = 0; c2 = gc_nMaxCol0; } val = this._findRowUnderCursor(_y, true); if (val) { r1 = r2 = val.row; } else { r1 = 0; r2 = gc_nMaxRow0; } if (!this.model.selectionRange.containsRange(new asc_Range(c1, r1, c2, r2))) { // Не попали в выделение (меняем первую точку) this.cleanSelection(); this.model.selectionRange.clean(); this._moveActiveCellToXY(x, y); this._drawSelection(); this._updateSelectionNameAndInfo(); } else if (isSelectOnShape) { this._updateSelectionNameAndInfo(); } }; /** * * @param x - координата или прибавка к column * @param y - координата или прибавка к row * @param isCoord - выделение с помощью мышки или с клавиатуры. При выделении с помощью мышки, не нужно отправлять эвенты о смене выделения и информации * @param keepType * @returns {*} */ WorksheetView.prototype.changeSelectionEndPoint = function (x, y, isCoord, keepType) { var isChangeSelectionShape = isCoord ? this._endSelectionShape() : false; var ar = this._getSelection().getLast(); var newRange = isCoord ? this._calcSelectionEndPointByXY(x, y, keepType) : this._calcSelectionEndPointByOffset(x, y); var isEqual = newRange.isEqual(ar); if (isEqual && !isCoord) { // При движении стрелками можем попасть на замерженную ячейку } if (!isEqual || isChangeSelectionShape) { this.cleanSelection(); ar.assign2(newRange); this._drawSelection(); //ToDo this.drawDepCells(); if (!this.isCellEditMode) { if (!this.isSelectionDialogMode) { this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/true)); if (!isCoord) { this.handlers.trigger("selectionChanged"); this.handlers.trigger("selectionMathInfoChanged", this.getSelectionMathInfo()); } } else { // Смена диапазона this.handlers.trigger("selectionRangeChanged", this.getSelectionRangeValue()); } } } this.model.workbook.handlers.trigger("asc_onHideComment"); return isCoord ? this._calcActiveRangeOffsetIsCoord(x, y) : this._calcActiveRangeOffset(); }; // Окончание выделения WorksheetView.prototype.changeSelectionDone = function () { if (this.stateFormatPainter) { this.applyFormatPainter(); } else { this.checkSelectionSparkline(); } }; // Обработка движения в выделенной области WorksheetView.prototype.changeSelectionActivePoint = function (dc, dr) { var ret; if (0 === dc && 0 === dr) { return this._calcActiveCellOffset(); } if (!this._moveActivePointInSelection(dc, dr)) { return this.changeSelectionStartPoint(dc, dr, /*isCoord*/false, false); } // Очищаем выделение this.cleanSelection(); // Перерисовываем this.updateSelectionWithSparklines(); // Смотрим, ушли ли мы за границу видимой области ret = this._calcActiveCellOffset(); // Эвент обновления this.handlers.trigger("selectionNameChanged", this.getSelectionName(/*bRangeText*/false)); this.handlers.trigger("selectionChanged"); return ret; }; WorksheetView.prototype.checkSelectionSparkline = function () { if (!this.getSelectionShape() && !this.isFormulaEditMode && !this.isCellEditMode) { var cell = this.model.selectionRange.activeCell; var mc = this.model.getMergedByCell(cell.row, cell.col); var c1 = mc ? mc.c1 : cell.col; var r1 = mc ? mc.r1 : cell.row; var oSparklineInfo = this.model.getSparklineGroup(c1, r1); if (oSparklineInfo) { this.cleanSelection(); this.cleanFormulaRanges(); var range = oSparklineInfo.getLocationRanges(); range.ranges.forEach(function (item) { item.isName = true; item.noColor = true; }); this.arrActiveFormulaRanges.push(range); this._drawSelection(); return true; } } }; // ----- Changing cells ----- WorksheetView.prototype.applyFormatPainter = function () { var t = this; var from = t.handlers.trigger('getRangeFormatPainter').getLast(), to = this.model.selectionRange.getLast().getAllRange(); var onApplyFormatPainterCallback = function (isSuccess) { // Очищаем выделение t.cleanSelection(); if (true === isSuccess) { AscCommonExcel.promoteFromTo(from, t.model, to, t.model); } t.expandColsOnScroll(false, true, to.c2 + 1); t.expandRowsOnScroll(false, true, to.r2 + 1); // Сбрасываем параметры t._updateCellsRange(to, /*canChangeColWidth*/c_oAscCanChangeColWidth.none, /*lockDraw*/true); if (c_oAscFormatPainterState.kMultiple !== t.stateFormatPainter) { t.handlers.trigger('onStopFormatPainter'); } // Перерисовываем t._recalculateAfterUpdate([to]); }; var result = AscCommonExcel.preparePromoteFromTo(from, to); if (!result) { // ToDo вывести ошибку onApplyFormatPainterCallback(false); return; } this._isLockedCells(to, null, onApplyFormatPainterCallback); }; WorksheetView.prototype.formatPainter = function (stateFormatPainter) { // Если передали состояние, то выставляем его. Если нет - то меняем на противоположное. this.stateFormatPainter = (null != stateFormatPainter) ? stateFormatPainter : ((c_oAscFormatPainterState.kOff !== this.stateFormatPainter) ? c_oAscFormatPainterState.kOff : c_oAscFormatPainterState.kOn); if (this.stateFormatPainter) { this.copyActiveRange = this.model.selectionRange.clone(); this._drawFormatPainterRange(); } else { this.cleanSelection(); this.copyActiveRange = null; this._drawSelection(); } return this.copyActiveRange; }; /* Функция для работы автозаполнения (selection). (x, y) - координаты точки мыши на области */ WorksheetView.prototype.changeSelectionFillHandle = function (x, y) { // Возвращаемый результат var ret = null; // Если мы только первый раз попали сюда, то копируем выделенную область if (null === this.activeFillHandle) { this.activeFillHandle = this.model.selectionRange.getLast().clone(); // Для первого раза нормализуем (т.е. первая точка - это левый верхний угол) this.activeFillHandle.normalize(); return ret; } // Пересчитываем координаты x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); // Очищаем выделение, будем рисовать заново this.cleanSelection(); // Копируем выделенную область var ar = this.model.selectionRange.getLast().clone(true); // Получаем координаты левого верхнего угла выделения var xL = this.getCellLeft(ar.c1, /*pt*/1); var yL = this.getCellTop(ar.r1, /*pt*/1); // Получаем координаты правого нижнего угла выделения var xR = this.getCellLeft(ar.c2, /*pt*/1) + this.cols[ar.c2].width; var yR = this.getCellTop(ar.r2, /*pt*/1) + this.rows[ar.r2].height; // range для пересчета видимой области var activeFillHandleCopy; // Колонка по X и строка по Y var colByX = this._findColUnderCursor(x, /*canReturnNull*/false, true).col; var rowByY = this._findRowUnderCursor(y, /*canReturnNull*/false, true).row; // Колонка по X и строка по Y (без половинчатого счета). Для сдвига видимой области var colByXNoDX = this._findColUnderCursor(x, /*canReturnNull*/false, false).col; var rowByYNoDY = this._findRowUnderCursor(y, /*canReturnNull*/false, false).row; // Сдвиг в столбцах и строках от крайней точки var dCol; var dRow; // Пересчитываем X и Y относительно видимой области x += (this.cols[this.visibleRange.c1].left - this.cellsLeft); y += (this.rows[this.visibleRange.r1].top - this.cellsTop); // Вычисляем расстояние от (x, y) до (xL, yL) var dXL = x - xL; var dYL = y - yL; // Вычисляем расстояние от (x, y) до (xR, yR) var dXR = x - xR; var dYR = y - yR; var dXRMod; var dYRMod; // Определяем область попадания и точку /* (1) (2) (3) ------------|-----------------------|------------ | | (4) | (5) | (6) | | ------------|-----------------------|------------ (7) (8) (9) */ // Область точки (x, y) var _tmpArea = 0; if (dXR <= 0) { // Области (1), (2), (4), (5), (7), (8) if (dXL <= 0) { // Области (1), (4), (7) if (dYR <= 0) { // Области (1), (4) if (dYL <= 0) { // Область (1) _tmpArea = 1; } else { // Область (4) _tmpArea = 4; } } else { // Область (7) _tmpArea = 7; } } else { // Области (2), (5), (8) if (dYR <= 0) { // Области (2), (5) if (dYL <= 0) { // Область (2) _tmpArea = 2; } else { // Область (5) _tmpArea = 5; } } else { // Область (3) _tmpArea = 8; } } } else { // Области (3), (6), (9) if (dYR <= 0) { // Области (3), (6) if (dYL <= 0) { // Область (3) _tmpArea = 3; } else { // Область (6) _tmpArea = 6; } } else { // Область (9) _tmpArea = 9; } } // Проверяем, в каком направлении движение switch (_tmpArea) { case 2: case 8: // Двигаемся по вертикали. this.fillHandleDirection = 1; break; case 4: case 6: // Двигаемся по горизонтали. this.fillHandleDirection = 0; break; case 1: // Сравниваем расстояния от точки до левого верхнего угла выделения dXRMod = Math.abs(x - xL); dYRMod = Math.abs(y - yL); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c1); dRow = Math.abs(rowByY - ar.r1); // Определим направление позднее this.fillHandleDirection = -1; break; case 3: // Сравниваем расстояния от точки до правого верхнего угла выделения dXRMod = Math.abs(x - xR); dYRMod = Math.abs(y - yL); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c2); dRow = Math.abs(rowByY - ar.r1); // Определим направление позднее this.fillHandleDirection = -1; break; case 7: // Сравниваем расстояния от точки до левого нижнего угла выделения dXRMod = Math.abs(x - xL); dYRMod = Math.abs(y - yR); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c1); dRow = Math.abs(rowByY - ar.r2); // Определим направление позднее this.fillHandleDirection = -1; break; case 5: case 9: // Сравниваем расстояния от точки до правого нижнего угла выделения dXRMod = Math.abs(dXR); dYRMod = Math.abs(dYR); // Сдвиги по столбцам и строкам dCol = Math.abs(colByX - ar.c2); dRow = Math.abs(rowByY - ar.r2); // Определим направление позднее this.fillHandleDirection = -1; break; } //console.log(_tmpArea); // Возможно еще не определили направление if (-1 === this.fillHandleDirection) { // Проверим сдвиги по столбцам и строкам, если не поможет, то рассчитываем по расстоянию if (0 === dCol && 0 !== dRow) { // Двигаемся по вертикали. this.fillHandleDirection = 1; } else if (0 !== dCol && 0 === dRow) { // Двигаемся по горизонтали. this.fillHandleDirection = 0; } else if (dXRMod >= dYRMod) { // Двигаемся по горизонтали. this.fillHandleDirection = 0; } else { // Двигаемся по вертикали. this.fillHandleDirection = 1; } } // Проверяем, в каком направлении движение if (0 === this.fillHandleDirection) { // Определяем область попадания и точку /* | | | | (1) | (2) | (3) | | | | */ if (dXR <= 0) { // Область (1) или (2) if (dXL <= 0) { // Область (1) this.fillHandleArea = 1; } else { // Область (2) this.fillHandleArea = 2; } } else { // Область (3) this.fillHandleArea = 3; } // Находим колонку для точки this.activeFillHandle.c2 = colByX; switch (this.fillHandleArea) { case 1: // Первая точка (xR, yR), вторая точка (x, yL) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.r2 = ar.r1; // Случай, если мы еще не вышли из внутренней области if (this.activeFillHandle.c2 == ar.c1) { this.fillHandleArea = 2; } break; case 2: // Первая точка (xR, yR), вторая точка (x, yL) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.r2 = ar.r1; if (this.activeFillHandle.c2 > this.activeFillHandle.c1) { // Ситуация половинки последнего столбца this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.c2 = ar.c1; this.activeFillHandle.r2 = ar.r1; } break; case 3: // Первая точка (xL, yL), вторая точка (x, yR) this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.r2 = ar.r2; break; } // Копируем в range для пересчета видимой области activeFillHandleCopy = this.activeFillHandle.clone(); activeFillHandleCopy.c2 = colByXNoDX; } else { // Определяем область попадания и точку /* (1) ____________________________ (2) ____________________________ (3) */ if (dYR <= 0) { // Область (1) или (2) if (dYL <= 0) { // Область (1) this.fillHandleArea = 1; } else { // Область (2) this.fillHandleArea = 2; } } else { // Область (3) this.fillHandleArea = 3; } // Находим строку для точки this.activeFillHandle.r2 = rowByY; switch (this.fillHandleArea) { case 1: // Первая точка (xR, yR), вторая точка (xL, y) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.c2 = ar.c1; // Случай, если мы еще не вышли из внутренней области if (this.activeFillHandle.r2 == ar.r1) { this.fillHandleArea = 2; } break; case 2: // Первая точка (xR, yR), вторая точка (xL, y) this.activeFillHandle.c1 = ar.c2; this.activeFillHandle.r1 = ar.r2; this.activeFillHandle.c2 = ar.c1; if (this.activeFillHandle.r2 > this.activeFillHandle.r1) { // Ситуация половинки последней строки this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.c2 = ar.c1; this.activeFillHandle.r2 = ar.r1; } break; case 3: // Первая точка (xL, yL), вторая точка (xR, y) this.activeFillHandle.c1 = ar.c1; this.activeFillHandle.r1 = ar.r1; this.activeFillHandle.c2 = ar.c2; break; } // Копируем в range для пересчета видимой области activeFillHandleCopy = this.activeFillHandle.clone(); activeFillHandleCopy.r2 = rowByYNoDY; } //console.log ("row1: " + this.activeFillHandle.r1 + " col1: " + this.activeFillHandle.c1 + " row2: " + this.activeFillHandle.r2 + " col2: " + this.activeFillHandle.c2); // Перерисовываем this._drawSelection(); // Смотрим, ушли ли мы за границу видимой области ret = this._calcFillHandleOffset(activeFillHandleCopy); this.model.workbook.handlers.trigger("asc_onHideComment"); return ret; }; /* Функция для применения автозаполнения */ WorksheetView.prototype.applyFillHandle = function (x, y, ctrlPress) { var t = this; // Текущее выделение (к нему применится автозаполнение) var arn = t.model.selectionRange.getLast(); var range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); // Были ли изменения var bIsHaveChanges = false; // Вычисляем индекс сдвига var nIndex = 0; /*nIndex*/ if (0 === this.fillHandleDirection) { // Горизонтальное движение nIndex = this.activeFillHandle.c2 - arn.c1; if (2 === this.fillHandleArea) { // Для внутренности нужно вычесть 1 из значения bIsHaveChanges = arn.c2 !== (this.activeFillHandle.c2 - 1); } else { bIsHaveChanges = arn.c2 !== this.activeFillHandle.c2; } } else { // Вертикальное движение nIndex = this.activeFillHandle.r2 - arn.r1; if (2 === this.fillHandleArea) { // Для внутренности нужно вычесть 1 из значения bIsHaveChanges = arn.r2 !== (this.activeFillHandle.r2 - 1); } else { bIsHaveChanges = arn.r2 !== this.activeFillHandle.r2; } } // Меняли ли что-то if (bIsHaveChanges && (this.activeFillHandle.r1 !== this.activeFillHandle.r2 || this.activeFillHandle.c1 !== this.activeFillHandle.c2)) { // Диапазон ячеек, который мы будем менять var changedRange = arn.clone(); // Очищаем выделение this.cleanSelection(); if (2 === this.fillHandleArea) { // Мы внутри, будет удаление cбрасываем первую ячейку // Проверяем, удалили ли мы все (если да, то область не меняется) if (arn.c1 !== this.activeFillHandle.c2 || arn.r1 !== this.activeFillHandle.r2) { // Уменьшаем диапазон (мы удалили не все) if (0 === this.fillHandleDirection) { // Горизонтальное движение (для внутренности необходимо вычесть 1) arn.c2 = this.activeFillHandle.c2 - 1; changedRange.c1 = changedRange.c2; changedRange.c2 = this.activeFillHandle.c2; } else { // Вертикальное движение (для внутренности необходимо вычесть 1) arn.r2 = this.activeFillHandle.r2 - 1; changedRange.r1 = changedRange.r2; changedRange.r2 = this.activeFillHandle.r2; } } } else { // Мы вне выделения. Увеличиваем диапазон if (0 === this.fillHandleDirection) { // Горизонтальное движение if (1 === this.fillHandleArea) { arn.c1 = this.activeFillHandle.c2; changedRange.c2 = changedRange.c1 - 1; changedRange.c1 = this.activeFillHandle.c2; } else { arn.c2 = this.activeFillHandle.c2; changedRange.c1 = changedRange.c2 + 1; changedRange.c2 = this.activeFillHandle.c2; } } else { // Вертикальное движение if (1 === this.fillHandleArea) { arn.r1 = this.activeFillHandle.r2; changedRange.r2 = changedRange.r1 - 1; changedRange.r1 = this.activeFillHandle.r2; } else { arn.r2 = this.activeFillHandle.r2; changedRange.r1 = changedRange.r2 + 1; changedRange.r2 = this.activeFillHandle.r2; } } } changedRange.normalize(); var applyFillHandleCallback = function (res) { if (res) { // Автозаполняем ячейки var oCanPromote = range.canPromote(/*bCtrl*/ctrlPress, /*bVertical*/(1 === t.fillHandleDirection), nIndex); if (null != oCanPromote) { History.Create_NewPoint(); History.StartTransaction(); if(t.model.autoFilters.bIsExcludeHiddenRows(changedRange, t.model.selectionRange.activeCell)){ t.model.excludeHiddenRows(true); } range.promote(/*bCtrl*/ctrlPress, /*bVertical*/(1 === t.fillHandleDirection), nIndex, oCanPromote); t.model.excludeHiddenRows(false); // Вызываем функцию пересчета для заголовков форматированной таблицы t.model.autoFilters.renameTableColumn(arn); // Сбрасываем параметры автозаполнения t.activeFillHandle = null; t.fillHandleDirection = -1; // Обновляем выделенные ячейки t.isChanged = true; t._updateCellsRange(arn); History.SetSelection(range.bbox.clone()); History.SetSelectionRedo(oCanPromote.to.clone()); History.EndTransaction(); } else { t.handlers.trigger("onErrorEvent", c_oAscError.ID.CannotFillRange, c_oAscError.Level.NoCritical); t.model.selectionRange.assign2(range.bbox); // Сбрасываем параметры автозаполнения t.activeFillHandle = null; t.fillHandleDirection = -1; t.updateSelection(); } } else { // Сбрасываем параметры автозаполнения t.activeFillHandle = null; t.fillHandleDirection = -1; // Перерисовываем t._drawSelection(); } }; if (this.model.inPivotTable(changedRange)) { // Сбрасываем параметры автозаполнения this.activeFillHandle = null; this.fillHandleDirection = -1; // Перерисовываем this._drawSelection(); this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } // Можно ли применять автозаполнение ? this._isLockedCells(changedRange, /*subType*/null, applyFillHandleCallback); } else { // Ничего не менялось, сбрасываем выделение this.cleanSelection(); // Сбрасываем параметры автозаполнения this.activeFillHandle = null; this.fillHandleDirection = -1; // Перерисовываем this._drawSelection(); } }; /* Функция для работы перемещения диапазона (selection). (x, y) - координаты точки мыши на области * ToDo нужно переделать, чтобы moveRange появлялся только после сдвига от текущей ячейки */ WorksheetView.prototype.changeSelectionMoveRangeHandle = function (x, y) { // Возвращаемый результат var ret = null; // Пересчитываем координаты x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); //если выделена ячейка заголовка ф/т, меняем выделение с ячейки на столбец ф/т //если выделена вся видимая часть форматированной таблицы, но не выделены последние скрытые строчки var selectionRange = this.model.selectionRange.getLast().clone(); if (null === this.startCellMoveRange) { this.af_changeSelectionTablePart(selectionRange); } // Колонка по X и строка по Y var colByX = this._findColUnderCursor(x, /*canReturnNull*/false, false).col; var rowByY = this._findRowUnderCursor(y, /*canReturnNull*/false, false).row; var type = selectionRange.getType(); if (type === c_oAscSelectionType.RangeRow) { colByX = 0; } else if (type === c_oAscSelectionType.RangeCol) { rowByY = 0; } else if (type === c_oAscSelectionType.RangeMax) { colByX = 0; rowByY = 0; } // Если мы только первый раз попали сюда, то копируем выделенную область if (null === this.startCellMoveRange) { // Учитываем погрешность (мы должны быть внутри диапазона при старте) if (colByX < selectionRange.c1) { colByX = selectionRange.c1; } else if (colByX > selectionRange.c2) { colByX = selectionRange.c2; } if (rowByY < selectionRange.r1) { rowByY = selectionRange.r1; } else if (rowByY > selectionRange.r2) { rowByY = selectionRange.r2; } this.startCellMoveRange = new asc_Range(colByX, rowByY, colByX, rowByY); this.startCellMoveRange.isChanged = false; // Флаг, сдвигались ли мы от первоначального диапазона return ret; } // Разница, на сколько мы сдвинулись var colDelta = colByX - this.startCellMoveRange.c1; var rowDelta = rowByY - this.startCellMoveRange.r1; // Проверяем, нужно ли отрисовывать перемещение (сдвигались или нет) if (false === this.startCellMoveRange.isChanged && 0 === colDelta && 0 === rowDelta) { return ret; } // Выставляем флаг this.startCellMoveRange.isChanged = true; // Очищаем выделение, будем рисовать заново this.cleanSelection(); this.activeMoveRange = selectionRange; // Для первого раза нормализуем (т.е. первая точка - это левый верхний угол) this.activeMoveRange.normalize(); // Выставляем this.activeMoveRange.c1 += colDelta; if (0 > this.activeMoveRange.c1) { colDelta -= this.activeMoveRange.c1; this.activeMoveRange.c1 = 0; } this.activeMoveRange.c2 += colDelta; this.activeMoveRange.r1 += rowDelta; if (0 > this.activeMoveRange.r1) { rowDelta -= this.activeMoveRange.r1; this.activeMoveRange.r1 = 0; } this.activeMoveRange.r2 += rowDelta; // Увеличиваем, если выходим за область видимости // Critical Bug 17413 while (!this.cols[this.activeMoveRange.c2]) { this.expandColsOnScroll(true); this.handlers.trigger("reinitializeScrollX"); } while (!this.rows[this.activeMoveRange.r2]) { this.expandRowsOnScroll(true); this.handlers.trigger("reinitializeScrollY"); } // Перерисовываем this._drawSelection(); var d = {}; /*var d = { deltaX : this.activeMoveRange.c1 < this.visibleRange.c1 ? this.activeMoveRange.c1-this.visibleRange.c1 : this.activeMoveRange.c2>this.visibleRange.c2 ? this.activeMoveRange.c2-this.visibleRange.c2 : 0, deltaY : this.activeMoveRange.r1 < this.visibleRange.r1 ? this.activeMoveRange.r1-this.visibleRange.r1 : this.activeMoveRange.r2>this.visibleRange.r2 ? this.activeMoveRange.r2-this.visibleRange.r2 : 0 }; while ( this._isColDrawnPartially( this.activeMoveRange.c2, this.visibleRange.c1 + d.deltaX) ) {++d.deltaX;} while ( this._isRowDrawnPartially( this.activeMoveRange.r2, this.visibleRange.r1 + d.deltaY) ) {++d.deltaY;}*/ if (y <= this.cellsTop + this.height_2px) { d.deltaY = -1; } else if (y >= this.drawingCtx.getHeight() - this.height_2px) { d.deltaY = 1; } if (x <= this.cellsLeft + this.width_2px) { d.deltaX = -1; } else if (x >= this.drawingCtx.getWidth() - this.width_2px) { d.deltaX = 1; } this.model.workbook.handlers.trigger("asc_onHideComment"); type = this.activeMoveRange.getType(); if (type === c_oAscSelectionType.RangeRow) { d.deltaX = 0; } else if (type === c_oAscSelectionType.RangeCol) { d.deltaY = 0; } else if (type === c_oAscSelectionType.RangeMax) { d.deltaX = 0; d.deltaY = 0; } return d; }; WorksheetView.prototype.changeSelectionMoveResizeRangeHandle = function (x, y, targetInfo, editor) { // Возвращаемый результат if (!targetInfo) { return null; } var type; var indexFormulaRange = targetInfo.indexFormulaRange, d = {deltaY: 0, deltaX: 0}, newFormulaRange = null; // Пересчитываем координаты x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var ar = (0 == targetInfo.targetArr ? this.arrActiveFormulaRanges[indexFormulaRange] : this.arrActiveChartRanges[indexFormulaRange]).getLast().clone(); // Колонка по X и строка по Y var colByX = this._findColUnderCursor(x, /*canReturnNull*/false, false).col; var rowByY = this._findRowUnderCursor(y, /*canReturnNull*/false, false).row; // Если мы только первый раз попали сюда, то копируем выделенную область if (null === this.startCellMoveResizeRange) { if ((targetInfo.cursor == kCurNEResize || targetInfo.cursor == kCurSEResize)) { this.startCellMoveResizeRange = ar.clone(true); this.startCellMoveResizeRange2 = new asc_Range(targetInfo.col, targetInfo.row, targetInfo.col, targetInfo.row, true); } else { this.startCellMoveResizeRange = ar.clone(true); if (colByX < ar.c1) { colByX = ar.c1; } else if (colByX > ar.c2) { colByX = ar.c2; } if (rowByY < ar.r1) { rowByY = ar.r1; } else if (rowByY > ar.r2) { rowByY = ar.r2; } this.startCellMoveResizeRange2 = new asc_Range(colByX, rowByY, colByX, rowByY); } return null; } // Очищаем выделение, будем рисовать заново // this.cleanSelection(); this.overlayCtx.clear(); if (targetInfo.cursor == kCurNEResize || targetInfo.cursor == kCurSEResize) { if (colByX < this.startCellMoveResizeRange2.c1) { ar.c2 = this.startCellMoveResizeRange2.c1; ar.c1 = colByX; } else if (colByX > this.startCellMoveResizeRange2.c1) { ar.c1 = this.startCellMoveResizeRange2.c1; ar.c2 = colByX; } else { ar.c1 = this.startCellMoveResizeRange2.c1; ar.c2 = this.startCellMoveResizeRange2.c1 } if (rowByY < this.startCellMoveResizeRange2.r1) { ar.r2 = this.startCellMoveResizeRange2.r2; ar.r1 = rowByY; } else if (rowByY > this.startCellMoveResizeRange2.r1) { ar.r1 = this.startCellMoveResizeRange2.r1; ar.r2 = rowByY; } else { ar.r1 = this.startCellMoveResizeRange2.r1; ar.r2 = this.startCellMoveResizeRange2.r1; } } else { this.startCellMoveResizeRange.normalize(); type = this.startCellMoveResizeRange.getType(); var colDelta = type !== c_oAscSelectionType.RangeRow && type !== c_oAscSelectionType.RangeMax ? colByX - this.startCellMoveResizeRange2.c1 : 0; var rowDelta = type !== c_oAscSelectionType.RangeCol && type !== c_oAscSelectionType.RangeMax ? rowByY - this.startCellMoveResizeRange2.r1 : 0; ar.c1 = this.startCellMoveResizeRange.c1 + colDelta; if (0 > ar.c1) { colDelta -= ar.c1; ar.c1 = 0; } ar.c2 = this.startCellMoveResizeRange.c2 + colDelta; ar.r1 = this.startCellMoveResizeRange.r1 + rowDelta; if (0 > ar.r1) { rowDelta -= ar.r1; ar.r1 = 0; } ar.r2 = this.startCellMoveResizeRange.r2 + rowDelta; } if (y <= this.cellsTop + this.height_2px) { d.deltaY = -1; } else if (y >= this.drawingCtx.getHeight() - this.height_2px) { d.deltaY = 1; } if (x <= this.cellsLeft + this.width_2px) { d.deltaX = -1; } else if (x >= this.drawingCtx.getWidth() - this.width_2px) { d.deltaX = 1; } type = this.startCellMoveResizeRange.getType(); if (type === c_oAscSelectionType.RangeRow) { d.deltaX = 0; } else if (type === c_oAscSelectionType.RangeCol) { d.deltaY = 0; } else if (type === c_oAscSelectionType.RangeMax) { d.deltaX = 0; d.deltaY = 0; } if (0 == targetInfo.targetArr) { var _p = this.arrActiveFormulaRanges[indexFormulaRange].cursorePos, _l = this.arrActiveFormulaRanges[indexFormulaRange].formulaRangeLength; this.arrActiveFormulaRanges[indexFormulaRange].getLast().assign2(ar.clone(true)); this.arrActiveFormulaRanges[indexFormulaRange].cursorePos = _p; this.arrActiveFormulaRanges[indexFormulaRange].formulaRangeLength = _l; newFormulaRange = this.arrActiveFormulaRanges[indexFormulaRange].getLast(); } else { this.arrActiveChartRanges[indexFormulaRange].getLast().assign2(ar.clone(true)); this.moveRangeDrawingObjectTo = ar.clone(); } this._drawSelection(); if (newFormulaRange) { editor.changeCellRange(newFormulaRange); } return d; }; WorksheetView.prototype._cleanSelectionMoveRange = function () { // Перерисовываем и сбрасываем параметры this.cleanSelection(); this.activeMoveRange = null; this.startCellMoveRange = null; this._drawSelection(); }; /* Функция для применения перемещения диапазона */ WorksheetView.prototype.applyMoveRangeHandle = function (ctrlKey) { if (null === this.activeMoveRange) { // Сбрасываем параметры this.startCellMoveRange = null; return; } var arnFrom = this.model.selectionRange.getLast(); var arnTo = this.activeMoveRange.clone(true); if (arnFrom.isEqual(arnTo)) { this._cleanSelectionMoveRange(); return; } if (this.model.inPivotTable([arnFrom, arnTo])) { this._cleanSelectionMoveRange(); this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } var resmove = this.model._prepareMoveRange(arnFrom, arnTo); if (resmove === -2) { this.handlers.trigger("onErrorEvent", c_oAscError.ID.CannotMoveRange, c_oAscError.Level.NoCritical); this._cleanSelectionMoveRange(); } else if (resmove === -1) { var t = this; this.model.workbook.handlers.trigger("asc_onConfirmAction", Asc.c_oAscConfirm.ConfirmReplaceRange, function (can) { if (can) { t.moveRangeHandle(arnFrom, arnTo, ctrlKey); } else { t._cleanSelectionMoveRange(); } }); } else { this.moveRangeHandle(arnFrom, arnTo, ctrlKey); } }; WorksheetView.prototype.applyMoveResizeRangeHandle = function ( target ) { if ( -1 == target.targetArr && !this.startCellMoveResizeRange.isEqual( this.moveRangeDrawingObjectTo ) ) { this.objectRender.moveRangeDrawingObject( this.startCellMoveResizeRange, this.moveRangeDrawingObjectTo ); } this.startCellMoveResizeRange = null; this.startCellMoveResizeRange2 = null; this.moveRangeDrawingObjectTo = null; }; WorksheetView.prototype.moveRangeHandle = function (arnFrom, arnTo, copyRange) { var t = this; var onApplyMoveRangeHandleCallback = function (isSuccess) { if (false === isSuccess) { t.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedAllError, c_oAscError.Level.NoCritical); t._cleanSelectionMoveRange(); return; } var onApplyMoveAutoFiltersCallback = function (isSuccess) { if (false === isSuccess) { t.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedAllError, c_oAscError.Level.NoCritical); t._cleanSelectionMoveRange(); return; } // Очищаем выделение t.cleanSelection(); //ToDo t.cleanDepCells(); History.Create_NewPoint(); History.SetSelection(arnFrom.clone()); History.SetSelectionRedo(arnTo.clone()); History.StartTransaction(); t.model.autoFilters._preMoveAutoFilters(arnFrom, arnTo, copyRange); t.model._moveRange(arnFrom, arnTo, copyRange); t.cellCommentator.moveRangeComments(arnFrom, arnTo, copyRange); t.objectRender.moveRangeDrawingObject(arnFrom, arnTo); // Вызываем функцию пересчета для заголовков форматированной таблицы t.model.autoFilters.renameTableColumn(arnFrom); t.model.autoFilters.renameTableColumn(arnTo); t.model.autoFilters.reDrawFilter(arnFrom); t.model.autoFilters.afterMoveAutoFilters(arnFrom, arnTo); t._updateCellsRange(arnTo, false, true); t.model.selectionRange.assign2(arnTo); // Сбрасываем параметры t.activeMoveRange = null; t.startCellMoveRange = null; t._updateCellsRange(arnFrom, false, true); // Тут будет отрисовка select-а t._recalculateAfterUpdate([arnFrom, arnTo]); // Вызовем на всякий случай, т.к. мы можем уже обновиться из-за формул ToDo возможно стоит убрать это в дальнейшем (но нужна переработка формул) - http://bugzilla.onlyoffice.com/show_bug.cgi?id=24505 t._updateSelectionNameAndInfo(); if (null !== t.model.getRange3(arnTo.r1, arnTo.c1, arnTo.r2, arnTo.c2).hasMerged() && false !== t.model.autoFilters._intersectionRangeWithTableParts(arnTo)) { t.model.autoFilters.unmergeTablesAfterMove(arnTo); t._updateCellsRange(arnTo, false, true); t._recalculateAfterUpdate([arnFrom, arnTo]); //не делаем действий в asc_onConfirmAction, потому что во время диалога может выполниться autosave и новые измения добавятся в точку, которую уже отправили //тем более результат диалога ни на что не влияет t.model.workbook.handlers.trigger("asc_onConfirmAction", Asc.c_oAscConfirm.ConfirmPutMergeRange, function () { }); } History.EndTransaction(); }; if (t.model.autoFilters._searchFiltersInRange(arnFrom, true)) { t._isLockedAll(onApplyMoveAutoFiltersCallback); if(copyRange){ t._isLockedDefNames(null, null); } } else { onApplyMoveAutoFiltersCallback(); } }; if (this.af_isCheckMoveRange(arnFrom, arnTo)) { this._isLockedCells([arnFrom, arnTo], null, onApplyMoveRangeHandleCallback); } else { this._cleanSelectionMoveRange(); } }; WorksheetView.prototype.emptySelection = function ( options ) { // Удаляем выделенные графичекие объекты if ( this.objectRender.selectedGraphicObjectsExists() ) { this.objectRender.controller.deleteSelectedObjects(); } else { this.setSelectionInfo( "empty", options ); } }; WorksheetView.prototype.setSelectionInfo = function (prop, val, onlyActive) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } var t = this; var checkRange = []; var activeCell = this.model.selectionRange.activeCell.clone(); var arn = this.model.selectionRange.getLast().clone(true); var onSelectionCallback = function (isSuccess) { if (false === isSuccess) { return; } var bIsUpdate = true; var oUpdateRanges = {}, hasUpdates = false; var callTrigger = false; var res; var mc, r, c, cell; function makeBorder(b) { var border = new AscCommonExcel.BorderProp(); if (b === false) { border.setStyle(c_oAscBorderStyles.None); } else if (b) { if (b.style !== null && b.style !== undefined) { border.setStyle(b.style); } if (b.color !== null && b.color !== undefined) { if (b.color instanceof Asc.asc_CColor) { border.c = AscCommonExcel.CorrectAscColor(b.color); } } } return border; } History.Create_NewPoint(); History.StartTransaction(); checkRange.forEach(function (item, i) { var range = t.model.getRange3(item.r1, item.c1, item.r2, item.c2); var isLargeRange = t._isLargeRange(range.bbox); var canChangeColWidth = c_oAscCanChangeColWidth.none; if(t.model.autoFilters.bIsExcludeHiddenRows(arn, activeCell)) { t.model.excludeHiddenRows(true); } switch (prop) { case "fn": range.setFontname(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "fs": range.setFontsize(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "b": range.setBold(val); break; case "i": range.setItalic(val); break; case "u": range.setUnderline(val); break; case "s": range.setStrikeout(val); break; case "fa": range.setFontAlign(val); break; case "a": range.setAlignHorizontal(val); break; case "va": range.setAlignVertical(val); break; case "c": range.setFontcolor(val); break; case "bc": range.setFill(val || null); break; // ToDo можно делать просто отрисовку case "wrap": range.setWrap(val); break; case "shrink": range.setShrinkToFit(val); break; case "value": range.setValue(val); break; case "format": range.setNumFormat(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "angle": range.setAngle(val); break; case "rh": range.removeHyperlink(null, true); break; case "border": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } // None if (val.length < 1) { range.setBorder(null); break; } res = new AscCommonExcel.Border(); // Diagonal res.d = makeBorder(val[c_oAscBorderOptions.DiagD] || val[c_oAscBorderOptions.DiagU]); res.dd = !!val[c_oAscBorderOptions.DiagD]; res.du = !!val[c_oAscBorderOptions.DiagU]; // Vertical res.l = makeBorder(val[c_oAscBorderOptions.Left]); res.iv = makeBorder(val[c_oAscBorderOptions.InnerV]); res.r = makeBorder(val[c_oAscBorderOptions.Right]); // Horizontal res.t = makeBorder(val[c_oAscBorderOptions.Top]); res.ih = makeBorder(val[c_oAscBorderOptions.InnerH]); res.b = makeBorder(val[c_oAscBorderOptions.Bottom]); // Change border range.setBorder(res); break; case "merge": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } switch (val) { case c_oAscMergeOptions.MergeCenter: case c_oAscMergeOptions.Merge: range.merge(val); t.cellCommentator.mergeComments(range.getBBox0()); break; case c_oAscMergeOptions.None: range.unmerge(); break; case c_oAscMergeOptions.MergeAcross: for (res = arn.r1; res <= arn.r2; ++res) { t.model.getRange3(res, arn.c1, res, arn.c2).merge(val); cell = new asc_Range(arn.c1, res, arn.c2, res); t.cellCommentator.mergeComments(cell); } break; } break; case "sort": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } t.cellCommentator.sortComments(range.sort(val.type, activeCell.col, val.color, true)); break; case "empty": if (isLargeRange && !callTrigger) { callTrigger = true; t.handlers.trigger("slowOperation", true); } /* отключаем отрисовку на случай необходимости пересчета ячеек, заносим ячейку, при необходимости в список перерисовываемых */ t.model.workbook.dependencyFormulas.lockRecal(); switch(val) { case c_oAscCleanOptions.All: range.cleanAll(); t.model.deletePivotTables(range.bbox); t.model.removeSparklines(arn); // Удаляем комментарии t.cellCommentator.deleteCommentsRange(arn); break; case c_oAscCleanOptions.Text: case c_oAscCleanOptions.Formula: range.cleanText(); t.model.deletePivotTables(range.bbox); break; case c_oAscCleanOptions.Format: range.cleanFormat(); break; case c_oAscCleanOptions.Comments: t.cellCommentator.deleteCommentsRange(arn); break; case c_oAscCleanOptions.Hyperlinks: range.cleanHyperlinks(); break; case c_oAscCleanOptions.Sparklines: t.model.removeSparklines(arn); break; case c_oAscCleanOptions.SparklineGroups: t.model.removeSparklineGroups(arn); break; } t.model.excludeHiddenRows(false); // Если нужно удалить автофильтры - удаляем if (window['AscCommonExcel'].filteringMode) { if (val === c_oAscCleanOptions.All || val === c_oAscCleanOptions.Text) { t.model.autoFilters.isEmptyAutoFilters(arn); } else if (val === c_oAscCleanOptions.Format) { t.model.autoFilters.cleanFormat(arn); } } // Вызываем функцию пересчета для заголовков форматированной таблицы if (val === c_oAscCleanOptions.All || val === c_oAscCleanOptions.Text) { t.model.autoFilters.renameTableColumn(arn); } /* возвращаем отрисовку. и перерисовываем ячейки с предварительным пересчетом */ t.model.workbook.dependencyFormulas.unlockRecal(); break; case "changeDigNum": res = t.cols.slice(arn.c1, arn.c2 + 1).reduce(function (r, c) { r.push(c.charCount); return r; }, []); range.shiftNumFormat(val, res); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; case "changeFontSize": mc = t.model.getMergedByCell(activeCell.row, activeCell.col); c = mc ? mc.c1 : activeCell.col; r = mc ? mc.r1 : activeCell.row; cell = t._getVisibleCell(c, r); var oldFontSize = cell.getFont().getSize(); var newFontSize = asc_incDecFonSize(val, oldFontSize); if (null !== newFontSize) { range.setFontsize(newFontSize); canChangeColWidth = c_oAscCanChangeColWidth.numbers; } break; case "style": range.setCellStyle(val); canChangeColWidth = c_oAscCanChangeColWidth.numbers; break; break; case "paste": var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; specialPasteHelper.specialPasteProps = specialPasteHelper.specialPasteProps ? specialPasteHelper.specialPasteProps : new Asc.SpecialPasteProps(); t._loadDataBeforePaste(isLargeRange, val.fromBinary, val.data, bIsUpdate, canChangeColWidth); bIsUpdate = false; break; case "hyperlink": if (val && val.hyperlinkModel) { if (Asc.c_oAscHyperlinkType.RangeLink === val.asc_getType()) { var hyperlinkRangeTmp = t.model.getRange2(val.asc_getRange()); if (null === hyperlinkRangeTmp) { bIsUpdate = false; break; } } val.hyperlinkModel.Ref = range; range.setHyperlink(val.hyperlinkModel); // Вставим текст в активную ячейку (а не так, как MSExcel в первую ячейку диапазона) mc = t.model.getMergedByCell(activeCell.row, activeCell.col); c = mc ? mc.c1 : activeCell.col; r = mc ? mc.r1 : activeCell.row; if (null !== val.asc_getText()) { t.model.getRange3(r, c, r, c).setValue(val.asc_getText()); // Вызываем функцию пересчета для заголовков форматированной таблицы t.model.autoFilters.renameTableColumn(arn); } break; } else { bIsUpdate = false; break; } default: bIsUpdate = false; break; } t.model.excludeHiddenRows(false); if (bIsUpdate) { hasUpdates = true; oUpdateRanges[i] = item; oUpdateRanges[i].canChangeColWidth = canChangeColWidth; bIsUpdate = false; } }); if (hasUpdates) { t.updateRanges(oUpdateRanges, false, true); } if (callTrigger) { t.handlers.trigger("slowOperation", false); } //в случае, если вставляем из глобального буфера, транзакцию закрываем внутри функции _loadDataBeforePaste на callbacks от загрузки шрифтов и картинок if (prop !== "paste" || (prop === "paste" && val.fromBinary)) { History.EndTransaction(); if(prop === "paste") { window['AscCommon'].g_specialPasteHelper.Paste_Process_End(); } } }; if ("paste" === prop) { if (val.onlyImages) { onSelectionCallback(true); return; } else { var newRange = val.fromBinary ? this._pasteFromBinary(val.data, true) : this._pasteFromHTML(val.data, true); checkRange = [newRange]; } } else if (onlyActive) { checkRange.push(new asc_Range(activeCell.col, activeCell.row, activeCell.col, activeCell.row)); } else { this.model.selectionRange.ranges.forEach(function (item) { checkRange.push(item.getAllRange()); }); } if (("merge" === prop || "paste" === prop || "sort" === prop || "hyperlink" === prop || "rh" === prop) && this.model.inPivotTable(checkRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } if ("empty" === prop && !this.model.checkDeletePivotTables(checkRange)) { // ToDo other error this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(checkRange, /*subType*/null, onSelectionCallback); }; WorksheetView.prototype.specialPaste = function (props) { var api = window["Asc"]["editor"]; var t = this; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteData = specialPasteHelper.specialPasteData; if(!specialPasteData) { return; } var isIntoShape = t.objectRender.controller.getTargetDocContent(); var onSelectionCallback = function(isSuccess) { if(!isSuccess) { return false; } window['AscCommon'].g_specialPasteHelper.Paste_Process_Start(); window['AscCommon'].g_specialPasteHelper.Special_Paste_Start(); api.asc_Undo(); //транзакция закроется в end_paste History.Create_NewPoint(); History.StartTransaction(); //далее специальная вставка specialPasteHelper.specialPasteProps = props; //TODO пока для закрытия транзации выставляю флаг. пересмотреть! window['AscCommon'].g_specialPasteHelper.bIsEndTransaction = true; AscCommonExcel.g_clipboardExcel.pasteData(t, specialPasteData._format, specialPasteData.data1, specialPasteData.data2, specialPasteData.text_data, true); }; if(specialPasteData.activeRange && !isIntoShape) { this._isLockedCells(specialPasteData.activeRange.ranges, /*subType*/null, onSelectionCallback); } else { onSelectionCallback(true); } }; WorksheetView.prototype._pasteData = function (isLargeRange, fromBinary, val, bIsUpdate, canChangeColWidth) { var t = this; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteProps = specialPasteHelper.specialPasteProps; if ( val.props && val.props.onlyImages === true ) { if(!specialPasteHelper.specialPasteStart) { this.handlers.trigger("showSpecialPasteOptions", [Asc.c_oSpecialPasteProps.picture]); } return; } var callTrigger = false; if (isLargeRange) { callTrigger = true; t.handlers.trigger("slowOperation", true); } //добавляем форматированные таблицы var arnToRange = t.model.selectionRange.getLast(); var pasteRange = AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange; var activeCellsPasteFragment = typeof pasteRange === "string" ? AscCommonExcel.g_oRangeCache.getAscRange(pasteRange) : pasteRange; var tablesMap = null; if (fromBinary && val.TableParts && val.TableParts.length && specialPasteProps.formatTable) { var range, tablePartRange, tables = val.TableParts, diffRow, diffCol, curTable, bIsAddTable; var activeRange = AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange; var refInsertBinary = AscCommonExcel.g_oRangeCache.getAscRange(activeRange); for (var i = 0; i < tables.length; i++) { curTable = tables[i]; tablePartRange = curTable.Ref; diffRow = tablePartRange.r1 - refInsertBinary.r1 + arnToRange.r1; diffCol = tablePartRange.c1 - refInsertBinary.c1 + arnToRange.c1; range = t.model.getRange3(diffRow, diffCol, diffRow + (tablePartRange.r2 - tablePartRange.r1), diffCol + (tablePartRange.c2 - tablePartRange.c1)); //если в активную область при записи попала лишь часть таблицы if(activeCellsPasteFragment && !activeCellsPasteFragment.containsRange(tablePartRange)){ continue; } //если область вставки содержит форматированную таблицу, которая пересекается с вставляемой форматированной таблицей var intersectionRangeWithTableParts = t.model.autoFilters._intersectionRangeWithTableParts(range.bbox); if (intersectionRangeWithTableParts) { continue; } if (curTable.style) { range.cleanFormat(); } //TODO использовать bWithoutFilter из tablePart var bWithoutFilter = false; if (!curTable.AutoFilter) { bWithoutFilter = true; } var offset = { offsetCol: range.bbox.c1 - tablePartRange.c1, offsetRow: range.bbox.r1 - tablePartRange.r1 }; var newDisplayName = this.model.workbook.dependencyFormulas.getNextTableName(); var props = { bWithoutFilter: bWithoutFilter, tablePart: curTable, offset: offset, displayName: newDisplayName }; t.model.autoFilters.addAutoFilter(curTable.TableStyleInfo.Name, range.bbox, true, true, props); if (null === tablesMap) { tablesMap = {}; } tablesMap[curTable.DisplayName] = newDisplayName; } if(bIsAddTable) { t._isLockedDefNames(null, null); } } //делаем unmerge ф/т var intersectionRangeWithTableParts = t.model.autoFilters._intersectionRangeWithTableParts(arnToRange); if (intersectionRangeWithTableParts && intersectionRangeWithTableParts.length) { var tablePart; for (var i = 0; i < intersectionRangeWithTableParts.length; i++) { tablePart = intersectionRangeWithTableParts[i]; this.model.getRange3(tablePart.Ref.r1, tablePart.Ref.c1, tablePart.Ref.r2, tablePart.Ref.c2).unmerge(); } } t.model.workbook.dependencyFormulas.lockRecal(); var selectData; if (fromBinary) { selectData = t._pasteFromBinary(val, null, tablesMap); } else { selectData = t._pasteFromHTML(val, null, specialPasteProps); } t.model.autoFilters.renameTableColumn(t.model.selectionRange.getLast()); if (!selectData) { bIsUpdate = false; t.model.workbook.dependencyFormulas.unlockRecal(); if (callTrigger) { t.handlers.trigger("slowOperation", false); } return; } this.expandColsOnScroll(false, true); this.expandRowsOnScroll(false, true); var arrFormula = selectData[1]; for (var i = 0; i < arrFormula.length; ++i) { var rangeF = arrFormula[i].range; var valF = arrFormula[i].val; if (rangeF.isOneCell()) { rangeF.setValue(valF, null, true); } else { var oBBox = rangeF.getBBox0(); t.model._getCell(oBBox.r1, oBBox.c1, function(cell) { cell.setValue(valF, null, true); }); } } t.model.workbook.dependencyFormulas.unlockRecal(); var arn = selectData[0]; var selectionRange = arn.clone(true); if (bIsUpdate) { if (callTrigger) { t.handlers.trigger("slowOperation", false); } t.isChanged = true; t._updateCellsRange(arn, canChangeColWidth); } var oSelection = History.GetSelection(); if (null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(selectionRange.c1, selectionRange.r1, selectionRange.c2, selectionRange.r2); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } //for special paste if(!window['AscCommon'].g_specialPasteHelper.specialPasteStart) { //var specialPasteShowOptions = new Asc.SpecialPasteShowOptions(); var allowedSpecialPasteProps; var sProps = Asc.c_oSpecialPasteProps; if(fromBinary) { allowedSpecialPasteProps = [sProps.paste, sProps.pasteOnlyFormula, sProps.formulaNumberFormat, sProps.formulaAllFormatting, sProps.formulaWithoutBorders, sProps.formulaColumnWidth, sProps.pasteOnlyValues, sProps.valueNumberFormat, sProps.valueAllFormating, sProps.pasteOnlyFormating/*, sProps.link*/]; if(!(val.TableParts && val.TableParts.length)) { //add transpose property allowedSpecialPasteProps.push(sProps.transpose); } } else { //matchDestinationFormatting - пока не добавляю, так как работает как и values allowedSpecialPasteProps = [sProps.sourceformatting, sProps.destinationFormatting]; } window['AscCommon'].g_specialPasteHelper.CleanButtonInfo(); window['AscCommon'].g_specialPasteHelper.buttonInfo.asc_setOptions(allowedSpecialPasteProps); window['AscCommon'].g_specialPasteHelper.buttonInfo.setRange(selectData[0]); } else { window['AscCommon'].g_specialPasteHelper.buttonInfo.setRange(selectData[0]); window['AscCommon'].g_specialPasteHelper.SpecialPasteButton_Update_Position(); } }; WorksheetView.prototype._loadDataBeforePaste = function ( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ) { var t = this; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteProps = specialPasteHelper.specialPasteProps; //paste from excel binary if(fromBinary) { t._pasteData(isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth); } else { var callbackLoadFonts = function() { var api = asc["editor"]; var isEndTransaction = false; var imagesFromWord = pasteContent.props.addImagesFromWord; if ( imagesFromWord && imagesFromWord.length != 0 && !(window["Asc"]["editor"] && window["Asc"]["editor"].isChartEditor) && specialPasteProps.images) { var oObjectsForDownload = AscCommon.GetObjectsForImageDownload( pasteContent.props._aPastedImages ); //if already load images on server if ( AscCommonExcel.g_clipboardExcel.pasteProcessor.alreadyLoadImagesOnServer === true ) { var oImageMap = {}; for ( var i = 0, length = oObjectsForDownload.aBuilderImagesByUrl.length; i < length; ++i ) { var url = oObjectsForDownload.aUrls[i]; //get name from array already load on server urls var name = AscCommonExcel.g_clipboardExcel.pasteProcessor.oImages[url]; var aImageElem = oObjectsForDownload.aBuilderImagesByUrl[i]; if ( name ) { if ( Array.isArray( aImageElem ) ) { for ( var j = 0; j < aImageElem.length; ++j ) { var imageElem = aImageElem[j]; if ( null != imageElem ) { imageElem.SetUrl( name ); } } } oImageMap[i] = name; } else { oImageMap[i] = url; } } t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); AscCommonExcel.g_clipboardExcel.pasteProcessor._insertImagesFromBinaryWord( t, pasteContent, oImageMap ); isEndTransaction = true; } else { if(window["NATIVE_EDITOR_ENJINE"]) { var oImageMap = {}; AscCommon.ResetNewUrls( data, oObjectsForDownload.aUrls, oObjectsForDownload.aBuilderImagesByUrl, oImageMap ); t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); AscCommonExcel.g_clipboardExcel.pasteProcessor._insertImagesFromBinaryWord( t, pasteContent, oImageMap ); isEndTransaction = true; } else { AscCommon.sendImgUrls( api, oObjectsForDownload.aUrls, function ( data ) { var oImageMap = {}; AscCommon.ResetNewUrls( data, oObjectsForDownload.aUrls, oObjectsForDownload.aBuilderImagesByUrl, oImageMap ); t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); AscCommonExcel.g_clipboardExcel.pasteProcessor._insertImagesFromBinaryWord( t, pasteContent, oImageMap ); //закрываем транзакцию, поскольку в setSelectionInfo она не закроется History.EndTransaction(); window['AscCommon'].g_specialPasteHelper.Paste_Process_End(); }, true ); } } } else { t._pasteData( isLargeRange, fromBinary, pasteContent, bIsUpdate, canChangeColWidth ); isEndTransaction = true; } //закрываем транзакцию, поскольку в setSelectionInfo она не закроется if ( isEndTransaction ) { History.EndTransaction(); window['AscCommon'].g_specialPasteHelper.Paste_Process_End(); } }; //загрузка шрифтов, в случае удачи на callback вставляем текст t._loadFonts( pasteContent.props.fontsNew, callbackLoadFonts); } }; WorksheetView.prototype._pasteFromHTML = function (pasteContent, isCheckSelection, specialPasteProps) { var t = this; var wb = window["Asc"]["editor"].wb; var lastSelection = this.model.selectionRange.getLast(); var arn = AscCommonExcel.g_clipboardExcel.pasteProcessor && AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange ? AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange : lastSelection; var arrFormula = []; var numFor = 0; var rMax = pasteContent.content.length + pasteContent.props.rowSpanSpCount + arn.r1; var cMax = pasteContent.props.cellCount + arn.c1; var isMultiple = false; var firstCell = t.model.getRange3(arn.r1, arn.c1, arn.r1, arn.c1); var isMergedFirstCell = firstCell.hasMerged(); var rangeUnMerge = t.model.getRange3(arn.r1, arn.c1, rMax - 1, cMax - 1); var isOneMerge = false; //если вставляем в мерженную ячейку, диапазон которой больше или равен var fPasteCell = pasteContent.content[0][0]; if (arn.c2 >= cMax - 1 && arn.r2 >= rMax - 1 && isMergedFirstCell && isMergedFirstCell.isEqual(arn) && cMax - arn.c1 === fPasteCell.colSpan && rMax - arn.r1 === fPasteCell.rowSpan) { if (!isCheckSelection) { pasteContent.content[0][0].colSpan = isMergedFirstCell.c2 - isMergedFirstCell.c1 + 1; pasteContent.content[0][0].rowSpan = isMergedFirstCell.r2 - isMergedFirstCell.r1 + 1; } isOneMerge = true; } else { //проверка на наличие части объединённой ячейки в области куда осуществляем вставку for (var rFirst = arn.r1; rFirst < rMax; ++rFirst) { for (var cFirst = arn.c1; cFirst < cMax; ++cFirst) { var range = t.model.getRange3(rFirst, cFirst, rFirst, cFirst); var merged = range.hasMerged(); if (merged) { if (merged.r1 < arn.r1 || merged.r2 > rMax - 1 || merged.c1 < arn.c1 || merged.c2 > cMax - 1) { //ошибка в случае если вставка происходит в часть объедененной ячейки if (isCheckSelection) { return arn; } else { this.handlers.trigger("onErrorEvent", c_oAscError.ID.PastInMergeAreaError, c_oAscError.Level.NoCritical); return; } } } } } } var rMax2 = rMax; var cMax2 = cMax; var rMax = pasteContent.content.length; if (isCheckSelection) { var newArr = arn.clone(true); newArr.r2 = rMax2 - 1; newArr.c2 = cMax2 - 1; if (isMultiple || isOneMerge) { newArr.r2 = lastSelection.r2; newArr.c2 = lastSelection.c2; } return newArr; } //если не возникает конфликт, делаем unmerge if(specialPasteProps.format) { rangeUnMerge.unmerge(); //this.cellCommentator.deleteCommentsRange(rangeUnMerge.bbox); } if (!isOneMerge) { arn.r2 = (rMax2 - 1 > 0) ? (rMax2 - 1) : 0; arn.c2 = (cMax2 - 1 > 0) ? (cMax2 - 1) : 0; } if (isMultiple)//случай автозаполнения сложных форм { if(specialPasteProps.format) { t.model.getRange3(lastSelection.r1, lastSelection.c1, lastSelection.r2, lastSelection.c2).unmerge(); } var maxARow = heightArea / heightPasteFr; var maxACol = widthArea / widthPasteFr; var plRow = (rMax2 - arn.r1); var plCol = (arn.c2 - arn.c1) + 1; } else { var maxARow = 1; var maxACol = 1; var plRow = 0; var plCol = 0; } var mergeArr = []; var putInsertedCellIntoRange = function(row, col, currentObj) { var pastedRangeProps = {}; var contentCurrentObj = currentObj.content; var range = t.model.getRange3(row, col, row, col); //value if (contentCurrentObj.length === 1) { var onlyOneChild = contentCurrentObj[0]; var valFormat = onlyOneChild.text; pastedRangeProps.val = valFormat; pastedRangeProps.font = onlyOneChild.format; } else { pastedRangeProps.value2 = contentCurrentObj; pastedRangeProps.alignVertical = currentObj.va; pastedRangeProps.val = currentObj.textVal; } if (contentCurrentObj.length === 1 && contentCurrentObj[0].format) { var fs = contentCurrentObj[0].format.getSize(); if (fs !== '' && fs !== null && fs !== undefined) { pastedRangeProps.fontSize = fs; } } //AlignHorizontal if (!isOneMerge) { pastedRangeProps.alignHorizontal = currentObj.a; } //for merge var isMerged = false; for (var mergeCheck = 0; mergeCheck < mergeArr.length; ++mergeCheck) { if (mergeArr[mergeCheck].contains(col, row)) { isMerged = true; } } if ((currentObj.colSpan > 1 || currentObj.rowSpan > 1) && !isMerged) { var offsetCol = currentObj.colSpan - 1; var offsetRow = currentObj.rowSpan - 1; pastedRangeProps.offsetLast = {offsetCol: offsetCol, offsetRow: offsetRow}; mergeArr.push(new Asc.Range(range.bbox.c1, range.bbox.r1, range.bbox.c2 + offsetCol, range.bbox.r2 + offsetRow)); if (contentCurrentObj[0] == undefined) { pastedRangeProps.val = ''; } pastedRangeProps.merge = c_oAscMergeOptions.Merge; } //borders if (!isOneMerge) { pastedRangeProps.borders = currentObj.borders; } //wrap pastedRangeProps.wrap = currentObj.wrap; //fill if (currentObj.bc && currentObj.bc.rgb) { pastedRangeProps.fill = currentObj.bc; } //hyperlink var link = currentObj.hyperLink; if (link) { pastedRangeProps.hyperLink = currentObj; } //apply props by cell t._setPastedDataByCurrentRange(range, pastedRangeProps, null, specialPasteProps); }; for (var autoR = 0; autoR < maxARow; ++autoR) { for (var autoC = 0; autoC < maxACol; ++autoC) { for (var r = 0; r < rMax; ++r) { for (var c = 0; c < pasteContent.content[r].length; ++c) { if (undefined !== pasteContent.content[r][c]) { var pasteIntoRow = r + autoR * plRow + arn.r1; var pasteIntoCol = c + autoC * plCol + arn.c1; var currentObj = pasteContent.content[r][c]; putInsertedCellIntoRange(pasteIntoRow, pasteIntoCol, currentObj); } } } } } if (isMultiple) { arn.r2 = lastSelection.r2; arn.c2 = lastSelection.c2; } t.isChanged = true; lastSelection.c2 = arn.c2; lastSelection.r2 = arn.r2; var arnFor = [arn, arrFormula]; return arnFor; }; WorksheetView.prototype._pasteFromBinary = function (val, isCheckSelection, tablesMap) { var t = this; var trueActiveRange = t.model.selectionRange.getLast().clone(); var lastSelection = this.model.selectionRange.getLast(); var arn = t.model.selectionRange.getLast().clone(); var arrFormula = []; var pasteRange = AscCommonExcel.g_clipboardExcel.pasteProcessor.activeRange; var activeCellsPasteFragment = typeof pasteRange === "string" ? AscCommonExcel.g_oRangeCache.getAscRange(pasteRange) : pasteRange; var specialPasteHelper = window['AscCommon'].g_specialPasteHelper; var specialPasteProps = specialPasteHelper.specialPasteProps; var countPasteRow = activeCellsPasteFragment.r2 - activeCellsPasteFragment.r1 + 1; var countPasteCol = activeCellsPasteFragment.c2 - activeCellsPasteFragment.c1 + 1; if(specialPasteProps && specialPasteProps.transpose) { countPasteRow = activeCellsPasteFragment.c2 - activeCellsPasteFragment.c1 + 1; countPasteCol = activeCellsPasteFragment.r2 - activeCellsPasteFragment.r1 + 1; } var rMax = countPasteRow + arn.r1; var cMax = countPasteCol + arn.c1; if (cMax > gc_nMaxCol0) { cMax = gc_nMaxCol0; } if (rMax > gc_nMaxRow0) { rMax = gc_nMaxRow0; } var isMultiple = false; var firstCell = t.model.getRange3(arn.r1, arn.c1, arn.r1, arn.c1); var isMergedFirstCell = firstCell.hasMerged(); var isOneMerge = false; var startCell = val.getCell3(activeCellsPasteFragment.r1, activeCellsPasteFragment.c1); var isMergedStartCell = startCell.hasMerged(); var firstValuesCol; var firstValuesRow; if (isMergedStartCell != null) { firstValuesCol = isMergedStartCell.c2 - isMergedStartCell.c1; firstValuesRow = isMergedStartCell.r2 - isMergedStartCell.r1; } else { firstValuesCol = 0; firstValuesRow = 0; } var rowDiff = arn.r1 - activeCellsPasteFragment.r1; var colDiff = arn.c1 - activeCellsPasteFragment.c1; var newPasteRange = new Asc.Range(arn.c1 - colDiff, arn.r1 - rowDiff, arn.c2 - colDiff, arn.r2 - rowDiff); //если вставляем в мерженную ячейку, диапазон которой больше или меньше, но не равен выделенной области if (isMergedFirstCell && isMergedFirstCell.isEqual(arn) && cMax - arn.c1 === (firstValuesCol + 1) && rMax - arn.r1 === (firstValuesRow + 1) && !newPasteRange.isEqual(activeCellsPasteFragment)) { isOneMerge = true; rMax = arn.r2 + 1; cMax = arn.c2 + 1; } else if (arn.c2 >= cMax - 1 && arn.r2 >= rMax - 1) { //если область кратная куску вставки var widthArea = arn.c2 - arn.c1 + 1; var heightArea = arn.r2 - arn.r1 + 1; var widthPasteFr = cMax - arn.c1; var heightPasteFr = rMax - arn.r1; //если кратны, то обрабатываем if (widthArea % widthPasteFr === 0 && heightArea % heightPasteFr === 0) { isMultiple = true; } else if (firstCell.hasMerged() !== null)//в противном случае ошибка { if (isCheckSelection) { return arn; } else { this.handlers.trigger("onError", c_oAscError.ID.PastInMergeAreaError, c_oAscError.Level.NoCritical); return; } } } else { //проверка на наличие части объединённой ячейки в области куда осуществляем вставку for (var rFirst = arn.r1; rFirst < rMax; ++rFirst) { for (var cFirst = arn.c1; cFirst < cMax; ++cFirst) { var range = t.model.getRange3(rFirst, cFirst, rFirst, cFirst); var merged = range.hasMerged(); if (merged) { if (merged.r1 < arn.r1 || merged.r2 > rMax - 1 || merged.c1 < arn.c1 || merged.c2 > cMax - 1) { //ошибка в случае если вставка происходит в часть объедененной ячейки if (isCheckSelection) { return arn; } else { this.handlers.trigger("onErrorEvent", c_oAscError.ID.PastInMergeAreaError, c_oAscError.Level.NoCritical); return; } } } } } } var rangeUnMerge = t.model.getRange3(arn.r1, arn.c1, rMax - 1, cMax - 1); var rMax2 = rMax; var cMax2 = cMax; //var rMax = values.length; if (isCheckSelection) { var newArr = arn.clone(true); newArr.r2 = rMax2 - 1; newArr.c2 = cMax2 - 1; if (isMultiple || isOneMerge) { newArr.r2 = arn.r2; newArr.c2 = arn.c2; } return newArr; } //если не возникает конфликт, делаем unmerge if(specialPasteProps.format) { rangeUnMerge.unmerge(); this.cellCommentator.deleteCommentsRange(rangeUnMerge.bbox); } if (!isOneMerge) { arn.r2 = rMax2 - 1; arn.c2 = cMax2 - 1; } if (isMultiple)//случай автозаполнения сложных форм { if(specialPasteProps.format) { t.model.getRange3(trueActiveRange.r1, trueActiveRange.c1, trueActiveRange.r2, trueActiveRange.c2).unmerge(); } var maxARow = heightArea / heightPasteFr; var maxACol = widthArea / widthPasteFr; var plRow = (rMax2 - arn.r1); var plCol = (arn.c2 - arn.c1) + 1; } else { var maxARow = 1; var maxACol = 1; var plRow = 0; var plCol = 0; trueActiveRange.r2 = arn.r2; trueActiveRange.c2 = arn.c2; } //необходимо проверить, пересекаемся ли мы с фоматированной таблицей //если да, то подхватывать dxf при вставке не нужно var intersectionAllRangeWithTables = t.model.autoFilters._intersectionRangeWithTableParts(trueActiveRange); var addComments = function(pasteRow, pasteCol, comments) { var comment; for (var i = 0; i < comments.length; i++) { comment = comments[i]; if (comment.nCol == pasteCol && comment.nRow == pasteRow) { var commentData = comment.clone(); //change nRow, nCol commentData.asc_putCol(nCol); commentData.asc_putRow(nRow); t.cellCommentator.addComment(commentData, true); } } }; var mergeArr = []; var checkMerge = function(range, curMerge, nRow, nCol, rowDiff, colDiff, pastedRangeProps) { var isMerged = false; for (var mergeCheck = 0; mergeCheck < mergeArr.length; ++mergeCheck) { if (mergeArr[mergeCheck].contains(nCol, nRow)) { isMerged = true; } } if (!isOneMerge) { if (curMerge != null && !isMerged) { var offsetCol = curMerge.c2 - curMerge.c1; if (offsetCol + nCol >= gc_nMaxCol0) { offsetCol = gc_nMaxCol0 - nCol; } var offsetRow = curMerge.r2 - curMerge.r1; if (offsetRow + nRow >= gc_nMaxRow0) { offsetRow = gc_nMaxRow0 - nRow; } pastedRangeProps.offsetLast = {offsetCol: offsetCol, offsetRow: offsetRow}; if(specialPasteProps.transpose) { mergeArr.push(new Asc.Range( curMerge.c1 + arn.c1 - activeCellsPasteFragment.r1 + colDiff, curMerge.r1 + arn.r1 - activeCellsPasteFragment.c1 + rowDiff, curMerge.c2 + arn.c1 - activeCellsPasteFragment.r1 + colDiff, curMerge.r2 + arn.r1 - activeCellsPasteFragment.c1 + rowDiff )); } else { mergeArr.push(new Asc.Range( curMerge.c1 + arn.c1 - activeCellsPasteFragment.c1 + colDiff, curMerge.r1 + arn.r1 - activeCellsPasteFragment.r1 + rowDiff, curMerge.c2 + arn.c1 - activeCellsPasteFragment.c1 + colDiff, curMerge.r2 + arn.r1 - activeCellsPasteFragment.r1 + rowDiff )); } } } else { if (!isMerged) { pastedRangeProps.offsetLast = {offsetCol: isMergedFirstCell.c2 - isMergedFirstCell.c1, offsetRow: isMergedFirstCell.r2 - isMergedFirstCell.r1}; mergeArr.push(new Asc.Range(isMergedFirstCell.c1, isMergedFirstCell.r1, isMergedFirstCell.c2, isMergedFirstCell.r2)); } } }; var getTableDxf = function (pasteRow, pasteCol, newVal) { var dxf = null; if(false !== intersectionAllRangeWithTables){ return {dxf: null}; } var tables = val.autoFilters._intersectionRangeWithTableParts(newVal.bbox); var blocalArea = true; if (tables && tables[0]) { var table = tables[0]; var styleInfo = table.TableStyleInfo; var styleForCurTable = styleInfo ? t.model.workbook.TableStyles.AllStyles[styleInfo.Name] : null; if (activeCellsPasteFragment.containsRange(table.Ref)) { blocalArea = false; } if (!styleForCurTable) { return null; } var headerRowCount = 1; var totalsRowCount = 0; if (null != table.HeaderRowCount) { headerRowCount = table.HeaderRowCount; } if (null != table.TotalsRowCount) { totalsRowCount = table.TotalsRowCount; } var bbox = new Asc.Range(table.Ref.c1, table.Ref.r1, table.Ref.c2, table.Ref.r2); styleForCurTable.initStyle(val.sheetMergedStyles, bbox, styleInfo, headerRowCount, totalsRowCount); val._getCell(pasteRow, pasteCol, function(cell) { if (cell) { dxf = cell.getCompiledStyle(); } if (null === dxf) { pasteRow = pasteRow - table.Ref.r1; pasteCol = pasteCol - table.Ref.c1; dxf = val.getCompiledStyle(pasteRow, pasteCol); } }); } return {dxf: dxf, blocalArea: blocalArea}; }; var colsWidth = {}; var putInsertedCellIntoRange = function(nRow, nCol, pasteRow, pasteCol, rowDiff, colDiff, range, newVal, curMerge, transposeRange) { var pastedRangeProps = {}; //range может далее изменится в связи с наличием мерженных ячеек, firstRange - не меняется(ему делаем setValue, как первой ячейке в диапазоне мерженных) var firstRange = range.clone(); //****paste comments**** if (specialPasteProps.comment && val.aComments && val.aComments.length) { addComments(pasteRow, pasteCol, val.aComments); } //merge checkMerge(range, curMerge, nRow, nCol, rowDiff, colDiff, pastedRangeProps); //set style if (!isOneMerge) { pastedRangeProps.cellStyle = newVal.getStyleName(); } if (!isOneMerge)//settings for cell(format) { //format var numFormat = newVal.getNumFormat(); var nameFormat; if (numFormat && numFormat.sFormat) { nameFormat = numFormat.sFormat; } pastedRangeProps.numFormat = nameFormat; } if (!isOneMerge)//settings for cell { var align = newVal.getAlign(); //vertical align pastedRangeProps.alignVertical = align.getAlignVertical(); //horizontal align pastedRangeProps.alignHorizontal = align.getAlignHorizontal(); //borders var fullBorders; if(specialPasteProps.transpose) { //TODO сделано для правильного отображения бордеров при транспонирования. возможно стоит использовать эту функцию во всех ситуациях. проверить! fullBorders = newVal.getBorder(newVal.bbox.r1, newVal.bbox.c1).clone(); } else { fullBorders = newVal.getBorderFull(); } if (pastedRangeProps.offsetLast && pastedRangeProps.offsetLast.offsetCol > 0 && curMerge && fullBorders) { //для мерженных ячеек, правая границу var endMergeCell = val.getCell3(pasteRow, curMerge.c2); var fullBordersEndMergeCell = endMergeCell.getBorderFull(); if (fullBordersEndMergeCell && fullBordersEndMergeCell.r) { fullBorders.r = fullBordersEndMergeCell.r; } } pastedRangeProps.bordersFull = fullBorders; //fill pastedRangeProps.fill = newVal.getFill(); //wrap //range.setWrap(newVal.getWrap()); pastedRangeProps.wrap = align.getWrap(); //angle pastedRangeProps.angle = align.getAngle(); //hyperlink pastedRangeProps.hyperlinkObj = newVal.getHyperlink(); } var tableDxf = getTableDxf(pasteRow, pasteCol, newVal); if(tableDxf && tableDxf.blocalArea) { pastedRangeProps.tableDxfLocal = tableDxf.dxf; } else if(tableDxf) { pastedRangeProps.tableDxf = tableDxf.dxf; } if(undefined === colsWidth[nCol]) { colsWidth[nCol] = val._getCol(pasteCol); } pastedRangeProps.colsWidth = colsWidth; //apply props by cell var formulaProps = {firstRange: firstRange, arrFormula: arrFormula, tablesMap: tablesMap, newVal: newVal, isOneMerge: isOneMerge, val: val, activeCellsPasteFragment: activeCellsPasteFragment, transposeRange: transposeRange}; t._setPastedDataByCurrentRange(range, pastedRangeProps, formulaProps, specialPasteProps); }; for (var autoR = 0; autoR < maxARow; ++autoR) { for (var autoC = 0; autoC < maxACol; ++autoC) { for (var r = 0; r < rMax - arn.r1; ++r) { for (var c = 0; c < cMax - arn.c1; ++c) { var pasteRow = r + activeCellsPasteFragment.r1; var pasteCol = c + activeCellsPasteFragment.c1; if(specialPasteProps.transpose) { pasteRow = c + activeCellsPasteFragment.r1; pasteCol = r + activeCellsPasteFragment.c1; } var newVal = val.getCell3(pasteRow, pasteCol); if (undefined !== newVal) { var nRow = r + autoR * plRow + arn.r1; var nCol = c + autoC * plCol + arn.c1; if (nRow > gc_nMaxRow0) { nRow = gc_nMaxRow0; } if (nCol > gc_nMaxCol0) { nCol = gc_nMaxCol0; } var curMerge = newVal.hasMerged(); if(curMerge && specialPasteProps.transpose) { curMerge = curMerge.clone(); var r1 = curMerge.r1; var r2 = curMerge.r2; var c1 = curMerge.c1; var c2 = curMerge.c2; curMerge.r1 = c1; curMerge.r2 = c2; curMerge.c1 = r1; curMerge.c2 = r2; } var range = t.model.getRange3(nRow, nCol, nRow, nCol); var transposeRange = null; if(specialPasteProps.transpose) { transposeRange = t.model.getRange3(c + autoR * plRow + arn.r1, r + autoC * plCol + arn.c1, c + autoR * plRow + arn.r1, r + autoC * plCol + arn.c1); } putInsertedCellIntoRange(nRow, nCol, pasteRow, pasteCol, autoR * plRow, autoC * plCol, range, newVal, curMerge, transposeRange); //если замержили range c = range.bbox.c2 - autoC * plCol - arn.c1; if (c === cMax) { r = range.bbox.r2 - autoC * plCol - arn.r1; } } } } } } t.isChanged = true; var arnFor = [trueActiveRange, arrFormula]; //TODO переделать на setSelection. закомментировал в связи с падением, когда вставляем ниже видимой зоны таблицы //this.setSelection(trueActiveRange); lastSelection.c2 = trueActiveRange.c2; lastSelection.r2 = trueActiveRange.r2; return arnFor; }; WorksheetView.prototype._setPastedDataByCurrentRange = function(range, rangeStyle, formulaProps, specialPasteProps) { var t = this; var firstRange, arrFormula, tablesMap, newVal, isOneMerge, val, activeCellsPasteFragment, transposeRange; if(formulaProps) { //TODO firstRange возможно стоит убрать(добавлено было для правки бага 27745) firstRange = formulaProps.firstRange; arrFormula = formulaProps.arrFormula; tablesMap = formulaProps.tablesMap; newVal = formulaProps.newVal; isOneMerge = formulaProps.isOneMerge; val = formulaProps.val; activeCellsPasteFragment = formulaProps.activeCellsPasteFragment; transposeRange = formulaProps.transposeRange; } var transposeOutStack = function(outStack) { for(var i = 0; i < outStack.length; i++) { if(outStack[i].bbox || "object" === typeof outStack[i].range) { var range = outStack[i].bbox ? outStack[i].bbox : outStack[i].range; var diffCol1 = range.c1 - activeCellsPasteFragment.c1; var diffRow1 = range.r1 - activeCellsPasteFragment.r1; var diffCol2 = range.c2 - activeCellsPasteFragment.c1; var diffRow2 = range.r2 - activeCellsPasteFragment.r1; range.c1 = activeCellsPasteFragment.c1 + diffRow1; range.r1 = activeCellsPasteFragment.r1 + diffCol1; range.c2 = activeCellsPasteFragment.c1 + diffRow2; range.r2 = activeCellsPasteFragment.r1 + diffCol2; } } }; //set formula - for paste from binary var calculateValueAndBinaryFormula = function(newVal, firstRange, range) { var skipFormat = null; var noSkipVal = null; var cellValueData = newVal.getValueData(); if(cellValueData && cellValueData.value) { if(!specialPasteProps.formula) { cellValueData.formula = null; } rangeStyle.cellValueData = cellValueData; } else if(cellValueData && cellValueData.formula && !specialPasteProps.formula) { cellValueData.formula = null; rangeStyle.cellValueData = cellValueData; } else { rangeStyle.val = newVal.getValue(); } var value2 = newVal.getValue2(); var isFromula = false; for (var nF = 0; nF < value2.length; nF++) { if (value2[nF] && value2[nF].sId) { isFromula = true; break; } else if (value2[nF] && value2[nF].format && value2[nF].format.getSkip()) { skipFormat = true; } else if (value2[nF] && value2[nF].format && !value2[nF].format.getSkip()) { noSkipVal = nF; } } //TODO вместо range где возможно использовать cell if (value2.length === 1 || isFromula !== false || (skipFormat != null && noSkipVal != null)) { var numStyle = 0; if (skipFormat != null && noSkipVal != null) { numStyle = noSkipVal; } //formula if (newVal.getFormula() && !isOneMerge) { var offset, callAdress; if(specialPasteProps.transpose && transposeRange) { //для transpose необходимо брать offset перевернутого range callAdress = new AscCommon.CellAddress(value2[0].sId); offset = new AscCommonExcel.CRangeOffset((transposeRange.bbox.c1 - callAdress.col + 1), (transposeRange.bbox.r1 - callAdress.row + 1)); } else { callAdress = new AscCommon.CellAddress(value2[0].sId); offset = new AscCommonExcel.CRangeOffset((range.bbox.c1 - callAdress.col + 1), (range.bbox.r1 - callAdress.row + 1)); } var assemb, _p_ = new AscCommonExcel.parserFormula(value2[0].sFormula, null, t.model); if (_p_.parse()) { if(specialPasteProps.transpose) { //для transpose необходимо перевернуть все дипазоны в формулах transposeOutStack(_p_.outStack); } if(null !== tablesMap) { var renameParams = {}; renameParams.offset = offset; renameParams.tableNameMap = tablesMap; _p_.renameSheetCopy(renameParams); assemb = _p_.assemble(true) } else { assemb = _p_.changeOffset(offset).assemble(true); } rangeStyle.formula = {range: range, val: "=" + assemb}; //arrFormula.push({range: range, val: "=" + assemb}); } } else { newVal.getLeftTopCellNoEmpty(function(cellFrom) { if (cellFrom) { var range; if (isOneMerge && range && range.bbox) { range = t._getCell(range.bbox.c1, range.bbox.r1); } else { range = firstRange; } rangeStyle.cellValueData2 = {valueData: cellFrom.getValueData(), row: range.bbox.r1, col: range.bbox.c1}; } }); } if (!isOneMerge)//settings for text { rangeStyle.font = value2[numStyle].format; //range.setFont(value2[numStyle].format); } } else { rangeStyle.value2 = value2; //firstRange.setValue2(value2); } }; //column width var col = range.bbox.c1; if(specialPasteProps.width && rangeStyle.colsWidth[col]) { var widthProp = rangeStyle.colsWidth[col]; t.model.setColWidth(widthProp.width, col, col); t.model.setColHidden(widthProp.hd, col, col); t.model.setColBestFit(widthProp.BestFit, widthProp.width, col, col); rangeStyle.colsWidth[col] = null; } //offsetLast if(rangeStyle.offsetLast && specialPasteProps.merge) { range.setOffsetLast(rangeStyle.offsetLast); range.merge(rangeStyle.merge); } //for formula if(formulaProps) { calculateValueAndBinaryFormula(newVal, firstRange, range); } //cellStyle if(rangeStyle.cellStyle && specialPasteProps.cellStyle) { //сделал для того, чтобы не перетерались старые бордеры бордерами стиля в случае, если специальная вставка без бордеров var oldBorders = null; if(!specialPasteProps.borders) { oldBorders = range.getBorderFull(); if(oldBorders) { oldBorders = oldBorders.clone(); } } range.setCellStyle(rangeStyle.cellStyle); if(oldBorders) { range.setBorder(null); range.setBorder(oldBorders); } } //если не вставляем форматированную таблицу, но формат необходимо вставить if(specialPasteProps.format && !specialPasteProps.formatTable && rangeStyle.tableDxf) { range.getLeftTopCell(function(firstCell){ if(firstCell) { firstCell.setStyle(rangeStyle.tableDxf); } }); } //numFormat if(rangeStyle.numFormat && specialPasteProps.numFormat) { range.setNumFormat(rangeStyle.numFormat); } //font if(rangeStyle.font && specialPasteProps.font) { var font = rangeStyle.font; //если вставляем форматированную таблицу с параметров values + all formating if(specialPasteProps.format && !specialPasteProps.formatTable && rangeStyle.tableDxf && rangeStyle.tableDxf.font) { font = rangeStyle.tableDxf.font.merge(rangeStyle.font); } range.setFont(font); } //***value*** if(rangeStyle.formula && specialPasteProps.formula) { arrFormula.push(rangeStyle.formula); } else if(rangeStyle.cellValueData2 && specialPasteProps.font && specialPasteProps.val) { t.model._getCell(rangeStyle.cellValueData2.row, rangeStyle.cellValueData2.col, function(cell){ cell.setValueData(rangeStyle.cellValueData2.valueData); }); } else if(rangeStyle.value2 && specialPasteProps.font && specialPasteProps.val) { if(formulaProps) { firstRange.setValue2(rangeStyle.value2); } else { range.setValue2(rangeStyle.value2); } } else if(rangeStyle.cellValueData && specialPasteProps.val) { range.setValueData(rangeStyle.cellValueData); } else if(rangeStyle.val && specialPasteProps.val) { range.setValue(rangeStyle.val); } //alignVertical if(undefined !== rangeStyle.alignVertical && specialPasteProps.alignVertical) { range.setAlignVertical(rangeStyle.alignVertical); } //alignHorizontal if(undefined !== rangeStyle.alignHorizontal && specialPasteProps.alignHorizontal) { range.setAlignHorizontal(rangeStyle.alignHorizontal); } //fontSize if(rangeStyle.fontSize && specialPasteProps.fontSize) { range.setFontsize(rangeStyle.fontSize); } //borders if(rangeStyle.borders && specialPasteProps.borders) { range.setBorderSrc(rangeStyle.borders); } //bordersFull if(rangeStyle.bordersFull && specialPasteProps.borders) { range.setBorder(rangeStyle.bordersFull); } //wrap if(rangeStyle.wrap && specialPasteProps.wrap) { range.setWrap(rangeStyle.wrap); } //fill if(specialPasteProps.fill && undefined !== rangeStyle.fill) { range.setFill(rangeStyle.fill); } //angle if(undefined !== rangeStyle.angle && specialPasteProps.angle) { range.setAngle(rangeStyle.angle); } if(rangeStyle.tableDxfLocal && specialPasteProps.format) { range.getLeftTopCell(function(firstCell) { if (firstCell) { firstCell.setStyle(rangeStyle.tableDxfLocal); } }); } //hyperLink if (rangeStyle.hyperLink && specialPasteProps.hyperlink) { var _link = rangeStyle.hyperLink.hyperLink; var newHyperlink = new AscCommonExcel.Hyperlink(); if (_link.search('#') === 0) { newHyperlink.setLocation(_link.replace('#', '')); } else { newHyperlink.Hyperlink = _link; } newHyperlink.Ref = range; newHyperlink.Tooltip = rangeStyle.hyperLink.toolTip; range.setHyperlink(newHyperlink); } else if (rangeStyle.hyperlinkObj && specialPasteProps.hyperlink) { rangeStyle.hyperlinkObj.Ref = range; range.setHyperlink(rangeStyle.hyperlinkObj, true); } }; WorksheetView.prototype.showSpecialPasteOptions = function(options/*, range, positionShapeContent*/) { var _clipboard = AscCommonExcel.g_clipboardExcel; var specialPasteShowOptions = window['AscCommon'].g_specialPasteHelper.buttonInfo; var positionShapeContent = options.position; var range = options.range; var props = options.options; var cellCoord; if(!positionShapeContent) { window['AscCommon'].g_specialPasteHelper.CleanButtonInfo(); window['AscCommon'].g_specialPasteHelper.buttonInfo.setRange(range); var isVisible = null !== this.getCellVisibleRange(range.c2, range.r2); cellCoord = this.getSpecialPasteCoords(range, isVisible); } else { //var isVisible = null !== this.getCellVisibleRange(range.c2, range.r2); cellCoord = [new AscCommon.asc_CRect( positionShapeContent.x, positionShapeContent.y, 0, 0 )]; } specialPasteShowOptions.asc_setOptions(props); specialPasteShowOptions.asc_setCellCoord(cellCoord); this.handlers.trigger("showSpecialPasteOptions", specialPasteShowOptions); }; WorksheetView.prototype.updateSpecialPasteButton = function() { var specialPasteShowOptions, range; var isIntoShape = this.objectRender.controller.getTargetDocContent(); if(window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton && isIntoShape) { if(window['AscCommon'].g_specialPasteHelper.buttonInfo.shapeId === isIntoShape.Id) { specialPasteShowOptions = window['AscCommon'].g_specialPasteHelper.buttonInfo; range = specialPasteShowOptions.range; specialPasteShowOptions.asc_setOptions(null); var curShape = isIntoShape.Parent.parent; var asc_getcvt = Asc.getCvtRatio; var mmToPx = asc_getcvt(3/*px*/, 0/*pt*/, this._getPPIX()); var ptToPx = asc_getcvt(1/*px*/, 0/*pt*/, this._getPPIX()); var cellsLeft = this.cellsLeft * ptToPx; var cellsTop = this.cellsTop * ptToPx; var cursorPos = range; var offsetX = this.cols[this.visibleRange.c1].left * ptToPx - cellsLeft; var offsetY = this.rows[this.visibleRange.r1].top * ptToPx - cellsTop; var posX = curShape.transformText.TransformPointX(cursorPos.X, cursorPos.Y) * mmToPx - offsetX + cellsLeft; var posY = curShape.transformText.TransformPointY(cursorPos.X, cursorPos.Y) * mmToPx - offsetY + cellsTop; cellCoord = [new AscCommon.asc_CRect( posX, posY, 0, 0 )]; specialPasteShowOptions.asc_setCellCoord(cellCoord); this.handlers.trigger("showSpecialPasteOptions", specialPasteShowOptions); } } else if(window['AscCommon'].g_specialPasteHelper.showSpecialPasteButton) { specialPasteShowOptions = window['AscCommon'].g_specialPasteHelper.buttonInfo; specialPasteShowOptions.asc_setOptions(null); range = specialPasteShowOptions.range; var isVisible = null !== this.getCellVisibleRange(range.c2, range.r2); var cellCoord = this.getSpecialPasteCoords(range, isVisible); specialPasteShowOptions.asc_setCellCoord(cellCoord); this.handlers.trigger("showSpecialPasteOptions", specialPasteShowOptions); } }; WorksheetView.prototype.getSpecialPasteCoords = function(range, isVisible) { var disableCoords = function() { cellCoord._x = -1; cellCoord._y = -1; }; //TODO пересмотреть когда иконка вылезает за пределы области видимости var cellCoord = this.getCellCoord(range.c2, range.r2); if(window['AscCommon'].g_specialPasteHelper.buttonInfo.shapeId) { disableCoords(); cellCoord = [cellCoord]; } else { var visibleRange = this.getVisibleRange(); var intersectionVisibleRange = visibleRange.intersection(range); if(intersectionVisibleRange) { cellCoord = []; cellCoord[0] = this.getCellCoord(intersectionVisibleRange.c2, intersectionVisibleRange.r2); cellCoord[1] = this.getCellCoord(range.c1, range.r1); } else { disableCoords(); cellCoord = [cellCoord]; } } return cellCoord; }; // Залочена ли панель для закрепления WorksheetView.prototype._isLockedFrozenPane = function ( callback ) { var sheetId = this.model.getId(); var lockInfo = this.collaborativeEditing.getLockInfo( c_oAscLockTypeElem.Object, null, sheetId, AscCommonExcel.c_oAscLockNameFrozenPane ); if ( false === this.collaborativeEditing.getCollaborativeEditing() ) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование asc_applyFunction( callback, true ); callback = undefined; } if ( false !== this.collaborativeEditing.getLockIntersection( lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/false ) ) { // Редактируем сами asc_applyFunction( callback, true ); return; } else if ( false !== this.collaborativeEditing.getLockIntersection( lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false ) ) { // Уже ячейку кто-то редактирует asc_applyFunction( callback, false ); return; } this.collaborativeEditing.onStartCheckLock(); this.collaborativeEditing.addCheckLock( lockInfo ); this.collaborativeEditing.onEndCheckLock( callback ); }; WorksheetView.prototype._isLockedDefNames = function ( callback, defNameId ) { var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Object, null /*c_oAscLockTypeElemSubType.DefinedNames*/, -1, defNameId); if ( false === this.collaborativeEditing.getCollaborativeEditing() ) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование asc_applyFunction( callback, true ); callback = undefined; } if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/ false)) { // Редактируем сами asc_applyFunction( callback, true ); return; } else if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже ячейку кто-то редактирует asc_applyFunction( callback, false ); return; } this.collaborativeEditing.onStartCheckLock(); this.collaborativeEditing.addCheckLock( lockInfo ); this.collaborativeEditing.onEndCheckLock( callback ); }; // Залочен ли весь лист WorksheetView.prototype._isLockedAll = function (callback) { var sheetId = this.model.getId(); var subType = c_oAscLockTypeElemSubType.ChangeProperties; var ar = this.model.selectionRange.getLast(); var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/subType, sheetId, new AscCommonExcel.asc_CCollaborativeRange(ar.c1, ar.r1, ar.c2, ar.r2)); if (false === this.collaborativeEditing.getCollaborativeEditing()) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование asc_applyFunction(callback, true); callback = undefined; } if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeMine, /*bCheckOnlyLockAll*/ true)) { // Редактируем сами asc_applyFunction(callback, true); return; } else if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/ true)) { // Уже ячейку кто-то редактирует asc_applyFunction(callback, false); return; } this.collaborativeEditing.onStartCheckLock(); this.collaborativeEditing.addCheckLock(lockInfo); this.collaborativeEditing.onEndCheckLock(callback); }; // Пересчет для входящих ячеек в добавленные строки/столбцы WorksheetView.prototype._recalcRangeByInsertRowsAndColumns = function (sheetId, ar) { var isIntersection = false, isIntersectionC1 = true, isIntersectionC2 = true, isIntersectionR1 = true, isIntersectionR2 = true; do { if (isIntersectionC1 && this.collaborativeEditing.isIntersectionInCols(sheetId, ar.c1)) { ar.c1 += 1; } else { isIntersectionC1 = false; } if (isIntersectionR1 && this.collaborativeEditing.isIntersectionInRows(sheetId, ar.r1)) { ar.r1 += 1; } else { isIntersectionR1 = false; } if (isIntersectionC2 && this.collaborativeEditing.isIntersectionInCols(sheetId, ar.c2)) { ar.c2 -= 1; } else { isIntersectionC2 = false; } if (isIntersectionR2 && this.collaborativeEditing.isIntersectionInRows(sheetId, ar.r2)) { ar.r2 -= 1; } else { isIntersectionR2 = false; } if (ar.c1 > ar.c2 || ar.r1 > ar.r2) { isIntersection = true; break; } } while (isIntersectionC1 || isIntersectionC2 || isIntersectionR1 || isIntersectionR2) ; if (false === isIntersection) { ar.c1 = this.collaborativeEditing.getLockMeColumn(sheetId, ar.c1); ar.c2 = this.collaborativeEditing.getLockMeColumn(sheetId, ar.c2); ar.r1 = this.collaborativeEditing.getLockMeRow(sheetId, ar.r1); ar.r2 = this.collaborativeEditing.getLockMeRow(sheetId, ar.r2); } return isIntersection; }; // Функция проверки lock (возвращаемый результат нельзя использовать в качестве ответа, он нужен только для редактирования ячейки) WorksheetView.prototype._isLockedCells = function (range, subType, callback) { var sheetId = this.model.getId(); var isIntersection = false; var newCallback = callback; var t = this; this.collaborativeEditing.onStartCheckLock(); var isArrayRange = Array.isArray(range); var nLength = isArrayRange ? range.length : 1; var nIndex = 0; var ar = null; for (; nIndex < nLength; ++nIndex) { ar = isArrayRange ? range[nIndex].clone(true) : range.clone(true); if (c_oAscLockTypeElemSubType.InsertColumns !== subType && c_oAscLockTypeElemSubType.InsertRows !== subType) { // Пересчет для входящих ячеек в добавленные строки/столбцы isIntersection = this._recalcRangeByInsertRowsAndColumns(sheetId, ar); } if (false === isIntersection) { var lockInfo = this.collaborativeEditing.getLockInfo(c_oAscLockTypeElem.Range, /*subType*/subType, sheetId, new AscCommonExcel.asc_CCollaborativeRange(ar.c1, ar.r1, ar.c2, ar.r2)); if (false !== this.collaborativeEditing.getLockIntersection(lockInfo, c_oAscLockTypes.kLockTypeOther, /*bCheckOnlyLockAll*/false)) { // Уже ячейку кто-то редактирует asc_applyFunction(callback, false); return false; } else { if (c_oAscLockTypeElemSubType.InsertColumns === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.addColsRange(sheetId, range.clone(true)); t.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1); } callback(isSuccess); }; } else if (c_oAscLockTypeElemSubType.InsertRows === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1); } callback(isSuccess); }; } else if (c_oAscLockTypeElemSubType.DeleteColumns === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1); } callback(isSuccess); }; } else if (c_oAscLockTypeElemSubType.DeleteRows === subType) { newCallback = function (isSuccess) { if (isSuccess) { t.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1); } callback(isSuccess); }; } this.collaborativeEditing.addCheckLock(lockInfo); } } else { if (c_oAscLockTypeElemSubType.InsertColumns === subType) { t.collaborativeEditing.addColsRange(sheetId, range.clone(true)); t.collaborativeEditing.addCols(sheetId, range.c1, range.c2 - range.c1 + 1); } else if (c_oAscLockTypeElemSubType.InsertRows === subType) { t.collaborativeEditing.addRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.addRows(sheetId, range.r1, range.r2 - range.r1 + 1); } else if (c_oAscLockTypeElemSubType.DeleteColumns === subType) { t.collaborativeEditing.removeColsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeCols(sheetId, range.c1, range.c2 - range.c1 + 1); } else if (c_oAscLockTypeElemSubType.DeleteRows === subType) { t.collaborativeEditing.removeRowsRange(sheetId, range.clone(true)); t.collaborativeEditing.removeRows(sheetId, range.r1, range.r2 - range.r1 + 1); } } } if (false === this.collaborativeEditing.getCollaborativeEditing()) { // Пользователь редактирует один: не ждем ответа, а сразу продолжаем редактирование newCallback(true); newCallback = undefined; } this.collaborativeEditing.onEndCheckLock(newCallback); return true; }; WorksheetView.prototype.changeWorksheet = function (prop, val) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } var t = this; var arn = this.model.selectionRange.getLast().clone(); var checkRange = arn.getAllRange(); var range, count; var oRecalcType = AscCommonExcel.recalcType.recalc; var reinitRanges = false; var updateDrawingObjectsInfo = null; var updateDrawingObjectsInfo2 = null;//{bInsert: false, operType: c_oAscInsertOptions.InsertColumns, updateRange: arn} var isUpdateCols = false, isUpdateRows = false; var isCheckChangeAutoFilter; var functionModelAction = null; var lockDraw = false; // Параметр, при котором не будет отрисовки (т.к. мы просто обновляем информацию на неактивном листе) var lockRange, arrChangedRanges = []; var onChangeWorksheetCallback = function (isSuccess) { if (false === isSuccess) { return; } asc_applyFunction(functionModelAction); t._initCellsArea(oRecalcType); if (oRecalcType) { t.cache.reset(); } t._cleanCellsTextMetricsCache(); t._prepareCellTextMetricsCache(); arrChangedRanges = arrChangedRanges.concat(t.model.hiddenManager.getRecalcHidden()); t.cellCommentator.updateAreaComments(); if (t.objectRender) { if (reinitRanges && t.objectRender.drawingArea) { t.objectRender.drawingArea.reinitRanges(); } if (null !== updateDrawingObjectsInfo) { t.objectRender.updateSizeDrawingObjects(updateDrawingObjectsInfo); } if (null !== updateDrawingObjectsInfo2) { t.objectRender.updateDrawingObject(updateDrawingObjectsInfo2.bInsert, updateDrawingObjectsInfo2.operType, updateDrawingObjectsInfo2.updateRange); } t.model.onUpdateRanges(arrChangedRanges); t.objectRender.rebuildChartGraphicObjects(arrChangedRanges); } t.draw(lockDraw); t.handlers.trigger("reinitializeScroll"); if (isUpdateCols) { t._updateVisibleColsCount(); } if (isUpdateRows) { t._updateVisibleRowsCount(); } t.handlers.trigger("selectionChanged"); t.handlers.trigger("selectionMathInfoChanged", t.getSelectionMathInfo()); }; var checkLocalChange = function(val){ if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = val; } }; var checkDeleteCellsFilteringMode = function () { if (!window['AscCommonExcel'].filteringMode) { if (val === c_oAscDeleteOptions.DeleteCellsAndShiftLeft || val === c_oAscDeleteOptions.DeleteColumns) { //запрещаем в этом режиме удалять столбцы return false; } else if (val === c_oAscDeleteOptions.DeleteCellsAndShiftTop || val === c_oAscDeleteOptions.DeleteRows) { var tempRange = arn; if (val === c_oAscDeleteOptions.DeleteRows) { tempRange = new asc_Range(0, checkRange.r1, gc_nMaxCol0, checkRange.r2); } //запрещаем удалять последнюю строку фильтра и его заголовок + запрещаем удалять ф/т var autoFilter = t.model.AutoFilter; if (autoFilter && autoFilter.Ref) { var ref = autoFilter.Ref; //нельзя удалять целиком а/ф if (tempRange.containsRange(ref)) { return false; } else if (tempRange.containsRange(new asc_Range(ref.c1, ref.r1, ref.c2, ref.r1))) { //нельзя удалять первую строку а/ф return false; } /*else if (ref.r2 === ref.r1 + 1) { //нельзя удалять последнюю строку тела а/ф if (tempRange.containsRange(new asc_Range(ref.c1, ref.r1 + 1, ref.c2, ref.r1 + 1))) { return false; } }*/ } //нельзя целиком удалять ф/т var tableParts = t.model.TableParts; for (var i = 0; i < tableParts.length; i++) { if (tempRange.containsRange(tableParts[i].Ref)) { return false; } } } } return true; }; switch (prop) { case "colWidth": functionModelAction = function () { t.model.setColWidth(val, checkRange.c1, checkRange.c2); isUpdateCols = true; oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.ColumnResize, col: checkRange.c1}; }; this._isLockedAll(onChangeWorksheetCallback); break; case "showCols": functionModelAction = function () { checkLocalChange(true); t.model.setColHidden(false, arn.c1, arn.c2); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.ColumnResize, col: arn.c1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "hideCols": functionModelAction = function () { checkLocalChange(true); t.model.setColHidden(true, arn.c1, arn.c2); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.ColumnResize, col: arn.c1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "rowHeight": functionModelAction = function () { // Приводим к px (чтобы было ровно) val = val / 0.75; val = (val | val) * 0.75; // 0.75 - это размер 1px в pt (можно было 96/72) t.model.setRowHeight(Math.min(val, t.maxRowHeight), checkRange.r1, checkRange.r2, true); isUpdateRows = true; oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.RowResize, row: checkRange.r1}; }; return this._isLockedAll(onChangeWorksheetCallback); case "showRows": functionModelAction = function () { checkLocalChange(true); t.model.setRowHidden(false, arn.r1, arn.r2); t.model.autoFilters.reDrawFilter(arn); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.RowResize, row: arn.r1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "hideRows": functionModelAction = function () { checkLocalChange(true); t.model.setRowHidden(true, arn.r1, arn.r2); t.model.autoFilters.reDrawFilter(arn); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; updateDrawingObjectsInfo = {target: c_oTargetType.RowResize, row: arn.r1}; checkLocalChange(false); }; this._isLockedAll(onChangeWorksheetCallback); break; case "insCell": if (!window['AscCommonExcel'].filteringMode) { if(val === c_oAscInsertOptions.InsertCellsAndShiftRight || val === c_oAscInsertOptions.InsertColumns){ return; } } range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); switch (val) { case c_oAscInsertOptions.InsertCellsAndShiftRight: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscInsertOptions.InsertCellsAndShiftRight, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (range.addCellsShiftRight()) { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.cellCommentator.updateCommentsDependencies(true, val, arn); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; } History.EndTransaction(); }; arrChangedRanges.push(lockRange = new asc_Range(arn.c1, arn.r1, gc_nMaxCol0, arn.r2)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscInsertOptions.InsertCellsAndShiftDown: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscInsertOptions.InsertCellsAndShiftDown, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (range.addCellsShiftBottom()) { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.cellCommentator.updateCommentsDependencies(true, val, arn); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; } History.EndTransaction(); }; arrChangedRanges.push(lockRange = new asc_Range(arn.c1, arn.r1, arn.c2, gc_nMaxRow0)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscInsertOptions.InsertColumns: isCheckChangeAutoFilter = t.model.autoFilters.isRangeIntersectionSeveralTableParts(arn); if (isCheckChangeAutoFilter === true) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); return; } lockRange = new asc_Range(arn.c1, 0, arn.c2, gc_nMaxRow0); count = arn.c2 - arn.c1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(count, 0))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.model.insertColsBefore(arn.c1, count); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; t.cellCommentator.updateCommentsDependencies(true, val, arn); History.EndTransaction(); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.InsertColumns, onChangeWorksheetCallback); break; case c_oAscInsertOptions.InsertRows: lockRange = new asc_Range(0, arn.r1, gc_nMaxCol0, arn.r2); count = arn.r2 - arn.r1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(0, count))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; t.model.insertRowsBefore(arn.r1, count); updateDrawingObjectsInfo2 = {bInsert: true, operType: val, updateRange: arn}; t.cellCommentator.updateCommentsDependencies(true, val, arn); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.InsertRows, onChangeWorksheetCallback); break; } break; case "delCell": if (!checkDeleteCellsFilteringMode()) { return; } range = t.model.getRange3(checkRange.r1, checkRange.c1, checkRange.r2, checkRange.c2); switch (val) { case c_oAscDeleteOptions.DeleteCellsAndShiftLeft: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscDeleteOptions.DeleteCellsAndShiftLeft, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (isCheckChangeAutoFilter === true) { t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteCellsAndShiftLeft); } if (range.deleteCellsShiftLeft(function () { t._cleanCache(lockRange); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); })) { updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; } History.EndTransaction(); reinitRanges = true; }; arrChangedRanges.push( lockRange = new asc_Range(checkRange.c1, checkRange.r1, gc_nMaxCol0, checkRange.r2)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscDeleteOptions.DeleteCellsAndShiftTop: isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, c_oAscDeleteOptions.DeleteCellsAndShiftTop, prop); if (isCheckChangeAutoFilter === false) { return; } functionModelAction = function () { History.Create_NewPoint(); History.StartTransaction(); if (isCheckChangeAutoFilter === true) { t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteCellsAndShiftTop); } if (range.deleteCellsShiftUp(function () { t._cleanCache(lockRange); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); })) { updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; } History.EndTransaction(); reinitRanges = true; }; arrChangedRanges.push( lockRange = new asc_Range(checkRange.c1, checkRange.r1, checkRange.c2, gc_nMaxRow0)); if (this.model.inPivotTable(lockRange)) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } this._isLockedCells(lockRange, null, onChangeWorksheetCallback); break; case c_oAscDeleteOptions.DeleteColumns: isCheckChangeAutoFilter = t.model.autoFilters.isActiveCellsCrossHalfFTable(checkRange, c_oAscDeleteOptions.DeleteColumns, prop); if (isCheckChangeAutoFilter === false) { return; } lockRange = new asc_Range(checkRange.c1, 0, checkRange.c2, gc_nMaxRow0); count = checkRange.c2 - checkRange.c1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(-count, 0))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; History.Create_NewPoint(); History.StartTransaction(); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteColumns); t.model.removeCols(checkRange.c1, checkRange.c2); updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; History.EndTransaction(); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.DeleteColumns, onChangeWorksheetCallback); break; case c_oAscDeleteOptions.DeleteRows: isCheckChangeAutoFilter = t.model.autoFilters.isActiveCellsCrossHalfFTable(checkRange, c_oAscDeleteOptions.DeleteRows, prop); if (isCheckChangeAutoFilter === false) { return; } lockRange = new asc_Range(0, checkRange.r1, gc_nMaxCol0, checkRange.r2); count = checkRange.r2 - checkRange.r1 + 1; if (this.model.checkShiftPivotTable(lockRange, new AscCommonExcel.CRangeOffset(0, -count))) { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedCellPivot, c_oAscError.Level.NoCritical); return; } functionModelAction = function () { oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; History.Create_NewPoint(); History.StartTransaction(); checkRange = t.model.autoFilters.checkDeleteAllRowsFormatTable(checkRange, true); t.cellCommentator.updateCommentsDependencies(false, val, checkRange); t.model.autoFilters.isEmptyAutoFilters(arn, c_oAscDeleteOptions.DeleteRows); t.model.removeRows(checkRange.r1, checkRange.r2); updateDrawingObjectsInfo2 = {bInsert: false, operType: val, updateRange: arn}; History.EndTransaction(); }; arrChangedRanges.push(lockRange); this._isLockedCells(lockRange, c_oAscLockTypeElemSubType.DeleteRows, onChangeWorksheetCallback); break; } this.handlers.trigger("selectionNameChanged", t.getSelectionName(/*bRangeText*/false)); break; case "sheetViewSettings": functionModelAction = function () { if (AscCH.historyitem_Worksheet_SetDisplayGridlines === val.type) { t.model.setDisplayGridlines(val.value); } else { t.model.setDisplayHeadings(val.value); } isUpdateCols = true; isUpdateRows = true; oRecalcType = AscCommonExcel.recalcType.full; reinitRanges = true; }; this._isLockedAll(onChangeWorksheetCallback); break; case "update": if (val !== undefined) { lockDraw = true === val.lockDraw; reinitRanges = !!val.reinitRanges; } onChangeWorksheetCallback(true); break; } }; WorksheetView.prototype.expandColsOnScroll = function (isNotActive, updateColsCount, newColsCount) { var maxColObjects = this.objectRender ? this.objectRender.getMaxColRow().col : -1; var maxc = Math.max(this.model.getColsCount() + 1, this.cols.length, maxColObjects); if (newColsCount) { maxc = Math.max(maxc, newColsCount); } // Сохраняем старое значение var nLastCols = this.nColsCount; if (isNotActive) { this.nColsCount = maxc + 1; } else if (updateColsCount) { this.nColsCount = maxc; if (this.cols.length < this.nColsCount) { nLastCols = this.cols.length; } } // Проверяем ограничения по столбцам if (gc_nMaxCol < this.nColsCount) { this.nColsCount = gc_nMaxCol; } this._calcWidthColumns(AscCommonExcel.recalcType.newLines); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } return nLastCols !== this.nColsCount; }; WorksheetView.prototype.expandRowsOnScroll = function (isNotActive, updateRowsCount, newRowsCount) { var maxRowObjects = this.objectRender ? this.objectRender.getMaxColRow().row : -1; var maxr = Math.max(this.model.getRowsCount() + 1, this.rows.length, maxRowObjects); if (newRowsCount) { maxr = Math.max(maxr, newRowsCount); } // Сохраняем старое значение var nLastRows = this.nRowsCount; if (isNotActive) { this.nRowsCount = maxr + 1; } else if (updateRowsCount) { this.nRowsCount = maxr; if (this.rows.length < this.nRowsCount) { nLastRows = this.rows.length; } } // Проверяем ограничения по строкам if (gc_nMaxRow < this.nRowsCount) { this.nRowsCount = gc_nMaxRow; } this._calcHeightRows(AscCommonExcel.recalcType.newLines); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } return nLastRows !== this.nRowsCount; }; WorksheetView.prototype.onChangeWidthCallback = function (col, r1, r2, onlyIfMore) { var width = null; var row, ct, c, fl, str, maxW, tm, mc, isMerged, oldWidth, oldColWidth; var lastHeight = null; var filterButton = null; if (null == r1) { r1 = 0; } if (null == r2) { r2 = this.rows.length - 1; } oldColWidth = this.cols[col].charCount; this.cols[col].isCustomWidth = false; for (row = r1; row <= r2; ++row) { // пересчет метрик текста this._addCellTextToCache(col, row, /*canChangeColWidth*/c_oAscCanChangeColWidth.all); ct = this._getCellTextCache(col, row); if (ct === undefined) { continue; } fl = ct.flags; isMerged = fl.isMerged(); if (isMerged) { mc = fl.merged; // Для замерженных ячеек (с 2-мя или более колонками) оптимизировать не нужно if (mc.c1 !== mc.c2) { continue; } } if (ct.metrics.height > this.maxRowHeight) { if (isMerged) { continue; } // Запоминаем старую ширину (в случае, если у нас по высоте не уберется) oldWidth = ct.metrics.width; lastHeight = null; // вычисление новой ширины столбца, чтобы высота текста была меньше maxRowHeight c = this._getCell(col, row); str = c.getValue2(); maxW = ct.metrics.width + this.maxDigitWidth; while (1) { tm = this._roundTextMetrics(this.stringRender.measureString(str, fl, maxW)); if (tm.height <= this.maxRowHeight) { break; } if (lastHeight === tm.height) { // Ситуация, когда у нас текст не уберется по высоте (http://bugzilla.onlyoffice.com/show_bug.cgi?id=19974) tm.width = oldWidth; break; } lastHeight = tm.height; maxW += this.maxDigitWidth; } width = Math.max(width, tm.width); } else { filterButton = this.af_getSizeButton(col, row); if (null !== filterButton && CellValueType.String === ct.cellType) { width = Math.max(width, ct.metrics.width + filterButton.width); } else { width = Math.max(width, ct.metrics.width); } } } var pad, cc, cw; if (width > 0) { pad = this.width_padding * 2 + this.width_1px; cc = Math.min(this.model.colWidthToCharCount(width + pad), Asc.c_oAscMaxColumnWidth); } else { cc = this.defaultColWidthChars; } cw = this.model.charCountToModelColWidth(cc); if (cc === oldColWidth || (onlyIfMore && cc < oldColWidth)) { return -1; } History.Create_NewPoint(); if (!onlyIfMore) { var oSelection = History.GetSelection(); if (null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(col, 0, col, gc_nMaxRow0); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } } History.StartTransaction(); // Выставляем, что это bestFit this.model.setColBestFit(true, cw, col, col); History.EndTransaction(); return oldColWidth !== cc ? cw : -1; }; WorksheetView.prototype.autoFitColumnWidth = function (col1, col2) { var t = this; return this._isLockedAll(function (isSuccess) { if (false === isSuccess) { return; } if (null === col1) { var lastSelection = t.model.selectionRange.getLast(); col1 = lastSelection.c1; col2 = lastSelection.c2; } var w, bUpdate = false; History.Create_NewPoint(); History.StartTransaction(); for (var c = col1; c <= col2; ++c) { w = t.onChangeWidthCallback(c, null, null); if (-1 !== w) { t.cols[c] = t._calcColWidth(w); t.cols[c].isCustomWidth = false; bUpdate = true; t._cleanCache(new asc_Range(c, 0, c, t.rows.length - 1)); } } if (bUpdate) { t._updateColumnPositions(); t._updateVisibleColsCount(); t._calcHeightRows(AscCommonExcel.recalcType.recalc); t._updateVisibleRowsCount(); t.objectRender.drawingArea.reinitRanges(); t.changeWorksheet("update"); } History.EndTransaction(); }); }; WorksheetView.prototype.autoFitRowHeight = function (row1, row2) { var t = this; var onChangeHeightCallback = function (isSuccess) { if (false === isSuccess) { return; } if (null === row1) { var lastSelection = t.model.selectionRange.getLast(); row1 = lastSelection.r1; row2 = lastSelection.r2; } History.Create_NewPoint(); var oSelection = History.GetSelection(); if (null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(0, row1, gc_nMaxCol0, row2); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } History.StartTransaction(); var height, col, ct, mc; for (var r = row1; r <= row2; ++r) { height = t.defaultRowHeight; for (col = 0; col < t.cols.length; ++col) { ct = t._getCellTextCache(col, r); if (ct === undefined) { continue; } if (ct.flags.isMerged()) { mc = ct.flags.merged; // Для замерженных ячеек (с 2-мя или более строками) оптимизировать не нужно if (mc.r1 !== mc.r2) { continue; } } height = Math.max(height, ct.metrics.height + t.height_1px); } t.model.setRowBestFit(true, Math.min(height, t.maxRowHeight), r, r); } t.nRowsCount = 0; t._calcHeightRows(AscCommonExcel.recalcType.recalc); t._updateVisibleRowsCount(); t._cleanCache(new asc_Range(0, row1, t.cols.length - 1, row2)); t.objectRender.drawingArea.reinitRanges(); t.changeWorksheet("update"); History.EndTransaction(); }; return this._isLockedAll(onChangeHeightCallback); }; // ----- Search ----- WorksheetView.prototype._isCellEqual = function (c, r, options) { var cell, cellText; // Не пользуемся RegExp, чтобы не возиться со спец.символами var mc = this.model.getMergedByCell(r, c); cell = mc ? this._getVisibleCell(mc.c1, mc.r1) : this._getVisibleCell(c, r); cellText = (options.lookIn === Asc.c_oAscFindLookIn.Formulas) ? cell.getValueForEdit() : cell.getValue(); if (true !== options.isMatchCase) { cellText = cellText.toLowerCase(); } if ((cellText.indexOf(options.findWhat) >= 0) && (true !== options.isWholeCell || options.findWhat.length === cellText.length)) { return (mc ? new asc_Range(mc.c1, mc.r1, mc.c1, mc.r1) : new asc_Range(c, r, c, r)); } return null; }; WorksheetView.prototype.findCellText = function (options) { var self = this; if (true !== options.isMatchCase) { options.findWhat = options.findWhat.toLowerCase(); } var selectionRange = options.selectionRange || this.model.selectionRange; var lastRange = selectionRange.getLast(); var ar = selectionRange.activeCell; var c = ar.col; var r = ar.row; var merge = this.model.getMergedByCell(r, c); options.findInSelection = options.scanOnOnlySheet && !(selectionRange.isSingleRange() && (lastRange.isOneCell() || lastRange.isEqual(merge))); var minC, minR, maxC, maxR; if (options.findInSelection) { minC = lastRange.c1; minR = lastRange.r1; maxC = lastRange.c2; maxR = lastRange.r2; } else { minC = 0; minR = 0; maxC = this.cols.length - 1; maxR = this.rows.length - 1; } var inc = options.scanForward ? +1 : -1; var isEqual; function findNextCell() { var ct = undefined; do { if (options.scanByRows) { c += inc; if (c < minC || c > maxC) { c = options.scanForward ? minC : maxC; r += inc; } } else { r += inc; if (r < minR || r > maxR) { r = options.scanForward ? minR : maxR; c += inc; } } if (c < minC || c > maxC || r < minR || r > maxR) { return undefined; } self.model._getCellNoEmpty(r, c, function(cell){ if (cell && !cell.isNullTextString()) { ct = true; } }); } while (!ct); return ct; } while (findNextCell()) { isEqual = this._isCellEqual(c, r, options); if (null !== isEqual) { return isEqual; } } // Продолжаем циклический поиск if (options.scanForward) { // Идем вперед с первой ячейки if (options.scanByRows) { c = minC - 1; r = minR; maxR = ar.row; } else { c = minC; r = minR - 1; maxC = ar.col; } } else { // Идем назад с последней c = maxC; r = maxR; if (options.scanByRows) { c = maxC + 1; r = maxR; minR = ar.row; } else { c = maxC; r = maxR + 1; minC = ar.col; } } while (findNextCell()) { isEqual = this._isCellEqual(c, r, options); if (null !== isEqual) { return isEqual; } } return null; }; WorksheetView.prototype.replaceCellText = function (options, lockDraw, callback) { if (!options.isMatchCase) { options.findWhat = options.findWhat.toLowerCase(); } // Очищаем результаты options.countFind = 0; options.countReplace = 0; var t = this; var activeCell; var aReplaceCells = []; if (options.isReplaceAll) { var selectionRange = this.model.selectionRange.clone(); activeCell = selectionRange.activeCell; var aReplaceCellsIndex = {}; options.selectionRange = selectionRange; var findResult, index; while (true) { findResult = t.findCellText(options); if (null === findResult) { break; } index = findResult.c1 + '-' + findResult.r1; if (aReplaceCellsIndex[index]) { break; } aReplaceCellsIndex[index] = true; aReplaceCells.push(findResult); activeCell.col = findResult.c1; activeCell.row = findResult.r1; } } else { activeCell = this.model.selectionRange.activeCell; // Попробуем сначала найти var isEqual = this._isCellEqual(activeCell.col, activeCell.row, options); if (isEqual) { aReplaceCells.push(isEqual); } } if (0 > aReplaceCells.length) { return callback(options); } return this._replaceCellsText(aReplaceCells, options, lockDraw, callback); }; WorksheetView.prototype._replaceCellsText = function (aReplaceCells, options, lockDraw, callback) { var t = this; if (this.model.inPivotTable(aReplaceCells)) { options.error = true; return callback(options); } var findFlags = "g"; // Заменяем все вхождения if (true !== options.isMatchCase) { findFlags += "i"; } // Не чувствителен к регистру var valueForSearching = options.findWhat .replace(/(\\)/g, "\\\\").replace(/(\^)/g, "\\^") .replace(/(\()/g, "\\(").replace(/(\))/g, "\\)") .replace(/(\+)/g, "\\+").replace(/(\[)/g, "\\[") .replace(/(\])/g, "\\]").replace(/(\{)/g, "\\{") .replace(/(\})/g, "\\}").replace(/(\$)/g, "\\$") .replace(/(\.)/g, "\\.") .replace(/(~)?\*/g, function ($0, $1) { return $1 ? $0 : '(.*)'; }) .replace(/(~)?\?/g, function ($0, $1) { return $1 ? $0 : '.'; }) .replace(/(~\*)/g, "\\*").replace(/(~\?)/g, "\\?"); valueForSearching = new RegExp(valueForSearching, findFlags); options.indexInArray = 0; options.countFind = aReplaceCells.length; options.countReplace = 0; if (options.isReplaceAll && false === this.collaborativeEditing.getCollaborativeEditing()) { this._isLockedCells(aReplaceCells, /*subType*/null, function () { t._replaceCellText(aReplaceCells, valueForSearching, options, lockDraw, callback, true); }); } else { this._replaceCellText(aReplaceCells, valueForSearching, options, lockDraw, callback, false); } }; WorksheetView.prototype._replaceCellText = function (aReplaceCells, valueForSearching, options, lockDraw, callback, oneUser) { var t = this; if (options.indexInArray >= aReplaceCells.length) { this.draw(lockDraw); return callback(options); } var onReplaceCallback = function (isSuccess) { var cell = aReplaceCells[options.indexInArray]; ++options.indexInArray; if (false !== isSuccess) { ++options.countReplace; var c = t._getVisibleCell(cell.c1, cell.r1); var cellValue = c.getValueForEdit(); cellValue = cellValue.replace(valueForSearching, options.replaceWith); var oCellEdit = new asc_Range(cell.c1, cell.r1, cell.c1, cell.r1); var v, newValue; // get first fragment and change its text v = c.getValueForEdit2().slice(0, 1); // Создаем новый массив, т.к. getValueForEdit2 возвращает ссылку newValue = []; newValue[0] = new AscCommonExcel.Fragment({text: cellValue, format: v[0].format.clone()}); if (!t._saveCellValueAfterEdit(oCellEdit, c, newValue, /*flags*/undefined, /*isNotHistory*/true, /*lockDraw*/true)) { options.error = true; t.draw(lockDraw); return callback(options); } } window.setTimeout(function () { t._replaceCellText(aReplaceCells, valueForSearching, options, lockDraw, callback, oneUser); }, 1); }; return oneUser ? onReplaceCallback(true) : this._isLockedCells(aReplaceCells[options.indexInArray], /*subType*/null, onReplaceCallback); }; WorksheetView.prototype.findCell = function (reference, isViewMode) { var mc, ranges = AscCommonExcel.getRangeByRef(reference, this.model, true); if (0 === ranges.length && !isViewMode) { /*TODO: сделать поиск по названиям автофигур, должен искать до того как вызвать поиск по именованным диапазонам*/ if (this.collaborativeEditing.getGlobalLock() || !this.handlers.trigger("getLockDefNameManagerStatus")) { this.handlers.trigger("onErrorEvent", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); this._updateSelectionNameAndInfo(); return true; } // ToDo multiselect defined names var selectionLast = this.model.selectionRange.getLast(); mc = selectionLast.isOneCell() ? this.model.getMergedByCell(selectionLast.r1, selectionLast.c1) : null; var defName = this.model.workbook.editDefinesNames(null, new Asc.asc_CDefName(reference, parserHelp.get3DRef(this.model.getName(), (mc || selectionLast).getAbsName()))); if (defName) { this._isLockedDefNames(null, defName.getNodeId()); } else { this.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.InvalidReferenceOrName, c_oAscError.Level.NoCritical); } } return ranges; }; /* Ищет дополнение для ячейки */ WorksheetView.prototype.getCellAutoCompleteValues = function (cell, maxCount) { var merged = this._getVisibleCell(cell.col, cell.row).hasMerged(); if (merged) { cell = new AscCommon.CellBase(merged.r1, merged.c1); } var arrValues = [], objValues = {}; var range = this.findCellAutoComplete(cell, 1, maxCount); this.getColValues(range, cell.col, arrValues, objValues); range = this.findCellAutoComplete(cell, -1, maxCount); this.getColValues(range, cell.col, arrValues, objValues); arrValues.sort(); return arrValues; }; /* Ищет дополнение для ячейки (снизу или сверху) */ WorksheetView.prototype.findCellAutoComplete = function (cellActive, step, maxCount) { var col = cellActive.col, row = cellActive.row; row += step; if (!maxCount) { maxCount = Number.MAX_VALUE; } var count = 0, isBreak = false, end = 0 < step ? this.model.getRowsCount() - 1 : 0, isEnd = true, colsCount = this.model.getColsCount(), range = new asc_Range(col, row, col, row); for (; row * step <= end && count < maxCount; row += step, isEnd = true, ++count) { for (col = range.c1; col <= range.c2; ++col) { this.model._getCellNoEmpty(row, col, function(cell) { if (cell && false === cell.isNullText()) { isEnd = false; isBreak = true; } }); if (isBreak) { isBreak = false; break; } } // Идем влево по колонкам for (col = range.c1 - 1; col >= 0; --col) { this.model._getCellNoEmpty(row, col, function(cell) { isBreak = (null === cell || cell.isNullText()); }); if (isBreak) { isBreak = false; break; } isEnd = false; } range.c1 = col + 1; // Идем вправо по колонкам for (col = range.c2 + 1; col < colsCount; ++col) { this.model._getCellNoEmpty(row, col, function(cell) { isBreak = (null === cell || cell.isNullText()); }); if (isBreak) { isBreak = false; break; } isEnd = false; } range.c2 = col - 1; if (isEnd) { break; } } if (0 < step) { range.r2 = row - 1; } else { range.r1 = row + 1; } return range.r1 <= range.r2 ? range : null; }; /* Формирует уникальный массив */ WorksheetView.prototype.getColValues = function (range, col, arrValues, objValues) { if (null === range) { return; } var row, value, valueLowCase; for (row = range.r1; row <= range.r2; ++row) { this.model._getCellNoEmpty(row, col, function(cell) { if (cell && CellValueType.String === cell.getType()) { value = cell.getValue(); valueLowCase = value.toLowerCase(); if (!objValues.hasOwnProperty(valueLowCase)) { arrValues.push(value); objValues[valueLowCase] = 1; } } }); } }; // ----- Cell Editor ----- WorksheetView.prototype.setCellEditMode = function ( isCellEditMode ) { this.isCellEditMode = isCellEditMode; }; WorksheetView.prototype.setFormulaEditMode = function ( isFormulaEditMode ) { this.isFormulaEditMode = isFormulaEditMode; }; WorksheetView.prototype.setSelectionDialogMode = function (selectionDialogType, selectRange) { if (selectionDialogType === this.selectionDialogType) { return; } var oldSelectionDialogType = this.selectionDialogType; this.selectionDialogType = selectionDialogType; this.isSelectionDialogMode = c_oAscSelectionDialogType.None !== this.selectionDialogType; this.cleanSelection(); if (false === this.isSelectionDialogMode) { if (null !== this.copyActiveRange) { this.model.selectionRange = this.copyActiveRange.clone(); } this.copyActiveRange = null; if (oldSelectionDialogType === c_oAscSelectionDialogType.Chart) { this.objectRender.controller.checkChartForProps(false); } } else { this.copyActiveRange = this.model.selectionRange.clone(); if (selectRange) { if (typeof selectRange === 'string') { selectRange = this.model.getRange2(selectRange); if (selectRange) { selectRange = selectRange.getBBox0(); } } if (null != selectRange) { this.model.selectionRange.assign2(selectRange); } } if (selectionDialogType === c_oAscSelectionDialogType.Chart) { this.objectRender.controller.checkChartForProps(true); } } this._drawSelection(); }; // Получаем свойство: редактируем мы сейчас или нет WorksheetView.prototype.getCellEditMode = function () { return this.isCellEditMode; }; WorksheetView.prototype._isFormula = function ( val ) { return (0 < val.length && 1 < val[0].text.length && '=' === val[0].text.charAt( 0 )); }; WorksheetView.prototype.getActiveCell = function (x, y, isCoord) { var t = this; var col, row; if (isCoord) { x *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, t._getPPIY()); col = t._findColUnderCursor(x, true); row = t._findRowUnderCursor(y, true); if (!col || !row) { return false; } col = col.col; row = row.row; } else { col = t.model.selectionRange.activeCell.col; row = t.model.selectionRange.activeCell.row; } // Проверим замерженность var mergedRange = this.model.getMergedByCell(row, col); return mergedRange ? mergedRange : new asc_Range(col, row, col, row); }; WorksheetView.prototype._saveCellValueAfterEdit = function (oCellEdit, c, val, flags, isNotHistory, lockDraw) { var t = this; var oldMode = this.isFormulaEditMode; this.isFormulaEditMode = false; if (!isNotHistory) { History.Create_NewPoint(); History.StartTransaction(); } var oAutoExpansionTable; var isFormula = this._isFormula(val); if (isFormula) { var ftext = val.reduce(function (pv, cv) { return pv + cv.text; }, ""); var ret = true; // ToDo - при вводе формулы в заголовок автофильтра надо писать "0" c.setValue(ftext, function (r) { ret = r; }); if (!ret) { this.isFormulaEditMode = oldMode; History.EndTransaction(); return false; } isFormula = c.isFormula(); this.model.autoFilters.renameTableColumn(oCellEdit); } else { c.setValue2(val); // Вызываем функцию пересчета для заголовков форматированной таблицы this.model.autoFilters.renameTableColumn(oCellEdit); var api = window["Asc"]["editor"]; var bFast = api.collaborativeEditing.m_bFast; var bIsSingleUser = !api.collaborativeEditing.getCollaborativeEditing(); if (!(bFast && !bIsSingleUser)) { oAutoExpansionTable = this.model.autoFilters.checkTableAutoExpansion(oCellEdit); } } if (!isFormula) { for (var i = 0; i < val.length; ++i) { if (-1 !== val[i].text.indexOf(kNewLine)) { c.setWrap(true); break; } } } this._updateCellsRange(oCellEdit, isNotHistory ? c_oAscCanChangeColWidth.none : c_oAscCanChangeColWidth.numbers, lockDraw); if (!isNotHistory) { History.EndTransaction(); } if (oAutoExpansionTable) { var callback = function () { var options = { props: [Asc.c_oAscAutoCorrectOptions.UndoTableAutoExpansion], cell: oCellEdit, wsId: t.model.getId() }; t.handlers.trigger("toggleAutoCorrectOptions", true, options); }; t.af_changeTableRange(oAutoExpansionTable.name, oAutoExpansionTable.range, callback); } else { t.handlers.trigger("toggleAutoCorrectOptions"); } // если вернуть false, то редактор не закроется return true; }; WorksheetView.prototype.openCellEditor = function (editor, fragments, cursorPos, isFocus, isClearCell, isHideCursor, isQuickInput, selectionRange) { var t = this, tc = this.cols, tr = this.rows, col, row, c, fl, mc, bg, isMerged; if (selectionRange) { this.model.selectionRange = selectionRange; } if (0 < this.arrActiveFormulaRanges.length) { this.cleanSelection(); this.cleanFormulaRanges(); this._drawSelection(); } var cell = this.model.selectionRange.activeCell; function getVisibleRangeObject() { var vr = t.visibleRange.clone(), offsetX = 0, offsetY = 0; if (t.topLeftFrozenCell) { var cFrozen = t.topLeftFrozenCell.getCol0(); var rFrozen = t.topLeftFrozenCell.getRow0(); if (0 < cFrozen) { if (col >= cFrozen) { offsetX = tc[cFrozen].left - tc[0].left; } else { vr.c1 = 0; vr.c2 = cFrozen - 1; } } if (0 < rFrozen) { if (row >= rFrozen) { offsetY = tr[rFrozen].top - tr[0].top; } else { vr.r1 = 0; vr.r2 = rFrozen - 1; } } } return {vr: vr, offsetX: offsetX, offsetY: offsetY}; } col = cell.col; row = cell.row; // Возможно стоит заменить на ячейку из кеша c = this._getVisibleCell(col, row); fl = this._getCellFlags(c); isMerged = fl.isMerged(); if (isMerged) { mc = fl.merged; c = this._getVisibleCell(mc.c1, mc.r1); fl = this._getCellFlags(c); } // Выставляем режим 'не редактируем' (иначе мы попытаемся переместить редактор, который еще не открыт) this.isCellEditMode = false; this.handlers.trigger("onScroll", this._calcActiveCellOffset()); this.isCellEditMode = true; bg = c.getFill(); this.isFormulaEditMode = false; var font = c.getFont(); // Скрываем окно редактирования комментария this.model.workbook.handlers.trigger("asc_onHideComment"); if (fragments === undefined) { var _fragmentsTmp = c.getValueForEdit2(); fragments = []; for (var i = 0; i < _fragmentsTmp.length; ++i) { fragments.push(_fragmentsTmp[i].clone()); } } var arrAutoComplete = this.getCellAutoCompleteValues(cell, kMaxAutoCompleteCellEdit); var arrAutoCompleteLC = asc.arrayToLowerCase(arrAutoComplete); editor.open({ fragments: fragments, flags: fl, font: new asc.FontProperties(font.getName(), font.getSize()), background: bg || this.settings.cells.defaultState.background, textColor: font.getColor(), cursorPos: cursorPos, zoom: this.getZoom(), focus: isFocus, isClearCell: isClearCell, isHideCursor: isHideCursor, isQuickInput: isQuickInput, isAddPersentFormat: isQuickInput && Asc.c_oAscNumFormatType.Percent === c.getNumFormatType(), autoComplete: arrAutoComplete, autoCompleteLC: arrAutoCompleteLC, cellName: c.getName(), cellNumFormat: c.getNumFormatType(), saveValueCallback: function (val, flags) { var oCellEdit = isMerged ? new asc_Range(mc.c1, mc.r1, mc.c1, mc.r1) : new asc_Range(col, row, col, row); return t._saveCellValueAfterEdit(oCellEdit, c, val, flags, /*isNotHistory*/false, /*lockDraw*/false); }, getSides: function () { var _c1, _r1, _c2, _r2, ri = 0, bi = 0; if (isMerged) { _c1 = mc.c1; _c2 = mc.c2; _r1 = mc.r1; _r2 = mc.r2; } else { _c1 = _c2 = col; _r1 = _r2 = row; } var vro = getVisibleRangeObject(); var i, w, h, arrLeftS = [], arrRightS = [], arrBottomS = []; var offsX = tc[vro.vr.c1].left - tc[0].left - vro.offsetX; var offsY = tr[vro.vr.r1].top - tr[0].top - vro.offsetY; var cellX = tc[_c1].left - offsX, cellY = tr[_r1].top - offsY; for (i = _c1; i >= vro.vr.c1; --i) { if (t.width_1px < tc[i].width) { arrLeftS.push(tc[i].left - offsX); } } if (_c2 > vro.vr.c2) { _c2 = vro.vr.c2; } for (i = _c1; i <= vro.vr.c2; ++i) { w = tc[i].width; if (t.width_1px < w) { arrRightS.push(tc[i].left + w - offsX); } if (_c2 === i) { ri = arrRightS.length - 1; } } w = t.drawingCtx.getWidth(); if (arrRightS[arrRightS.length - 1] > w) { arrRightS[arrRightS.length - 1] = w; } if (_r2 > vro.vr.r2) { _r2 = vro.vr.r2; } for (i = _r1; i <= vro.vr.r2; ++i) { h = tr[i].height; if (t.height_1px < h) { arrBottomS.push(tr[i].top + h - offsY); } if (_r2 === i) { bi = arrBottomS.length - 1; } } h = t.drawingCtx.getHeight(); if (arrBottomS[arrBottomS.length - 1] > h) { arrBottomS[arrBottomS.length - 1] = h; } return {l: arrLeftS, r: arrRightS, b: arrBottomS, cellX: cellX, cellY: cellY, ri: ri, bi: bi}; } }); return true; }; WorksheetView.prototype.openCellEditorWithText = function (editor, text, cursorPos, isFocus, selectionRange) { var t = this; selectionRange = (selectionRange) ? selectionRange : this.model.selectionRange; var activeCell = selectionRange.activeCell; var c = t._getVisibleCell(activeCell.col, activeCell.row); var v, copyValue; // get first fragment and change its text v = c.getValueForEdit2().slice(0, 1); // Создаем новый массив, т.к. getValueForEdit2 возвращает ссылку copyValue = []; copyValue[0] = new AscCommonExcel.Fragment({text: text, format: v[0].format.clone()}); var bSuccess = t.openCellEditor(editor, /*fragments*/undefined, /*cursorPos*/undefined, isFocus, /*isClearCell*/ true, /*isHideCursor*/false, /*isQuickInput*/false, selectionRange); if (bSuccess) { editor.paste(copyValue, cursorPos); } return bSuccess; }; WorksheetView.prototype.getFormulaRanges = function () { return this.arrActiveFormulaRanges; }; /** * * @param {Object} ranges * @param canChangeColWidth * @param lockDraw * @param updateHeight */ WorksheetView.prototype.updateRanges = function (ranges, lockDraw, updateHeight) { var arrRanges = [], range; for (var i in ranges) { range = ranges[i]; this.updateRange(range, range.canChangeColWidth || c_oAscCanChangeColWidth.none, true); arrRanges.push(range); } if (0 < arrRanges.length) { if (updateHeight) { this.isChanged = true; } this._recalculateAfterUpdate(arrRanges, lockDraw); } }; // ToDo избавиться от этой функции!!!!Заглушка для принятия изменений WorksheetView.prototype._checkUpdateRange = function (range) { // Для принятия изменения нужно делать расширение диапазона if (this.model.workbook.bCollaborativeChanges) { var bIsUpdateX = false, bIsUpdateY = false; if (range.c2 >= this.nColsCount) { this.expandColsOnScroll(false, true, 0); // Передаем 0, чтобы увеличить размеры // Проверка, вдруг пришел диапазон за пределами существующей области if (range.c2 >= this.nColsCount) { if (range.c1 >= this.nColsCount) { return; } range.c2 = this.nColsCount - 1; } bIsUpdateX = true; } if (range.r2 >= this.nRowsCount) { this.expandRowsOnScroll(false, true, 0); // Передаем 0, чтобы увеличить размеры // Проверка, вдруг пришел диапазон за пределами существующей области if (range.r2 >= this.nRowsCount) { if (range.r1 >= this.nRowsCount) { return; } range.r2 = this.nRowsCount - 1; } bIsUpdateY = true; } if (bIsUpdateX && bIsUpdateY) { this.handlers.trigger("reinitializeScroll"); } else if (bIsUpdateX) { this.handlers.trigger("reinitializeScrollX"); } else if (bIsUpdateY) { this.handlers.trigger("reinitializeScrollY"); } } }; WorksheetView.prototype.updateRange = function (range, canChangeColWidth, lockDraw) { this._checkUpdateRange(range); this._updateCellsRange(range, canChangeColWidth, lockDraw); }; WorksheetView.prototype._updateCellsRange = function (range, canChangeColWidth, lockDraw) { var r, c, h, d, ct, isMerged; var mergedRange, bUpdateRowHeight; if (range === undefined) { range = this.model.selectionRange.getLast().clone(); } else { // ToDo заглушка..пора уже переделать обновление данных if (range.r1 >= this.nRowsCount || range.c1 >= this.nColsCount) { return; } range.r2 = Math.min(range.r2, this.nRowsCount - 1); range.c2 = Math.min(range.c2, this.nColsCount - 1); } if (gc_nMaxCol0 === range.c2 || gc_nMaxRow0 === range.r2) { range = range.clone(); if (gc_nMaxCol0 === range.c2) { range.c2 = this.cols.length - 1; } if (gc_nMaxRow0 === range.r2) { range.r2 = this.rows.length - 1; } } this._cleanCache(range); // Если размер диапазона превышает размер видимой области больше чем в 3 раза, то очищаем весь кэш if (this._isLargeRange(range)) { this.changeWorksheet("update", {lockDraw: lockDraw}); this._updateSelectionNameAndInfo(); return; } var cto; for (r = range.r1; r <= range.r2; ++r) { if (this.height_1px > this.rows[r].height) { continue; } for (c = range.c1; c <= range.c2; ++c) { if (this.width_1px > this.cols[c].width) { continue; } c = this._addCellTextToCache(c, r, canChangeColWidth); // may change member 'this.isChanged' } for (h = this.defaultRowHeight, d = this.defaultRowDescender, c = 0; c < this.cols.length; ++c) { ct = this._getCellTextCache(c, r, true); if (!ct) { continue; } /** * Пробегаемся по строке и смотрим не продолжается ли ячейка на соседние. * С помощью этой правки уйдем от обновления всей строки при каких-либо действиях */ if ((c < range.c1 || c > range.c2) && (0 !== ct.sideL || 0 !== ct.sideR)) { cto = this._calcCellTextOffset(c, r, ct.cellHA, ct.metrics.width); ct.cellW = cto.maxWidth; ct.sideL = cto.leftSide; ct.sideR = cto.rightSide; } // Замерженная ячейка (с 2-мя или более строками) не влияет на высоту строк! isMerged = ct.flags.isMerged(); if (!isMerged) { bUpdateRowHeight = true; } else { mergedRange = ct.flags.merged; // Для замерженных ячеек (с 2-мя или более строками) оптимизировать не нужно bUpdateRowHeight = mergedRange.r1 === mergedRange.r2; } if (bUpdateRowHeight) { h = Math.max(h, ct.metrics.height + this.height_1px); } if (ct.cellVA !== Asc.c_oAscVAlign.Top && ct.cellVA !== Asc.c_oAscVAlign.Center && !isMerged) { d = Math.max(d, ct.metrics.height - ct.metrics.baseline); } } if (Math.abs(h - this.rows[r].height) > 0.000001 && !this.rows[r].isCustomHeight) { this.rows[r].heightReal = this.rows[r].height = Math.min(h, this.maxRowHeight); History.TurnOff(); this.model.setRowHeight(this.rows[r].height, r, r, false); History.TurnOn(); this.isChanged = true; } if (Math.abs(d - this.rows[r].descender) > 0.000001) { this.rows[r].descender = d; this.isChanged = true; } } if (!lockDraw) { this._recalculateAfterUpdate([range]); } }; WorksheetView.prototype._recalculateAfterUpdate = function (arrChanged, lockDraw) { if (this.isChanged) { this.isChanged = false; this._initCellsArea(AscCommonExcel.recalcType.full); this.cache.reset(); this._cleanCellsTextMetricsCache(); this._prepareCellTextMetricsCache(); this.handlers.trigger("reinitializeScroll"); } if (!lockDraw) { this._updateSelectionNameAndInfo(); } arrChanged = arrChanged.concat(this.model.hiddenManager.getRecalcHidden()); this.model.onUpdateRanges(arrChanged); this.objectRender.rebuildChartGraphicObjects(arrChanged); this.cellCommentator.updateActiveComment(); //this.updateSpecialPasteOptionsPosition(); this.handlers.trigger("onDocumentPlaceChanged"); this.draw(lockDraw); }; WorksheetView.prototype.setChartRange = function (range) { this.isChartAreaEditMode = true; this.arrActiveChartRanges[0].assign2(range); }; WorksheetView.prototype.endEditChart = function () { if (this.isChartAreaEditMode) { this.isChartAreaEditMode = false; this.arrActiveChartRanges[0].clean(); } }; WorksheetView.prototype.enterCellRange = function (editor) { if (!this.isFormulaEditMode) { return; } var currentFormula = this.arrActiveFormulaRanges[this.arrActiveFormulaRangesPosition]; var currentRange = currentFormula.getLast().clone(); var activeCellId = currentFormula.activeCellId; var activeCell = currentFormula.activeCell.clone(); // Замерженную ячейку должны отдать только левую верхнюю. var mergedRange = this.model.getMergedByCell(currentRange.r1, currentRange.c1); if (mergedRange && currentRange.isEqual(mergedRange)) { currentRange.r2 = currentRange.r1; currentRange.c2 = currentRange.c1; } /* var defName = this.model.workbook.findDefinesNames(this.model.getName()+"!"+currentRange.getAbsName(),this.model.getId()); console.log("defName #2 " + defName);*/ var sheetName = "", cFEWSO = editor.handlers.trigger("getCellFormulaEnterWSOpen"); if (editor.formulaIsOperator() && cFEWSO && cFEWSO.model.getId() != this.model.getId()) { sheetName = parserHelp.getEscapeSheetName(this.model.getName()) + "!"; } editor.enterCellRange(/*defName || */sheetName + currentRange.getAllRange().getName()); for (var tmpRange, i = 0; i < this.arrActiveFormulaRanges.length; ++i) { tmpRange = this.arrActiveFormulaRanges[i]; if (tmpRange.getLast().isEqual(currentRange)) { tmpRange.activeCellId = activeCellId; tmpRange.activeCell.col = activeCell.col; tmpRange.activeCell.row = activeCell.row; break; } } }; WorksheetView.prototype.addFormulaRange = function (range) { var r = this.model.selectionRange.clone(); if (range) { r.assign2(range); var lastSelection = r.getLast(); lastSelection.cursorePos = range.cursorePos; lastSelection.formulaRangeLength = range.formulaRangeLength; lastSelection.colorRangePos = range.colorRangePos; lastSelection.colorRangeLength = range.colorRangeLength; lastSelection.isName = range.isName; } this.arrActiveFormulaRanges.push(r); this.arrActiveFormulaRangesPosition = this.arrActiveFormulaRanges.length - 1; this._fixSelectionOfMergedCells(); }; WorksheetView.prototype.activeFormulaRange = function (range) { this.arrActiveFormulaRangesPosition = -1; for (var i = 0; i < this.arrActiveFormulaRanges.length; ++i) { if (this.arrActiveFormulaRanges[i].getLast().isEqual(range)) { this.arrActiveFormulaRangesPosition = i; return; } } }; WorksheetView.prototype.removeFormulaRange = function (range) { this.arrActiveFormulaRangesPosition = -1; for (var i = 0; i < this.arrActiveFormulaRanges.length; ++i) { if (this.arrActiveFormulaRanges[i].getLast().isEqual(range)) { this.arrActiveFormulaRanges.splice(i, 1); return; } } }; WorksheetView.prototype.cleanFormulaRanges = function () { // Очищаем массив ячеек для текущей формулы this.arrActiveFormulaRangesPosition = -1; this.arrActiveFormulaRanges = []; }; WorksheetView.prototype.addAutoFilter = function (styleName, addFormatTableOptionsObj) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } if (!this.handlers.trigger("getLockDefNameManagerStatus")) { this.handlers.trigger("onErrorEvent", c_oAscError.ID.LockCreateDefName, c_oAscError.Level.NoCritical); return; } if (!window['AscCommonExcel'].filteringMode) { return; } var t = this; var ar = this.model.selectionRange.getLast().clone(); var isChangeAutoFilterToTablePart = function (addFormatTableOptionsObj) { var res = false; var worksheet = t.model; var activeRange = AscCommonExcel.g_oRangeCache.getAscRange(addFormatTableOptionsObj.asc_getRange()); if (activeRange && worksheet.AutoFilter && activeRange.containsRange(worksheet.AutoFilter.Ref) && activeRange.r1 === worksheet.AutoFilter.Ref.r1) { res = true; } return res; }; var filterRange, bIsChangeFilterToTable, addNameColumn; var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { t.model.workbook.handlers.trigger("asc_onError", c_oAscError.ID.LockedAllError, c_oAscError.Level.NoCritical); t.handlers.trigger("selectionChanged"); return; } var addFilterCallBack; if (bIsChangeFilterToTable)//CHANGE FILTER TO TABLEPART { addFilterCallBack = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.changeAutoFilterToTablePart(styleName, ar, addFormatTableOptionsObj); t._onUpdateFormatTable(filterRange, !!(styleName), true); History.EndTransaction(); }; if (addNameColumn) { filterRange.r2 = filterRange.r2 + 1; } t._isLockedCells(filterRange, /*subType*/null, addFilterCallBack); } else//ADD { addFilterCallBack = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); if (null !== styleName) { t.handlers.trigger("slowOperation", true); } //add to model t.model.autoFilters.addAutoFilter(styleName, ar, addFormatTableOptionsObj); //updates if (styleName && addNameColumn) { t.setSelection(filterRange); } t._onUpdateFormatTable(filterRange, !!(styleName), true); if (null !== styleName) { t.handlers.trigger("slowOperation", false); } History.EndTransaction(); }; if (styleName === null) { addFilterCallBack(true); } else { t._isLockedCells(filterRange, null, addFilterCallBack) } } }; //calculate filter range if (addFormatTableOptionsObj && isChangeAutoFilterToTablePart(addFormatTableOptionsObj) === true) { filterRange = t.model.AutoFilter.Ref.clone(); addNameColumn = false; if (addFormatTableOptionsObj === false) { addNameColumn = true; } else if (typeof addFormatTableOptionsObj == 'object') { addNameColumn = !addFormatTableOptionsObj.asc_getIsTitle(); } bIsChangeFilterToTable = true; } else { if (styleName === null) { filterRange = ar; } else { var filterInfo = t.model.autoFilters._getFilterInfoByAddTableProps(ar, addFormatTableOptionsObj, true); filterRange = filterInfo.filterRange; addNameColumn = filterInfo.addNameColumn; } } var checkFilterRange = filterInfo ? filterInfo.rangeWithoutDiff : filterRange; if (t._checkAddAutoFilter(checkFilterRange, styleName, addFormatTableOptionsObj) === true) { this._isLockedAll(onChangeAutoFilterCallback); this._isLockedDefNames(null, null); } else//для того, чтобы в случае ошибки кнопка отжималась! { t.handlers.trigger("selectionChanged"); } }; WorksheetView.prototype.changeAutoFilter = function (tableName, optionType, val) { // Проверка глобального лока if (this.collaborativeEditing.getGlobalLock()) { return; } if (!window['AscCommonExcel'].filteringMode) { return; } var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { t.handlers.trigger("selectionChanged"); return; } switch (optionType) { case Asc.c_oAscChangeFilterOptions.filter: { //DELETE if (!val) { var filterRange = null; var tablePartsContainsRange = t.model.autoFilters._isTablePartsContainsRange(ar); if (tablePartsContainsRange && tablePartsContainsRange.Ref) { filterRange = tablePartsContainsRange.Ref.clone(); } else if (t.model.AutoFilter) { filterRange = t.model.AutoFilter.Ref; } if (null === filterRange) { return; } var deleteFilterCallBack = function () { t.model.autoFilters.deleteAutoFilter(ar, tableName); t.af_drawButtons(filterRange); t._onUpdateFormatTable(filterRange, false, true); }; t._isLockedCells(filterRange, /*subType*/null, deleteFilterCallBack); } else//ADD ONLY FILTER { var addFilterCallBack = function () { History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.addAutoFilter(null, ar); t._onUpdateFormatTable(filterRange, false, true); History.EndTransaction(); }; var filterInfo = t.model.autoFilters._getFilterInfoByAddTableProps(ar); t._isLockedCells(filterInfo.filterRange, null, addFilterCallBack) } break; } case Asc.c_oAscChangeFilterOptions.style://CHANGE STYLE { var changeStyleFilterCallBack = function () { History.Create_NewPoint(); History.StartTransaction(); //TODO внутри вызывается _isTablePartsContainsRange t.model.autoFilters.changeTableStyleInfo(val, ar, tableName); t._onUpdateFormatTable(filterRange, false, true); History.EndTransaction(); }; var filterRange; //calculate lock range and callback parameters var isTablePartsContainsRange = t.model.autoFilters._isTablePartsContainsRange(ar); if (isTablePartsContainsRange !== null)//if one of the tableParts contains activeRange { filterRange = isTablePartsContainsRange.Ref.clone(); } t._isLockedCells(filterRange, /*subType*/null, changeStyleFilterCallBack); break; } } }; if (Asc.c_oAscChangeFilterOptions.style === optionType) { onChangeAutoFilterCallback(true); } else { this._isLockedAll(onChangeAutoFilterCallback); } }; WorksheetView.prototype.applyAutoFilter = function (autoFilterObject) { var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var applyFilterProps = t.model.autoFilters.applyAutoFilter(autoFilterObject, ar); var minChangeRow = applyFilterProps.minChangeRow; var rangeOldFilter = applyFilterProps.rangeOldFilter; if (null !== rangeOldFilter && !t.model.workbook.bUndoChanges && !t.model.workbook.bRedoChanges) { t._onUpdateFormatTable(rangeOldFilter, false, true); if (applyFilterProps.nOpenRowsCount !== applyFilterProps.nAllRowsCount) { t.handlers.trigger('onFilterInfo', applyFilterProps.nOpenRowsCount, applyFilterProps.nAllRowsCount); } } if (null !== minChangeRow) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: minChangeRow}); } }; if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = true; onChangeAutoFilterCallback(); History.LocalChange = false; } else { this._isLockedAll(onChangeAutoFilterCallback); } }; WorksheetView.prototype.reapplyAutoFilter = function (tableName) { var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } //reApply var applyFilterProps = t.model.autoFilters.reapplyAutoFilter(tableName, ar); //reSort var filter = applyFilterProps.filter; if (filter && filter.SortState && filter.SortState.SortConditions && filter.SortState.SortConditions[0]) { var sortState = filter.SortState; var rangeWithoutHeaderFooter = filter.getRangeWithoutHeaderFooter(); var sortRange = t.model.getRange3(rangeWithoutHeaderFooter.r1, rangeWithoutHeaderFooter.c1, rangeWithoutHeaderFooter.r2, rangeWithoutHeaderFooter.c2); var startCol = sortState.SortConditions[0].Ref.c1; var type; var rgbColor = null; switch (sortState.SortConditions[0].ConditionSortBy) { case Asc.ESortBy.sortbyCellColor: { type = Asc.c_oAscSortOptions.ByColorFill; rgbColor = sortState.SortConditions[0].dxf.fill.bg; break; } case Asc.ESortBy.sortbyFontColor: { type = Asc.c_oAscSortOptions.ByColorFont; rgbColor = sortState.SortConditions[0].dxf.font.getColor(); break; } default: { type = Asc.c_oAscSortOptions.ByColorFont; if (sortState.SortConditions[0].ConditionDescending) { type = Asc.c_oAscSortOptions.Descending; } else { type = Asc.c_oAscSortOptions.Ascending; } } } var sort = sortRange.sort(type, startCol, rgbColor); t.cellCommentator.sortComments(sort); } t.model.autoFilters._resetTablePartStyle(); var minChangeRow = applyFilterProps.minChangeRow; var updateRange = applyFilterProps.updateRange; if (updateRange && !t.model.workbook.bUndoChanges && !t.model.workbook.bRedoChanges) { t._onUpdateFormatTable(updateRange, false, true); } if (null !== minChangeRow) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: minChangeRow}); } }; if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = true; onChangeAutoFilterCallback(); History.LocalChange = false; } else { this._isLockedAll(onChangeAutoFilterCallback); } }; WorksheetView.prototype.applyAutoFilterByType = function (autoFilterObject) { var t = this; var activeCell = this.model.selectionRange.activeCell.clone(); var ar = this.model.selectionRange.getLast().clone(); var isStartRangeIntoFilterOrTable = t.model.autoFilters.isStartRangeContainIntoTableOrFilter(activeCell); var isApplyAutoFilter = null, isAddAutoFilter = null, cellId = null, isFromatTable = null; if (null !== isStartRangeIntoFilterOrTable)//into autofilter or format table { isFromatTable = !(-1 === isStartRangeIntoFilterOrTable); var filterRef = isFromatTable ? t.model.TableParts[isStartRangeIntoFilterOrTable].Ref : t.model.AutoFilter.Ref; cellId = t.model.autoFilters._rangeToId(Asc.Range(ar.c1, filterRef.r1, ar.c1, filterRef.r1)); isApplyAutoFilter = true; if (isFromatTable && !t.model.TableParts[isStartRangeIntoFilterOrTable].AutoFilter)//add autofilter to tablepart { isAddAutoFilter = true; } } else//without filter { isAddAutoFilter = true; isApplyAutoFilter = true; } var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); if (null !== isAddAutoFilter) { //delete old filter if (!isFromatTable && t.model.AutoFilter && t.model.AutoFilter.Ref) { t.model.autoFilters.isEmptyAutoFilters(t.model.AutoFilter.Ref); } //add new filter t.model.autoFilters.addAutoFilter(null, ar, null); //generate cellId if (null === cellId) { cellId = t.model.autoFilters._rangeToId( Asc.Range(activeCell.col, t.model.AutoFilter.Ref.r1, activeCell.col, t.model.AutoFilter.Ref.r1)); } } if (null !== isApplyAutoFilter) { autoFilterObject.asc_setCellId(cellId); var filter = autoFilterObject.filter; if (c_oAscAutoFilterTypes.CustomFilters === filter.type) { t.model._getCell(activeCell.row, activeCell.col, function(cell) { var val = cell.getValueWithoutFormat(); filter.filter.CustomFilters[0].Val = val; }); } else if (c_oAscAutoFilterTypes.ColorFilter === filter.type) { t.model._getCell(activeCell.row, activeCell.col, function(cell) { if (filter.filter && filter.filter.dxf && filter.filter.dxf.fill) { if (false === filter.filter.CellColor) { var fontColor = cell.xfs && cell.xfs.font ? cell.xfs.font.getColor() : null; //TODO добавлять дефолтовый цвет шрифта в случае, если цвет шрифта не указан if (null !== fontColor) { filter.filter.dxf.fill.bg = fontColor; } } else { //TODO просмотерть ситуации без заливки var color = cell.getStyle(); var cellColor = null !== color && color.fill && color.fill.bg ? color.fill.bg : null; filter.filter.dxf.fill.bg = null !== cellColor ? new AscCommonExcel.RgbColor(cellColor.rgb) : new AscCommonExcel.RgbColor(null); } } }); } var applyFilterProps = t.model.autoFilters.applyAutoFilter(autoFilterObject, ar); var minChangeRow = applyFilterProps.minChangeRow; var rangeOldFilter = applyFilterProps.rangeOldFilter; if (null !== rangeOldFilter && !t.model.workbook.bUndoChanges && !t.model.workbook.bRedoChanges) { t._onUpdateFormatTable(rangeOldFilter, false, true); } if (null !== minChangeRow) { t.objectRender.updateSizeDrawingObjects({target: c_oTargetType.RowResize, row: minChangeRow}); } } History.EndTransaction(); }; if (null === isAddAutoFilter)//do not add autoFilter { if (!window['AscCommonExcel'].filteringMode) { History.LocalChange = true; onChangeAutoFilterCallback(); History.LocalChange = false; } else { this._isLockedAll(onChangeAutoFilterCallback); } } else//add autofilter + apply { if (!window['AscCommonExcel'].filteringMode) { return; } if (t._checkAddAutoFilter(ar, null, autoFilterObject, true) === true) { this._isLockedAll(onChangeAutoFilterCallback); this._isLockedDefNames(null, null); } } }; WorksheetView.prototype.sortRange = function (type, cellId, displayName, color, bIsExpandRange) { var t = this; var ar = this.model.selectionRange.getLast().clone(); if (!window['AscCommonExcel'].filteringMode) { return; } var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var sortProps = t.model.autoFilters.getPropForSort(cellId, ar, displayName); var onSortAutoFilterCallBack = function () { History.Create_NewPoint(); History.StartTransaction(); var rgbColor = color ? new AscCommonExcel.RgbColor((color.asc_getR() << 16) + (color.asc_getG() << 8) + color.asc_getB()) : null; var sort = sortProps.sortRange.sort(type, sortProps.startCol, rgbColor); t.cellCommentator.sortComments(sort); t.model.autoFilters.sortColFilter(type, cellId, ar, sortProps, displayName, rgbColor); t._onUpdateFormatTable(sortProps.sortRange.bbox, false); History.EndTransaction(); }; if (null === sortProps) { var rgbColor = color ? new AscCommonExcel.RgbColor((color.asc_getR() << 16) + (color.asc_getG() << 8) + color.asc_getB()) : null; //expand selectionRange if(bIsExpandRange) { var selectionRange = t.model.selectionRange; var activeCell = selectionRange.activeCell.clone(); var activeRange = selectionRange.getLast(); var expandRange = t.model.autoFilters._getAdjacentCellsAF(activeRange, true, true, true); var bIgnoreFirstRow = window['AscCommonExcel'].ignoreFirstRowSort(t.model, expandRange); if(bIgnoreFirstRow) { expandRange.r1++; } //change selection t.setSelection(expandRange); selectionRange.activeCell = activeCell; } //sort t.setSelectionInfo("sort", {type: type, color: rgbColor}); //TODO возможно стоит возвратить selection обратно } else if (false !== sortProps) { t._isLockedCells(sortProps.sortRange.bbox, /*subType*/null, onSortAutoFilterCallBack); } }; this._isLockedAll(onChangeAutoFilterCallback); }; WorksheetView.prototype.getAddFormatTableOptions = function (range) { var selectionRange = this.model.selectionRange.getLast(); //TODO возможно стоит перенести getAddFormatTableOptions во view return this.model.autoFilters.getAddFormatTableOptions(selectionRange, range); }; WorksheetView.prototype.clearFilter = function () { var t = this; var ar = this.model.selectionRange.getLast().clone(); var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var updateRange = t.model.autoFilters.isApplyAutoFilterInCell(ar, true); if (false !== updateRange) { t._onUpdateFormatTable(updateRange, false, true); } }; this._isLockedAll(onChangeAutoFilterCallback); }; WorksheetView.prototype.clearFilterColumn = function (cellId, displayName) { var t = this; var onChangeAutoFilterCallback = function (isSuccess) { if (false === isSuccess) { return; } var updateRange = t.model.autoFilters.clearFilterColumn(cellId, displayName); if (false !== updateRange) { t._onUpdateFormatTable(updateRange, false, true); } }; this._isLockedAll(onChangeAutoFilterCallback); }; /** * Обновление при изменениях форматированной таблицы * @param range - обновляемый диапазон (он же диапазон для выделения) * @param recalc - делать ли автоподбор по названию столбца * @param changeRowsOrMerge - менялись ли строки (скрытие раскрытие) или был unmerge * @private */ WorksheetView.prototype._onUpdateFormatTable = function (range, recalc, changeRowsOrMerge) { //ToDo заглушка, чтобы не падало. Нужно полностью переделывать этот код!!!! (Перенес выше из-за бага http://bugzilla.onlyoffice.com/show_bug.cgi?id=26705) this._checkUpdateRange(range); if (!recalc) { // При скрытии/открытии строк стоит делать update всему if (changeRowsOrMerge) { this.isChanged = true; } // Пока вызовем updateRange, но стоит делать просто draw this._updateCellsRange(range); // ToDo убрать совсем reinitRanges if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } return; } if (!this.model.selectionRange.getLast().isEqual(range)) { this.setSelection(range); } var i, r = range.r1, bIsUpdate = false, w; for (i = range.c1; i <= range.c2; ++i) { w = this.onChangeWidthCallback(i, r, r, /*onlyIfMore*/true); if (-1 !== w) { this.cols[i] = this._calcColWidth(w); this._cleanCache(new asc_Range(i, 0, i, this.rows.length - 1)); bIsUpdate = true; } } if (bIsUpdate) { this._updateColumnPositions(); this._updateVisibleColsCount(); this.changeWorksheet("update"); } else if (changeRowsOrMerge) { // Был merge, нужно обновить (ToDo) this._initCellsArea(AscCommonExcel.recalcType.full); this.cache.reset(); this._cleanCellsTextMetricsCache(); this._prepareCellTextMetricsCache(); if (this.objectRender && this.objectRender.drawingArea) { this.objectRender.drawingArea.reinitRanges(); } var arrChanged = [new asc_Range(range.c1, 0, range.c2, gc_nMaxRow0)]; this.model.onUpdateRanges(arrChanged); this.objectRender.rebuildChartGraphicObjects(arrChanged); this.draw(); this.handlers.trigger("reinitializeScroll"); this._updateSelectionNameAndInfo(); } else { // Просто отрисуем this.draw(); this._updateSelectionNameAndInfo(); } }; WorksheetView.prototype._loadFonts = function (fonts, callback) { var api = window["Asc"]["editor"]; api._loadFonts(fonts, callback); }; WorksheetView.prototype.setData = function (oData) { History.Clear(); History.TurnOff(); var oAllRange = new AscCommonExcel.Range(this.model, 0, 0, this.nRowsCount - 1, this.nColsCount - 1); oAllRange.cleanAll(); var row, oCell; for (var r = 0; r < oData.length; ++r) { row = oData[r]; for (var c = 0; c < row.length; ++c) { if (row[c]) { oCell = this._getVisibleCell(c, r); oCell.setValue(row[c]); } } } History.TurnOn(); this._updateCellsRange(oAllRange.bbox); // ToDo Стоит обновить nRowsCount и nColsCount }; WorksheetView.prototype.getData = function () { var arrResult, arrCells = [], c, r, row, lastC = -1, lastR = -1, val; var maxCols = Math.min(this.model.getColsCount(), gc_nMaxCol); var maxRows = Math.min(this.model.getRowsCount(), gc_nMaxRow); for (r = 0; r < maxRows; ++r) { row = []; for (c = 0; c < maxCols; ++c) { this.model._getCellNoEmpty(r, c, function(cell) { if (cell && '' !== (val = cell.getValue())) { lastC = Math.max(lastC, c); lastR = Math.max(lastR, r); } else { val = ''; } }); row.push(val); } arrCells.push(row); } arrResult = arrCells.slice(0, lastR + 1); ++lastC; if (lastC < maxCols) { for (r = 0; r < arrResult.length; ++r) { arrResult[r] = arrResult[r].slice(0, lastC); } } return arrResult; }; WorksheetView.prototype.af_drawButtons = function (updatedRange, offsetX, offsetY) { var i, aWs = this.model; var t = this; if (aWs.workbook.bUndoChanges || aWs.workbook.bRedoChanges) { return false; } var drawCurrentFilterButtons = function (filter) { var autoFilter = filter.isAutoFilter() ? filter : filter.AutoFilter; if(!filter.Ref) { return; } var range = new Asc.Range(filter.Ref.c1, filter.Ref.r1, filter.Ref.c2, filter.Ref.r1); if (range.isIntersect(updatedRange)) { var row = range.r1; var sortCondition = filter.isApplySortConditions() ? filter.SortState.SortConditions[0] : null; for (var col = range.c1; col <= range.c2; col++) { if (col >= updatedRange.c1 && col <= updatedRange.c2) { var isSetFilter = false; var isShowButton = true; var isSortState = null;//true - ascending, false - descending var colId = filter.isAutoFilter() ? t.model.autoFilters._getTrueColId(autoFilter, col - range.c1) : col - range.c1; if (autoFilter.FilterColumns && autoFilter.FilterColumns.length) { var filterColumn = null, filterColumnWithMerge = null; for (var i = 0; i < autoFilter.FilterColumns.length; i++) { if (autoFilter.FilterColumns[i].ColId === col - range.c1) { filterColumn = autoFilter.FilterColumns[i]; } if (colId === col - range.c1 && filterColumn !== null) { filterColumnWithMerge = filterColumn; break; } else if (autoFilter.FilterColumns[i].ColId === colId) { filterColumnWithMerge = autoFilter.FilterColumns[i]; } } if (filterColumnWithMerge && filterColumnWithMerge.isApplyAutoFilter()) { isSetFilter = true; } if (filterColumn && filterColumn.ShowButton === false) { isShowButton = false; } } if(sortCondition && sortCondition.Ref) { if(colId === sortCondition.Ref.c1 - range.c1) { isSortState = !!(sortCondition.ConditionDescending); } } if (isShowButton === false) { continue; } t.af_drawCurrentButton(offsetX, offsetY, {isSortState: isSortState, isSetFilter: isSetFilter, row: row, col: col}); } } } }; if (aWs.AutoFilter) { drawCurrentFilterButtons(aWs.AutoFilter); } if (aWs.TableParts && aWs.TableParts.length) { for (i = 0; i < aWs.TableParts.length; i++) { if (aWs.TableParts[i].AutoFilter && aWs.TableParts[i].HeaderRowCount !== 0) { drawCurrentFilterButtons(aWs.TableParts[i], true); } } } var pivotButtons = this.model.getPivotTableButtons(updatedRange); for (i = 0; i < pivotButtons.length; ++i) { this.af_drawCurrentButton(offsetX, offsetY, {isSortState: null, isSetFilter: false, row: pivotButtons[i].row, col: pivotButtons[i].col}); } return true; }; WorksheetView.prototype.af_drawCurrentButton = function (offsetX, offsetY, props) { var t = this; var ctx = t.drawingCtx; var isMobileRetina = false; //TODO пересмотреть масштабирование!!! var isApplyAutoFilter = props.isSetFilter; var isApplySortState = props.isSortState; var row = props.row; var col = props.col; var widthButtonPx = 17; var heightButtonPx = 17; if (AscBrowser.isRetina) { widthButtonPx = AscCommon.AscBrowser.convertToRetinaValue(widthButtonPx, true); heightButtonPx = AscCommon.AscBrowser.convertToRetinaValue(heightButtonPx, true); } var widthBorder = 1; var scaleIndex = 1; var scaleFactor = ctx.scaleFactor; var width_1px = t.width_1px; var height_1px = t.height_1px; var m_oColor = new CColor(120, 120, 120); var widthWithBorders = widthButtonPx * width_1px; var heightWithBorders = heightButtonPx * height_1px; var width = (widthButtonPx - widthBorder * 2) * width_1px; var height = (heightButtonPx - widthBorder * 2) * height_1px; var colWidth = t.cols[col].width; var rowHeight = t.rows[row].height; if (rowHeight < heightWithBorders) { widthWithBorders = widthWithBorders * (rowHeight / heightWithBorders); heightWithBorders = rowHeight; } //стартовая позиция кнопки var x1 = t.cols[col].left + t.cols[col].width - widthWithBorders - 0.5 - offsetX; var y1 = t.rows[row].top + t.rows[row].height - heightWithBorders - 0.5 - offsetY; var _drawButtonFrame = function(startX, startY, width, height) { ctx.setFillStyle(t.settings.cells.defaultState.background); ctx.setLineWidth(1); ctx.setStrokeStyle(t.settings.cells.defaultState.border); ctx.fillRect(startX, startY, width, height); ctx.strokeRect(startX, startY, width, height); }; var _drawSortArrow = function(startX, startY, isDescending, heightArrow) { //isDescending = true - стрелочка смотрит вниз //рисуем сверху вниз ctx.beginPath(); ctx.lineVer(startX, startY, startY + heightArrow * height_1px * scaleIndex); var x = startX; var y = startY; var heightArrow1 = heightArrow * height_1px * scaleIndex - 1*width_1px/scaleFactor; var height = 3 * scaleIndex * scaleFactor; var x1, x2, y1; if(isDescending) { for(var i = 0; i < height; i++) { x1 = x - (i*width_1px/scaleFactor); x2 = x - (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y - (i*width_1px/scaleFactor) + heightArrow1; ctx.lineHor(x1, y1, x2); x1 = x + (i*width_1px/scaleFactor); x2 = x + (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y - (i*width_1px/scaleFactor) + heightArrow1; ctx.lineHor(x1, y1, x2); } } else { for(var i = 0; i < height; i++) { x1 = x - (i*width_1px/scaleFactor); x2 = x - (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y + (i*width_1px/scaleFactor); ctx.lineHor(x1, y1, x2); x1 = x + (i*width_1px/scaleFactor); x2 = x + (i*width_1px/scaleFactor) + 1*width_1px/scaleFactor; y1 = y + (i*width_1px/scaleFactor); ctx.lineHor(x1, y1, x2); } } if(isMobileRetina) { ctx.setLineWidth(AscBrowser.retinaPixelRatio * 2); } else { ctx.setLineWidth(AscBrowser.retinaPixelRatio * width_1px); } ctx.setStrokeStyle(m_oColor); ctx.stroke(); }; var _drawFilterMark = function (x, y, height) { var heightLine = Math.round(height); var heightCleanLine = heightLine - 2*height_1px; ctx.beginPath(); ctx.moveTo(x, y); ctx.lineTo(x, y - heightCleanLine); if(isMobileRetina) { ctx.setLineWidth(4 * AscBrowser.retinaPixelRatio); } else { ctx.setLineWidth(AscBrowser.retinaPixelRatio * t.width_2px); } ctx.setStrokeStyle(m_oColor); ctx.stroke(); var heightTriangle = 4; y = y - heightLine + 1*width_1px / scaleFactor; _drawFilterDreieck(x, y, heightTriangle, 2); }; var _drawFilterDreieck = function (x, y, height, base) { ctx.beginPath(); x = x + 1*width_1px/scaleFactor; var diffY = (height / 2) * scaleFactor; height = height * scaleIndex*scaleFactor; for(var i = 0; i < height; i++) { ctx.lineHor(x - (i*width_1px/scaleFactor + base*width_1px/scaleFactor) , y + (height*height_1px - i*height_1px/scaleFactor) - diffY, x + i*width_1px/scaleFactor) } if(isMobileRetina) { ctx.setLineWidth(AscBrowser.retinaPixelRatio * 2); } else { ctx.setLineWidth(AscBrowser.retinaPixelRatio * width_1px); } ctx.setStrokeStyle(m_oColor); ctx.stroke(); }; //TODO пересмотреть отрисовку кнопок + отрисовку при масштабировании var _drawButton = function(upLeftXButton, upLeftYButton) { //квадрат кнопки рисуем _drawButtonFrame(upLeftXButton, upLeftYButton, width, height); //координаты центра var centerX = upLeftXButton + (width / 2); var centerY = upLeftYButton + (height / 2); if(null !== isApplySortState && isApplyAutoFilter) { var heigthObj = Math.ceil((height / 2) / height_1px) * height_1px + 1 * height_1px; var marginTop = Math.floor(((height - heigthObj) / 2) / height_1px) * height_1px; centerY = upLeftYButton + heigthObj + marginTop; _drawSortArrow(upLeftXButton + 4 * width_1px * scaleIndex, upLeftYButton + 5 * height_1px * scaleIndex, isApplySortState, 8); _drawFilterMark(centerX + 2 * width_1px, centerY, heigthObj); } else if(null !== isApplySortState) { _drawSortArrow(upLeftXButton + width - 5 * width_1px * scaleIndex, upLeftYButton + 3 * height_1px * scaleIndex, isApplySortState, 10); _drawFilterDreieck(centerX - 4 * width_1px, centerY + 1 * height_1px, 3, 1); } else if (isApplyAutoFilter) { var heigthObj = Math.ceil((height / 2) / height_1px) * height_1px + 1 * height_1px; var marginTop = Math.floor(((height - heigthObj) / 2) / height_1px) * height_1px; centerY = upLeftYButton + heigthObj + marginTop; _drawFilterMark(centerX, centerY, heigthObj); } else { _drawFilterDreieck(centerX, centerY, 4, 1); } }; var diffX = 0; var diffY = 0; if ((colWidth - 2) < width && rowHeight < (height + 2)) { if (rowHeight < colWidth) { scaleIndex = rowHeight / height; width = width * scaleIndex; height = rowHeight; } else { scaleIndex = colWidth / width; diffY = width - colWidth; diffX = width - colWidth; width = colWidth; height = height * scaleIndex; } } else if ((colWidth - 2) < width) { scaleIndex = colWidth / width; //смещения по x и y diffY = width - colWidth; diffX = width - colWidth + 2; width = colWidth; height = height * scaleIndex; } else if (rowHeight < height) { scaleIndex = rowHeight / height; width = width * scaleIndex; height = rowHeight; } if(window['IS_NATIVE_EDITOR']) { isMobileRetina = true; } if(AscBrowser.isRetina) { scaleIndex *= 2; } _drawButton(x1 + diffX, y1 + diffY); }; WorksheetView.prototype.af_checkCursor = function (x, y, _vr, offsetX, offsetY, r, c) { var aWs = this.model; var t = this; var result = null; var _isShowButtonInFilter = function (col, filter) { var result = true; var autoFilter = filter.isAutoFilter() ? filter : filter.AutoFilter; if (filter.HeaderRowCount === 0) { result = null; } else if (autoFilter && autoFilter.FilterColumns)//проверяем скрытые ячейки { var colId = col - autoFilter.Ref.c1; for (var i = 0; i < autoFilter.FilterColumns.length; i++) { if (autoFilter.FilterColumns[i].ColId === colId) { if (autoFilter.FilterColumns[i].ShowButton === false) { result = null; } break; } } } else if (!filter.isAutoFilter() && autoFilter === null)//если форматированная таблица и отсутсвует а/ф { result = null; } return result; }; var checkCurrentFilter = function (filter, num) { var range = new Asc.Range(filter.Ref.c1, filter.Ref.r1, filter.Ref.c2, filter.Ref.r1); if (range.contains(c.col, r.row) && _isShowButtonInFilter(c.col, filter)) { var row = range.r1; for (var col = range.c1; col <= range.c2; col++) { if (col === c.col) { if(t._hitCursorFilterButton(x, y, col, row)){ result = {cursor: kCurAutoFilter, target: c_oTargetType.FilterObject, col: -1, row: -1, idFilter: {id: num, colId: col - range.c1}}; break; } } } } }; if(_vr.contains(c.col, r.row)) { x = x + offsetX; y = y + offsetY; if (aWs.AutoFilter && aWs.AutoFilter.Ref) { checkCurrentFilter(aWs.AutoFilter, null); } if (aWs.TableParts && aWs.TableParts.length && !result) { for (var i = 0; i < aWs.TableParts.length; i++) { if (aWs.TableParts[i].AutoFilter) { checkCurrentFilter(aWs.TableParts[i], i); } } } } return result; }; WorksheetView.prototype._hitCursorFilterButton = function(x, y, col, row) { var ws = this; var width = 13; var height = 13; var rowHeight = ws.rows[row].height; if (rowHeight < height) { width = width * (rowHeight / height); height = rowHeight; } var x1 = ws.cols[col].left + ws.cols[col].width - width - 0.5; var y1 = ws.rows[row].top + ws.rows[row].height - height - 0.5; var x2 = ws.cols[col].left + ws.cols[col].width - 0.5; var y2 = ws.rows[row].top + ws.rows[row].height - 0.5; return (x >= x1 && x <= x2 && y >= y1 && y <= y2); }; WorksheetView.prototype._checkAddAutoFilter = function (activeRange, styleName, addFormatTableOptionsObj, filterByCellContextMenu) { //write error, if not add autoFilter and return false var result = true; var worksheet = this.model; var filter = worksheet.AutoFilter; if (filter && styleName && filter.Ref.isIntersect(activeRange) && !(filter.Ref.containsRange(activeRange) && (activeRange.isOneCell() || (filter.Ref.isEqual(activeRange))) || (filter.Ref.r1 === activeRange.r1 && activeRange.containsRange(filter.Ref)))) { worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (!styleName && activeRange.isOneCell() && worksheet.autoFilters._isEmptyRange(activeRange, 1)) { //add filter to empty range - if select contains 1 cell worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (!styleName && !activeRange.isOneCell() && worksheet.autoFilters._isEmptyRange(activeRange, 0)) { //add filter to empty range worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (!styleName && filterByCellContextMenu && false === worksheet.autoFilters._getAdjacentCellsAF(activeRange, this).isIntersect(activeRange)) { //add filter to empty range worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); result = false; } else if (styleName && addFormatTableOptionsObj && addFormatTableOptionsObj.isTitle === false && worksheet.autoFilters._isEmptyCellsUnderRange(activeRange) == false && worksheet.autoFilters._isPartTablePartsUnderRange(activeRange)) { //add format table without title if down another format table worksheet.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); result = false; } else if (this.model.inPivotTable(activeRange)) { result = false; } return result; }; WorksheetView.prototype.af_getSizeButton = function (c, r) { var ws = this; var result = null; var isCellContainsAutoFilterButton = function (col, row) { var aWs = ws.model; if (aWs.TableParts) { var tablePart; for (var i = 0; i < aWs.TableParts.length; i++) { tablePart = aWs.TableParts[i]; //TODO добавить проверку на isHidden у кнопки if (tablePart.Ref.contains(col, row) && tablePart.Ref.r1 === row) { return true; } } } //TODO добавить проверку на isHidden у кнопки if (aWs.AutoFilter && aWs.AutoFilter.Ref.contains(col, row) && aWs.AutoFilter.Ref.r1 === row) { return true; } return false; }; if (isCellContainsAutoFilterButton(c, r)) { var height = 11; var width = 11; var rowHeight = ws.rows[r].height; var index = 1; if (rowHeight < height) { index = rowHeight / height; width = width * index; height = rowHeight; } result = {width: width, height: height}; } return result; }; WorksheetView.prototype.af_setDialogProp = function (filterProp, isReturnProps) { var ws = this.model; if(!filterProp){ return; } //get filter var filter, autoFilter, displayName = null; if (filterProp.id === null) { autoFilter = ws.AutoFilter; filter = ws.AutoFilter; } else { autoFilter = ws.TableParts[filterProp.id].AutoFilter; filter = ws.TableParts[filterProp.id]; displayName = filter.DisplayName; } //get values var colId = filterProp.colId; var openAndClosedValues = ws.autoFilters.getOpenAndClosedValues(filter, colId); var values = openAndClosedValues.values; var automaticRowCount = openAndClosedValues.automaticRowCount; //для случае когда скрыто только пустое значение не отображаем customfilter var ignoreCustomFilter = openAndClosedValues.ignoreCustomFilter; var filters = autoFilter.getFilterColumn(colId); var rangeButton = Asc.Range(autoFilter.Ref.c1 + colId, autoFilter.Ref.r1, autoFilter.Ref.c1 + colId, autoFilter.Ref.r1); var cellId = ws.autoFilters._rangeToId(rangeButton); var cellCoord = this.getCellCoord(autoFilter.Ref.c1 + colId, autoFilter.Ref.r1); //get filter object var filterObj = new Asc.AutoFilterObj(); if (filters && filters.ColorFilter) { filterObj.type = c_oAscAutoFilterTypes.ColorFilter; filterObj.filter = filters.ColorFilter.clone(); } else if (!ignoreCustomFilter && filters && filters.CustomFiltersObj && filters.CustomFiltersObj.CustomFilters) { filterObj.type = c_oAscAutoFilterTypes.CustomFilters; filterObj.filter = filters.CustomFiltersObj; } else if (filters && filters.DynamicFilter) { filterObj.type = c_oAscAutoFilterTypes.DynamicFilter; filterObj.filter = filters.DynamicFilter.clone(); } else if (filters && filters.Top10) { filterObj.type = c_oAscAutoFilterTypes.Top10; filterObj.filter = filters.Top10.clone(); } else if (filters) { filterObj.type = c_oAscAutoFilterTypes.Filters; } else { filterObj.type = c_oAscAutoFilterTypes.None; } //get sort var sortVal = null; var sortColor = null; if (filter && filter.SortState && filter.SortState.SortConditions && filter.SortState.SortConditions[0]) { var SortConditions = filter.SortState.SortConditions[0]; if (rangeButton.c1 == SortConditions.Ref.c1) { var conditionSortBy = SortConditions.ConditionSortBy; switch (conditionSortBy) { case Asc.ESortBy.sortbyCellColor: { sortVal = Asc.c_oAscSortOptions.ByColorFill; sortColor = SortConditions.dxf && SortConditions.dxf.fill ? SortConditions.dxf.fill.bg : null; break; } case Asc.ESortBy.sortbyFontColor: { sortVal = Asc.c_oAscSortOptions.ByColorFont; sortColor = SortConditions.dxf && SortConditions.dxf.font ? SortConditions.dxf.font.getColor() : null; break; } default: { if (filter.SortState.SortConditions[0].ConditionDescending) { sortVal = Asc.c_oAscSortOptions.Descending; } else { sortVal = Asc.c_oAscSortOptions.Ascending; } break; } } } } var ascColor = null; if (null !== sortColor) { ascColor = new Asc.asc_CColor(); ascColor.asc_putR(sortColor.getR()); ascColor.asc_putG(sortColor.getG()); ascColor.asc_putB(sortColor.getB()); ascColor.asc_putA(sortColor.getA()); } //set menu object var autoFilterObject = new Asc.AutoFiltersOptions(); autoFilterObject.asc_setSortState(sortVal); autoFilterObject.asc_setCellCoord(cellCoord); autoFilterObject.asc_setCellId(cellId); autoFilterObject.asc_setValues(values); autoFilterObject.asc_setFilterObj(filterObj); autoFilterObject.asc_setAutomaticRowCount(automaticRowCount); autoFilterObject.asc_setDiplayName(displayName); autoFilterObject.asc_setSortColor(ascColor); var columnRange = Asc.Range(rangeButton.c1, autoFilter.Ref.r1 + 1, rangeButton.c1, autoFilter.Ref.r2); var filterTypes = this.af_getFilterTypes(columnRange); autoFilterObject.asc_setIsTextFilter(filterTypes.text); autoFilterObject.asc_setColorsFill(filterTypes.colors); autoFilterObject.asc_setColorsFont(filterTypes.fontColors); if (isReturnProps) { return autoFilterObject; } else { this.handlers.trigger("setAutoFiltersDialog", autoFilterObject); } }; WorksheetView.prototype.af_getFilterTypes = function (columnRange) { var t = this; var ws = this.model; var res = {text: true, colors: [], fontColors: []}; var alreadyAddColors = {}, alreadyAddFontColors = {}; var getAscColor = function (color) { var ascColor = new Asc.asc_CColor(); ascColor.asc_putR(color.getR()); ascColor.asc_putG(color.getG()); ascColor.asc_putB(color.getB()); ascColor.asc_putA(color.getA()); return ascColor; }; var addFontColorsToArray = function (fontColor) { var rgb = null === fontColor || fontColor && 0 === fontColor.rgb ? null : fontColor.rgb; var isDefaultFontColor = !!(null === rgb); if (true !== alreadyAddFontColors[rgb]) { if (isDefaultFontColor) { res.fontColors.push(null); alreadyAddFontColors[null] = true; } else { var ascFontColor = getAscColor(fontColor); res.fontColors.push(ascFontColor); alreadyAddFontColors[rgb] = true; } } }; var addCellColorsToArray = function (color) { var rgb = null !== color && color.fill && color.fill.bg ? color.fill.bg.rgb : null; var isDefaultCellColor = !!(null === rgb); if (true !== alreadyAddColors[rgb]) { if (isDefaultCellColor) { res.colors.push(null); alreadyAddColors[null] = true; } else { var ascColor = getAscColor(color.fill.bg); res.colors.push(ascColor); alreadyAddColors[rgb] = true; } } }; var tempText = 0, tempDigit = 0; ws.getRange3(columnRange.r1, columnRange.c1, columnRange.r2, columnRange.c1)._foreachNoEmpty(function(cell) { //добавляем без цвета ячейку if (!cell) { if (true !== alreadyAddColors[null]) { alreadyAddColors[null] = true; res.colors.push(null); } return; } if (false === cell.isNullText()) { var type = cell.getType(); if (type === 0) { tempDigit++; } else { tempText++; } } //font colors var multiText = cell.getValueMultiText(); if (null !== multiText) { for (var j = 0; j < multiText.length; j++) { var fontColor = multiText[j].format ? multiText[j].format.getColor() : null; addFontColorsToArray(fontColor); } } else { var fontColor = cell.xfs && cell.xfs.font ? cell.xfs.font.getColor() : null; addFontColorsToArray(fontColor); } //cell colors addCellColorsToArray(cell.getStyle()); }); //если один элемент в массиве, не отправляем его в меню if (res.colors.length === 1) { res.colors = []; } if (res.fontColors.length === 1) { res.fontColors = []; } res.text = tempDigit > tempText ? false : true; return res; }; WorksheetView.prototype.af_changeSelectionTablePart = function (activeRange) { var t = this; var tableParts = t.model.TableParts; var _changeSelectionToAllTablePart = function () { var tablePart; for (var i = 0; i < tableParts.length; i++) { tablePart = tableParts[i]; if (tablePart.Ref.intersection(activeRange)) { if (t.model.autoFilters._activeRangeContainsTablePart(activeRange, tablePart.Ref)) { var newActiveRange = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2); t.setSelection(newActiveRange); } break; } } }; var _changeSelectionFromCellToColumn = function () { if (tableParts && tableParts.length && activeRange.isOneCell()) { for (var i = 0; i < tableParts.length; i++) { if (tableParts[i].HeaderRowCount !== 0 && tableParts[i].Ref.containsRange(activeRange) && tableParts[i].Ref.r1 === activeRange.r1) { var newActiveRange = new Asc.Range(activeRange.c1, activeRange.r1, activeRange.c1, tableParts[i].Ref.r2); if (!activeRange.isEqual(newActiveRange)) { t.setSelection(newActiveRange); } break; } } } }; if (activeRange.isOneCell()) { _changeSelectionFromCellToColumn(activeRange); } else { _changeSelectionToAllTablePart(activeRange); } }; WorksheetView.prototype.af_isCheckMoveRange = function (arnFrom, arnTo) { var ws = this.model; var tableParts = ws.TableParts; var tablePart; var checkMoveRangeIntoApplyAutoFilter = function (arnTo) { if (ws.AutoFilter && ws.AutoFilter.Ref && arnTo.intersection(ws.AutoFilter.Ref)) { //если затрагиваем скрытые строки а/ф - выдаём ошибку if (ws.autoFilters._searchHiddenRowsByFilter(ws.AutoFilter, arnTo)) { return false; } } return true; }; //1) если выделена часть форматированной таблицы и ещё часть(либо полностью) var counterIntersection = 0; var counterContains = 0; for (var i = 0; i < tableParts.length; i++) { tablePart = tableParts[i]; if (tablePart.Ref.intersection(arnFrom)) { if (arnFrom.containsRange(tablePart.Ref)) { counterContains++; } else { counterIntersection++; } } } if ((counterIntersection > 0 && counterContains > 0) || (counterIntersection > 1)) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterDataRangeError, c_oAscError.Level.NoCritical); return false; } //2)если затрагиваем перемещаемым диапазоном часть а/ф со скрытыми строчками if (!checkMoveRangeIntoApplyAutoFilter(arnTo)) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterMoveToHiddenRangeError, c_oAscError.Level.NoCritical); return false; } return true; }; WorksheetView.prototype.af_changeSelectionFormatTable = function (tableName, optionType) { var t = this; var ws = this.model; var tablePart = ws.autoFilters._getFilterByDisplayName(tableName); if (!tablePart || (tablePart && !tablePart.Ref)) { return false; } var refTablePart = tablePart.Ref; var lastSelection = this.model.selectionRange.getLast(); var startCol = lastSelection.c1; var endCol = lastSelection.c2; var startRow = lastSelection.r1; var endRow = lastSelection.r2; switch (optionType) { case c_oAscChangeSelectionFormatTable.all: { startCol = refTablePart.c1; endCol = refTablePart.c2; startRow = refTablePart.r1; endRow = refTablePart.r2; break; } case c_oAscChangeSelectionFormatTable.data: { var rangeWithoutHeaderFooter = tablePart.getRangeWithoutHeaderFooter(); startCol = lastSelection.c1 < refTablePart.c1 ? refTablePart.c1 : lastSelection.c1; endCol = lastSelection.c2 > refTablePart.c2 ? refTablePart.c2 : lastSelection.c2; startRow = rangeWithoutHeaderFooter.r1; endRow = rangeWithoutHeaderFooter.r2; break; } case c_oAscChangeSelectionFormatTable.row: { startCol = refTablePart.c1; endCol = refTablePart.c2; startRow = lastSelection.r1 < refTablePart.r1 ? refTablePart.r1 : lastSelection.r1; endRow = lastSelection.r2 > refTablePart.r2 ? refTablePart.r2 : lastSelection.r2; break; } case c_oAscChangeSelectionFormatTable.column: { startCol = lastSelection.c1 < refTablePart.c1 ? refTablePart.c1 : lastSelection.c1; endCol = lastSelection.c2 > refTablePart.c2 ? refTablePart.c2 : lastSelection.c2; startRow = refTablePart.r1; endRow = refTablePart.r2; break; } } t.setSelection(new Asc.Range(startCol, startRow, endCol, endRow)); }; WorksheetView.prototype.af_changeFormatTableInfo = function (tableName, optionType, val) { var tablePart = this.model.autoFilters._getFilterByDisplayName(tableName); var t = this; var ar = this.model.selectionRange.getLast(); if (!tablePart || (tablePart && !tablePart.TableStyleInfo)) { return false; } if (!window['AscCommonExcel'].filteringMode) { return false; } var isChangeTableInfo = this.af_checkChangeTableInfo(tablePart, optionType); if (isChangeTableInfo !== false) { var callback = function (isSuccess) { if (false === isSuccess) { t.handlers.trigger("selectionChanged"); return; } History.Create_NewPoint(); History.StartTransaction(); var newTableRef = t.model.autoFilters.changeFormatTableInfo(tableName, optionType, val); if (newTableRef.r1 > ar.r1 || newTableRef.r2 < ar.r2) { var startRow = newTableRef.r1 > ar.r1 ? newTableRef.r1 : ar.r1; var endRow = newTableRef.r2 < ar.r2 ? newTableRef.r2 : ar.r2; var newActiveRange = new Asc.Range(ar.c1, startRow, ar.c2, endRow); t.setSelection(newActiveRange); History.SetSelectionRedo(newActiveRange); } t._onUpdateFormatTable(isChangeTableInfo, false, true); History.EndTransaction(); }; var lockRange = t.af_getRangeForChangeTableInfo(tablePart, optionType, val); if (lockRange) { t._isLockedCells(lockRange, null, callback); } else { callback(); } } }; WorksheetView.prototype.af_checkChangeTableInfo = function (tablePart, optionType) { var res = tablePart.Ref; var ws = this.model, rangeUpTable; if (optionType === c_oAscChangeTableStyleInfo.rowHeader && tablePart.HeaderRowCount !== null) { //add header row rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, tablePart.Ref.r1 - 1); } else if (optionType === c_oAscChangeTableStyleInfo.rowTotal && tablePart.TotalsRowCount === null) { //add total row rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r2 + 1, tablePart.Ref.c2, tablePart.Ref.r2 + 1); //add total table if down another format table if(ws.autoFilters._isPartTablePartsUnderRange(tablePart.Ref)){ ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); return false; } } if (rangeUpTable && this.model.autoFilters._isEmptyRange(rangeUpTable, 0) && this.model.autoFilters._isPartTablePartsUnderRange(tablePart.Ref) === true) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterMoveToHiddenRangeError, c_oAscError.Level.NoCritical); res = false; } return res; }; WorksheetView.prototype.af_getRangeForChangeTableInfo = function (tablePart, optionType, val) { var res = null; switch (optionType) { case c_oAscChangeTableStyleInfo.columnBanded: case c_oAscChangeTableStyleInfo.columnFirst: case c_oAscChangeTableStyleInfo.columnLast: case c_oAscChangeTableStyleInfo.rowBanded: case c_oAscChangeTableStyleInfo.filterButton: { res = tablePart.Ref; break; } case c_oAscChangeTableStyleInfo.rowTotal: { if (val === false) { res = tablePart.Ref; } else { var rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r2 + 1, tablePart.Ref.c2, tablePart.Ref.r2 + 1); if(this.model.autoFilters._isEmptyRange(rangeUpTable, 0) && this.model.autoFilters.searchRangeInTableParts(rangeUpTable) === -1){ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2 + 1); } else{ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r2 + 1, tablePart.Ref.c2, gc_nMaxRow0); } } break; } case c_oAscChangeTableStyleInfo.rowHeader: { if (val === false) { res = tablePart.Ref; } else { var rangeUpTable = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, tablePart.Ref.r1 - 1); if(this.model.autoFilters._isEmptyRange(rangeUpTable, 0) && this.model.autoFilters.searchRangeInTableParts(rangeUpTable) === -1){ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, tablePart.Ref.r2); } else{ res = new Asc.Range(tablePart.Ref.c1, tablePart.Ref.r1 - 1, tablePart.Ref.c2, gc_nMaxRow0); } } break; } } return res; }; WorksheetView.prototype.af_insertCellsInTable = function (tableName, optionType) { var t = this; var ws = this.model; var tablePart = ws.autoFilters._getFilterByDisplayName(tableName); if (!tablePart || (tablePart && !tablePart.Ref)) { return false; } var insertCellsAndShiftDownRight = function (arn, displayName, type) { var range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); var isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, type, "insCell", true); if (isCheckChangeAutoFilter === false) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); var shiftCells = type === c_oAscInsertOptions.InsertCellsAndShiftRight ? range.addCellsShiftRight(displayName) : range.addCellsShiftBottom(displayName); if (shiftCells) { t.cellCommentator.updateCommentsDependencies(true, type, arn); t.objectRender.updateDrawingObject(true, type, arn); t._onUpdateFormatTable(range, false, true); } History.EndTransaction(); }; var changedRange = new asc_Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2); t._isLockedCells(changedRange, null, callback); }; var newActiveRange = this.model.selectionRange.getLast().clone(); var displayName = null; var type = null; switch (optionType) { case c_oAscInsertOptions.InsertTableRowAbove: { newActiveRange.c1 = tablePart.Ref.c1; newActiveRange.c2 = tablePart.Ref.c2; type = c_oAscInsertOptions.InsertCellsAndShiftDown; break; } case c_oAscInsertOptions.InsertTableRowBelow: { newActiveRange.c1 = tablePart.Ref.c1; newActiveRange.c2 = tablePart.Ref.c2; newActiveRange.r1 = tablePart.Ref.r2 + 1; newActiveRange.r2 = tablePart.Ref.r2 + 1; displayName = tableName; type = c_oAscInsertOptions.InsertCellsAndShiftDown; break; } case c_oAscInsertOptions.InsertTableColLeft: { newActiveRange.r1 = tablePart.Ref.r1; newActiveRange.r2 = tablePart.Ref.r2; type = c_oAscInsertOptions.InsertCellsAndShiftRight; break; } case c_oAscInsertOptions.InsertTableColRight: { newActiveRange.c1 = tablePart.Ref.c2 + 1; newActiveRange.c2 = tablePart.Ref.c2 + 1; newActiveRange.r1 = tablePart.Ref.r1; newActiveRange.r2 = tablePart.Ref.r2; displayName = tableName; type = c_oAscInsertOptions.InsertCellsAndShiftRight; break; } } insertCellsAndShiftDownRight(newActiveRange, displayName, type) }; WorksheetView.prototype.af_deleteCellsInTable = function (tableName, optionType) { var t = this; var ws = this.model; var tablePart = ws.autoFilters._getFilterByDisplayName(tableName); if (!tablePart || (tablePart && !tablePart.Ref)) { return false; } var deleteCellsAndShiftLeftTop = function (arn, type) { var isCheckChangeAutoFilter = t.af_checkInsDelCells(arn, type, "delCell", true); if (isCheckChangeAutoFilter === false) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); if (isCheckChangeAutoFilter === true) { t.model.autoFilters.isEmptyAutoFilters(arn, type); } var preDeleteAction = function () { t.cellCommentator.updateCommentsDependencies(false, type, arn); }; var res; var range; if (type === c_oAscInsertOptions.InsertCellsAndShiftRight) { range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); res = range.deleteCellsShiftLeft(preDeleteAction); } else { arn = t.model.autoFilters.checkDeleteAllRowsFormatTable(arn, true); range = t.model.getRange3(arn.r1, arn.c1, arn.r2, arn.c2); res = range.deleteCellsShiftUp(preDeleteAction); } if (res) { t.objectRender.updateDrawingObject(true, type, arn); t._onUpdateFormatTable(range, false, true); } History.EndTransaction(); }; var changedRange = new asc_Range(tablePart.Ref.c1, tablePart.Ref.r1, tablePart.Ref.c2, tablePart.Ref.r2); t._isLockedCells(changedRange, null, callback); }; var deleteTableCallback = function (ref) { if (!window['AscCommonExcel'].filteringMode) { return false; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.isEmptyAutoFilters(ref); var cleanRange = t.model.getRange3(ref.r1, ref.c1, ref.r2, ref.c2); cleanRange.cleanAll(); t.cellCommentator.deleteCommentsRange(cleanRange.bbox); t._onUpdateFormatTable(ref, false, true); History.EndTransaction(); }; t._isLockedCells(ref, null, callback); }; var newActiveRange = this.model.selectionRange.getLast().clone(); var val = null; switch (optionType) { case c_oAscDeleteOptions.DeleteColumns: { newActiveRange.r1 = tablePart.Ref.r1; newActiveRange.r2 = tablePart.Ref.r2; val = c_oAscDeleteOptions.DeleteCellsAndShiftLeft; break; } case c_oAscDeleteOptions.DeleteRows: { newActiveRange.c1 = tablePart.Ref.c1; newActiveRange.c2 = tablePart.Ref.c2; val = c_oAscDeleteOptions.DeleteCellsAndShiftTop; break; } case c_oAscDeleteOptions.DeleteTable: { deleteTableCallback(tablePart.Ref.clone()); break; } } if (val !== null) { deleteCellsAndShiftLeftTop(newActiveRange, val); } }; WorksheetView.prototype.af_changeDisplayNameTable = function (tableName, newName) { this.model.autoFilters.changeDisplayNameTable(tableName, newName); }; WorksheetView.prototype.af_checkInsDelCells = function (activeRange, val, prop, isFromFormatTable) { var ws = this.model; var res = true; if (!window['AscCommonExcel'].filteringMode) { if(val === c_oAscInsertOptions.InsertCellsAndShiftRight || val === c_oAscInsertOptions.InsertColumns){ return false; }else if(val === c_oAscDeleteOptions.DeleteCellsAndShiftLeft || val === c_oAscDeleteOptions.DeleteColumns){ return false; } } var intersectionTableParts = ws.autoFilters.getTableIntersectionRange(activeRange); var isPartTablePartsUnderRange = ws.autoFilters._isPartTablePartsUnderRange(activeRange); var isPartTablePartsRightRange = ws.autoFilters.isPartTablePartsRightRange(activeRange); var isOneTableIntersection = intersectionTableParts && intersectionTableParts.length === 1 ? intersectionTableParts[0] : null; var checkInsCells = function () { switch (val) { case c_oAscInsertOptions.InsertCellsAndShiftDown: { if (isFromFormatTable) { //если внизу находится часть форматированной таблицы или это часть форматированной таблицы if (isPartTablePartsUnderRange) { res = false; } else if (isOneTableIntersection !== null && !(isOneTableIntersection.Ref.c1 === activeRange.c1 && isOneTableIntersection.Ref.c2 === activeRange.c2)) { res = false; } } else { if (isPartTablePartsUnderRange) { res = false; } else if (intersectionTableParts && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscInsertOptions.InsertCellsAndShiftRight: { //если справа находится часть форматированной таблицы или это часть форматированной таблицы if (isFromFormatTable) { if (isPartTablePartsRightRange) { res = false; } } else { if (isPartTablePartsRightRange) { res = false; } else if (intersectionTableParts && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscInsertOptions.InsertColumns: { break; } case c_oAscInsertOptions.InsertRows: { break; } } }; var checkDelCells = function () { switch (val) { case c_oAscDeleteOptions.DeleteCellsAndShiftTop: { if (isFromFormatTable) { if (isPartTablePartsUnderRange) { res = false; } } else { if (isPartTablePartsUnderRange) { res = false; } else if (!isOneTableIntersection && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscDeleteOptions.DeleteCellsAndShiftLeft: { if (isFromFormatTable) { if (isPartTablePartsRightRange) { res = false; } } else { if (isPartTablePartsRightRange) { res = false; } else if (!isOneTableIntersection && null !== isOneTableIntersection) { res = false; } else if (isOneTableIntersection && !isOneTableIntersection.Ref.isEqual(activeRange)) { res = false; } } break; } case c_oAscDeleteOptions.DeleteColumns: { break; } case c_oAscDeleteOptions.DeleteRows: { break; } } }; prop === "insCell" ? checkInsCells() : checkDelCells(); if (res === false) { ws.workbook.handlers.trigger("asc_onError", c_oAscError.ID.AutoFilterChangeFormatTableError, c_oAscError.Level.NoCritical); } return res; }; WorksheetView.prototype.af_setDisableProps = function (tablePart, formatTableInfo) { var selectionRange = this.model.selectionRange; var lastRange = selectionRange.getLast(); var activeCell = selectionRange.activeCell; if (!tablePart) { return false; } var refTable = tablePart.Ref; var refTableContainsActiveRange = selectionRange.isSingleRange() && refTable.containsRange(lastRange); //если курсор стоит в нижней строке, то разрешаем добавление нижней строки formatTableInfo.isInsertRowBelow = (refTableContainsActiveRange && ((tablePart.TotalsRowCount === null && activeCell.row === refTable.r2) || (tablePart.TotalsRowCount !== null && activeCell.row === refTable.r2 - 1))); //если курсор стоит в правом столбце, то разрешаем добавление одного столбца правее formatTableInfo.isInsertColumnRight = (refTableContainsActiveRange && activeCell.col === refTable.c2); //если внутри находится вся активная область или если выходит активная область за границу справа formatTableInfo.isInsertColumnLeft = refTableContainsActiveRange; //если внутри находится вся активная область(кроме строки заголовков) или если выходит активная область за границу снизу formatTableInfo.isInsertRowAbove = (refTableContainsActiveRange && ((lastRange.r1 > refTable.r1 && tablePart.HeaderRowCount === null) || (lastRange.r1 >= refTable.r1 && tablePart.HeaderRowCount !== null))); //если есть заголовок, и в данных всего одна строка //todo пределать все проверки HeaderRowCount на вызов функции isHeaderRow var dataRange = tablePart.getRangeWithoutHeaderFooter(); if((tablePart.isHeaderRow() || tablePart.isTotalsRow()) && dataRange.r1 === dataRange.r2 && lastRange.r1 === lastRange.r2 && dataRange.r1 === lastRange.r1) { formatTableInfo.isDeleteRow = false; } else { formatTableInfo.isDeleteRow = refTableContainsActiveRange && !(lastRange.r1 <= refTable.r1 && lastRange.r2 >= refTable.r1 && null === tablePart.HeaderRowCount); } formatTableInfo.isDeleteColumn = true; formatTableInfo.isDeleteTable = true; if (!window['AscCommonExcel'].filteringMode) { formatTableInfo.isDeleteColumn = false; formatTableInfo.isInsertColumnRight = false; formatTableInfo.isInsertColumnLeft = false; } }; WorksheetView.prototype.af_convertTableToRange = function (tableName) { var t = this; if (!window['AscCommonExcel'].filteringMode) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.workbook.dependencyFormulas.lockRecal(); t.model.autoFilters.convertTableToRange(tableName); t._onUpdateFormatTable(tableRange, false, true); t.model.workbook.dependencyFormulas.unlockRecal(); History.EndTransaction(); }; var table = t.model.autoFilters._getFilterByDisplayName(tableName); var tableRange = null !== table ? table.Ref : null; var lockRange = tableRange; var callBackLockedDefNames = function (isSuccess) { if (false === isSuccess) { return; } t._isLockedCells(lockRange, null, callback); }; //лочим данный именованный диапазон var defNameId = t.model.workbook.dependencyFormulas.getDefNameByName(tableName, t.model.getId()); defNameId = defNameId ? defNameId.getNodeId() : null; t._isLockedDefNames(callBackLockedDefNames, defNameId); }; WorksheetView.prototype.af_changeTableRange = function (tableName, range, callbackAfterChange) { var t = this; if(typeof range === "string"){ range = AscCommonExcel.g_oRangeCache.getAscRange(range); } if (!window['AscCommonExcel'].filteringMode) { return; } var callback = function (isSuccess) { if (false === isSuccess) { return; } History.Create_NewPoint(); History.StartTransaction(); t.model.autoFilters.changeTableRange(tableName, range); t._onUpdateFormatTable(range, false, true); //TODO добавить перерисовку таблицы и перерисовку шаблонов History.EndTransaction(); if(callbackAfterChange){ callbackAfterChange(); } }; //TODO возможно не стоит лочить весь диапазон. проверить: когда один ползователь меняет диапазон, другой снимает а/ф с ф/т. в этом случае в deleteAutoFilter передавать не range а имя ф/т var table = t.model.autoFilters._getFilterByDisplayName(tableName); var tableRange = null !== table ? table.Ref : null; var lockRange = range; if (null !== tableRange) { var r1 = tableRange.r1 < range.r1 ? tableRange.r1 : range.r1; var r2 = tableRange.r2 > range.r2 ? tableRange.r2 : range.r2; var c1 = tableRange.c1 < range.c1 ? tableRange.c1 : range.c1; var c2 = tableRange.c2 > range.c2 ? tableRange.c2 : range.c2; lockRange = new Asc.Range(c1, r1, c2, r2); } var callBackLockedDefNames = function (isSuccess) { if (false === isSuccess) { return; } t._isLockedCells(lockRange, null, callback); }; //лочим данный именованный диапазон при смене размера ф/т var defNameId = t.model.workbook.dependencyFormulas.getDefNameByName(tableName, t.model.getId()); defNameId = defNameId ? defNameId.getNodeId() : null; t._isLockedDefNames(callBackLockedDefNames, defNameId); }; WorksheetView.prototype.af_checkChangeRange = function (range) { var res = null; var intersectionTables = this.model.autoFilters.getTableIntersectionRange(range); if (0 < intersectionTables.length) { var tablePart = intersectionTables[0]; if (range.isOneCell()) { res = c_oAscError.ID.FTChangeTableRangeError } else if (range.r1 !== tablePart.Ref.r1)//первая строка таблицы не равна первой строке выделенного диапазона { res = c_oAscError.ID.FTChangeTableRangeError; } else if (intersectionTables.length !== 1)//выделено несколько таблиц { res = c_oAscError.ID.FTRangeIncludedOtherTables; } else if (this.model.AutoFilter && this.model.AutoFilter.Ref && this.model.AutoFilter.Ref.isIntersect(range)) { res = c_oAscError.ID.FTChangeTableRangeError; } } else { res = c_oAscError.ID.FTChangeTableRangeError; } return res; }; // Convert coordinates methods WorksheetView.prototype.ConvertXYToLogic = function (x, y) { x *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIX()); y *= asc_getcvt(0/*px*/, 1/*pt*/, this._getPPIY()); var c = this.visibleRange.c1, cFrozen, widthDiff; var r = this.visibleRange.r1, rFrozen, heightDiff; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; if (x < this.cellsLeft + widthDiff && 0 !== widthDiff) { c = 0; } rFrozen = this.topLeftFrozenCell.getRow0(); heightDiff = this.rows[rFrozen].top - this.rows[0].top; if (y < this.cellsTop + heightDiff && 0 !== heightDiff) { r = 0; } } x += this.cols[c].left - this.cellsLeft - this.cellsLeft; y += this.rows[r].top - this.cellsTop - this.cellsTop; x *= asc_getcvt(1/*pt*/, 3/*mm*/, this._getPPIX()); y *= asc_getcvt(1/*pt*/, 3/*mm*/, this._getPPIY()); return {X: x, Y: y}; }; WorksheetView.prototype.ConvertLogicToXY = function (xL, yL) { xL *= asc_getcvt(3/*mm*/, 1/*pt*/, this._getPPIX()); yL *= asc_getcvt(3/*mm*/, 1/*pt*/, this._getPPIY()); var c = this.visibleRange.c1, cFrozen, widthDiff = 0; var r = this.visibleRange.r1, rFrozen, heightDiff = 0; if (this.topLeftFrozenCell) { cFrozen = this.topLeftFrozenCell.getCol0(); widthDiff = this.cols[cFrozen].left - this.cols[0].left; if (xL < widthDiff && 0 !== widthDiff) { c = 0; widthDiff = 0; } rFrozen = this.topLeftFrozenCell.getRow0(); heightDiff = this.rows[rFrozen].top - this.rows[0].top; if (yL < heightDiff && 0 !== heightDiff) { r = 0; heightDiff = 0; } } xL -= (this.cols[c].left - widthDiff - this.cellsLeft - this.cellsLeft); yL -= (this.rows[r].top - heightDiff - this.cellsTop - this.cellsTop); xL *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIX()); yL *= asc_getcvt(1/*pt*/, 0/*px*/, this._getPPIY()); return {X: xL, Y: yL}; }; //------------------------------------------------------------export--------------------------------------------------- window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window["AscCommonExcel"].CellFlags = CellFlags; window["AscCommonExcel"].WorksheetView = WorksheetView; })(window);
fix Bug 36888
cell/view/WorksheetView.js
fix Bug 36888
<ide><path>ell/view/WorksheetView.js <ide> WorksheetView.prototype.emptySelection = function ( options ) { <ide> // Удаляем выделенные графичекие объекты <ide> if ( this.objectRender.selectedGraphicObjectsExists() ) { <del> this.objectRender.controller.deleteSelectedObjects(); <add> this.objectRender.controller.remove(); <ide> } else { <ide> this.setSelectionInfo( "empty", options ); <ide> }
JavaScript
mit
5aa7435cb46a38b12229aa58d7a09eafa7e58424
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' 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 = { 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) { const stats = nextProps.stats this.setState({ stats: stats, }) } if (nextProps.posts !== this.props.posts) { this.setState({ posts: nextProps.posts, }) } } render() { const firstThreePosts = this.state.posts.slice(0, 3) return ( <DocumentTitle title="Blockstack, building the decentralized internet"> <div className="body-hero"> <div className="col-centered block"> <div className="container"> <section className="hero"> <h1 className="hero-head"> What will you build on the decentralized internet? </h1> <p className="lead hero-lead col-md-5 block"> Blockstack is a new decentralized internet where you own your data and apps run locally without remote servers. </p> <p className="no-padding col-md-12"> <Link to="/tutorials/hello-blockstack" role="button" className="btn btn-lg btn-secondary btn-block"> Watch Tutorial </Link> </p> <p className="no-padding col-md-12 hero-caption"> <Link to="/install" className="hero-caption-text"> Try the browser portal &nbsp; › &nbsp; <span className="hero-caption-link">Install</span> </Link> </p> </section> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> The decentralized internet is already here </h1> <div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> In production for over 2 years </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> {this.state.stats.domains} domains registered </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Used by OpenBazaar, Microsoft & more </h3> </div> </div> </section> </div> </div> <div className="section-odd container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> The internet, evolved </h1> <p className="lead lead-centered col-md-10 block col-centered text-center"> The decentralized internet is powered by a technological breakthrough in consensus algorithms that lets you take back your safety, privacy, and property rights. Experience the internet as it was truly meant to be. </p> <p className="lead lead-centered col-md-10 block col-centered text-center"> Blockstack gives you access to the decentralized internet within your favorite browser. Claim your identity, try out the decentralized apps, find friends in the public directory, make payments with digital currency, and connect storage providers to host and own your data. </p> <p className="lead-centered"> <Link to="/install" role="button" className="btn btn-lg btn-outline-primary btn-block"> Install Browser Portal </Link> </p> </section> </div> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> The future of app development is decentralized </h1> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> No infrastructure </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Build apps without databases or server maintainance. Publish apps to the decentralized internet where they will run on user devices and live forever. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Get users faster </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Make it easier than ever for users to switch with shared data protocols between apps and freedom from walled gardens, censorship, and middlemen. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Be paid for open source </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> New business models enable you to get paid for open source code. Utilize micropayments, blockchain protocols, and more. </p> </div> </section> </div> </div> <div className="section-odd container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> Easily build apps like </h1> <div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Decentralized social networks </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Liquid democracy </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Peer-to-peer marketplaces </h3> </div> </div> <div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Open ridesharing </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Verified file publishing </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Encrypted health records </h3> </div> </div> </section> </div> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> A full trustless stack </h1> <div className="row"> <div className="col-md-3 no-padding"> <h3 className="modern text-center"> Identity & Auth </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> With Blockstack, users get a set of digital keys that let them own their identity. From there, they can sign in to apps locally without remote servers or identity providers. </p> </div> <div className="col-md-3 no-padding"> <h3 className="modern text-center"> Storage </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Blockstack's storage system allows users to bring their own storage providers and control their data. Data is encrypted and easily shared between applications. </p> </div> <div className="col-md-3 no-padding"> <h3 className="modern text-center"> Naming </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Blockstack's naming system (BNS), built on Blockstack's blockchain and P2P network, is completely decentralized and securely maps names to keys and routing info. </p> </div> <div className="col-md-3 no-padding"> <h3 className="modern text-center"> Payments </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> With Blockstack, you can accept simple one-time payments, enable continuous micropayments, and do much more. All with a global-accepted and decentralized currency called Bitcoin. </p> </div> </div> </section> </div> </div> <div className="section-odd container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> Step-by-step tutorials </h1> <p className="lead lead-centered col-md-10 block col-centered text-center"> <Link to="/tutorials/hello-blockstack"> <Image src="/images/tutorials/hello-blockstack-fastforward.gif" fallbackSrc="/images/tutorials/hello-blockstack-fastforward.gif" retinaSupport={false} /> </Link> </p> <p className="lead lead-centered col-md-10 block col-centered 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> <p className="lead lead-centered col-md-10 block col-centered text-center"> <Link to="/tutorials/hello-blockstack" role="button" className="btn btn-outline-primary btn-block"> Hello Blockstack Tutorial </Link> </p> <p className="lead lead-centered col-md-10 block col-centered text-center"> Want to learn more about building apps on blockstack? Tutorials on building serverless apps with decentralized storage are coming soon. </p> </section> </div> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> News </h1> <div className="row"> { firstThreePosts.map((post, index) => { return ( <div className="col-md-4" key={index}> { post.urlSlug && post.title ? <Link to={'/blog/' + post.urlSlug}> <h3>{ post.title }</h3> </Link> : null } { post.preview ? <div dangerouslySetInnerHTML={{ __html: post.preview }}> </div> : null } <div className="post-meta"> { post.creator ? <span>{post.creator.name} |&nbsp;</span> : null } { post.datetime && post.date ? <time className="post-date" dateTime={post.datetime}> {post.date} </time> : null } </div> </div> ) }) } </div> <p className="lead-centered"> <Link to="/newsletter" role="button" className="btn btn-lg btn-outline-primary btn-block"> Get Updates </Link> </p> </section> </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' 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 = { 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) { const stats = nextProps.stats this.setState({ stats: stats, }) } if (nextProps.posts !== this.props.posts) { this.setState({ posts: nextProps.posts, }) } } render() { const firstThreePosts = this.state.posts.slice(0, 3) return ( <DocumentTitle title="Blockstack, building the decentralized internet"> <div className="body-hero"> <div className="col-centered block"> <div className="container"> <section className="hero"> <h1 className="hero-head"> What will you build on the decentralized internet? </h1> <p className="lead hero-lead col-md-5 block"> Blockstack is a new decentralized internet where you own your data and apps run locally without remote servers. </p> <p className="no-padding col-md-12"> <Link to="/tutorials/hello-blockstack" role="button" className="btn btn-lg btn-secondary btn-block"> Watch Tutorial </Link> </p> <p className="no-padding col-md-12 hero-caption"> <Link to="/install" className="hero-caption-text"> Try the browser portal &nbsp; › &nbsp; <span className="hero-caption-link">Install</span> </Link> </p> </section> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> The decentralized internet is already here </h1> <div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> In production for over 2 years </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> {this.state.stats.domains} domains registered </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Used by OpenBazaar, Microsoft & more </h3> </div> </div> </section> </div> </div> <div className="section-odd container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> The internet, evolved </h1> <p className="lead lead-centered col-md-10 block col-centered text-center"> The decentralized internet is powered by a technological breakthrough in consensus algorithms that lets you take back your safety, privacy, and property rights. Experience the internet as it was truly meant to be. </p> <p className="lead lead-centered col-md-10 block col-centered text-center"> Blockstack gives you access to the decentralized internet within your favorite browser. Claim your identity, try out the decentralized apps, find friends in the public directory, make payments with digital currency, and connect storage providers to host and own your data. </p> <p className="lead-centered"> <Link to="/install" role="button" className="btn btn-lg btn-outline-primary btn-block"> Install Browser Portal </Link> </p> </section> </div> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> The future of app development is decentralized </h1> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> No infrastructure </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Build apps without databases or server maintainance. Publish apps to the decentralized internet where they will run on user devices and live forever. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Get users faster </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Make it easier than ever for users to switch with shared data protocols between apps and freedom from walled gardens, censorship, and middlemen. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Be paid for open source </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> New business models enable you to get paid for open source code. Utilize micropayments, blockchain protocols, and more. </p> </div> </section> </div> </div> <div className="section-odd container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> Easily build apps like </h1> <div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Decentralized social networks </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Liquid democracy </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Peer-to-peer marketplaces </h3> </div> </div> <div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Open ridesharing </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Verified file publishing </h3> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Encrypted health records </h3> </div> </div> </section> </div> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> Blockstack gives you a full trustless stack </h1> <div className="row"> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Identity & Auth </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> With Blockstack, users get a set of digital keys that let them own their identity. From there, they can sign in to apps locally without remote servers or identity providers. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Storage </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Blockstack's storage system allows users to bring their own storage providers and control their data. Data is encrypted and easily shared between applications. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Naming </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> Blockstack's naming system (BNS), built on Blockstack's blockchain and P2P network, is completely decentralized and securely maps names to keys and routing info. </p> </div> </div> <div className="row"> <div className="col-md-4 offset-md-2 no-padding"> <h3 className="modern text-center"> Payments </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> With Blockstack, you can accept simple one-time payments, enable continuous micropayments, and do much more. All with a global-accepted and decentralized currency called Bitcoin. </p> </div> <div className="col-md-4 no-padding"> <h3 className="modern text-center"> Encryption </h3> <p className="lead lead-centered col-md-10 block col-centered text-center"> With Blockstack, all files and communication is end-to-end encrypted by default. Blockstack handles key distribution and discovery so you don't have to. </p> </div> </div> </section> </div> </div> <div className="section-odd container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> Step-by-step tutorials </h1> <p className="lead lead-centered col-md-10 block col-centered text-center"> <Link to="/tutorials/hello-blockstack"> <Image src="/images/tutorials/hello-blockstack-fastforward.gif" fallbackSrc="/images/tutorials/hello-blockstack-fastforward.gif" retinaSupport={false} /> </Link> </p> <p className="lead lead-centered col-md-10 block col-centered 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> <p className="lead lead-centered col-md-10 block col-centered text-center"> <Link to="/tutorials/hello-blockstack" role="button" className="btn btn-outline-primary btn-block"> Hello Blockstack Tutorial </Link> </p> <p className="lead lead-centered col-md-10 block col-centered text-center"> Want to learn more about building apps on blockstack? Tutorials on building serverless apps with decentralized storage are coming soon. </p> </section> </div> </div> <div className="section-even container-fluid"> <div className="container"> <section> <h1 className="modern text-center"> News </h1> <div className="row"> { firstThreePosts.map((post, index) => { return ( <div className="col-md-4" key={index}> { post.urlSlug && post.title ? <Link to={'/blog/' + post.urlSlug}> <h3>{ post.title }</h3> </Link> : null } { post.preview ? <div dangerouslySetInnerHTML={{ __html: post.preview }}> </div> : null } <div className="post-meta"> { post.creator ? <span>{post.creator.name} |&nbsp;</span> : null } { post.datetime && post.date ? <time className="post-date" dateTime={post.datetime}> {post.date} </time> : null } </div> </div> ) }) } </div> <p className="lead-centered"> <Link to="/newsletter" role="button" className="btn btn-lg btn-outline-primary btn-block"> Get Updates </Link> </p> </section> </div> </div> </div> </div> </DocumentTitle> ) } } export default connect(mapStateToProps, mapDispatchToProps)(HomePage)
update home page copy
app/js/pages/HomePage.js
update home page copy
<ide><path>pp/js/pages/HomePage.js <ide> <div className="container"> <ide> <section> <ide> <h1 className="modern text-center"> <del> Blockstack gives you a full trustless stack <add> A full trustless stack <ide> </h1> <ide> <div className="row"> <del> <div className="col-md-4 no-padding"> <add> <div className="col-md-3 no-padding"> <ide> <h3 className="modern text-center"> <ide> Identity & Auth <ide> </h3> <ide> From there, they can sign in to apps locally without remote servers or identity providers. <ide> </p> <ide> </div> <del> <div className="col-md-4 no-padding"> <add> <div className="col-md-3 no-padding"> <ide> <h3 className="modern text-center"> <ide> Storage <ide> </h3> <ide> Data is encrypted and easily shared between applications. <ide> </p> <ide> </div> <del> <div className="col-md-4 no-padding"> <add> <div className="col-md-3 no-padding"> <ide> <h3 className="modern text-center"> <ide> Naming <ide> </h3> <ide> Blockstack's naming system (BNS), built on Blockstack's blockchain and P2P network, is completely decentralized and securely maps names to keys and routing info. <ide> </p> <ide> </div> <del> </div> <del> <div className="row"> <del> <div className="col-md-4 offset-md-2 no-padding"> <add> <div className="col-md-3 no-padding"> <ide> <h3 className="modern text-center"> <ide> Payments <ide> </h3> <ide> All with a global-accepted and decentralized currency called Bitcoin. <ide> </p> <ide> </div> <del> <div className="col-md-4 no-padding"> <del> <h3 className="modern text-center"> <del> Encryption <del> </h3> <del> <p className="lead lead-centered col-md-10 block col-centered text-center"> <del> With Blockstack, all files and communication is end-to-end encrypted by default. <del> Blockstack handles key distribution and discovery so you don't have to. <del> </p> <del> </div> <del> </div> <add> </div> <add> <ide> </section> <ide> </div> <ide> </div>
Java
apache-2.0
a6db56fe023ca749f5cf050abb91a674b9d78cb4
0
riptano/brisk,milliondreams/brisk,milliondreams/brisk,milliondreams/brisk,milliondreams/brisk,riptano/brisk,riptano/brisk,riptano/brisk
/** * 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.cassandra.hadoop.fs; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.UUIDGen; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.Progressable; public class CassandraOutputStream extends OutputStream { private Configuration conf; private int bufferSize; private CassandraFileSystemStore store; private Path path; private long blockSize; private long subBlockSize; private ByteArrayOutputStream backupStream; private boolean closed; private int pos = 0; private long filePos = 0; private long bytesWrittenToBlock = 0; private long bytesWrittenToSubBlock = 0; private byte[] outBuf; private List<Block> blocks = new ArrayList<Block>(); private Block nextBlock; private List<SubBlock> subBlocks = new ArrayList<SubBlock>(); private SubBlock nextSubBlock; private final Progressable progress; private FsPermission perms; /** * Holds the current block UUID to be written. * Since the subBLock is written first, we need to know the Block UUID ahead of time. */ private UUID currentBlockUUID; public CassandraOutputStream(Configuration conf, CassandraFileSystemStore store, Path path, FsPermission perms, long blockSize, long subBlockSize, Progressable progress, int buffersize) throws IOException { this.conf = conf; this.store = store; this.path = path; this.blockSize = blockSize; this.subBlockSize = subBlockSize; this.backupStream = new ByteArrayOutputStream((int) blockSize); this.bufferSize = buffersize; this.progress = progress; this.outBuf = new byte[bufferSize]; this.perms = perms; this.currentBlockUUID = generateTimeUUID(); // Integrity check. if (blockSize < subBlockSize) { throw new IllegalArgumentException( String.format("blockSize{%d} cannot be smaller than SubBlockSize{%d}", blockSize, subBlockSize)); } } public long getPos() throws IOException { return filePos; } @Override public synchronized void write(int b) throws IOException { if (closed) { throw new IOException("Stream closed"); } if ((bytesWrittenToBlock + pos == blockSize) || (bytesWrittenToSubBlock + pos == subBlockSize) || (pos >= bufferSize)) { flush(); } outBuf[pos++] = (byte) b; filePos++; } @Override public synchronized void write(byte b[], int off, int len) throws IOException { if (closed) { throw new IOException("Stream closed"); } while (len > 0) { int remaining = bufferSize - pos; int toWrite = Math.min(remaining, len); toWrite = Math.min(toWrite, (int) subBlockSize); System.arraycopy(b, off, outBuf, pos, toWrite); pos += toWrite; off += toWrite; len -= toWrite; filePos += toWrite; if (overFlowsBlockSize() || overFlowsSubBlockSize() || reachedLocalBuffer()) { flush(); } } } /** * @return TRUE if the subBlock size is overflowed due to probably last write (pos variable). */ private boolean overFlowsSubBlockSize() { return bytesWrittenToSubBlock + pos >= subBlockSize; } /** * @return TRUE if the local buffer size has been reached. */ private boolean reachedLocalBuffer() { return pos == bufferSize; } /** * @return TRUE if the block size is overflowed due to probably last write (pos variable). */ private boolean overFlowsBlockSize() { return bytesWrittenToBlock + pos >= blockSize; } /** * @return TRUE if the block limit has been reached. */ private boolean reachedBlockSize() { return bytesWrittenToBlock == blockSize; } /** * @return TRUE if the subBlock limit has been reached. */ private boolean reachedSubBlockSize() { return bytesWrittenToSubBlock == subBlockSize; } @Override public synchronized void flush() throws IOException { if (closed) { throw new IOException("Stream closed"); } if (overFlowsBlockSize() || overFlowsSubBlockSize()) { flushData((int)( subBlockSize - bytesWrittenToSubBlock )); } if (reachedSubBlockSize()) { endSubBlock(); } if (reachedBlockSize()) { // If there is a partial subBlock if (bytesWrittenToSubBlock != 0) { // means that we have some data in the subBlock to be flushed. // we also need to truncate the current subBlock as the Block is done. endSubBlock(); } // NO ELSE. endSubBlock was called before. Nothing to worry about. endBlock(); } // Flush remaining data from the last write. flushData(pos); } private synchronized void flushData(int maxPos) throws IOException { int workingPos = Math.min(pos, maxPos); if (workingPos > 0) { // To the local block backup, write just the bytes backupStream.write(outBuf, 0, workingPos); // Track position bytesWrittenToBlock += workingPos; bytesWrittenToSubBlock += workingPos; System.arraycopy(outBuf, workingPos, outBuf, 0, pos - workingPos); pos -= workingPos; } } private synchronized void endBlock() throws IOException { // Send it to Cassandra if(progress != null) progress.progress(); nextBlockOutputStream(); //store.storeBlock(nextBlock, backupStream); //internalClose(); bytesWrittenToBlock = 0; } /** * - flushes the current buffer into the DB, * - reset the backupStream, and * - reset subBlock counter to 0 for the next subBlock. */ private synchronized void endSubBlock() throws IOException { if(progress != null) progress.progress(); nextSubBlockOutputStream(); store.storeSubBlock(currentBlockUUID, nextSubBlock, backupStream); // Get the stream ready for next subBlock backupStream.reset(); // Reset counter for subBlock as this subBlock is full. bytesWrittenToSubBlock = 0; } private synchronized void nextSubBlockOutputStream() { // SubBlock offset ==> bytesWrittenToBlock - bytesWrittenToSubBlock - pos nextSubBlock = new SubBlock(generateTimeUUID(), bytesWrittenToBlock - bytesWrittenToSubBlock - pos, bytesWrittenToSubBlock); subBlocks.add(nextSubBlock); // Reset counter for subBlock as this subBlock is full. bytesWrittenToSubBlock = 0; } private synchronized void nextBlockOutputStream() throws IOException { nextBlock = new Block(currentBlockUUID, filePos - bytesWrittenToBlock - pos, bytesWrittenToBlock, subBlocks.toArray(new SubBlock[]{})); blocks.add(nextBlock); // Clean up the sub blocks collection for the next block. subBlocks.clear(); bytesWrittenToBlock = 0; // Generate the next UUID for the upcoming block so that subBlocks can reference to it. currentBlockUUID = generateTimeUUID(); } private UUID generateTimeUUID() { return UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()); } private synchronized void internalClose() throws IOException { INode inode = new INode( System.getProperty("user.name","none"), System.getProperty("user.name","none"), perms, INode.FileType.FILE, blocks.toArray(new Block[]{})); store.storeINode(path, inode); } @Override public synchronized void close() throws IOException { if (closed) { return; } flush(); if (filePos == 0 || bytesWrittenToBlock != 0) { if (bytesWrittenToSubBlock != 0) { endSubBlock(); } endBlock(); } // Save the INode to the DB after ending the subBlocks and Blocks. internalClose(); backupStream.close(); super.close(); closed = true; } }
src/java/src/org/apache/cassandra/hadoop/fs/CassandraOutputStream.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.cassandra.hadoop.fs; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.apache.cassandra.utils.FBUtilities; import org.apache.cassandra.utils.UUIDGen; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.permission.FsPermission; import org.apache.hadoop.util.Progressable; public class CassandraOutputStream extends OutputStream { private Configuration conf; private int bufferSize; private CassandraFileSystemStore store; private Path path; private long blockSize; private long subBlockSize; private ByteArrayOutputStream backupStream; private boolean closed; private int pos = 0; private long filePos = 0; private long bytesWrittenToBlock = 0; private long bytesWrittenToSubBlock = 0; private byte[] outBuf; private List<Block> blocks = new ArrayList<Block>(); private Block nextBlock; private List<SubBlock> subBlocks = new ArrayList<SubBlock>(); private SubBlock nextSubBlock; private final Progressable progress; private FsPermission perms; /** * Holds the current block UUID to be written. * Since the subBLock is written first, we need to know the Block UUID ahead of time. */ private UUID currentBlockUUID; public CassandraOutputStream(Configuration conf, CassandraFileSystemStore store, Path path, FsPermission perms, long blockSize, long subBlockSize, Progressable progress, int buffersize) throws IOException { this.conf = conf; this.store = store; this.path = path; this.blockSize = blockSize; this.subBlockSize = subBlockSize; this.backupStream = new ByteArrayOutputStream((int) blockSize); this.bufferSize = buffersize; this.progress = progress; this.outBuf = new byte[bufferSize]; this.perms = perms; this.currentBlockUUID = generateTimeUUID(); // Integrity check. if (blockSize < subBlockSize) { throw new IllegalArgumentException( String.format("blockSize{%d} cannot be smaller than SubBlockSize{%d}", blockSize, subBlockSize)); } } public long getPos() throws IOException { return filePos; } @Override public synchronized void write(int b) throws IOException { if (closed) { throw new IOException("Stream closed"); } if ((bytesWrittenToBlock + pos == blockSize) || (bytesWrittenToSubBlock + pos == subBlockSize) || (pos >= bufferSize)) { flush(); } outBuf[pos++] = (byte) b; filePos++; } @Override public synchronized void write(byte b[], int off, int len) throws IOException { if (closed) { throw new IOException("Stream closed"); } while (len > 0) { int remaining = bufferSize - pos; int toWrite = Math.min(remaining, len); toWrite = Math.min(toWrite, (int) subBlockSize); System.arraycopy(b, off, outBuf, pos, toWrite); pos += toWrite; off += toWrite; len -= toWrite; filePos += toWrite; if (overFlowsBlockSize() || overFlowsSubBlockSize() || reachedLocalBuffer()) { flush(); } } } /** * @return TRUE if the subBlock size is overflowed due to probably last write (pos variable). */ private boolean overFlowsSubBlockSize() { return bytesWrittenToSubBlock + pos >= subBlockSize; } /** * @return TRUE if the local buffer size has been reached. */ private boolean reachedLocalBuffer() { return pos == bufferSize; } /** * @return TRUE if the block size is overflowed due to probably last write (pos variable). */ private boolean overFlowsBlockSize() { return bytesWrittenToBlock + pos >= blockSize; } /** * @return TRUE if the block limit has been reached. */ private boolean reachedBlockSize() { return bytesWrittenToBlock == blockSize; } /** * @return TRUE if the subBlock limit has been reached. */ private boolean reachedSubBlockSize() { return bytesWrittenToSubBlock == subBlockSize; } @Override public synchronized void flush() throws IOException { if (closed) { throw new IOException("Stream closed"); } if (overFlowsBlockSize() || overFlowsSubBlockSize()) { flushData((int)( subBlockSize - bytesWrittenToSubBlock )); } if (reachedSubBlockSize()) { endSubBlock(); } if (reachedBlockSize()) { // If there is a partial subBlock if (bytesWrittenToSubBlock != 0) { // means that we have some data in the subBlock to be flushed. // we also need to truncate the current subBlock as the Block is done. endSubBlock(); } // NO ELSE. endSubBlock was called before. Nothing to worry about. endBlock(); } // Flush remaining data from the last write. flushData(pos); } private synchronized void flushData(int maxPos) throws IOException { int workingPos = Math.min(pos, maxPos); if (workingPos > 0) { // To the local block backup, write just the bytes backupStream.write(outBuf, 0, workingPos); // Track position bytesWrittenToBlock += workingPos; bytesWrittenToSubBlock += workingPos; System.arraycopy(outBuf, workingPos, outBuf, 0, pos - workingPos); pos -= workingPos; } } private synchronized void endBlock() throws IOException { // Send it to Cassandra if(progress != null) progress.progress(); nextBlockOutputStream(); //store.storeBlock(nextBlock, backupStream); //internalClose(); bytesWrittenToBlock = 0; } /** * - flushes the current buffer into the DB, * - reset the backupStream, and * - reset subBlock counter to 0 for the next subBlock. */ private synchronized void endSubBlock() throws IOException { if(progress != null) progress.progress(); nextSubBlockOutputStream(); store.storeSubBlock(currentBlockUUID, nextSubBlock, backupStream); // Get the stream ready for next subBlock backupStream.reset(); // Reset counter for subBlock as this subBlock is full. bytesWrittenToSubBlock = 0; } private synchronized void nextSubBlockOutputStream() { // SubBlock offset ==> bytesWrittenToBlock - bytesWrittenToSubBlock - pos nextSubBlock = new SubBlock(generateTimeUUID(), bytesWrittenToBlock - bytesWrittenToSubBlock - pos, bytesWrittenToSubBlock); subBlocks.add(nextSubBlock); // Reset counter for subBlock as this subBlock is full. bytesWrittenToSubBlock = 0; } private synchronized void nextBlockOutputStream() throws IOException { nextBlock = new Block(currentBlockUUID, filePos - bytesWrittenToBlock - pos, bytesWrittenToBlock, subBlocks.toArray(new SubBlock[subBlocks.size()])); blocks.add(nextBlock); // Clean up the sub blocks collection for the next block. subBlocks.clear(); bytesWrittenToBlock = 0; // Generate the next UUID for the upcoming block so that subBlocks can reference to it. currentBlockUUID = generateTimeUUID(); } private UUID generateTimeUUID() { return UUIDGen.makeType1UUIDFromHost(FBUtilities.getLocalAddress()); } private synchronized void internalClose() throws IOException { INode inode = new INode( System.getProperty("user.name","none"), System.getProperty("user.name","none"), perms, INode.FileType.FILE, blocks.toArray(new Block[blocks.size()])); store.storeINode(path, inode); } @Override public synchronized void close() throws IOException { if (closed) { return; } flush(); if (filePos == 0 || bytesWrittenToBlock != 0) { if (bytesWrittenToSubBlock != 0) { endSubBlock(); } endBlock(); } // Save the INode to the DB after ending the subBlocks and Blocks. internalClose(); backupStream.close(); super.close(); closed = true; } }
fix unnessisary allocation
src/java/src/org/apache/cassandra/hadoop/fs/CassandraOutputStream.java
fix unnessisary allocation
<ide><path>rc/java/src/org/apache/cassandra/hadoop/fs/CassandraOutputStream.java <ide> { <ide> nextBlock = new Block(currentBlockUUID, <ide> filePos - bytesWrittenToBlock - pos, bytesWrittenToBlock, <del> subBlocks.toArray(new SubBlock[subBlocks.size()])); <add> subBlocks.toArray(new SubBlock[]{})); <ide> blocks.add(nextBlock); <ide> // Clean up the sub blocks collection for the next block. <ide> subBlocks.clear(); <ide> System.getProperty("user.name","none"), <ide> perms, <ide> INode.FileType.FILE, <del> blocks.toArray(new Block[blocks.size()])); <add> blocks.toArray(new Block[]{})); <ide> <ide> store.storeINode(path, inode); <ide> }
Java
apache-2.0
2411e5dfef83ade5d58678ae0367a7c2f595a074
0
xmairaa/eiffel-remrem-publish,Ericsson/eiffel-remrem-produce,Ericsson/eiffel-remrem-publish,xmairaa/eiffel-remrem-publish,xumakap/eiffel-remrem-publish,xumakap/eiffel-remrem-publish
/* Copyright 2018 Ericsson AB. For a full list of individual contributors, please see the commit history. 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.ericsson.eiffel.remrem.publish.controller; import java.util.Map; import com.ericsson.eiffel.remrem.publish.constants.RemremPublishServiceConstants; import io.swagger.annotations.*; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.ericsson.eiffel.remrem.protocol.MsgService; import com.ericsson.eiffel.remrem.publish.helper.PublishUtils; import com.ericsson.eiffel.remrem.publish.helper.RMQHelper; import com.ericsson.eiffel.remrem.publish.service.MessageService; import com.ericsson.eiffel.remrem.publish.service.SendResult; import com.ericsson.eiffel.remrem.shared.VersionService; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import ch.qos.logback.classic.Logger; @RestController @RequestMapping("/*") @Api(value = "REMReM Publish Service", description = "REST API for publishing Eiffel messages to message bus") public class ProducerController { @Autowired private MsgService msgServices[]; @Autowired @Qualifier("messageServiceRMQImpl") private MessageService messageService; @Autowired private RMQHelper rmqHelper; @Autowired private GenerateURLTemplate generateURLTemplate; private RestTemplate restTemplate = new RestTemplate(); private JsonParser parser = new JsonParser(); private Logger log = (Logger) LoggerFactory.getLogger(ProducerController.class); public void setMsgServices(MsgService[] msgServices) { this.msgServices = msgServices; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation(value = "To publish eiffel event to message bus", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Event sent successfully"), @ApiResponse(code = 400, message = "Invalid event content"), @ApiResponse(code = 404, message = "RabbitMq properties not found"), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 503, message = "Service Unavailable") }) @RequestMapping(value = "/producer/msg", method = RequestMethod.POST) @ResponseBody public ResponseEntity send(@ApiParam(value = "message protocol", required = true) @RequestParam(value = "mp") final String msgProtocol, @ApiParam(value = "user domain") @RequestParam(value = "ud", required = false) final String userDomain, @ApiParam(value = "tag") @RequestParam(value = "tag", required = false) final String tag, @ApiParam(value = "routing key") @RequestParam(value = "rk", required = false) final String routingKey, @ApiParam(value = "eiffel event", required = true) @RequestBody final JsonElement body) { MsgService msgService = PublishUtils.getMessageService(msgProtocol, msgServices); log.debug("mp: " + msgProtocol); log.debug("body: " + body); log.debug("user domain suffix: " + userDomain + " tag: " + tag + " Routing Key: " + routingKey); if (msgService != null && msgProtocol != null) { rmqHelper.rabbitMqPropertiesInit(msgProtocol); } SendResult result = messageService.send(body, msgService, userDomain, tag, routingKey); return new ResponseEntity(result, messageService.getHttpStatus()); } /** * This controller provides single RemRem REST API End Point for both RemRem * Generate and Publish. * * @param msgProtocol * message protocol (required) * @param msgType * message type (required) * @param userDomain * user domain (not required) * @param tag * (not required) * @param routingKey * (not required) * @return A response entity which contains http status and result * * @use A typical CURL command: curl -H "Content-Type: application/json" -X POST * --data "@inputGenerate_activity_finished.txt" * "http://localhost:8986/generateAndPublish/?mp=eiffelsemantics&msgType=EiffelActivityFinished" */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation(value = "To generate and publish eiffel event to message bus", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Event sent successfully"), @ApiResponse(code = 400, message = "Invalid event content"), @ApiResponse(code = 404, message = "RabbitMq properties not found"), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 503, message = "Message protocol is invalid") }) @RequestMapping(value = "/generateAndPublish", method = RequestMethod.POST) @ResponseBody public ResponseEntity generateAndPublish(@ApiParam(value = "message protocol", required = true) @RequestParam(value = "mp") final String msgProtocol, @ApiParam(value = "message type", required = true) @RequestParam("msgType") final String msgType, @ApiParam(value = "user domain") @RequestParam(value = "ud", required = false) final String userDomain, @ApiParam(value = "tag") @RequestParam(value = "tag", required = false) final String tag, @ApiParam(value = "routing key") @RequestParam(value = "rk", required = false) final String routingKey, @ApiParam(value = "JSON message", required = true) @RequestBody final JsonObject bodyJson) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(bodyJson.toString(), headers); try { ResponseEntity<String> response = restTemplate.postForEntity(generateURLTemplate.getUrl(), entity, String.class, generateURLTemplate.getMap(msgProtocol, msgType)); if(response.getStatusCode() == HttpStatus.OK) { log.info("The result from REMReM Generate is: " + response.getStatusCodeValue()); // publishing requires an array if you want status code String responseBody = "[" + response.getBody() + "]"; MsgService msgService = PublishUtils.getMessageService(msgProtocol, msgServices); log.debug("mp: " + msgProtocol); log.debug("body: " + responseBody); log.debug("user domain suffix: " + userDomain + " tag: " + tag + " routing key: " + routingKey); if (msgService != null && msgProtocol != null) { rmqHelper.rabbitMqPropertiesInit(msgProtocol); } SendResult result = messageService.send(responseBody, msgService, userDomain, tag, routingKey); return new ResponseEntity(result, messageService.getHttpStatus()); } else { return response; } } catch (Exception e) { log.info("The result from REMReM Generate is not OK and have value: " + e.getMessage()); if (e.getMessage().startsWith(Integer.toString(HttpStatus.BAD_REQUEST.value()))) { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_BAD_REQUEST), HttpStatus.BAD_REQUEST); } else if (e.getMessage().startsWith(Integer.toString(HttpStatus.SERVICE_UNAVAILABLE.value()))) { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_NO_SERVICE_ERROR), HttpStatus.SERVICE_UNAVAILABLE); } else if (e.getMessage().startsWith(Integer.toString(HttpStatus.UNAUTHORIZED.value()))) { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_UNAUTHORIZED), HttpStatus.UNAUTHORIZED); } else { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR); } } } /** * @return this method returns the current version of publish and all loaded * protocols. */ @ApiOperation(value = "To get versions of publish and all loaded protocols", response = String.class) @RequestMapping(value = "/versions", method = RequestMethod.GET) public JsonElement getVersions() { JsonParser parser = new JsonParser(); Map<String, Map<String, String>> versions = new VersionService().getMessagingVersions(); return parser.parse(versions.toString()); } }
publish-service/src/main/java/com/ericsson/eiffel/remrem/publish/controller/ProducerController.java
/* Copyright 2018 Ericsson AB. For a full list of individual contributors, please see the commit history. 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.ericsson.eiffel.remrem.publish.controller; import java.util.Map; import com.ericsson.eiffel.remrem.publish.constants.RemremPublishServiceConstants; import io.swagger.annotations.*; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import com.ericsson.eiffel.remrem.protocol.MsgService; import com.ericsson.eiffel.remrem.publish.helper.PublishUtils; import com.ericsson.eiffel.remrem.publish.helper.RMQHelper; import com.ericsson.eiffel.remrem.publish.service.MessageService; import com.ericsson.eiffel.remrem.publish.service.SendResult; import com.ericsson.eiffel.remrem.shared.VersionService; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import ch.qos.logback.classic.Logger; @RestController @RequestMapping("/*") @Api(value = "REMReM Publish Service", description = "REST API for publishing Eiffel messages to message bus") public class ProducerController { @Autowired private MsgService msgServices[]; @Autowired @Qualifier("messageServiceRMQImpl") private MessageService messageService; @Autowired private RMQHelper rmqHelper; @Autowired private GenerateURLTemplate generateURLTemplate; private RestTemplate restTemplate = new RestTemplate(); private JsonParser parser = new JsonParser(); private Logger log = (Logger) LoggerFactory.getLogger(ProducerController.class); public void setMsgServices(MsgService[] msgServices) { this.msgServices = msgServices; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation(value = "To publish eiffel event to message bus", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Event sent successfully"), @ApiResponse(code = 400, message = "Invalid event content"), @ApiResponse(code = 404, message = "RabbitMq properties not found"), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 503, message = "Service Unavailable") }) @RequestMapping(value = "/producer/msg", method = RequestMethod.POST) @ResponseBody public ResponseEntity send(@ApiParam(value = "message protocol", required = true) @RequestParam(value = "mp") final String msgProtocol, @ApiParam(value = "user domain") @RequestParam(value = "ud", required = false) final String userDomain, @ApiParam(value = "tag") @RequestParam(value = "tag", required = false) final String tag, @ApiParam(value = "routing key") @RequestParam(value = "rk", required = false) final String routingKey, @ApiParam(value = "eiffel event", required = true) @RequestBody final JsonElement body) { MsgService msgService = PublishUtils.getMessageService(msgProtocol, msgServices); log.debug("mp: " + msgProtocol); log.debug("body: " + body); log.debug("user domain suffix: " + userDomain + " tag: " + tag + " Routing Key: " + routingKey); if (msgService != null && msgProtocol != null) { rmqHelper.rabbitMqPropertiesInit(msgProtocol); } SendResult result = messageService.send(body, msgService, userDomain, tag, routingKey); return new ResponseEntity(result, messageService.getHttpStatus()); } /** * This controller provides single RemRem REST API End Point for both RemRem * Generate and Publish. * * @param msgProtocol * message protocol (required) * @param msgType * message type (required) * @param userDomain * user domain (not required) * @param tag * (not required) * @param routingKey * (not required) * @return A response entity which contains http status and result * * @use A typical CURL command: curl -H "Content-Type: application/json" -X POST * --data "@inputGenerate_activity_finished.txt" * "http://localhost:8986/generateAndPublish/?mp=eiffelsemantics&msgType=EiffelActivityFinished" */ @SuppressWarnings({ "rawtypes", "unchecked" }) @ApiOperation(value = "To generate and publish eiffel event to message bus", response = String.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "Event sent successfully"), @ApiResponse(code = 400, message = "Invalid event content"), @ApiResponse(code = 404, message = "RabbitMq properties not found"), @ApiResponse(code = 500, message = "Internal server error"), @ApiResponse(code = 503, message = "Message protocol is invalid") }) @RequestMapping(value = "/generateAndPublish", method = RequestMethod.POST) @ResponseBody public ResponseEntity generateAndPublish(@ApiParam(value = "message protocol", required = true) @RequestParam(value = "mp") final String msgProtocol, @ApiParam(value = "message type", required = true) @RequestParam("msgType") final String msgType, @ApiParam(value = "user domain") @RequestParam(value = "ud", required = false) final String userDomain, @ApiParam(value = "tag") @RequestParam(value = "tag", required = false) final String tag, @ApiParam(value = "routing key") @RequestParam(value = "rk", required = false) final String routingKey, @ApiParam(value = "JSON message", required = true) @RequestBody final JsonObject bodyJson) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> entity = new HttpEntity<>(bodyJson.toString(), headers); String postURL = generateURLTemplate.getUrl(); Map<String, String> map = generateURLTemplate.getMap(msgProtocol, msgType); try { ResponseEntity<String> response = restTemplate.postForEntity(postURL, entity, String.class, map); if(response.getStatusCode() == HttpStatus.OK) { log.info("The result from REMReM Generate is: " + response.getStatusCodeValue()); // publishing requires an array if you want status code String responseBody = "[" + response.getBody() + "]"; MsgService msgService = PublishUtils.getMessageService(msgProtocol, msgServices); log.debug("mp: " + msgProtocol); log.debug("body: " + responseBody); log.debug("user domain suffix: " + userDomain + " tag: " + tag + " routing key: " + routingKey); if (msgService != null && msgProtocol != null) { rmqHelper.rabbitMqPropertiesInit(msgProtocol); } SendResult result = messageService.send(responseBody, msgService, userDomain, tag, routingKey); return new ResponseEntity(result, messageService.getHttpStatus()); } else { return response; } } catch (Exception e) { log.info("The result from REMReM Generate is not OK and have value: " + e.getMessage()); if (e.getMessage().startsWith(Integer.toString(HttpStatus.BAD_REQUEST.value()))) { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_BAD_REQUEST), HttpStatus.BAD_REQUEST); } else if (e.getMessage().startsWith(Integer.toString(HttpStatus.SERVICE_UNAVAILABLE.value()))) { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_NO_SERVICE_ERROR), HttpStatus.SERVICE_UNAVAILABLE); } else if (e.getMessage().startsWith(Integer.toString(HttpStatus.UNAUTHORIZED.value()))) { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_UNAUTHORIZED), HttpStatus.UNAUTHORIZED); } else { return new ResponseEntity(parser.parse(RemremPublishServiceConstants.GENERATE_INTERNAL_ERROR), HttpStatus.INTERNAL_SERVER_ERROR); } } } /** * @return this method returns the current version of publish and all loaded * protocols. */ @ApiOperation(value = "To get versions of publish and all loaded protocols", response = String.class) @RequestMapping(value = "/versions", method = RequestMethod.GET) public JsonElement getVersions() { JsonParser parser = new JsonParser(); Map<String, Map<String, String>> versions = new VersionService().getMessagingVersions(); return parser.parse(versions.toString()); } }
Fixed issue in /generateAndPublish endpoint
publish-service/src/main/java/com/ericsson/eiffel/remrem/publish/controller/ProducerController.java
Fixed issue in /generateAndPublish endpoint
<ide><path>ublish-service/src/main/java/com/ericsson/eiffel/remrem/publish/controller/ProducerController.java <ide> headers.setContentType(MediaType.APPLICATION_JSON); <ide> HttpEntity<String> entity = new HttpEntity<>(bodyJson.toString(), headers); <ide> <del> String postURL = generateURLTemplate.getUrl(); <del> Map<String, String> map = generateURLTemplate.getMap(msgProtocol, msgType); <del> <ide> try { <del> ResponseEntity<String> response = restTemplate.postForEntity(postURL, entity, String.class, map); <add> ResponseEntity<String> response = restTemplate.postForEntity(generateURLTemplate.getUrl(), <add> entity, String.class, generateURLTemplate.getMap(msgProtocol, msgType)); <ide> <ide> if(response.getStatusCode() == HttpStatus.OK) { <ide> log.info("The result from REMReM Generate is: " + response.getStatusCodeValue());
Java
apache-2.0
193b3aeac33ede28198a7e7da53930ffe79559b9
0
diorcety/intellij-community,consulo/consulo,ryano144/intellij-community,ol-loginov/intellij-community,ernestp/consulo,slisson/intellij-community,da1z/intellij-community,supersven/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,TangHao1987/intellij-community,diorcety/intellij-community,da1z/intellij-community,vladmm/intellij-community,xfournet/intellij-community,signed/intellij-community,asedunov/intellij-community,blademainer/intellij-community,FHannes/intellij-community,consulo/consulo,slisson/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,vladmm/intellij-community,izonder/intellij-community,amith01994/intellij-community,semonte/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,gnuhub/intellij-community,wreckJ/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,hurricup/intellij-community,kdwink/intellij-community,hurricup/intellij-community,asedunov/intellij-community,izonder/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,izonder/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,alphafoobar/intellij-community,mglukhikh/intellij-community,dslomov/intellij-community,supersven/intellij-community,da1z/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,suncycheng/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,fnouama/intellij-community,idea4bsd/idea4bsd,retomerz/intellij-community,diorcety/intellij-community,fengbaicanhe/intellij-community,signed/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,Distrotech/intellij-community,kool79/intellij-community,supersven/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,holmes/intellij-community,allotria/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,FHannes/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,vladmm/intellij-community,idea4bsd/idea4bsd,ftomassetti/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,blademainer/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,Distrotech/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,ivan-fedorov/intellij-community,ryano144/intellij-community,vladmm/intellij-community,Lekanich/intellij-community,petteyg/intellij-community,diorcety/intellij-community,xfournet/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,ibinti/intellij-community,xfournet/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,slisson/intellij-community,xfournet/intellij-community,amith01994/intellij-community,clumsy/intellij-community,fitermay/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,signed/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,hurricup/intellij-community,alphafoobar/intellij-community,signed/intellij-community,suncycheng/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,asedunov/intellij-community,retomerz/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,ryano144/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,izonder/intellij-community,consulo/consulo,MichaelNedzelsky/intellij-community,semonte/intellij-community,da1z/intellij-community,allotria/intellij-community,da1z/intellij-community,semonte/intellij-community,blademainer/intellij-community,diorcety/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,kool79/intellij-community,blademainer/intellij-community,jagguli/intellij-community,joewalnes/idea-community,hurricup/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,adedayo/intellij-community,alphafoobar/intellij-community,semonte/intellij-community,vladmm/intellij-community,jexp/idea2,SerCeMan/intellij-community,slisson/intellij-community,diorcety/intellij-community,apixandru/intellij-community,samthor/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,joewalnes/idea-community,samthor/intellij-community,kdwink/intellij-community,holmes/intellij-community,holmes/intellij-community,supersven/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,FHannes/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,retomerz/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,suncycheng/intellij-community,kool79/intellij-community,vladmm/intellij-community,slisson/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,slisson/intellij-community,jagguli/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,kool79/intellij-community,petteyg/intellij-community,Distrotech/intellij-community,SerCeMan/intellij-community,suncycheng/intellij-community,allotria/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,signed/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,clumsy/intellij-community,ryano144/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,slisson/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,diorcety/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,wreckJ/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,kdwink/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,samthor/intellij-community,petteyg/intellij-community,kdwink/intellij-community,samthor/intellij-community,samthor/intellij-community,tmpgit/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,dslomov/intellij-community,caot/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,muntasirsyed/intellij-community,dslomov/intellij-community,ernestp/consulo,ivan-fedorov/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,signed/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,Lekanich/intellij-community,blademainer/intellij-community,Lekanich/intellij-community,ernestp/consulo,jagguli/intellij-community,nicolargo/intellij-community,MER-GROUP/intellij-community,Lekanich/intellij-community,gnuhub/intellij-community,ol-loginov/intellij-community,robovm/robovm-studio,fnouama/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,da1z/intellij-community,FHannes/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,holmes/intellij-community,vladmm/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,lucafavatella/intellij-community,hurricup/intellij-community,signed/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,idea4bsd/idea4bsd,samthor/intellij-community,izonder/intellij-community,da1z/intellij-community,izonder/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,ibinti/intellij-community,fnouama/intellij-community,fnouama/intellij-community,amith01994/intellij-community,youdonghai/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,amith01994/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,jagguli/intellij-community,izonder/intellij-community,retomerz/intellij-community,dslomov/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,allotria/intellij-community,signed/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,kdwink/intellij-community,fnouama/intellij-community,petteyg/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,izonder/intellij-community,salguarnieri/intellij-community,caot/intellij-community,FHannes/intellij-community,blademainer/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,joewalnes/idea-community,ahb0327/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ryano144/intellij-community,ryano144/intellij-community,jagguli/intellij-community,allotria/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,ibinti/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,apixandru/intellij-community,xfournet/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,caot/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,consulo/consulo,retomerz/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,Lekanich/intellij-community,fnouama/intellij-community,robovm/robovm-studio,robovm/robovm-studio,fitermay/intellij-community,allotria/intellij-community,petteyg/intellij-community,joewalnes/idea-community,SerCeMan/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,jexp/idea2,suncycheng/intellij-community,semonte/intellij-community,Distrotech/intellij-community,izonder/intellij-community,amith01994/intellij-community,caot/intellij-community,supersven/intellij-community,allotria/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,holmes/intellij-community,orekyuu/intellij-community,joewalnes/idea-community,vvv1559/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,hurricup/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,signed/intellij-community,blademainer/intellij-community,fnouama/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,kool79/intellij-community,ivan-fedorov/intellij-community,jexp/idea2,suncycheng/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,fitermay/intellij-community,xfournet/intellij-community,FHannes/intellij-community,kool79/intellij-community,dslomov/intellij-community,kdwink/intellij-community,diorcety/intellij-community,holmes/intellij-community,xfournet/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,clumsy/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,dslomov/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,apixandru/intellij-community,diorcety/intellij-community,consulo/consulo,caot/intellij-community,TangHao1987/intellij-community,Distrotech/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,MichaelNedzelsky/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,samthor/intellij-community,jexp/idea2,SerCeMan/intellij-community,Lekanich/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,asedunov/intellij-community,semonte/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,caot/intellij-community,fengbaicanhe/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,ibinti/intellij-community,jexp/idea2,Lekanich/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,akosyakov/intellij-community,fnouama/intellij-community,petteyg/intellij-community,ibinti/intellij-community,jagguli/intellij-community,robovm/robovm-studio,joewalnes/idea-community,caot/intellij-community,akosyakov/intellij-community,kool79/intellij-community,adedayo/intellij-community,ftomassetti/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,ftomassetti/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,clumsy/intellij-community,ryano144/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,slisson/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,kool79/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,joewalnes/idea-community,asedunov/intellij-community,jagguli/intellij-community,nicolargo/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,vladmm/intellij-community,blademainer/intellij-community,consulo/consulo,ibinti/intellij-community,caot/intellij-community,apixandru/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,fitermay/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,apixandru/intellij-community,ahb0327/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,robovm/robovm-studio,SerCeMan/intellij-community,holmes/intellij-community,dslomov/intellij-community,hurricup/intellij-community,izonder/intellij-community,caot/intellij-community,petteyg/intellij-community,slisson/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,jexp/idea2,adedayo/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,alphafoobar/intellij-community,ernestp/consulo,caot/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,petteyg/intellij-community,samthor/intellij-community,joewalnes/idea-community,gnuhub/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,semonte/intellij-community,ivan-fedorov/intellij-community,TangHao1987/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,kdwink/intellij-community,jexp/idea2,tmpgit/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,adedayo/intellij-community,ivan-fedorov/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,pwoodworth/intellij-community,signed/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,adedayo/intellij-community,adedayo/intellij-community,allotria/intellij-community,petteyg/intellij-community,xfournet/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,semonte/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,wreckJ/intellij-community,slisson/intellij-community,da1z/intellij-community,ernestp/consulo,ftomassetti/intellij-community,kool79/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,jexp/idea2,petteyg/intellij-community,slisson/intellij-community,robovm/robovm-studio,mglukhikh/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,amith01994/intellij-community,kdwink/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community
package com.intellij.openapi.actionSystem.impl; import com.intellij.ide.DataManager; import com.intellij.ide.impl.DataManagerImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionButtonLook; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManagerListener; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.keymap.ex.WeakKeymapManagerListener; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.UiNotifyConnector; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; public class ActionToolbarImpl extends JPanel implements ActionToolbar { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionToolbarImpl"); /** * This array contains Rectangles which define bounds of the corresponding * components in the toolbar. This list can be considerer as a cache of the * Rectangle objects that are used in calculation of preferred sizes and * layouting of components. */ private final ArrayList<Rectangle> myComponentBounds = new ArrayList<Rectangle>(); private Dimension myMinimumButtonSize; /** * @see ActionToolbar#getLayoutPolicy() */ private int myLayoutPolicy; private int myOrientation; private final ActionGroup myActionGroup; private final String myPlace; @SuppressWarnings({"FieldCanBeLocal"}) private final MyKeymapManagerListener myKeymapManagerListener; @SuppressWarnings({"FieldCanBeLocal"}) private final MyTimerListener myTimerListener; private ArrayList<AnAction> myNewVisibleActions; protected ArrayList<AnAction> myVisibleActions; private final PresentationFactory myPresentationFactory; /** * @see ActionToolbar#adjustTheSameSize(boolean) */ private boolean myAdjustTheSameSize; private ActionButtonLook myButtonLook = null; private final DataManager myDataManager; protected final ActionManagerEx myActionManager; private Rectangle myAutoPopupRec; private final Icon myAutoPopupIcon = IconLoader.getIcon("/ide/link.png"); private final KeymapManagerEx myKeymapManager; private int myFirstOusideIndex = -1; private JBPopup myPopup; private JComponent myTargetComponent; private boolean myReservePlaceAutoPopupIcon = true; public ActionToolbarImpl(final String place, final ActionGroup actionGroup, final boolean horizontal, DataManager dataManager, ActionManagerEx actionManager, KeymapManagerEx keymapManager) { super(null); myActionManager = actionManager; myKeymapManager = keymapManager; setMinimumButtonSize(DEFAULT_MINIMUM_BUTTON_SIZE); setLayoutPolicy(AUTO_LAYOUT_POLICY); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); myPlace = place; myActionGroup = actionGroup; myPresentationFactory = new PresentationFactory(); myKeymapManagerListener = new MyKeymapManagerListener(); myTimerListener = new MyTimerListener(); myVisibleActions = new ArrayList<AnAction>(); myNewVisibleActions = new ArrayList<AnAction>(); myDataManager = dataManager; setLayout(new BorderLayout()); setOrientation(horizontal ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL); updateActions(); // keymapManager.addKeymapManagerListener(new WeakKeymapManagerListener(keymapManager, myKeymapManagerListener)); actionManager.addTimerListener(500, new WeakTimerListener(actionManager, myTimerListener)); // If the panel doesn't handle mouse event then it will be passed to its parent. // It means that if the panel is in slidindg mode then the focus goes to the editor // and panel will be automatically hidden. enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK); } private void updateActions() { final Application app = ApplicationManager.getApplication(); if (!app.isUnitTestMode() && !app.isHeadlessEnvironment()) { if (app.isDispatchThread()) { updateActionsImmediately(); } else { UiNotifyConnector.doWhenFirstShown(this, new Runnable() { public void run() { updateActionsImmediately(); } }); } } } public JComponent getComponent() { return this; } public int getLayoutPolicy() { return myLayoutPolicy; } public void setLayoutPolicy(final int layoutPolicy) { if (layoutPolicy != NOWRAP_LAYOUT_POLICY && layoutPolicy != WRAP_LAYOUT_POLICY && layoutPolicy != AUTO_LAYOUT_POLICY) { throw new IllegalArgumentException("wrong layoutPolicy: " + layoutPolicy); } myLayoutPolicy = layoutPolicy; } protected void paintComponent(final Graphics g) { super.paintComponent(g); if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { if (myAutoPopupRec != null) { if (myOrientation == SwingConstants.HORIZONTAL) { final int dy = myAutoPopupRec.height / 2 - myAutoPopupIcon.getIconHeight() / 2; myAutoPopupIcon.paintIcon(this, g, (int)myAutoPopupRec.getMaxX() - myAutoPopupIcon.getIconWidth() - 1, myAutoPopupRec.y + dy); } else { final int dx = myAutoPopupRec.width / 2 - myAutoPopupIcon.getIconWidth() / 2; myAutoPopupIcon.paintIcon(this, g, myAutoPopupRec.x + dx, (int)myAutoPopupRec.getMaxY() - myAutoPopupIcon.getIconWidth() - 1); } } } } private void fillToolBar(final ArrayList<AnAction> actions) { for (int i = 0; i < actions.size(); i++) { final AnAction action = actions.get(i); if (action instanceof Separator) { if (i > 0 && i < actions.size() - 1) { add(new MySeparator()); } } else if (action instanceof CustomComponentAction) { add(((CustomComponentAction)action).createCustomComponent(myPresentationFactory.getPresentation(action))); } else { final ActionButton button = createToolbarButton(action); add(button); } } } public ActionButton createToolbarButton(final AnAction action, final ActionButtonLook look, final String place, final Presentation presentation, final Dimension minimumSize) { if (action.displayTextInToolbar()) { return new ActionButtonWithText(action, presentation, place, minimumSize); } final ActionButton actionButton = new ActionButton(action, presentation, place, minimumSize) { protected DataContext getDataContext() { return getToolbarDataContext(); } }; actionButton.setLook(look); return actionButton; } private ActionButton createToolbarButton(final AnAction action) { return createToolbarButton(action, myButtonLook, myPlace, myPresentationFactory.getPresentation(action), myMinimumButtonSize); } public void doLayout() { if (!isValid()) { calculateBounds(getSize(), myComponentBounds); } final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= myComponentBounds.size()); for (int i = componentCount - 1; i >= 0; i--) { final Component component = getComponent(i); component.setBounds(myComponentBounds.get(i)); } } public void validate() { if (!isValid()) { calculateBounds(getSize(), myComponentBounds); super.validate(); } } /** * @return maximum button width */ private int getMaxButtonWidth() { int width = 0; for (int i = 0; i < getComponentCount(); i++) { final Dimension dimension = getComponent(i).getPreferredSize(); width = Math.max(width, dimension.width); } return width; } /** * @return maximum button height */ public int getMaxButtonHeight() { int height = 0; for (int i = 0; i < getComponentCount(); i++) { final Dimension dimension = getComponent(i).getPreferredSize(); height = Math.max(height, dimension.height); } return height; } private void calculateBoundsNowrapImpl(ArrayList<Rectangle> bounds) { final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final int width = getWidth(); final int height = getHeight(); if (myAdjustTheSameSize) { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); if (myOrientation == SwingConstants.HORIZONTAL) { int xOffset = 0; for (int i = 0; i < componentCount; i++) { final Rectangle r = bounds.get(i); r.setBounds(xOffset, (height - maxHeight) / 2, maxWidth, maxHeight); xOffset += maxWidth; } } else { int yOffset = 0; for (int i = 0; i < componentCount; i++) { final Rectangle r = bounds.get(i); r.setBounds((width - maxWidth) / 2, yOffset, maxWidth, maxHeight); yOffset += maxHeight; } } } else { if (myOrientation == SwingConstants.HORIZONTAL) { final int maxHeight = getMaxButtonHeight(); int xOffset = 0; final int yOffset = 0; for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); final Dimension d = component.getPreferredSize(); final Rectangle r = bounds.get(i); r.setBounds(xOffset, yOffset + (maxHeight - d.height) / 2, d.width, d.height); xOffset += d.width; } } else { final int maxWidth = getMaxButtonWidth(); final int xOffset = 0; int yOffset = 0; for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); final Dimension d = component.getPreferredSize(); final Rectangle r = bounds.get(i); r.setBounds(xOffset + (maxWidth - d.width) / 2, yOffset, d.width, d.height); yOffset += d.height; } } } } private void calculateBoundsAutoImp(Dimension sizeToFit, ArrayList<Rectangle> bounds) { final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final boolean actualLayout = bounds == myComponentBounds; if (actualLayout) { myAutoPopupRec = null; } int autoButtonSize = myAutoPopupIcon.getIconWidth(); boolean full = false; if (myOrientation == SwingConstants.HORIZONTAL) { int eachX = 0; int eachY = 0; for (int i = 0; i < componentCount; i++) { final Rectangle eachBound = new Rectangle(getComponent(i).getPreferredSize()); if (!full) { boolean outside; if (i < componentCount - 1) { outside = eachX + eachBound.width + autoButtonSize <= sizeToFit.width; } else { outside = eachX + eachBound.width <= sizeToFit.width; } if (outside) { eachBound.x = eachX; eachBound.y = eachY; eachX += eachBound.width; } else { full = true; } } if (full) { if (myAutoPopupRec == null) { myAutoPopupRec = new Rectangle(eachX, eachY, sizeToFit.width - eachX - 1, sizeToFit.height - 1); myFirstOusideIndex = i; } eachBound.x = Integer.MAX_VALUE; eachBound.y = Integer.MAX_VALUE; } bounds.get(i).setBounds(eachBound); } } else { int eachX = 0; int eachY = 0; for (int i = 0; i < componentCount; i++) { final Rectangle eachBound = new Rectangle(getComponent(i).getPreferredSize()); if (!full) { boolean outside; if (i < componentCount - 1) { outside = eachY + eachBound.height + autoButtonSize < sizeToFit.height; } else { outside = eachY + eachBound.height < sizeToFit.height; } if (outside) { eachBound.x = eachX; eachBound.y = eachY; eachY += eachBound.height; } else { full = true; } } if (full) { if (myAutoPopupRec == null) { myAutoPopupRec = new Rectangle(eachX, eachY, sizeToFit.width - 1, sizeToFit.height - eachY - 1); myFirstOusideIndex = i; } eachBound.x = Integer.MAX_VALUE; eachBound.y = Integer.MAX_VALUE; } bounds.get(i).setBounds(eachBound); } } } private void calculateBoundsWrapImpl(Dimension sizeToFit, ArrayList<Rectangle> bounds) { // We have to gracefull handle case when toolbar was not layed out yet. // In this case we calculate bounds as it is a NOWRAP toolbar. if (getWidth() == 0 || getHeight() == 0) { try { setLayoutPolicy(NOWRAP_LAYOUT_POLICY); calculateBoundsNowrapImpl(bounds); } finally { setLayoutPolicy(WRAP_LAYOUT_POLICY); } return; } final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); if (myAdjustTheSameSize) { if (myOrientation == SwingConstants.HORIZONTAL) { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 row toolbar final int maxRowWidth = Math.max(sizeToFit.width, componentCount * maxWidth / 3); for (int i = 0; i < componentCount; i++) { if (xOffset + maxWidth > maxRowWidth) { // place component at new row xOffset = 0; yOffset += maxHeight; } final Rectangle each = bounds.get(i); each.setBounds(xOffset, maxWidth, yOffset, maxHeight); xOffset += maxWidth; } } else { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 column toolbar final int maxRowHeight = Math.max(sizeToFit.height, componentCount * myMinimumButtonSize.height / 3); for (int i = 0; i < componentCount; i++) { if (yOffset + maxHeight > maxRowHeight) { // place component at new row yOffset = 0; xOffset += maxWidth; } final Rectangle each = bounds.get(i); each.setBounds(xOffset, maxWidth, yOffset, maxHeight); yOffset += maxHeight; } } } else { if (myOrientation == SwingConstants.HORIZONTAL) { // Calculate row height int rowHeight = 0; final Dimension[] dims = new Dimension[componentCount]; // we will use this dimesions later for (int i = 0; i < componentCount; i++) { dims[i] = getComponent(i).getPreferredSize(); final int height = dims[i].height; rowHeight = Math.max(rowHeight, height); } // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 row toolbar final int maxRowWidth = Math.max(getWidth(), componentCount * myMinimumButtonSize.width / 3); for (int i = 0; i < componentCount; i++) { final Dimension d = dims[i]; if (xOffset + d.width > maxRowWidth) { // place component at new row xOffset = 0; yOffset += rowHeight; } final Rectangle each = bounds.get(i); each.setBounds(xOffset, yOffset + (rowHeight - d.height) / 2, d.width, d.height); xOffset += d.width; } } else { // Calculate row width int rowWidth = 0; final Dimension[] dims = new Dimension[componentCount]; // we will use this dimesions later for (int i = 0; i < componentCount; i++) { dims[i] = getComponent(i).getPreferredSize(); final int width = dims[i].width; rowWidth = Math.max(rowWidth, width); } // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 column toolbar final int maxRowHeight = Math.max(getHeight(), componentCount * myMinimumButtonSize.height / 3); for (int i = 0; i < componentCount; i++) { final Dimension d = dims[i]; if (yOffset + d.height > maxRowHeight) { // place component at new row yOffset = 0; xOffset += rowWidth; } final Rectangle each = bounds.get(i); each.setBounds(xOffset + (rowWidth - d.width) / 2, yOffset, d.width, d.height); yOffset += d.height; } } } } /** * Calculates bounds of all the components in the toolbar */ private void calculateBounds(Dimension size2Fit, ArrayList<Rectangle> bounds) { bounds.clear(); for (int i = 0; i < getComponentCount(); i++) { bounds.add(new Rectangle()); } if (myLayoutPolicy == NOWRAP_LAYOUT_POLICY) { calculateBoundsNowrapImpl(bounds); } else if (myLayoutPolicy == WRAP_LAYOUT_POLICY) { calculateBoundsWrapImpl(size2Fit, bounds); } else if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { calculateBoundsAutoImp(size2Fit, bounds); } else { throw new IllegalStateException("unknonw layoutPolicy: " + myLayoutPolicy); } } public Dimension getPreferredSize() { final ArrayList<Rectangle> bounds = new ArrayList<Rectangle>(); for (int i = 0; i < getComponentCount(); i++) { bounds.add(new Rectangle()); } calculateBounds(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE), bounds); int xLeft = Integer.MAX_VALUE; int yTop = Integer.MAX_VALUE; int xRight = Integer.MIN_VALUE; int yBottom = Integer.MIN_VALUE; for (int i = bounds.size() - 1; i >= 0; i--) { final Rectangle each = bounds.get(i); if (each.x == Integer.MAX_VALUE) continue; xLeft = Math.min(xLeft, each.x); yTop = Math.min(yTop, each.y); xRight = Math.max(xRight, each.x + each.width); yBottom = Math.max(yBottom, each.y + each.height); } final Dimension dimension = new Dimension(xRight - xLeft, yBottom - yTop); if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myReservePlaceAutoPopupIcon) { if (myOrientation == SwingConstants.HORIZONTAL) { dimension.width += myAutoPopupIcon.getIconWidth(); } else { dimension.height += myAutoPopupIcon.getIconHeight(); } } return dimension; } public Dimension getMinimumSize() { if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { return new Dimension(myAutoPopupIcon.getIconWidth(), myMinimumButtonSize.height); } else { return super.getMinimumSize(); } } private final class MySeparator extends JComponent { private final Dimension mySize; public MySeparator() { if (myOrientation == SwingConstants.HORIZONTAL) { mySize = new Dimension(6, 24); } else { mySize = new Dimension(24, 6); } } public Dimension getPreferredSize() { return mySize; } protected void paintComponent(final Graphics g) { g.setColor(UIUtil.getSeparatorShadow()); if (getParent() != null) { if (myOrientation == SwingConstants.HORIZONTAL) { UIUtil.drawLine(g, 3, 2, 3, getParent().getSize().height - 2); } else { UIUtil.drawLine(g, 2, 3, getParent().getSize().width - 2, 3); } } } } private final class MyKeymapManagerListener implements KeymapManagerListener { public void activeKeymapChanged(final Keymap keymap) { final int componentCount = getComponentCount(); for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); if (component instanceof ActionButton) { ((ActionButton)component).updateToolTipText(); } } } } private final class MyTimerListener implements TimerListener { public ModalityState getModalityState() { return ModalityState.stateForComponent(ActionToolbarImpl.this); } public void run() { if (!isShowing()) { return; } // do not update when a popup menu is shown (if popup menu contains action which is also in the toolbar, it should not be enabled/disabled) final MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager(); final MenuElement[] selectedPath = menuSelectionManager.getSelectedPath(); if (selectedPath.length > 0) { return; } // don't update toolbar if there is currently active modal dialog final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); if (window instanceof Dialog) { final Dialog dialog = (Dialog)window; if (dialog.isModal() && !SwingUtilities.isDescendingFrom(ActionToolbarImpl.this, dialog)) { return; } } updateActionsImmediately(); } } public void adjustTheSameSize(final boolean value) { if (myAdjustTheSameSize == value) { return; } myAdjustTheSameSize = value; revalidate(); } public void setMinimumButtonSize(@NotNull final Dimension size) { myMinimumButtonSize = size; for (int i = getComponentCount() - 1; i >= 0; i--) { final Component component = getComponent(i); if (component instanceof ActionButton) { final ActionButton button = (ActionButton)component; button.setMinimumButtonSize(size); } } revalidate(); } public void setOrientation(final int orientation) { if (SwingConstants.HORIZONTAL != orientation && SwingConstants.VERTICAL != orientation) { throw new IllegalArgumentException("wrong orientation: " + orientation); } myOrientation = orientation; } public void updateActionsImmediately() { ApplicationManager.getApplication().assertIsDispatchThread(); myNewVisibleActions.clear(); final DataContext dataContext = getDataContext(); Utils.expandActionGroup(myActionGroup, myNewVisibleActions, myPresentationFactory, dataContext, myPlace, myActionManager); if (!myNewVisibleActions.equals(myVisibleActions)) { // should rebuild UI final boolean changeBarVisibility = myNewVisibleActions.isEmpty() || myVisibleActions.isEmpty(); final ArrayList<AnAction> temp = myVisibleActions; myVisibleActions = myNewVisibleActions; myNewVisibleActions = temp; removeAll(); fillToolBar(myVisibleActions); if (changeBarVisibility) { revalidate(); } else { final Container parent = getParent(); if (parent != null) { parent.invalidate(); parent.validate(); } } repaint(); } } public void setTargetComponent(final JComponent component) { myTargetComponent = component; if (myTargetComponent != null && myTargetComponent.isVisible()) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { updateActions(); } }, ModalityState.stateForComponent(myTargetComponent)); } } protected DataContext getToolbarDataContext() { return getDataContext(); } protected DataContext getDataContext() { return myTargetComponent != null ? myDataManager.getDataContext(myTargetComponent) : ((DataManagerImpl)myDataManager).getDataContextTest(this); } protected void processMouseMotionEvent(final MouseEvent e) { super.processMouseMotionEvent(e); if (getLayoutPolicy() != AUTO_LAYOUT_POLICY) { return; } if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) { showAutoPopup(); } } private void showAutoPopup() { if (isPopupShowing()) return; final ActionGroup group; if (myOrientation == SwingConstants.HORIZONTAL) { group = myActionGroup; } else { final DefaultActionGroup outside = new DefaultActionGroup(); for (int i = myFirstOusideIndex; i < myVisibleActions.size(); i++) { outside.add(myVisibleActions.get(i)); } group = outside; } PopupToolbar popupToolbar = new PopupToolbar(myPlace, group, true, myDataManager, myActionManager, myKeymapManager) { protected void onOtherActionPerformed() { hidePopup(); } protected DataContext getDataContext() { return ActionToolbarImpl.this.getDataContext(); } }; popupToolbar.setLayoutPolicy(NOWRAP_LAYOUT_POLICY); Point location; if (myOrientation == SwingConstants.HORIZONTAL) { location = getLocationOnScreen(); } else { location = getLocationOnScreen(); location.y = location.y + getHeight() - popupToolbar.getPreferredSize().height; } final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(popupToolbar, null); builder.setResizable(false) .setRequestFocus(false) .setTitle(null) .setCancelOnClickOutside(true) .setCancelOnOtherWindowOpen(true) .setCancelCallback(new Computable<Boolean>() { public Boolean compute() { return myActionManager.isActionPopupStackEmpty(); } }) .setCancelOnMouseOutCallback(new MouseChecker() { public boolean check(final MouseEvent event) { return myAutoPopupRec != null && myActionManager.isActionPopupStackEmpty() && !new RelativeRectangle(ActionToolbarImpl.this, myAutoPopupRec).contains(new RelativePoint(event)); } }); builder.addListener(new JBPopupAdapter() { public void onClosed(final JBPopup popup) { processClosed(); } }); myPopup = builder.createPopup(); Disposer.register(myPopup, popupToolbar); myPopup.showInScreenCoordinates(this, location); final Window window = SwingUtilities.getWindowAncestor(this); if (window != null) { final ComponentAdapter componentAdapter = new ComponentAdapter() { public void componentResized(final ComponentEvent e) { hidePopup(); } public void componentMoved(final ComponentEvent e) { hidePopup(); } public void componentShown(final ComponentEvent e) { hidePopup(); } public void componentHidden(final ComponentEvent e) { hidePopup(); } }; window.addComponentListener(componentAdapter); Disposer.register(popupToolbar, new Disposable() { public void dispose() { window.removeComponentListener(componentAdapter); } }); } } private boolean isPopupShowing() { if (myPopup != null) { if (myPopup.getContent() != null) { return true; } } return false; } private void hidePopup() { if (myPopup != null) { myPopup.cancel(); processClosed(); } } private void processClosed() { if (myPopup == null) return; Disposer.dispose(myPopup); myPopup = null; updateActionsImmediately(); } abstract static class PopupToolbar extends ActionToolbarImpl implements AnActionListener, Disposable { public PopupToolbar(final String place, final ActionGroup actionGroup, final boolean horizontal, final DataManager dataManager, final ActionManagerEx actionManager, final KeymapManagerEx keymapManager) { super(place, actionGroup, horizontal, dataManager, actionManager, keymapManager); myActionManager.addAnActionListener(this); } public void dispose() { myActionManager.removeAnActionListener(this); } public void beforeActionPerformed(final AnAction action, final DataContext dataContext) { } public void afterActionPerformed(final AnAction action, final DataContext dataContext) { if (!myVisibleActions.contains(action)) { onOtherActionPerformed(); } } protected abstract void onOtherActionPerformed(); public void beforeEditorTyping(final char c, final DataContext dataContext) { } } public void setReservePlaceAutoPopupIcon(final boolean reserve) { myReservePlaceAutoPopupIcon = reserve; } }
platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
package com.intellij.openapi.actionSystem.impl; import com.intellij.ide.DataManager; import com.intellij.ide.impl.DataManagerImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.actionSystem.ex.ActionButtonLook; import com.intellij.openapi.actionSystem.ex.ActionManagerEx; import com.intellij.openapi.actionSystem.ex.AnActionListener; import com.intellij.openapi.actionSystem.ex.CustomComponentAction; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.application.Application; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.keymap.Keymap; import com.intellij.openapi.keymap.KeymapManagerListener; import com.intellij.openapi.keymap.ex.KeymapManagerEx; import com.intellij.openapi.keymap.ex.WeakKeymapManagerListener; import com.intellij.openapi.ui.popup.*; import com.intellij.openapi.util.Computable; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.IconLoader; import com.intellij.ui.awt.RelativePoint; import com.intellij.ui.awt.RelativeRectangle; import com.intellij.util.ui.UIUtil; import com.intellij.util.ui.update.UiNotifyConnector; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.awt.*; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.MouseEvent; import java.util.ArrayList; public class ActionToolbarImpl extends JPanel implements ActionToolbar { private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.actionSystem.impl.ActionToolbarImpl"); /** * This array contains Rectangles which define bounds of the corresponding * components in the toolbar. This list can be considerer as a cache of the * Rectangle objects that are used in calculation of preferred sizes and * layouting of components. */ private final ArrayList<Rectangle> myComponentBounds = new ArrayList<Rectangle>(); private Dimension myMinimumButtonSize; /** * @see ActionToolbar#getLayoutPolicy() */ private int myLayoutPolicy; private int myOrientation; private final ActionGroup myActionGroup; private final String myPlace; @SuppressWarnings({"FieldCanBeLocal"}) private final MyKeymapManagerListener myKeymapManagerListener; @SuppressWarnings({"FieldCanBeLocal"}) private final MyTimerListener myTimerListener; private ArrayList<AnAction> myNewVisibleActions; protected ArrayList<AnAction> myVisibleActions; private final PresentationFactory myPresentationFactory; /** * @see ActionToolbar#adjustTheSameSize(boolean) */ private boolean myAdjustTheSameSize; private ActionButtonLook myButtonLook = null; private final DataManager myDataManager; protected final ActionManagerEx myActionManager; private Rectangle myAutoPopupRec; private final Icon myAutoPopupIcon = IconLoader.getIcon("/ide/link.png"); private final KeymapManagerEx myKeymapManager; private int myFirstOusideIndex = -1; private JBPopup myPopup; private JComponent myTargetComponent; private boolean myReservePlaceAutoPopupIcon = true; public ActionToolbarImpl(final String place, final ActionGroup actionGroup, final boolean horizontal, DataManager dataManager, ActionManagerEx actionManager, KeymapManagerEx keymapManager) { super(null); myActionManager = actionManager; myKeymapManager = keymapManager; setMinimumButtonSize(DEFAULT_MINIMUM_BUTTON_SIZE); setLayoutPolicy(AUTO_LAYOUT_POLICY); setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); myPlace = place; myActionGroup = actionGroup; myPresentationFactory = new PresentationFactory(); myKeymapManagerListener = new MyKeymapManagerListener(); myTimerListener = new MyTimerListener(); myVisibleActions = new ArrayList<AnAction>(); myNewVisibleActions = new ArrayList<AnAction>(); myDataManager = dataManager; setLayout(new BorderLayout()); setOrientation(horizontal ? SwingConstants.HORIZONTAL : SwingConstants.VERTICAL); updateActions(); // keymapManager.addKeymapManagerListener(new WeakKeymapManagerListener(keymapManager, myKeymapManagerListener)); actionManager.addTimerListener(500, new WeakTimerListener(actionManager, myTimerListener)); // If the panel doesn't handle mouse event then it will be passed to its parent. // It means that if the panel is in slidindg mode then the focus goes to the editor // and panel will be automatically hidden. enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK | AWTEvent.MOUSE_EVENT_MASK); } private void updateActions() { final Application app = ApplicationManager.getApplication(); if (!app.isUnitTestMode() && !app.isHeadlessEnvironment()) { if (app.isDispatchThread()) { updateActionsImmediately(); } else { UiNotifyConnector.doWhenFirstShown(this, new Runnable() { public void run() { updateActionsImmediately(); } }); } } } public JComponent getComponent() { return this; } public int getLayoutPolicy() { return myLayoutPolicy; } public void setLayoutPolicy(final int layoutPolicy) { if (layoutPolicy != NOWRAP_LAYOUT_POLICY && layoutPolicy != WRAP_LAYOUT_POLICY && layoutPolicy != AUTO_LAYOUT_POLICY) { throw new IllegalArgumentException("wrong layoutPolicy: " + layoutPolicy); } myLayoutPolicy = layoutPolicy; } protected void paintComponent(final Graphics g) { super.paintComponent(g); if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { if (myAutoPopupRec != null) { if (myOrientation == SwingConstants.HORIZONTAL) { final int dy = myAutoPopupRec.height / 2 - myAutoPopupIcon.getIconHeight() / 2; myAutoPopupIcon.paintIcon(this, g, (int)myAutoPopupRec.getMaxX() - myAutoPopupIcon.getIconWidth() - 1, myAutoPopupRec.y + dy); } else { final int dx = myAutoPopupRec.width / 2 - myAutoPopupIcon.getIconWidth() / 2; myAutoPopupIcon.paintIcon(this, g, myAutoPopupRec.x + dx, (int)myAutoPopupRec.getMaxY() - myAutoPopupIcon.getIconWidth() - 1); } } } } private void fillToolBar(final ArrayList<AnAction> actions) { for (int i = 0; i < actions.size(); i++) { final AnAction action = actions.get(i); if (action instanceof Separator) { if (i > 0 && i < actions.size() - 1) { add(new MySeparator()); } } else if (action instanceof CustomComponentAction) { add(((CustomComponentAction)action).createCustomComponent(myPresentationFactory.getPresentation(action))); } else { final ActionButton button = createToolbarButton(action); add(button); } } } public ActionButton createToolbarButton(final AnAction action, final ActionButtonLook look, final String place, final Presentation presentation, final Dimension minimumSize) { if (action.displayTextInToolbar()) { return new ActionButtonWithText(action, presentation, place, minimumSize); } final ActionButton actionButton = new ActionButton(action, presentation, place, minimumSize) { protected DataContext getDataContext() { return getToolbarDataContext(); } }; actionButton.setLook(look); return actionButton; } private ActionButton createToolbarButton(final AnAction action) { return createToolbarButton(action, myButtonLook, myPlace, myPresentationFactory.getPresentation(action), myMinimumButtonSize); } public void doLayout() { if (!isValid()) { calculateBounds(getSize(), myComponentBounds); } final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= myComponentBounds.size()); for (int i = componentCount - 1; i >= 0; i--) { final Component component = getComponent(i); component.setBounds(myComponentBounds.get(i)); } } public void validate() { if (!isValid()) { calculateBounds(getSize(), myComponentBounds); super.validate(); } } /** * @return maximum button width */ private int getMaxButtonWidth() { int width = 0; for (int i = 0; i < getComponentCount(); i++) { final Dimension dimension = getComponent(i).getPreferredSize(); width = Math.max(width, dimension.width); } return width; } /** * @return maximum button height */ public int getMaxButtonHeight() { int height = 0; for (int i = 0; i < getComponentCount(); i++) { final Dimension dimension = getComponent(i).getPreferredSize(); height = Math.max(height, dimension.height); } return height; } private void calculateBoundsNowrapImpl(ArrayList<Rectangle> bounds) { final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final int width = getWidth(); final int height = getHeight(); if (myAdjustTheSameSize) { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); if (myOrientation == SwingConstants.HORIZONTAL) { int xOffset = 0; for (int i = 0; i < componentCount; i++) { final Rectangle r = bounds.get(i); r.setBounds(xOffset, (height - maxHeight) / 2, maxWidth, maxHeight); xOffset += maxWidth; } } else { int yOffset = 0; for (int i = 0; i < componentCount; i++) { final Rectangle r = bounds.get(i); r.setBounds((width - maxWidth) / 2, yOffset, maxWidth, maxHeight); yOffset += maxHeight; } } } else { if (myOrientation == SwingConstants.HORIZONTAL) { final int maxHeight = getMaxButtonHeight(); int xOffset = 0; final int yOffset = 0; for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); final Dimension d = component.getPreferredSize(); final Rectangle r = bounds.get(i); r.setBounds(xOffset, yOffset + (maxHeight - d.height) / 2, d.width, d.height); xOffset += d.width; } } else { final int maxWidth = getMaxButtonWidth(); final int xOffset = 0; int yOffset = 0; for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); final Dimension d = component.getPreferredSize(); final Rectangle r = bounds.get(i); r.setBounds(xOffset + (maxWidth - d.width) / 2, yOffset, d.width, d.height); yOffset += d.height; } } } } private void calculateBoundsAutoImp(Dimension sizeToFit, ArrayList<Rectangle> bounds) { final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); final boolean actualLayout = bounds == myComponentBounds; if (actualLayout) { myAutoPopupRec = null; } int autoButtonSize = myAutoPopupIcon.getIconWidth(); boolean full = false; if (myOrientation == SwingConstants.HORIZONTAL) { int eachX = 0; int eachY = 0; for (int i = 0; i < componentCount; i++) { final Rectangle eachBound = new Rectangle(getComponent(i).getPreferredSize()); if (!full) { boolean outside; if (i < componentCount - 1) { outside = eachX + eachBound.width + autoButtonSize <= sizeToFit.width; } else { outside = eachX + eachBound.width <= sizeToFit.width; } if (outside) { eachBound.x = eachX; eachBound.y = eachY; eachX += eachBound.width; } else { full = true; } } if (full) { if (myAutoPopupRec == null) { myAutoPopupRec = new Rectangle(eachX, eachY, sizeToFit.width - eachX - 1, sizeToFit.height - 1); myFirstOusideIndex = i; } eachBound.x = Integer.MAX_VALUE; eachBound.y = Integer.MAX_VALUE; } bounds.get(i).setBounds(eachBound); } } else { int eachX = 0; int eachY = 0; for (int i = 0; i < componentCount; i++) { final Rectangle eachBound = new Rectangle(getComponent(i).getPreferredSize()); if (!full) { boolean outside; if (i < componentCount - 1) { outside = eachY + eachBound.height + autoButtonSize < sizeToFit.height; } else { outside = eachY + eachBound.height < sizeToFit.height; } if (outside) { eachBound.x = eachX; eachBound.y = eachY; eachY += eachBound.height; } else { full = true; } } if (full) { if (myAutoPopupRec == null) { myAutoPopupRec = new Rectangle(eachX, eachY, sizeToFit.width - 1, sizeToFit.height - eachY - 1); myFirstOusideIndex = i; } eachBound.x = Integer.MAX_VALUE; eachBound.y = Integer.MAX_VALUE; } bounds.get(i).setBounds(eachBound); } } } private void calculateBoundsWrapImpl(Dimension sizeToFit, ArrayList<Rectangle> bounds) { // We have to gracefull handle case when toolbar was not layed out yet. // In this case we calculate bounds as it is a NOWRAP toolbar. if (getWidth() == 0 || getHeight() == 0) { try { setLayoutPolicy(NOWRAP_LAYOUT_POLICY); calculateBoundsNowrapImpl(bounds); } finally { setLayoutPolicy(WRAP_LAYOUT_POLICY); } return; } final int componentCount = getComponentCount(); LOG.assertTrue(componentCount <= bounds.size()); if (myAdjustTheSameSize) { if (myOrientation == SwingConstants.HORIZONTAL) { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 row toolbar final int maxRowWidth = Math.max(sizeToFit.width, componentCount * maxWidth / 3); for (int i = 0; i < componentCount; i++) { if (xOffset + maxWidth > maxRowWidth) { // place component at new row xOffset = 0; yOffset += maxHeight; } final Rectangle each = bounds.get(i); each.setBounds(xOffset, maxWidth, yOffset, maxHeight); xOffset += maxWidth; } } else { final int maxWidth = getMaxButtonWidth(); final int maxHeight = getMaxButtonHeight(); // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 column toolbar final int maxRowHeight = Math.max(sizeToFit.height, componentCount * myMinimumButtonSize.height / 3); for (int i = 0; i < componentCount; i++) { if (yOffset + maxHeight > maxRowHeight) { // place component at new row yOffset = 0; xOffset += maxWidth; } final Rectangle each = bounds.get(i); each.setBounds(xOffset, maxWidth, yOffset, maxHeight); yOffset += maxHeight; } } } else { if (myOrientation == SwingConstants.HORIZONTAL) { // Calculate row height int rowHeight = 0; final Dimension[] dims = new Dimension[componentCount]; // we will use this dimesions later for (int i = 0; i < componentCount; i++) { dims[i] = getComponent(i).getPreferredSize(); final int height = dims[i].height; rowHeight = Math.max(rowHeight, height); } // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 row toolbar final int maxRowWidth = Math.max(getWidth(), componentCount * myMinimumButtonSize.width / 3); for (int i = 0; i < componentCount; i++) { final Dimension d = dims[i]; if (xOffset + d.width > maxRowWidth) { // place component at new row xOffset = 0; yOffset += rowHeight; } final Rectangle each = bounds.get(i); each.setBounds(xOffset, yOffset + (rowHeight - d.height) / 2, d.width, d.height); xOffset += d.width; } } else { // Calculate row width int rowWidth = 0; final Dimension[] dims = new Dimension[componentCount]; // we will use this dimesions later for (int i = 0; i < componentCount; i++) { dims[i] = getComponent(i).getPreferredSize(); final int width = dims[i].width; rowWidth = Math.max(rowWidth, width); } // Lay components out int xOffset = 0; int yOffset = 0; // Calculate max size of a row. It's not possible to make more then 3 column toolbar final int maxRowHeight = Math.max(getHeight(), componentCount * myMinimumButtonSize.height / 3); for (int i = 0; i < componentCount; i++) { final Dimension d = dims[i]; if (yOffset + d.height > maxRowHeight) { // place component at new row yOffset = 0; xOffset += rowWidth; } final Rectangle each = bounds.get(i); each.setBounds(xOffset + (rowWidth - d.width) / 2, yOffset, d.width, d.height); yOffset += d.height; } } } } /** * Calculates bounds of all the components in the toolbar */ private void calculateBounds(Dimension size2Fit, ArrayList<Rectangle> bounds) { bounds.clear(); for (int i = 0; i < getComponentCount(); i++) { bounds.add(new Rectangle()); } if (myLayoutPolicy == NOWRAP_LAYOUT_POLICY) { calculateBoundsNowrapImpl(bounds); } else if (myLayoutPolicy == WRAP_LAYOUT_POLICY) { calculateBoundsWrapImpl(size2Fit, bounds); } else if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { calculateBoundsAutoImp(size2Fit, bounds); } else { throw new IllegalStateException("unknonw layoutPolicy: " + myLayoutPolicy); } } public Dimension getPreferredSize() { final ArrayList<Rectangle> bounds = new ArrayList<Rectangle>(); for (int i = 0; i < getComponentCount(); i++) { bounds.add(new Rectangle()); } calculateBounds(new Dimension(Integer.MAX_VALUE, Integer.MAX_VALUE), bounds); int xLeft = Integer.MAX_VALUE; int yTop = Integer.MAX_VALUE; int xRight = Integer.MIN_VALUE; int yBottom = Integer.MIN_VALUE; for (int i = bounds.size() - 1; i >= 0; i--) { final Rectangle each = bounds.get(i); if (each.x == Integer.MAX_VALUE) continue; xLeft = Math.min(xLeft, each.x); yTop = Math.min(yTop, each.y); xRight = Math.max(xRight, each.x + each.width); yBottom = Math.max(yBottom, each.y + each.height); } final Dimension dimension = new Dimension(xRight - xLeft, yBottom - yTop); if (myLayoutPolicy == AUTO_LAYOUT_POLICY && myReservePlaceAutoPopupIcon) { if (myOrientation == SwingConstants.HORIZONTAL) { dimension.width += myAutoPopupIcon.getIconWidth(); } else { dimension.height += myAutoPopupIcon.getIconHeight(); } } return dimension; } public Dimension getMinimumSize() { if (myLayoutPolicy == AUTO_LAYOUT_POLICY) { return new Dimension(myAutoPopupIcon.getIconWidth(), myMinimumButtonSize.height); } else { return super.getMinimumSize(); } } private final class MySeparator extends JComponent { private final Dimension mySize; public MySeparator() { if (myOrientation == SwingConstants.HORIZONTAL) { mySize = new Dimension(6, 24); } else { mySize = new Dimension(24, 6); } } public Dimension getPreferredSize() { return mySize; } protected void paintComponent(final Graphics g) { g.setColor(UIUtil.getSeparatorShadow()); if (getParent() != null) { if (myOrientation == SwingConstants.HORIZONTAL) { UIUtil.drawLine(g, 3, 2, 3, getParent().getSize().height - 2); } else { UIUtil.drawLine(g, 2, 3, getParent().getSize().width - 2, 3); } } } } private final class MyKeymapManagerListener implements KeymapManagerListener { public void activeKeymapChanged(final Keymap keymap) { final int componentCount = getComponentCount(); for (int i = 0; i < componentCount; i++) { final Component component = getComponent(i); if (component instanceof ActionButton) { ((ActionButton)component).updateToolTipText(); } } } } private final class MyTimerListener implements TimerListener { public ModalityState getModalityState() { return ModalityState.stateForComponent(ActionToolbarImpl.this); } public void run() { if (!isShowing()) { return; } // do not update when a popup menu is shown (if popup menu contains action which is also in the toolbar, it should not be enabled/disabled) final MenuSelectionManager menuSelectionManager = MenuSelectionManager.defaultManager(); final MenuElement[] selectedPath = menuSelectionManager.getSelectedPath(); if (selectedPath.length > 0) { return; } // don't update toolbar if there is currently active modal dialog final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow(); if (window instanceof Dialog) { final Dialog dialog = (Dialog)window; if (dialog.isModal() && !SwingUtilities.isDescendingFrom(ActionToolbarImpl.this, dialog)) { return; } } updateActionsImmediately(); } } public void adjustTheSameSize(final boolean value) { if (myAdjustTheSameSize == value) { return; } myAdjustTheSameSize = value; revalidate(); } public void setMinimumButtonSize(@NotNull final Dimension size) { myMinimumButtonSize = size; for (int i = getComponentCount() - 1; i >= 0; i--) { final Component component = getComponent(i); if (component instanceof ActionButton) { final ActionButton button = (ActionButton)component; button.setMinimumButtonSize(size); } } revalidate(); } public void setOrientation(final int orientation) { if (SwingConstants.HORIZONTAL != orientation && SwingConstants.VERTICAL != orientation) { throw new IllegalArgumentException("wrong orientation: " + orientation); } myOrientation = orientation; } public void updateActionsImmediately() { ApplicationManager.getApplication().assertIsDispatchThread(); myNewVisibleActions.clear(); final DataContext dataContext = getDataContext(); Utils.expandActionGroup(myActionGroup, myNewVisibleActions, myPresentationFactory, dataContext, myPlace, myActionManager); if (!myNewVisibleActions.equals(myVisibleActions)) { // should rebuild UI final boolean changeBarVisibility = myNewVisibleActions.isEmpty() || myVisibleActions.isEmpty(); final ArrayList<AnAction> temp = myVisibleActions; myVisibleActions = myNewVisibleActions; myNewVisibleActions = temp; removeAll(); fillToolBar(myVisibleActions); if (changeBarVisibility) { revalidate(); } else { final Container parent = getParent(); if (parent != null) { parent.invalidate(); parent.validate(); } } repaint(); } } public void setTargetComponent(final JComponent component) { myTargetComponent = component; updateActions(); } protected DataContext getToolbarDataContext() { return getDataContext(); } protected DataContext getDataContext() { return myTargetComponent != null ? myDataManager.getDataContext(myTargetComponent) : ((DataManagerImpl)myDataManager).getDataContextTest(this); } protected void processMouseMotionEvent(final MouseEvent e) { super.processMouseMotionEvent(e); if (getLayoutPolicy() != AUTO_LAYOUT_POLICY) { return; } if (myAutoPopupRec != null && myAutoPopupRec.contains(e.getPoint())) { showAutoPopup(); } } private void showAutoPopup() { if (isPopupShowing()) return; final ActionGroup group; if (myOrientation == SwingConstants.HORIZONTAL) { group = myActionGroup; } else { final DefaultActionGroup outside = new DefaultActionGroup(); for (int i = myFirstOusideIndex; i < myVisibleActions.size(); i++) { outside.add(myVisibleActions.get(i)); } group = outside; } PopupToolbar popupToolbar = new PopupToolbar(myPlace, group, true, myDataManager, myActionManager, myKeymapManager) { protected void onOtherActionPerformed() { hidePopup(); } protected DataContext getDataContext() { return ActionToolbarImpl.this.getDataContext(); } }; popupToolbar.setLayoutPolicy(NOWRAP_LAYOUT_POLICY); Point location; if (myOrientation == SwingConstants.HORIZONTAL) { location = getLocationOnScreen(); } else { location = getLocationOnScreen(); location.y = location.y + getHeight() - popupToolbar.getPreferredSize().height; } final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(popupToolbar, null); builder.setResizable(false) .setRequestFocus(false) .setTitle(null) .setCancelOnClickOutside(true) .setCancelOnOtherWindowOpen(true) .setCancelCallback(new Computable<Boolean>() { public Boolean compute() { return myActionManager.isActionPopupStackEmpty(); } }) .setCancelOnMouseOutCallback(new MouseChecker() { public boolean check(final MouseEvent event) { return myAutoPopupRec != null && myActionManager.isActionPopupStackEmpty() && !new RelativeRectangle(ActionToolbarImpl.this, myAutoPopupRec).contains(new RelativePoint(event)); } }); builder.addListener(new JBPopupAdapter() { public void onClosed(final JBPopup popup) { processClosed(); } }); myPopup = builder.createPopup(); Disposer.register(myPopup, popupToolbar); myPopup.showInScreenCoordinates(this, location); final Window window = SwingUtilities.getWindowAncestor(this); if (window != null) { final ComponentAdapter componentAdapter = new ComponentAdapter() { public void componentResized(final ComponentEvent e) { hidePopup(); } public void componentMoved(final ComponentEvent e) { hidePopup(); } public void componentShown(final ComponentEvent e) { hidePopup(); } public void componentHidden(final ComponentEvent e) { hidePopup(); } }; window.addComponentListener(componentAdapter); Disposer.register(popupToolbar, new Disposable() { public void dispose() { window.removeComponentListener(componentAdapter); } }); } } private boolean isPopupShowing() { if (myPopup != null) { if (myPopup.getContent() != null) { return true; } } return false; } private void hidePopup() { if (myPopup != null) { myPopup.cancel(); processClosed(); } } private void processClosed() { if (myPopup == null) return; Disposer.dispose(myPopup); myPopup = null; updateActionsImmediately(); } abstract static class PopupToolbar extends ActionToolbarImpl implements AnActionListener, Disposable { public PopupToolbar(final String place, final ActionGroup actionGroup, final boolean horizontal, final DataManager dataManager, final ActionManagerEx actionManager, final KeymapManagerEx keymapManager) { super(place, actionGroup, horizontal, dataManager, actionManager, keymapManager); myActionManager.addAnActionListener(this); } public void dispose() { myActionManager.removeAnActionListener(this); } public void beforeActionPerformed(final AnAction action, final DataContext dataContext) { } public void afterActionPerformed(final AnAction action, final DataContext dataContext) { if (!myVisibleActions.contains(action)) { onOtherActionPerformed(); } } protected abstract void onOtherActionPerformed(); public void beforeEditorTyping(final char c, final DataContext dataContext) { } } public void setReservePlaceAutoPopupIcon(final boolean reserve) { myReservePlaceAutoPopupIcon = reserve; } }
[revd lesya] Make update actions on setTargetComponent() async, since it otherwise is being called on partially initialized UI classes.
platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
[revd lesya] Make update actions on setTargetComponent() async, since it otherwise is being called on partially initialized UI classes.
<ide><path>latform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java <ide> import com.intellij.openapi.actionSystem.ex.ActionManagerEx; <ide> import com.intellij.openapi.actionSystem.ex.AnActionListener; <ide> import com.intellij.openapi.actionSystem.ex.CustomComponentAction; <add>import com.intellij.openapi.application.Application; <ide> import com.intellij.openapi.application.ApplicationManager; <ide> import com.intellij.openapi.application.ModalityState; <del>import com.intellij.openapi.application.Application; <ide> import com.intellij.openapi.diagnostic.Logger; <ide> import com.intellij.openapi.keymap.Keymap; <ide> import com.intellij.openapi.keymap.KeymapManagerListener; <ide> <ide> public void setTargetComponent(final JComponent component) { <ide> myTargetComponent = component; <del> updateActions(); <add> <add> if (myTargetComponent != null && myTargetComponent.isVisible()) { <add> ApplicationManager.getApplication().invokeLater(new Runnable() { <add> public void run() { <add> updateActions(); <add> } <add> }, ModalityState.stateForComponent(myTargetComponent)); <add> } <ide> } <ide> <ide> protected DataContext getToolbarDataContext() {
JavaScript
agpl-3.0
6c9b75cccb64907a4f07203f8f98a475f620fc0a
0
debiki/debiki-server-old,debiki/debiki-server-old,debiki/debiki-server-old,debiki/debiki-server-old
/* Debiki Utterscroll — dragscroll everywhere, adjusted to run in an <iframe> too. * http://www.debiki.com/dev/utterscroll * * Copyright (c) 2012 - 2013 Kaj Magnus Lindberg (born 1979) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ //---------------------------------------- (function($){ //---------------------------------------- var d = { i: debiki.internal, u: debiki.v0.util }; if (!debiki.Utterscroll) debiki.Utterscroll = {}; /** * Utterscroll. API: * * `enable(options)` enables Utterscroll. Options: * scrollstoppers: * jQuery selectors, e.g. '.CodeMirror, div.your-class'. * Dragging the mouse inside a scrollstopper never results in scrolling. * * `enable()` (with no options specified) enables Utterscroll and remembers * any option you specified the last time you did specify options. * * `disable()` * * `isEnabled()` * * `isScrolling()` is true iff the user is currently dragscrolling. */ debiki.Utterscroll = (function(options) { // Don't call console.debug in IE 9 (and 7 & 8); it's not available unless // the dev tools window is open. Use this safe wrapper instead of // console.log. (COULD make separate Prod and Dev builds, filter out logging) var debug = (typeof console === 'undefined' || !console.debug) ? function() {} : function() { console.debug.apply(console, arguments); }; var defaults = { defaultScrollstoppers: 'a, area, button, command, input, keygen, label,'+ ' option, select, textarea, video', // ?? canvas, embed, object scrollstoppers: '', onMousedownOnWinVtclScrollbar: function() {}, onMousedownOnWinHztlScrollbar: function() {}, onHasUtterscrolled: function() {} }; var enabled; var settings; var allScrollstoppers; var $elemToScroll; var startPos; var lastPos; // Avoids firing onHasUtterscrolled twice. var hasFiredHasUtterscrolled = false; // We fire onHasUtterscrolled, when the user has scrolled more than this. var fireHasUtterscrolledMinDist = 15; // pixels // Helps detect usage of the browser window scrollbars. var $viewportGhost = $('<div style="width: 100%; height: 100%;' + ' position: fixed; top: 0; left: 0; z-index: -999"></div>') .appendTo(document.body); $(document).mousedown(startScrollPerhaps); $(document).mousemove(checkIfMissedMousedown); var lastButtons = 0; var mousedownNoticed = false; /** * Firefox bug workaround. * * When Debiki Utterscroll is used both in an <iframe> and in the parent * window, and cooperates via postMessage, then mousedown and mouseup events * are sometimes lost, in Firefox 26 (and Kubuntu Linux) at least. * This function checks `event.buttons` to find out if a mousedown event was * missed, and, if so, starts scrolling. */ function checkIfMissedMousedown(event) { if (lastButtons === 0 && event.buttons === 1 && !mousedownNoticed) { // There was a mousedown that we never noticed, because of some browser // bug/issue probably related to <iframe>s. So fake a click and perhaps // start scrolling. lastButtons = event.buttons; event.which = 1; debug('Mousedown event missed, calling startScroll(event)'); // We don't know where the mouse was when it was clicked. However since // the mousedown event was lost, no text selection has started? And it's // better to start scrolling, as far as I've experienced. startScroll(event); return false; } }; function startScrollPerhaps(event) { mousedownNoticed = true; if (!enabled) return; // Only left button drag-scrolls. if (event.which !== 1 ) return; // Never scroll, when mouse down on certain elems. var $target = $(event.target); var $noScrollElem = $target.closest(allScrollstoppers); if ($noScrollElem.length > 0) return; // Fire event and cancel, on browser window scrollbar click. // - In Chrome, IE and FF, but not in Opera, when you mousedown on // a scrollbar, a mousedown event happens. // - The subsequent fix (for scrollbars in general) cannot handle the // *window* scrollbar case, because the <html> elem can be smaller // than the viewport, so checking that the mousedown // didn't happen inside the <html> elem won't work. We need // $viewportGhost, which always covers the whole viewport. if (event.pageX > $viewportGhost.offset().left + $viewportGhost.width()) { // Vertical scrollbar mousedown:ed. settings.onMousedownOnWinVtclScrollbar(); return; } if (event.pageY > $viewportGhost.offset().top + $viewportGhost.height()) { // Horizontal scrollbar mousedown:ed. settings.onMousedownOnWinHztlScrollbar(); return; } // Cancel if scrollbar clicked (other than the browser window scrollbars). // - Related: In Chrome, "Scrollbar triggers onmousedown, but fails to // trigger onmouseup". (Also mousemove won't happen!) // See http://code.google.com/p/chromium/issues/detail?id=14204. // - The workaround: Place a wigth & height 100% elem, $ghost, // inside $target, and if the mousedown position is not iside $ghost, // then the scrollbars were clicked. // (What about overflow === 'inherit'? Would anyone ever use that?) if ($target.css('overflow') === 'auto' || $target.css('overflow') === 'scroll') { // Okay, scrollbars might have been clicked, in Chrome. var $ghost = $('<div style="width: 100%; height: 100%; ' + 'position: absolute;"></div>'); // Specify top and left, so $ghost fills up the visible part of // $target, even if $target contains scrollbars that have been scrolled. $ghost.css({ top: $target.scrollTop(), left: $target.scrollLeft() }); var targetPosOrig = $target.css('position'); $target.css('position', 'relative'); $target.prepend($ghost) // Now $ghost fills up $target, up to the scrollbars. // Check if the click happened outside $ghost. var isScrollbar = false; if (event.pageX > $ghost.offset().left + $ghost.width()) isScrollbar = true; // vertical scrollbar clicked, don't dragscroll if (event.pageY > $ghost.offset().top + $ghost.height()) isScrollbar = true; // horizontal scrollbar clicked $ghost.remove(); $target.css('position', targetPosOrig); if (isScrollbar) return; } // Find the closest elem with scrollbars. // If the ':scrollable' selector isn't available, scroll the window. // Also don't scroll `html' and `body' — scroll `window' instead, that // works better across all browsers. $elemToScroll = $.expr[':'].scrollable ? $target.closest(':scrollable:not(html, body)').add($(window)).first() : $(window); // Scroll, unless the mouse down is a text selection attempt: // ----- // If there's no text in the event.target, then start scrolling. var containsText = searchForTextIn($target, 0); debug(event.target.nodeName +' containsText: '+ containsText); if (!containsText) return startScroll(event); function searchForTextIn($elem, recursionDepth) { if (recursionDepth > 6) return false; var $textElems = $elem.contents().filter(function(ix, child, ar) { // Is it a true text node with text? // BUG? What about CDATA? Isn't that text? (node type 4) if (child.nodeType === 3) { // 3 is text var onlyWhitespace = child.data.match(/^\s*$/); return !onlyWhitespace; } // Skip comments (or script dies in FF) if (child.nodeType === 8) // 8 is comment return false; // COULD skip some more node types? Which? // And should also test and verify afterwards. // Recurse into inline elems — I think they often contain // text? E.g. <li><a>...</a></li> or <p><small>...</small></p>. var $child = $(child); if ($child.css('display') === 'inline') { var foundText = searchForTextIn($child, recursionDepth + 1); return foundText; } // Skip block level children. If text in them is to be selected, // the user needs to click on those blocks. (Recursing into // block level elems could search the whole page, should you // click the <html> elem!) return false; }); return $textElems.length > 0; }; // Start scrolling if mouse press happened not very close to text. var dist = distFromTextToEvent($target, event); debug('Approx dist from $target text to mouse: '+ dist); if (dist === -1 || dist > 55) return startScroll(event); // Don't scroll and don't event.preventDefault(). — The user should be able // to e.g. click buttons and select text. }; /** * Finds the approximate closest distance from text in $elem to event. */ function distFromTextToEvent($elem, event) { // I don't think there's any built in browser support that helps // us to find the distance. // Therefore, place many magic marks inside $elem, and check the // distance from each mark to the mousedown evenet. Then return // the shortest distance. // We have no idea where the text line-wraps, so we cannot be // clever about where to insert the marks. // {{{ Two vaguely related StackOverflow questions. // <http://stackoverflow.com/questions/1589721/ // how-can-i-position-an-element-next-to-user-text-selection> // <http://stackoverflow.com/questions/2031518/ // javascript-selection-range-coordinates> }}} // Add marks to a copy of $elem's inner html. var $parent = $elem; var innerHtmlBefore = $parent.html(); var mark = '<span class="utrscrlhlpr"/>'; // First replace all html tags with a placeholder. // (When we add marks, we don't want to add them inside tags.) // (It seems any '<' in attribute values have been escaped to '&lt;') var savedTags = []; var innerHtmlNoTags = innerHtmlBefore.replace(/<[^>]*>/g, function($0) { savedTags.push($0); return '·'; // COULD find a rarer utf-8 char? (Also update TagDog) }); // For now, insert a mark between every two chars. We need frequent // marks if the font size is huge. Could check font size of // all elems in $target, and reduce num chars between marks. // (For one single elem: parseInt($elem.css('font-size')); ) // But not needed? Performance is fine, on my computer :-) var htmlWithMarksNoTags = mark + innerHtmlNoTags.replace( /(\s*.{0,2})/g, '$1'+ mark); // Put back all html tags. var savedTagsIx = 0; var htmlWithMarks = htmlWithMarksNoTags.replace(/·/g, function() { savedTagsIx += 1; return savedTags[savedTagsIx - 1]; }); // Clone $parent, and insert the marks into the clone. // We won't modify $parent itself — doing that would 1) destroy any // text selection object (but other Javascript code might need it), // and perhaps 2) break other related Javascript code and event // bindings in other ways. // {{{ You might wonder what happens if $parent is the <html> and the page // is huge. This isn't likely to happen though, because we only run // this code for elems that contains text or inline elems with text, // and such blocks are usually small. Well written text contains // reasonably small paragraphs, no excessively huge blocks of text? }}} var $parentClone = $parent.clone(); $parentClone.html(htmlWithMarks); // Replace the parent with the clone, so we can use the clone in // distance measurements. But don't remove the parent — that would // destroy any text selection. // One minor (?) issues/bug: // If the $parent is positioned via CSS like :last-child or // :only-child, that CSS wouldn't be applied to the clone, so distance // measurement might become inaccurate. // Is this unavoidable? We cannot remove the real $parent, or we'd // destroy the text selection (if there is one). $parentClone.insertBefore($parent); // {{{ Alternative approach // Place with 'position: absolute' the clone on the parent. // // However, if the start of the parent isn't at the parent's upper // left corner, word wrapping in the parent and the clone won't be // identical. Example: // |text text text text text text text text text text text| // |text text text text text text text<small>parent parent| // |parent parent</small> | // If you clone <small> and 'position: absolute' the clone on // the original <small>, the clone will have no line wraps, // but look like so: // |text text text text text text text text text text text| // —> |<small>parent parent parent parent</small>xt text text| // |parent parent</small> | // Possible solution: Find the closest elem with display: block, // and clone it. Then word wraps should become identical? // //$parentClone // .css({ // width: $parent.width(), // height: $parent.height(), // position: 'absolute' // }) // .insertBefore($parent) // .position({ my: 'left top', at: 'left top', of: $parent }); // // }}} // Find mousedown position relative document. // (This is supposedly cross browser compatible, see e.g. // http://stackoverflow.com/a/4430498/694469.) var mouseOffs; if (event.pageX || event.pageY) { mouseOffs = { x: event.pageX, y: event.pageY }; } else { var d = document; mouseOffs = { x: event.screenX + d.body.scrollLeft + d.documentElement.scrollLeft, y: event.screenY + d.body.scrollTop + d.documentElement.scrollTop }; } // Find min distance from [the marks inside the clone] to the mouse pos. var minDist2 = 999999999; $parentClone.find('.utrscrlhlpr').each(function() { var myOffs = $(this).offset(); var distX = mouseOffs.x - myOffs.left; var distY = mouseOffs.y - myOffs.top; var dist2 = distX * distX + distY * distY; if (dist2 < minDist2) { minDist2 = dist2; // debug('New max dist from: '+ myOffs.left +','+ myOffs.top + // ' to: '+ mouseOffs.x +','+ mouseOffs.y +' is: '+ dist2); } }); $parentClone.remove(); return Math.sqrt(minDist2); }; function startScroll(event) { $(document).mousemove(doScroll); $(document).mouseup(stopScroll); $(document.body).css('cursor', 'move'); // Y is the distance to the top. startPos = { x: event.screenX, y: event.screenY }; lastPos = { x: event.screenX, y: event.screenY }; if (d.i.isInIframe) window.parent.postMessage(['startUtterscrolling', cloneEvent(event)], '*'); return false; }; function doScroll(event) { // <iframe> FireFox issue workaround: (FF version 26 on Ubuntu Linux at least) // Sometimes the mouseup event never happens, if Debiki runs in an <iframe>. // Neither in the <iframe> nor in the parent window. Therefore, detect if the mouse // button has actually been released and we should stop scrolling, like so: // (And reproduce the issue by opening a HTML page with Debiki embedded // comments in Firefox, then open Firebug, and dragscrolling so the // mouse enters the Firebug window, then release the mouse and move the // mouse back over the html window. Now you'll still be scrolling although // you've released the mouse button — were it not for this workaround.) if (event.buttons === 0) return stopScroll(event); if (d.i.isInIframe) { // Message to parent sent by other `document.onmousemove`, see the end of // this file. return; } // Find movement since mousedown, and since last scroll step. var distTotal = { x: Math.abs(event.screenX - startPos.x), y: Math.abs(event.screenY - startPos.y) }; var distNow = { x: event.screenX - lastPos.x, y: event.screenY - lastPos.y }; // Sometimes we should scroll in one direction only. if ($elemToScroll[0] === window) { // $(window).css('overflow-x') and '...-y' results in an error: // "Cannot read property 'defaultView' of undefined" // therefore, always scroll, if window viewport too small. } else { if ($elemToScroll.css('overflow-y') === 'hidden') distNow.y = 0; if ($elemToScroll.css('overflow-x') === 'hidden') distNow.x = 0; } // Trigger onHasUtterscrolled(), if scrolled > min distance. if (!hasFiredHasUtterscrolled && (distTotal.x * distTotal.x + distTotal.y * distTotal.y > fireHasUtterscrolledMinDist * fireHasUtterscrolledMinDist)) { hasFiredHasUtterscrolled = true; settings.onHasUtterscrolled(); } // var origDebug = ' orig: '+ distNow.x +', '+ distNow.y; // Scroll faster, if you've scrolled far. // Then you can easily move viewport // large distances, and still retain high precision when // moving small distances. (The calculations below are just // heuristics that works well on my computer.) // Don't move too fast for Opera though: it re-renders the screen // slowly (unbearably slowly if there're lots of SVG arrows!) and // the reported mouse movement distances would becom terribly huge, // e.g. 1000px, and then the viewport jumps randomly. var mul; if (distTotal.x > 9){ mul = Math.log((distTotal.x - 9) / 3); if (mul > 1.7 && $.browser && $.browser.opera) mul = 1.7; // see comment above if (mul > 1) distNow.x *= mul; } if (distTotal.y > 5){ mul = Math.log((distTotal.y - 5) / 2); if (mul > 1.3 && $.browser && $.browser.opera) mul = 1.3; if (mul > 1) distNow.y *= mul; } /* debug( ' clnt: '+ event.clientX +', '+ event.clientY + ' strt: '+ startPos.x +', '+ startPos.y + origDebug + ' totl: '+ distTotal.x +', '+ distTotal.y + ' rslt: '+ distNow.x +', '+ distNow.y); */ if (d.i.isInIframe) { window.parent.postMessage(['doUtterscroll', cloneEvent(event)], '*'); } else { $elemToScroll.scrollLeft($elemToScroll.scrollLeft() - distNow.x); $elemToScroll.scrollTop($elemToScroll.scrollTop() - distNow.y); } lastPos = { x: event.screenX, y: event.screenY }; return false; }; function stopScroll(event) { $elemToScroll = undefined; startPos = undefined; lastPos = undefined; lastButtons = 0; mousedownNoticed = false; $(document.body).css('cursor', ''); // cancel 'move' cursor $.event.remove(document, 'mousemove', doScroll); $.event.remove(document, 'mouseup', stopScroll); if (d.i.isInIframe) window.parent.postMessage(['stopUtterscrolling', cloneEvent(event)], '*'); return false; }; function cloneEvent(event) { // This is all Utterscroll in this <iframe>'s parent window needs. return { screenX: event.screenX, screenY: event.screenY }; }; // If any iframe parent starts utterscrolling, help it continue scrolling when // the mouse is over the iframe, by posting these events to the parent that it // can use instead of e.g. the onmousemove event (which goes to the iframe // only). if (d.i.isInIframe) { var origOnMouseMove = document.onmousemove; var origOnMouseUp = document.onmouseup; document.onmousemove = function(event) { window.parent.postMessage(['onMouseMove', cloneEvent(event)], '*'); if (origOnMouseMove) return origOnMouseMove(event); } document.onmouseup = function(event) { var returnValue = undefined; if (origOnMouseUp) returnValue = origOnMouseUp(event); window.parent.postMessage(['stopUtterscrolling', cloneEvent(event)], '*'); return returnValue; } } var api = { enable: function(options) { enabled = true; // If no options specified, remember any options specified last time // Utterscroll was enabled. if (!options && settings) return; settings = $.extend({}, defaults, options); allScrollstoppers = settings.defaultScrollstoppers; if (settings.scrollstoppers.length > 0) allScrollstoppers += ', '+ options.scrollstoppers; }, disable: function() { enabled = false; }, isEnabled: function() { return enabled; }, isScrolling: function() { return !!startPos; } }; return api; })(); //---------------------------------------- })(jQuery); //---------------------------------------- // vim: fdm=marker et ts=2 sw=2 tw=80 fo=tcqwn list
client/page/scripts/debiki-utterscroll.js
/* Debiki Utterscroll — dragscroll everywhere, adjusted to run in an <iframe> too. * http://www.debiki.com/dev/utterscroll * * Copyright (c) 2012 - 2013 Kaj Magnus Lindberg (born 1979) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, see <http://www.gnu.org/licenses/>. */ //---------------------------------------- (function($){ //---------------------------------------- var d = { i: debiki.internal, u: debiki.v0.util }; if (!debiki.Utterscroll) debiki.Utterscroll = {}; /** * Utterscroll. API: * * `enable(options)` enables Utterscroll. Options: * scrollstoppers: * jQuery selectors, e.g. '.CodeMirror, div.your-class'. * Dragging the mouse inside a scrollstopper never results in scrolling. * * `enable()` (with no options specified) enables Utterscroll and remembers * any option you specified the last time you did specify options. * * `disable()` * * `isEnabled()` * * `isScrolling()` is true iff the user is currently dragscrolling. */ debiki.Utterscroll = (function(options) { // Don't call console.debug in IE 9 (and 7 & 8); it's not available unless // the dev tools window is open. Use this safe wrapper instead of // console.log. (COULD make separate Prod and Dev builds, filter out logging) var debug = (typeof console === 'undefined' || !console.debug) ? function() {} : function() { console.debug.apply(console, arguments); }; var defaults = { defaultScrollstoppers: 'a, area, button, command, input, keygen, label,'+ ' option, select, textarea, video', // ?? canvas, embed, object scrollstoppers: '', onMousedownOnWinVtclScrollbar: function() {}, onMousedownOnWinHztlScrollbar: function() {}, onHasUtterscrolled: function() {} }; var enabled; var settings; var allScrollstoppers; var $elemToScroll; var startPos; var lastPos; // Avoids firing onHasUtterscrolled twice. var hasFiredHasUtterscrolled = false; // We fire onHasUtterscrolled, when the user has scrolled more than this. var fireHasUtterscrolledMinDist = 15; // pixels // Helps detect usage of the browser window scrollbars. var $viewportGhost = $('<div style="width: 100%; height: 100%;' + ' position: fixed; top: 0; left: 0; z-index: -999"></div>') .appendTo(document.body); $(document).mousedown(startScrollPerhaps); $(document).mousemove(checkIfMissedMousedown); var lastButtons = 0; var mousedownNoticed = false; /** * Firefox bug workaround. * * When Debiki Utterscroll is used both in an <iframe> and in the parent * window, and cooperates via postMessage, then mousedown and mouseup events * are sometimes lost, in Firefox 26 (and Kubuntu Linux) at least. * This function checks `event.buttons` to find out if a mousedown event was * missed, and, if so, starts scrolling. */ function checkIfMissedMousedown(event) { if (lastButtons === 0 && event.buttons === 1 && !mousedownNoticed) { // There was a mousedown that we never noticed, because of some browser // bug/issue probably related to <iframe>s. So fake a click and perhaps // start scrolling. lastButtons = event.buttons; event.which = 1; debug('Mousedown event missed, calling startScroll(event)'); // We don't know where the mouse was when it was clicked. However since // the mousedown event was lost, no text selection has started? And it's // better to start scrolling, as far as I've experienced. startScroll(event); return false; } }; function startScrollPerhaps(event) { mousedownNoticed = true; if (!enabled) return; // Only left button drag-scrolls. if (event.which !== 1 ) return; // Never scroll, when mouse down on certain elems. var $target = $(event.target); var $noScrollElem = $target.closest(allScrollstoppers); if ($noScrollElem.length > 0) return; // Fire event and cancel, on browser window scrollbar click. // - In Chrome, IE and FF, but not in Opera, when you mousedown on // a scrollbar, a mousedown event happens. // - The subsequent fix (for scrollbars in general) cannot handle the // *window* scrollbar case, because the <html> elem can be smaller // than the viewport, so checking that the mousedown // didn't happen inside the <html> elem won't work. We need // $viewportGhost, which always covers the whole viewport. if (event.pageX > $viewportGhost.offset().left + $viewportGhost.width()) { // Vertical scrollbar mousedown:ed. settings.onMousedownOnWinVtclScrollbar(); return; } if (event.pageY > $viewportGhost.offset().top + $viewportGhost.height()) { // Horizontal scrollbar mousedown:ed. settings.onMousedownOnWinHztlScrollbar(); return; } // Cancel if scrollbar clicked (other than the browser window scrollbars). // - Related: In Chrome, "Scrollbar triggers onmousedown, but fails to // trigger onmouseup". (Also mousemove won't happen!) // See http://code.google.com/p/chromium/issues/detail?id=14204. // - The workaround: Place a wigth & height 100% elem, $ghost, // inside $target, and if the mousedown position is not iside $ghost, // then the scrollbars were clicked. // (What about overflow === 'inherit'? Would anyone ever use that?) if ($target.css('overflow') === 'auto' || $target.css('overflow') === 'scroll') { // Okay, scrollbars might have been clicked, in Chrome. var $ghost = $('<div style="width: 100%; height: 100%; ' + 'position: absolute;"></div>'); // Specify top and left, so $ghost fills up the visible part of // $target, even if $target contains scrollbars that have been scrolled. $ghost.css({ top: $target.scrollTop(), left: $target.scrollLeft() }); var targetPosOrig = $target.css('position'); $target.css('position', 'relative'); $target.prepend($ghost) // Now $ghost fills up $target, up to the scrollbars. // Check if the click happened outside $ghost. var isScrollbar = false; if (event.pageX > $ghost.offset().left + $ghost.width()) isScrollbar = true; // vertical scrollbar clicked, don't dragscroll if (event.pageY > $ghost.offset().top + $ghost.height()) isScrollbar = true; // horizontal scrollbar clicked $ghost.remove(); $target.css('position', targetPosOrig); if (isScrollbar) return; } // Find the closest elem with scrollbars. // If the ':scrollable' selector isn't available, scroll the window. // Also don't scroll `html' and `body' — scroll `window' instead, that // works better across all browsers. $elemToScroll = $.expr[':'].scrollable ? $target.closest(':scrollable:not(html, body)').add($(window)).first() : $(window); // Scroll, unless the mouse down is a text selection attempt: // ----- // If there's no text in the event.target, then start scrolling. var containsText = searchForTextIn($target, 0); debug(event.target.nodeName +' containsText: '+ containsText); if (!containsText) return startScroll(event); function searchForTextIn($elem, recursionDepth) { if (recursionDepth > 6) return false; var $textElems = $elem.contents().filter(function(ix, child, ar) { // Is it a true text node with text? // BUG? What about CDATA? Isn't that text? (node type 4) if (child.nodeType === 3) { // 3 is text var onlyWhitespace = child.data.match(/^\s*$/); return !onlyWhitespace; } // Skip comments (or script dies in FF) if (child.nodeType === 8) // 8 is comment return false; // COULD skip some more node types? Which? // And should also test and verify afterwards. // Recurse into inline elems — I think they often contain // text? E.g. <li><a>...</a></li> or <p><small>...</small></p>. var $child = $(child); if ($child.css('display') === 'inline') { var foundText = searchForTextIn($child, recursionDepth + 1); return foundText; } // Skip block level children. If text in them is to be selected, // the user needs to click on those blocks. (Recursing into // block level elems could search the whole page, should you // click the <html> elem!) return false; }); return $textElems.length > 0; }; // Start scrolling if mouse press happened not very close to text. var dist = distFromTextToEvent($target, event); debug('Approx dist from $target text to mouse: '+ dist); if (dist === -1 || dist > 55) return startScroll(event); // Don't scroll and don't event.preventDefault(). — The user should be able // to e.g. click buttons and select text. }; /** * Finds the approximate closest distance from text in $elem to event. */ function distFromTextToEvent($elem, event) { // I don't think there's any built in browser support that helps // us to find the distance. // Therefore, place many magic marks inside $elem, and check the // distance from each mark to the mousedown evenet. Then return // the shortest distance. // We have no idea where the text line-wraps, so we cannot be // clever about where to insert the marks. // {{{ Two vaguely related StackOverflow questions. // <http://stackoverflow.com/questions/1589721/ // how-can-i-position-an-element-next-to-user-text-selection> // <http://stackoverflow.com/questions/2031518/ // javascript-selection-range-coordinates> }}} // Add marks to a copy of $elem's inner html. var $parent = $elem; var innerHtmlBefore = $parent.html(); var mark = '<span class="utrscrlhlpr"/>'; // First replace all html tags with a placeholder. // (When we add marks, we don't want to add them inside tags.) // (It seems any '<' in attribute values have been escaped to '&lt;') var savedTags = []; var innerHtmlNoTags = innerHtmlBefore.replace(/<[^>]*>/g, function($0) { savedTags.push($0); return '·'; // COULD find a rarer utf-8 char? (Also update TagDog) }); // For now, insert a mark between every two chars. We need frequent // marks if the font size is huge. Could check font size of // all elems in $target, and reduce num chars between marks. // (For one single elem: parseInt($elem.css('font-size')); ) // But not needed? Performance is fine, on my computer :-) var htmlWithMarksNoTags = mark + innerHtmlNoTags.replace( /(\s*.{0,2})/g, '$1'+ mark); // Put back all html tags. var savedTagsIx = 0; var htmlWithMarks = htmlWithMarksNoTags.replace(/·/g, function() { savedTagsIx += 1; return savedTags[savedTagsIx - 1]; }); // Clone $parent, and insert the marks into the clone. // We won't modify $parent itself — doing that would 1) destroy any // text selection object (but other Javascript code might need it), // and perhaps 2) break other related Javascript code and event // bindings in other ways. // {{{ You might wonder what happens if $parent is the <html> and the page // is huge. This isn't likely to happen though, because we only run // this code for elems that contains text or inline elems with text, // and such blocks are usually small. Well written text contains // reasonably small paragraphs, no excessively huge blocks of text? }}} var $parentClone = $parent.clone(); $parentClone.html(htmlWithMarks); // Replace the parent with the clone, so we can use the clone in // distance measurements. But don't remove the parent — that would // destroy any text selection. // One minor (?) issues/bug: // If the $parent is positioned via CSS like :last-child or // :only-child, that CSS wouldn't be applied to the clone, so distance // measurement might become inaccurate. // Is this unavoidable? We cannot remove the real $parent, or we'd // destroy the text selection (if there is one). $parentClone.insertBefore($parent); // {{{ Alternative approach // Place with 'position: absolute' the clone on the parent. // // However, if the start of the parent isn't at the parent's upper // left corner, word wrapping in the parent and the clone won't be // identical. Example: // |text text text text text text text text text text text| // |text text text text text text text<small>parent parent| // |parent parent</small> | // If you clone <small> and 'position: absolute' the clone on // the original <small>, the clone will have no line wraps, // but look like so: // |text text text text text text text text text text text| // —> |<small>parent parent parent parent</small>xt text text| // |parent parent</small> | // Possible solution: Find the closest elem with display: block, // and clone it. Then word wraps should become identical? // //$parentClone // .css({ // width: $parent.width(), // height: $parent.height(), // position: 'absolute' // }) // .insertBefore($parent) // .position({ my: 'left top', at: 'left top', of: $parent }); // // }}} // Find mousedown position relative document. // (This is supposedly cross browser compatible, see e.g. // http://stackoverflow.com/a/4430498/694469.) var mouseOffs; if (event.pageX || event.pageY) { mouseOffs = { x: event.pageX, y: event.pageY }; } else { var d = document; mouseOffs = { x: event.screenX + d.body.scrollLeft + d.documentElement.scrollLeft, y: event.screenY + d.body.scrollTop + d.documentElement.scrollTop }; } // Find min distance from [the marks inside the clone] to the mouse pos. var minDist2 = 999999999; $parentClone.find('.utrscrlhlpr').each(function() { var myOffs = $(this).offset(); var distX = mouseOffs.x - myOffs.left; var distY = mouseOffs.y - myOffs.top; var dist2 = distX * distX + distY * distY; if (dist2 < minDist2) { minDist2 = dist2; // debug('New max dist from: '+ myOffs.left +','+ myOffs.top + // ' to: '+ mouseOffs.x +','+ mouseOffs.y +' is: '+ dist2); } }); $parentClone.remove(); return Math.sqrt(minDist2); }; function startScroll(event) { $(document).mousemove(doScroll); $(document).mouseup(stopScroll); $(document.body).css('cursor', 'move'); // Y is the distance to the top. startPos = { x: event.screenX, y: event.screenY }; lastPos = { x: event.screenX, y: event.screenY }; if (d.i.isInIframe) window.parent.postMessage(['startUtterscrolling', cloneEvent(event)], '*'); return false; }; function doScroll(event) { // <iframe> FireFox issue workaround: (FF version 26 on Ubuntu Linux at least) // Sometimes the mouseup event never happens, if Debiki runs in an <iframe>. // Neither in the <iframe> nor in the parent window. Therefore, detect if the mouse // button has actually been released and we should stop scrolling, like so: // (And reproduce the issue by opening a HTML page with Debiki embedded // comments in Firefox, then open Firebug, and dragscrolling so the // mouse enters the Firebug window, then release the mouse and move the // mouse back over the html window. Now you'll still be scrolling although // you've released the mouse button — were it not for this workaround.) if (event.buttons === 0) return stopScroll(event); if (d.i.isInIframe) { // Message to parent sent by other `document.onmousemove`, see the end of // this file. return; } // Find movement since mousedown, and since last scroll step. var distTotal = { x: Math.abs(event.screenX - startPos.x), y: Math.abs(event.screenY - startPos.y) }; var distNow = { x: event.screenX - lastPos.x, y: event.screenY - lastPos.y }; // Sometimes we should scroll in one direction only. if ($elemToScroll[0] === window) { // $(window).css('overflow-x') and '...-y' results in an error: // "Cannot read property 'defaultView' of undefined" // therefore, always scroll, if window viewport too small. } else { if ($elemToScroll.css('overflow-y') === 'hidden') distNow.y = 0; if ($elemToScroll.css('overflow-x') === 'hidden') distNow.x = 0; } // Trigger onHasUtterscrolled(), if scrolled > min distance. if (!hasFiredHasUtterscrolled && (distTotal.x * distTotal.x + distTotal.y * distTotal.y > fireHasUtterscrolledMinDist * fireHasUtterscrolledMinDist)) { hasFiredHasUtterscrolled = true; settings.onHasUtterscrolled(); } // var origDebug = ' orig: '+ distNow.x +', '+ distNow.y; // Scroll faster, if you've scrolled far. // Then you can easily move viewport // large distances, and still retain high precision when // moving small distances. (The calculations below are just // heuristics that works well on my computer.) // Don't move too fast for Opera though: it re-renders the screen // slowly (unbearably slowly if there're lots of SVG arrows!) and // the reported mouse movement distances would becom terribly huge, // e.g. 1000px, and then the viewport jumps randomly. var mul; if (distTotal.x > 9){ mul = Math.log((distTotal.x - 9) / 3); if (mul > 1.7 && $.browser.opera) mul = 1.7; // see comment above if (mul > 1) distNow.x *= mul; } if (distTotal.y > 5){ mul = Math.log((distTotal.y - 5) / 2); if (mul > 1.3 && $.browser.opera) mul = 1.3; if (mul > 1) distNow.y *= mul; } /* debug( ' clnt: '+ event.clientX +', '+ event.clientY + ' strt: '+ startPos.x +', '+ startPos.y + origDebug + ' totl: '+ distTotal.x +', '+ distTotal.y + ' rslt: '+ distNow.x +', '+ distNow.y); */ if (d.i.isInIframe) { window.parent.postMessage(['doUtterscroll', cloneEvent(event)], '*'); } else { $elemToScroll.scrollLeft($elemToScroll.scrollLeft() - distNow.x); $elemToScroll.scrollTop($elemToScroll.scrollTop() - distNow.y); } lastPos = { x: event.screenX, y: event.screenY }; return false; }; function stopScroll(event) { $elemToScroll = undefined; startPos = undefined; lastPos = undefined; lastButtons = 0; mousedownNoticed = false; $(document.body).css('cursor', ''); // cancel 'move' cursor $.event.remove(document, 'mousemove', doScroll); $.event.remove(document, 'mouseup', stopScroll); if (d.i.isInIframe) window.parent.postMessage(['stopUtterscrolling', cloneEvent(event)], '*'); return false; }; function cloneEvent(event) { // This is all Utterscroll in this <iframe>'s parent window needs. return { screenX: event.screenX, screenY: event.screenY }; }; // If any iframe parent starts utterscrolling, help it continue scrolling when // the mouse is over the iframe, by posting these events to the parent that it // can use instead of e.g. the onmousemove event (which goes to the iframe // only). if (d.i.isInIframe) { var origOnMouseMove = document.onmousemove; var origOnMouseUp = document.onmouseup; document.onmousemove = function(event) { window.parent.postMessage(['onMouseMove', cloneEvent(event)], '*'); if (origOnMouseMove) return origOnMouseMove(event); } document.onmouseup = function(event) { var returnValue = undefined; if (origOnMouseUp) returnValue = origOnMouseUp(event); window.parent.postMessage(['stopUtterscrolling', cloneEvent(event)], '*'); return returnValue; } } var api = { enable: function(options) { enabled = true; // If no options specified, remember any options specified last time // Utterscroll was enabled. if (!options && settings) return; settings = $.extend({}, defaults, options); allScrollstoppers = settings.defaultScrollstoppers; if (settings.scrollstoppers.length > 0) allScrollstoppers += ', '+ options.scrollstoppers; }, disable: function() { enabled = false; }, isEnabled: function() { return enabled; }, isScrolling: function() { return !!startPos; } }; return api; })(); //---------------------------------------- })(jQuery); //---------------------------------------- // vim: fdm=marker et ts=2 sw=2 tw=80 fo=tcqwn list
Make <iframe> Utterscroll compatible with jQuery 2.x jQuery 2.x might not have $.browser.
client/page/scripts/debiki-utterscroll.js
Make <iframe> Utterscroll compatible with jQuery 2.x
<ide><path>lient/page/scripts/debiki-utterscroll.js <ide> var mul; <ide> if (distTotal.x > 9){ <ide> mul = Math.log((distTotal.x - 9) / 3); <del> if (mul > 1.7 && $.browser.opera) mul = 1.7; // see comment above <add> if (mul > 1.7 && $.browser && $.browser.opera) mul = 1.7; // see comment above <ide> if (mul > 1) distNow.x *= mul; <ide> } <ide> if (distTotal.y > 5){ <ide> mul = Math.log((distTotal.y - 5) / 2); <del> if (mul > 1.3 && $.browser.opera) mul = 1.3; <add> if (mul > 1.3 && $.browser && $.browser.opera) mul = 1.3; <ide> if (mul > 1) distNow.y *= mul; <ide> } <ide>
Java
apache-2.0
191f24417919993f01e733ef90fb68d17fc59e08
0
lesfurets/dOOv
/* * Copyright 2017 Courtanet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.doov.gen; import static io.doov.gen.FieldInfoGen.constants; import static io.doov.gen.FieldInfoGen.createFieldInfos; import static io.doov.gen.FieldInfoGen.imports; import static io.doov.gen.FieldInfoGen.methods; import static io.doov.gen.ModelWrapperGen.*; import static io.doov.gen.utils.ClassUtils.transformPathToMethod; import static java.nio.file.Files.createDirectories; import static java.time.LocalDateTime.now; import static java.time.format.DateTimeFormatter.ofLocalizedDateTime; import static java.time.format.FormatStyle.SHORT; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_SOURCES; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.*; import org.apache.maven.plugin.*; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import com.google.common.io.Files; import io.doov.core.*; import io.doov.core.dsl.field.FieldTypeProvider; import io.doov.core.dsl.field.FieldTypes; import io.doov.core.dsl.path.FieldPath; import io.doov.core.dsl.path.FieldPathProvider; import io.doov.core.serial.TypeAdapterRegistry; import io.doov.core.serial.TypeAdapters; import io.doov.gen.processor.MacroProcessor; import io.doov.gen.processor.Templates; import io.doov.gen.utils.ClassLoaderUtils; import io.doov.gen.utils.ClassUtils; @Mojo(name = "generate", defaultPhase = GENERATE_SOURCES, threadSafe = true) public final class ModelMapGenMojo extends AbstractMojo { @Parameter(required = true, defaultValue = "${basedir}/src/generated/java") private File outputDirectory; @Parameter(required = true, property = "project.build.outputDirectory") private File buildDirectory; @Parameter(required = true, defaultValue = "${basedir}/target") private File outputResourceDirectory; @Parameter(required = true) private String sourceClass; @Parameter(required = true) private String fieldClass; @Parameter(required = true, readonly = true, property = "project") private MavenProject project; @Parameter(required = true) private String packageFilter; @Parameter private String fieldPathProvider; @Parameter private String baseClass; @Parameter private String typeAdapters; @Parameter(defaultValue = "true") private boolean enumFieldInfo; @Parameter private String fieldInfoTypes; @Parameter private String wrapperPackage; @Parameter private String fieldInfoPackage; @Parameter private String dslModelPackage; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (sourceClass == null) { getLog().warn("no project classes"); } if (sourceClass.isEmpty()) { getLog().warn("project is empty"); } if (fieldClass == null) { getLog().warn("no tunnel classes"); } if (fieldClass.isEmpty()) { getLog().warn("tunnel is empty"); } if (outputDirectory.exists() && !outputDirectory.isDirectory()) { throw new MojoFailureException(outputDirectory + " is not directory"); } // add source directory to current project try { createDirectories(outputDirectory.toPath()); project.addCompileSourceRoot(outputDirectory.getPath()); } catch (IOException e) { throw new MojoExecutionException("unable to create source folder", e); } final URLClassLoader classLoader = ClassLoaderUtils.getUrlClassLoader(project); try { List<FieldPath> fieldPaths = fieldPathProvider != null ? loadClassWithType(this.fieldPathProvider, FieldPathProvider.class, null, classLoader) .newInstance().values() : Collections.emptyList(); Class<?> modelClazz = Class.forName(sourceClass, true, classLoader); Class<? extends FieldId> fieldClazz = loadClassWithType(fieldClass, FieldId.class, null, classLoader); Class<? extends FieldModel> baseClazz = loadClassWithType(baseClass, AbstractWrapper.class, AbstractWrapper.class, classLoader); Class<? extends TypeAdapterRegistry> typeAdapterClazz = loadClassWithType(typeAdapters, TypeAdapterRegistry.class, TypeAdapters.class, classLoader); FieldTypeProvider typeProvider = loadClassWithType(fieldInfoTypes, FieldTypeProvider.class, FieldTypes.class, classLoader).newInstance(); generateModels(fieldClazz, modelClazz, baseClazz, typeAdapterClazz, typeProvider, fieldPaths); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } private <T> Class<? extends T> loadClassWithType(String className, Class<T> type, Class<? extends T> defaultClass, URLClassLoader classLoader) throws MojoExecutionException, ClassNotFoundException { Class<? extends T> classToLoad = defaultClass; if (className != null) { Class<?> loadedClass = Class.forName(className, true, classLoader); if (!type.isAssignableFrom(loadedClass)) { throw new MojoExecutionException("Class " + loadedClass + " does not implement " + type.getName()); } classToLoad = (Class<? extends T>) loadedClass; } return classToLoad; } private void generateModels(Class<? extends FieldId> fieldClazz, Class<?> modelClazz, Class<? extends FieldModel> baseClazz, Class<? extends TypeAdapterRegistry> typeAdapterClazz, FieldTypeProvider typeProvider, List<FieldPath> fieldPaths) { try { final List<VisitorPath> collected; if (fieldPaths.isEmpty()) { collected = process(modelClazz, packageFilter, fieldClazz); } else { collected = fieldPaths.stream().map(this::createVisitorPath).collect(toList()); } final Map<FieldId, VisitorPath> fieldPathMap = validatePath(collected, getLog()); final Map<FieldId, GeneratorFieldInfo> fieldInfoMap = createFieldInfos(fieldPathMap); Runnable generateCsv = () -> generateCsv(fieldPathMap, modelClazz); Runnable generateWrapper = () -> generateWrapper(fieldPathMap, modelClazz, fieldClazz, baseClazz, typeAdapterClazz); Runnable generateFieldInfo = () -> generateFieldInfo(fieldInfoMap, fieldClazz); Runnable generateDslFields = () -> generateDslFields(fieldInfoMap, modelClazz, fieldClazz, typeProvider); asList(generateWrapper, generateCsv, generateFieldInfo, generateDslFields).parallelStream() .forEach(Runnable::run); } catch (Exception e) { throw new RuntimeException("generation failed for class " + modelClazz, e); } } private VisitorPath createVisitorPath(FieldPath p) { getLog().debug("Processing field path " + p); LinkedHashMap<Class, Method> path = transformPathToMethod(p.getBaseClass(), p.getPath()); List<Class> classes = new ArrayList<>(path.keySet()); List<Method> methods = new ArrayList<>(path.values()); // Last class of the path is the container of the field Class<?> containerClass = classes.get(classes.size() - 1); Method readMethod = ClassUtils.getReferencedMethod(containerClass, p.getReadMethod()); Method writeMethod = ClassUtils.getReferencedMethod(containerClass, p.getWriteMethod()); Map<String, String> cannonicalReplacement = new HashMap<>(); PathConstraint constraint = p.getConstraint(); if (constraint != null && constraint.canonicalPathReplacements() != null) { cannonicalReplacement.putAll(constraint.canonicalPathReplacements()); } return new VisitorPath(p.getBaseClass(), methods, p.getFieldId(), p.getReadable(), readMethod, writeMethod, p.isTransient(), cannonicalReplacement); } private List<VisitorPath> process(Class<?> projetClass, String filter, Class<? extends FieldId> fieldClass) throws Exception { final List<VisitorPath> collected = new ArrayList<>(); new ModelVisitor(getLog()).visitModel(projetClass, fieldClass, new Visitor(projetClass, collected), filter); return collected; } private void generateCsv(Map<FieldId, VisitorPath> fieldPaths, Class<?> clazz) { final File targetFile = new File(outputResourceDirectory, clazz.getSimpleName() + ".csv"); targetFile.getParentFile().mkdirs(); FieldCsvGen.write(targetFile, fieldPaths); getLog().info("written : " + targetFile); } private void generateFieldInfo(Map<FieldId, GeneratorFieldInfo> fieldInfoMap, Class<?> fieldClass) { try { final String targetClassName = fieldInfoClassName(fieldClass); final String targetPackage = fieldInfoPackage == null ? fieldClass.getPackage().getName() : fieldInfoPackage; final File targetFile = new File(outputDirectory + "/" + targetPackage.replace('.', '/'), targetClassName + ".java"); final String classTemplate = enumFieldInfo ? Templates.fieldInfoEnum : Templates.fieldInfoClass; createDirectories(targetFile.getParentFile().toPath()); final Map<String, String> conf = new HashMap<>(); conf.put("package.name", targetPackage); conf.put("process.class", fieldClass.getName()); conf.put("process.date", ofLocalizedDateTime(SHORT).format(now())); conf.put("target.class.name", targetClassName); conf.put("imports", imports(fieldInfoMap, null)); conf.put("constants", constants(fieldInfoMap, enumFieldInfo)); conf.put("source.generator.name", getClass().getName()); final String content = MacroProcessor.replaceProperties(classTemplate, conf); Files.write(content, targetFile, Charset.forName("UTF8")); getLog().info("written : " + targetFile); } catch (IOException e) { throw new RuntimeException("error when generating wrapper", e); } } private static String fieldInfoClassName(Class<?> clazz) { return clazz.getSimpleName().startsWith("E") ? clazz.getSimpleName().substring(1) : clazz.getSimpleName() + "Info"; } private void generateDslFields(Map<FieldId, GeneratorFieldInfo> fieldInfoMap, Class<?> modelClazz, Class<?> fieldClass, FieldTypeProvider typeProvider) { try { final String targetClassName = dslFieldsClassName(modelClazz); final String fieldInfoClassName = fieldInfoClassName(fieldClass); final String targetPackage = dslModelPackage == null ? fieldClass.getPackage().getName() + ".dsl" : dslModelPackage; final File targetFile = new File(outputDirectory + "/" + targetPackage.replace('.', '/'), targetClassName + ".java"); createDirectories(targetFile.getParentFile().toPath()); final Map<String, String> conf = new HashMap<>(); conf.put("package.name", targetPackage); conf.put("process.class", fieldClass.getName()); conf.put("process.date", ofLocalizedDateTime(SHORT).format(now())); conf.put("target.class.name", targetClassName); conf.put("process.field.info.class", fieldClass.getPackage().getName() + "." + fieldInfoClassName); conf.put("imports", imports(fieldInfoMap, typeProvider)); conf.put("methods", methods(fieldInfoMap, typeProvider, enumFieldInfo)); conf.put("source.generator.name", getClass().getName()); final String content = MacroProcessor.replaceProperties(Templates.dslFieldModel, conf); Files.write(content, targetFile, Charset.forName("UTF8")); getLog().info("written : " + targetFile); } catch (IOException e) { throw new RuntimeException("error when generating wrapper", e); } } private static String dslFieldsClassName(Class<?> clazz) { return "DSL" + (clazz.getSimpleName().startsWith("E") ? clazz.getSimpleName().substring(1) : clazz.getSimpleName()); } private void generateWrapper(Map<FieldId, VisitorPath> fieldPaths, Class<?> modelClass, Class<?> fieldClass, Class<? extends FieldModel> baseClazz, Class<? extends TypeAdapterRegistry> typeAdapterClazz) throws RuntimeException { try { final String targetClassName = modelClass.getSimpleName() + "Wrapper"; final String targetPackage = wrapperPackage == null ? modelClass.getPackage().getName() : wrapperPackage; final File targetFile = new File(outputDirectory + "/" + targetPackage.replace('.', '/'), targetClassName + ".java"); createDirectories(targetFile.getParentFile().toPath()); Map<String, String> conf = new HashMap<>(); conf.put("package.name", targetPackage); conf.put("process.class", modelClass.getName()); conf.put("process.base.class.package", baseClazz.getCanonicalName()); conf.put("process.base.class.name", baseClassName(baseClazz, modelClass)); conf.put("process.date", ofLocalizedDateTime(SHORT).format(now())); conf.put("type.adapter.class.package", typeAdapterClazz.getCanonicalName()); conf.put("type.adapter.class.name", typeAdapterClazz.getSimpleName()); conf.put("constructors", mapConstructors(targetClassName, baseClazz, modelClass)); conf.put("target.model.class.name", modelClass.getSimpleName()); conf.put("target.model.class.full.name", modelClass.getName()); conf.put("target.field.info.package.name", fieldClass.getPackage().getName()); conf.put("target.field.info.class.name", fieldInfoClassName(fieldClass)); conf.put("target.class.name", targetClassName); conf.put("map.getter", mapGetter(fieldPaths)); conf.put("map.getter.if", mapFieldTypeIfStatement(Templates.mapGetIf, fieldPaths)); conf.put("map.setter", mapSetter(fieldPaths)); conf.put("map.setter.if", mapFieldTypeIfStatement(Templates.mapSetIf, fieldPaths)); conf.put("map.properties", mapFieldProperties(fieldPaths, modelClass)); conf.put("source.generator.name", getClass().getName()); String content = MacroProcessor.replaceProperties(Templates.wrapperClass, conf); Files.write(content, targetFile, Charset.forName("UTF8")); getLog().info("written : " + targetFile); } catch (IOException e) { throw new RuntimeException("error when generating wrapper", e); } } private String baseClassName(Class<? extends FieldModel> baseClazz, Class<?> modelClass) { if (AbstractWrapper.class.equals(baseClazz)) { return AbstractWrapper.class.getSimpleName() + "<" + modelClass.getSimpleName() + ">"; } else { return baseClazz.getSimpleName(); } } }
generator/src/main/java/io/doov/gen/ModelMapGenMojo.java
/* * Copyright 2017 Courtanet * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.doov.gen; import static io.doov.gen.FieldInfoGen.constants; import static io.doov.gen.FieldInfoGen.createFieldInfos; import static io.doov.gen.FieldInfoGen.imports; import static io.doov.gen.FieldInfoGen.methods; import static io.doov.gen.ModelWrapperGen.*; import static io.doov.gen.utils.ClassUtils.transformPathToMethod; import static java.nio.file.Files.createDirectories; import static java.time.LocalDateTime.now; import static java.time.format.DateTimeFormatter.ofLocalizedDateTime; import static java.time.format.FormatStyle.SHORT; import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; import static org.apache.maven.plugins.annotations.LifecyclePhase.GENERATE_SOURCES; import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.net.URLClassLoader; import java.nio.charset.Charset; import java.util.*; import org.apache.maven.plugin.*; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import com.google.common.io.Files; import io.doov.core.*; import io.doov.core.dsl.field.FieldTypeProvider; import io.doov.core.dsl.field.FieldTypes; import io.doov.core.dsl.path.FieldPath; import io.doov.core.dsl.path.FieldPathProvider; import io.doov.core.serial.TypeAdapterRegistry; import io.doov.core.serial.TypeAdapters; import io.doov.gen.processor.MacroProcessor; import io.doov.gen.processor.Templates; import io.doov.gen.utils.ClassLoaderUtils; import io.doov.gen.utils.ClassUtils; @Mojo(name = "generate", defaultPhase = GENERATE_SOURCES, threadSafe = true) public final class ModelMapGenMojo extends AbstractMojo { @Parameter(required = true, defaultValue = "${basedir}/src/generated/java") private File outputDirectory; @Parameter(required = true, property = "project.build.outputDirectory") private File buildDirectory; @Parameter(required = true, defaultValue = "${basedir}/target") private File outputResourceDirectory; @Parameter(required = true) private String sourceClass; @Parameter(required = true) private String fieldClass; @Parameter(required = true, readonly = true, property = "project") private MavenProject project; @Parameter(required = true) private String packageFilter; @Parameter private String fieldPathProvider; @Parameter private String baseClass; @Parameter private String typeAdapters; @Parameter(defaultValue = "true") private boolean enumFieldInfo; @Parameter private String fieldInfoTypes; @Parameter private String wrapperPackage; @Parameter private String fieldInfoPackage; @Parameter private String dslModelPackage; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (sourceClass == null) { getLog().warn("no project classes"); } if (sourceClass.isEmpty()) { getLog().warn("project is empty"); } if (fieldClass == null) { getLog().warn("no tunnel classes"); } if (fieldClass.isEmpty()) { getLog().warn("tunnel is empty"); } if (outputDirectory.exists() && !outputDirectory.isDirectory()) { throw new MojoFailureException(outputDirectory + " is not directory"); } // add source directory to current project try { createDirectories(outputDirectory.toPath()); project.addCompileSourceRoot(outputDirectory.getPath()); } catch (IOException e) { throw new MojoExecutionException("unable to create source folder", e); } final URLClassLoader classLoader = ClassLoaderUtils.getUrlClassLoader(project); try { List<FieldPath> fieldPaths = fieldPathProvider != null ? loadClassWithType(this.fieldPathProvider, FieldPathProvider.class, null, classLoader) .newInstance().values() : Collections.emptyList(); Class<?> modelClazz = Class.forName(sourceClass, true, classLoader); Class<? extends FieldId> fieldClazz = loadClassWithType(fieldClass, FieldId.class, null, classLoader); Class<? extends FieldModel> baseClazz = loadClassWithType(baseClass, AbstractWrapper.class, AbstractWrapper.class, classLoader); Class<? extends TypeAdapterRegistry> typeAdapterClazz = loadClassWithType(typeAdapters, TypeAdapterRegistry.class, TypeAdapters.class, classLoader); FieldTypeProvider typeProvider = loadClassWithType(fieldInfoTypes, FieldTypeProvider.class, FieldTypes.class, classLoader).newInstance(); generateModels(fieldClazz, modelClazz, baseClazz, typeAdapterClazz, typeProvider, fieldPaths); } catch (Exception e) { throw new MojoExecutionException(e.getMessage(), e); } } private <T> Class<? extends T> loadClassWithType(String className, Class<T> type, Class<? extends T> defaultClass, URLClassLoader classLoader) throws MojoExecutionException, ClassNotFoundException { Class<? extends T> classToLoad = defaultClass; if (className != null) { Class<?> loadedClass = Class.forName(className, true, classLoader); if (!type.isAssignableFrom(type)) { throw new MojoExecutionException("Class " + loadedClass + " does not implement " + type.getName()); } classToLoad = (Class<? extends T>) loadedClass; } return classToLoad; } private void generateModels(Class<? extends FieldId> fieldClazz, Class<?> modelClazz, Class<? extends FieldModel> baseClazz, Class<? extends TypeAdapterRegistry> typeAdapterClazz, FieldTypeProvider typeProvider, List<FieldPath> fieldPaths) { try { final List<VisitorPath> collected; if (fieldPaths.isEmpty()) { collected = process(modelClazz, packageFilter, fieldClazz); } else { collected = fieldPaths.stream().map(this::createVisitorPath).collect(toList()); } final Map<FieldId, VisitorPath> fieldPathMap = validatePath(collected, getLog()); final Map<FieldId, GeneratorFieldInfo> fieldInfoMap = createFieldInfos(fieldPathMap); Runnable generateCsv = () -> generateCsv(fieldPathMap, modelClazz); Runnable generateWrapper = () -> generateWrapper(fieldPathMap, modelClazz, fieldClazz, baseClazz, typeAdapterClazz); Runnable generateFieldInfo = () -> generateFieldInfo(fieldInfoMap, fieldClazz); Runnable generateDslFields = () -> generateDslFields(fieldInfoMap, modelClazz, fieldClazz, typeProvider); asList(generateWrapper, generateCsv, generateFieldInfo, generateDslFields).parallelStream() .forEach(Runnable::run); } catch (Exception e) { throw new RuntimeException("generation failed for class " + modelClazz, e); } } private VisitorPath createVisitorPath(FieldPath p) { getLog().debug("Processing field path " + p); LinkedHashMap<Class, Method> path = transformPathToMethod(p.getBaseClass(), p.getPath()); List<Class> classes = new ArrayList<>(path.keySet()); List<Method> methods = new ArrayList<>(path.values()); // Last class of the path is the container of the field Class<?> containerClass = classes.get(classes.size() - 1); Method readMethod = ClassUtils.getReferencedMethod(containerClass, p.getReadMethod()); Method writeMethod = ClassUtils.getReferencedMethod(containerClass, p.getWriteMethod()); Map<String, String> cannonicalReplacement = new HashMap<>(); PathConstraint constraint = p.getConstraint(); if (constraint != null && constraint.canonicalPathReplacements() != null) { cannonicalReplacement.putAll(constraint.canonicalPathReplacements()); } return new VisitorPath(p.getBaseClass(), methods, p.getFieldId(), p.getReadable(), readMethod, writeMethod, p.isTransient(), cannonicalReplacement); } private List<VisitorPath> process(Class<?> projetClass, String filter, Class<? extends FieldId> fieldClass) throws Exception { final List<VisitorPath> collected = new ArrayList<>(); new ModelVisitor(getLog()).visitModel(projetClass, fieldClass, new Visitor(projetClass, collected), filter); return collected; } private void generateCsv(Map<FieldId, VisitorPath> fieldPaths, Class<?> clazz) { final File targetFile = new File(outputResourceDirectory, clazz.getSimpleName() + ".csv"); targetFile.getParentFile().mkdirs(); FieldCsvGen.write(targetFile, fieldPaths); getLog().info("written : " + targetFile); } private void generateFieldInfo(Map<FieldId, GeneratorFieldInfo> fieldInfoMap, Class<?> fieldClass) { try { final String targetClassName = fieldInfoClassName(fieldClass); final String targetPackage = fieldInfoPackage == null ? fieldClass.getPackage().getName() : fieldInfoPackage; final File targetFile = new File(outputDirectory + "/" + targetPackage.replace('.', '/'), targetClassName + ".java"); final String classTemplate = enumFieldInfo ? Templates.fieldInfoEnum : Templates.fieldInfoClass; createDirectories(targetFile.getParentFile().toPath()); final Map<String, String> conf = new HashMap<>(); conf.put("package.name", targetPackage); conf.put("process.class", fieldClass.getName()); conf.put("process.date", ofLocalizedDateTime(SHORT).format(now())); conf.put("target.class.name", targetClassName); conf.put("imports", imports(fieldInfoMap, null)); conf.put("constants", constants(fieldInfoMap, enumFieldInfo)); conf.put("source.generator.name", getClass().getName()); final String content = MacroProcessor.replaceProperties(classTemplate, conf); Files.write(content, targetFile, Charset.forName("UTF8")); getLog().info("written : " + targetFile); } catch (IOException e) { throw new RuntimeException("error when generating wrapper", e); } } private static String fieldInfoClassName(Class<?> clazz) { return clazz.getSimpleName().startsWith("E") ? clazz.getSimpleName().substring(1) : clazz.getSimpleName() + "Info"; } private void generateDslFields(Map<FieldId, GeneratorFieldInfo> fieldInfoMap, Class<?> modelClazz, Class<?> fieldClass, FieldTypeProvider typeProvider) { try { final String targetClassName = dslFieldsClassName(modelClazz); final String fieldInfoClassName = fieldInfoClassName(fieldClass); final String targetPackage = dslModelPackage == null ? fieldClass.getPackage().getName() + ".dsl" : dslModelPackage; final File targetFile = new File(outputDirectory + "/" + targetPackage.replace('.', '/'), targetClassName + ".java"); createDirectories(targetFile.getParentFile().toPath()); final Map<String, String> conf = new HashMap<>(); conf.put("package.name", targetPackage); conf.put("process.class", fieldClass.getName()); conf.put("process.date", ofLocalizedDateTime(SHORT).format(now())); conf.put("target.class.name", targetClassName); conf.put("process.field.info.class", fieldClass.getPackage().getName() + "." + fieldInfoClassName); conf.put("imports", imports(fieldInfoMap, typeProvider)); conf.put("methods", methods(fieldInfoMap, typeProvider, enumFieldInfo)); conf.put("source.generator.name", getClass().getName()); final String content = MacroProcessor.replaceProperties(Templates.dslFieldModel, conf); Files.write(content, targetFile, Charset.forName("UTF8")); getLog().info("written : " + targetFile); } catch (IOException e) { throw new RuntimeException("error when generating wrapper", e); } } private static String dslFieldsClassName(Class<?> clazz) { return "DSL" + (clazz.getSimpleName().startsWith("E") ? clazz.getSimpleName().substring(1) : clazz.getSimpleName()); } private void generateWrapper(Map<FieldId, VisitorPath> fieldPaths, Class<?> modelClass, Class<?> fieldClass, Class<? extends FieldModel> baseClazz, Class<? extends TypeAdapterRegistry> typeAdapterClazz) throws RuntimeException { try { final String targetClassName = modelClass.getSimpleName() + "Wrapper"; final String targetPackage = wrapperPackage == null ? modelClass.getPackage().getName() : wrapperPackage; final File targetFile = new File(outputDirectory + "/" + targetPackage.replace('.', '/'), targetClassName + ".java"); createDirectories(targetFile.getParentFile().toPath()); Map<String, String> conf = new HashMap<>(); conf.put("package.name", targetPackage); conf.put("process.class", modelClass.getName()); conf.put("process.base.class.package", baseClazz.getCanonicalName()); conf.put("process.base.class.name", baseClassName(baseClazz, modelClass)); conf.put("process.date", ofLocalizedDateTime(SHORT).format(now())); conf.put("type.adapter.class.package", typeAdapterClazz.getCanonicalName()); conf.put("type.adapter.class.name", typeAdapterClazz.getSimpleName()); conf.put("constructors", mapConstructors(targetClassName, baseClazz, modelClass)); conf.put("target.model.class.name", modelClass.getSimpleName()); conf.put("target.model.class.full.name", modelClass.getName()); conf.put("target.field.info.package.name", fieldClass.getPackage().getName()); conf.put("target.field.info.class.name", fieldInfoClassName(fieldClass)); conf.put("target.class.name", targetClassName); conf.put("map.getter", mapGetter(fieldPaths)); conf.put("map.getter.if", mapFieldTypeIfStatement(Templates.mapGetIf, fieldPaths)); conf.put("map.setter", mapSetter(fieldPaths)); conf.put("map.setter.if", mapFieldTypeIfStatement(Templates.mapSetIf, fieldPaths)); conf.put("map.properties", mapFieldProperties(fieldPaths, modelClass)); conf.put("source.generator.name", getClass().getName()); String content = MacroProcessor.replaceProperties(Templates.wrapperClass, conf); Files.write(content, targetFile, Charset.forName("UTF8")); getLog().info("written : " + targetFile); } catch (IOException e) { throw new RuntimeException("error when generating wrapper", e); } } private String baseClassName(Class<? extends FieldModel> baseClazz, Class<?> modelClass) { if (AbstractWrapper.class.equals(baseClazz)) { return AbstractWrapper.class.getSimpleName() + "<" + modelClass.getSimpleName() + ">"; } else { return baseClazz.getSimpleName(); } } }
Fix for class type verification
generator/src/main/java/io/doov/gen/ModelMapGenMojo.java
Fix for class type verification
<ide><path>enerator/src/main/java/io/doov/gen/ModelMapGenMojo.java <ide> Class<? extends T> classToLoad = defaultClass; <ide> if (className != null) { <ide> Class<?> loadedClass = Class.forName(className, true, classLoader); <del> if (!type.isAssignableFrom(type)) { <add> if (!type.isAssignableFrom(loadedClass)) { <ide> throw new MojoExecutionException("Class " + loadedClass + " does not implement " + type.getName()); <ide> } <ide> classToLoad = (Class<? extends T>) loadedClass;
JavaScript
mit
923edadc9225e32241032f9149bb51a690cf8fab
0
nikolay-saskovets/typecode-js,Architizer/typecode-js
/* ============================================================================ >4SESz., _, ,gSEE2zx.,_ .azx ,w. @Sh. "QEE3. JEE3. &ss `*4EEEEE2x.,_ "EEV ,aS5^;dEEEE2x., VEEF _ \E2`_,gF4EEEx.?jF EE5L `*4EEEEE2zpn..ZEEF ;sz. `*EEESzw.w* '|EE. ,dEEF `"?j] _,_ ,_ _, _,. L.EEEF !EEF _,, `"`` EE7 ,,_ :EEE7 ,ws,`|EEL`JEEL`JEE)`JEEL zE5` E3. / [EE3 ,w. zE2` Ek .zE5^JZE3.,6EF [3 {EEE. VEE7.EE2 AE3. EEV ZEEL{EEL ws. ; [EE1 EEEt{E3. JEELEE3. JE5LJEEF ,w, \EEk,,>^ JEEL,@EEF ZE5L,ZE5^ "Q3. V2`. \EEk,,J' "Q[ yE2^ VE[_zEE[,"QEL V5F ,ss :EE7 ;EEF L,szzw.. ,., `` \E5.,E5F EE1. /; ``*4EEEZhw._ EEEL ```` `` JEEE. `"45EEEhw.,,,] From 2010 till ∞ typecode-js v 0.1 */ // this carousel implementation is based on the jQuery Tools "scrollable" implementation: // https://github.com/jquerytools/jquerytools/blob/master/src/scrollable/scrollable.js define(['jquery', 'NIseed'], function($) { var window = this, NI = window.NI, generate, focussed; generate = { carousel: function() { return $('<div class="carousel">\ <div class="viewport" style="overflow:hidden; position:relative;"">\ <div class="scroll" style="position:absolute; width:20000em;"></div>\ </div>\ </div>'); }, prev_btn: function(instance) { var $btn; $btn = $('<a href="#" class="btn btn-prev"><span>Previous</span></a>'); if (instance) { $btn.on('click.carousel', function(e) { e.preventDefault(); instance.prev(); }); } return $btn; }, next_btn: function(instance) { var $btn; $btn = $('<a href="#" class="btn btn-next"><span>Next</span></a>'); if (instance) { $btn.on('click.carousel', function(e) { e.preventDefault(); instance.next(); }); } return $btn; } }; function Carousel(options) { var me, o, $e, selectors, $elements, handlers, touch_info; me = this; // assumes arguments are class selectors specified without a '.' o = $.extend({ $e: null, viewport_dimensions: null, // { width: null, height: null }, viewport_class: 'viewport', scroll_class: 'scroll', panels: [], panel_class: 'panel', active_class: 'state-active', disabled_class: 'state-disabled', clone_class: 'clone', speed: 400, easing: 'swing', vertical: false, circular: true, elastic: false, elastic_delay: 100, keyboard: true, touch: true, offset: 0, on_before_move: function(instance, info) {}, on_move: function(instance, info) {} }, options); function init() { var $viewport; if (o.$e) { if (typeof o.$e === 'string') { o.$e = $(o.$e); } $e = o.$e; } else { $e = generate.carousel(); } selectors = { panel: '.' + o.panel_class, active: '.' + o.active_class, clone: '.' + o.clone_class }; $viewport = $e.find('.' + o.viewport_class); $elements = { viewport: $viewport, scroll: $viewport.find('.' + o.scroll_class), current_target: null, prev_btn: null, next_btn: null }; if (o.viewport_dimensions) { if (o.elastic) { o.viewport_dimensions = null; } else { if (typeof o.viewport_dimensions.width === 'number') { $elements.viewport.width(o.viewport_dimensions.width); } if (typeof o.viewport_dimensions.height === 'number') { $elements.viewport.height(o.viewport_dimensions.height); } } } if (o.keyboard) { $(window.document).on('keydown.carousel', handlers.keydown); } if (o.touch) { touch_info = {}; $elements.scroll[0].ontouchstart = handlers.touchstart; $elements.scroll[0].ontouchmove = handlers.touchmove; } if (o.elastic) { elastic_panel_sync(); $(window).on('resize', handlers.elastic_resize); } if (o.panels && o.panels.length) { $.each(o.panels, function(i, $panel) { me.add($panel); }); } me.set_orientation(o.vertical); me.begin(true); } function current() { return $elements.scroll.find(selectors.panel + selectors.active); } function target_position($panel) { if (o.vertical) { if (o.viewport_dimensions && typeof o.viewport_dimensions.height === 'number') { //return {top: -($panel.index()*o.viewport_dimensions.height) + o.offset}; return {top: -($panel.index()*o.viewport_dimensions.height)}; } //return {top: -($panel.position().top) + o.offset}; return {top: -($panel.position().top)}; } if (o.viewport_dimensions && typeof o.viewport_dimensions.width === 'number') { return {left: -($panel.index()*o.viewport_dimensions.width)}; } return {left: -($panel.position().left)}; } function move_to($panel, no_anim) { var info, $clone_target = false; if (!$panel.length) { return me; } $elements.current_target = $panel; // Determine if the target panel is a clone. // If it is, keep track of the real panel as $clone_target if ($panel.hasClass(o.clone_class)) { $clone_target = $elements.scroll.children(selectors.panel).not(selectors.clone)[$panel.hasClass('head') ? 'last' : 'first'](); $clone_target.addClass(o.active_class).siblings().removeClass(o.active_class); } else { $panel.addClass(o.active_class).siblings().removeClass(o.active_class); } info = me.info(); if ($clone_target) { info.is_clone = true; info.clone_target = $clone_target; } else { info.is_clone = false; info.clone_target = null; } if ($.isFunction(o.on_before_move)) { if (o.on_before_move(me, info) === false) { return me; } } $elements.scroll.stop(true, false).animate(target_position($panel), (no_anim ? 0 : o.speed), o.easing, function() { $elements.current_target = null; if ($clone_target) { $elements.scroll.css(target_position($clone_target)); } if (!o.circular) { if ($elements.prev_btn.length) { $elements.prev_btn[info.index === 0 ? 'addClass' : 'removeClass'](o.disabled_class); } if ($elements.next_btn.length) { $elements.next_btn[info.index === info.total-1 ? 'addClass' : 'removeClass'](o.disabled_class); } } if ($.isFunction(o.on_move)) { o.on_move(me, info); } } ); return me; } function elastic_panel_sync($panel) { var w, h; w = $e.width(); h = $e.height(); if (!$panel) { $panel = $elements.scroll.children(selectors.panel); } $panel.width(w).height(h); } function sync_current_animation() { if ($elements.current_target) { move_to($elements.current_target, true); } else { move_to(current(), true); } return me; } function register_btn(key) { var $btn; $btn = generate[key](me); if ($elements[key]) { $elements[key].add($btn); } else { $elements[key] = $btn; } return $btn; } handlers = { keydown: function(e) { if (focussed != me) { return; } if (me.info().total < 2) { return; } switch (e.which) { case NI.co.keyboard.LEFT: e.preventDefault(); me.prev(); break; case NI.co.keyboard.RIGHT: e.preventDefault(); me.next(); break; } }, touchstart: function(e) { touch_info.x = e.touches[0].clientX; touch_info.y = e.touches[0].clientY; }, touchmove: function(e) { var dx, dy; if (e.touches.length === 1 && !$elements.scroll.is(':animated')) { e.preventDefault(); dx = touch_info.x - e.touches[0].clientX; dy = touch_info.y - e.touches[0].clientY; me[o.vertical && dy > 0 || !o.vertical && dx > 0 ? 'next' : 'prev'](); } }, elastic_resize: NI.fn.debounce(function(e) { elastic_panel_sync(); sync_current_animation(); }, o.elastic_delay) }; // return an object with a reference to the currently active panel, // the current index, and the total number of panels this.info = function() { var $panels, $current, $current_clone, $next, $prev,index; $panels = $elements.scroll.children(selectors.panel).not(selectors.clone); $panels_with_clones = $elements.scroll.children(selectors.panel); $panels.each(function(i, panel) { var $p = $(panel); if ($p.hasClass(o.active_class)) { $prev = $p.prev(); $next = $p.next(); $current = $p; index = i; return false; } }); return { $current: $current, $next: $next, $prev: $prev, index: index, total: $panels.length, $panels: $panels, $panels_with_clones: $panels_with_clones }; }; // add a panel to the end of the carousel // (chainable) this.add = function($panel) { $panel.addClass(o.panel_class); //if (!o.vertical) { // $panel.css('float', 'left'); //} if (o.elastic) { elastic_panel_sync($panel); } else if (o.viewport_dimensions) { if (typeof o.viewport_dimensions.width === 'number') { $panel.width(o.viewport_dimensions.width); } if (typeof o.viewport_dimensions.height === 'number') { $panel.height(o.viewport_dimensions.height); } } $elements.scroll.append($panel); return this; }; // remove a panel from the carousel, // (return the removed panel) this.remove = function($panel) { var info, panel_index, current_index; if (!($.contains($elements.scroll[0], $panel[0])) || $panel.hasClass(o.clone_class)) { return false; } info = this.info(); if (info.total === 1) { $elements.scroll.children(selectors.clone).remove(); return $panel.detach(); } panel_index = $panel.index(); current_index = info.$current.index(); $panel.detach(); // if the removed panel came before the currently active panel, // update the offset of the scroll element if (panel_index < current_index) { move_to(info.$current, true); } // if the removed panel was the currently active panel, // activate the previous sibling panel else if (panel_index === current_index) { this.to_index(current_index - 1, true); } return $panel; }; // generate a 'previous' button bound to this instance // return a headless jQuery element representing the button this.register_prev_btn = function() { return register_btn('prev_btn'); }; // generate a 'next' button bound to this instance // return a headless jQuery element representing the button this.register_next_btn = function() { return register_btn('next_btn'); }; // return the jQuery element that represents the carousel this.get$e = function() { return $e; }; // Tell the Carousel to check itself before it wr-wr-wrecks itself. // If the Carousel is circular, generate its secret clone elements. // The Carousel should be refreshed after panels have been added to or removed from it. // add() and remove() do not automatically call refresh() (to allow for simultaneous calls // to manipulate the Carousel in row, without consecutively refreshing). // (chainable) this.refresh = function() { var $panels; if (o.circular) { $elements.scroll.children(selectors.clone).remove(); $panels = $elements.scroll.children(selectors.panel); $panels.last().clone(false).addClass(o.clone_class +' head').prependTo($elements.scroll); $panels.first().clone(false).addClass(o.clone_class +' tail').appendTo($elements.scroll); } return this; }; // move to the first panel and automatically refresh // (unless no_refresh is true) // (chainable) this.begin = function(no_anim, no_refresh) { if (!no_refresh) { this.refresh(); } return move_to($elements.scroll.children(selectors.panel).not(selectors.clone).first(), no_anim); }; // move to the last panel // (chainable) this.end = function(no_anim) { return move_to($elements.scroll.children(selectors.panel).not(selectors.clone).last(), no_anim); }; // move to the panel at the specified index // (chainable) this.to_index = function(index, no_anim) { $elements.scroll.children(selectors.panel).not(selectors.clone).each(function(i, panel) { if (i === index) { move_to($(panel), no_anim); return false; } }); return this; }; // move to the next panel // (chainable) this.next = function(no_anim) { return move_to(current().next(selectors.panel), no_anim); }; // move to the previous panel // (chainable) this.prev = function(no_anim) { return move_to(current().prev(selectors.panel), no_anim); }; // set focus on this carousel // (chainable) this.focus = function() { focussed = me; return me; }; // remove focus from this carousel // (chainable) this.blur = function() { if (focussed == me) { focussed = null; } return me; }; // set the carousel to vertical or horizontal // (chainable) this.set_orientation = function(vertical) { if (vertical === true) { o.vertical = true; $e.addClass('orientation-vertical'); $e.removeClass('orientation-horizontal'); } else { o.vertical = false; $e.removeClass('orientation-vertical'); $e.addClass('orientation-horizontal'); } return me; }; // destroy this instance // (the carousel element is automatically removed from the DOM) this.destroy = function() { me.blur(); if (o.elastic) { $(window).off('resize', handlers.elastic_resize); } if (o.keyboard) { $(window.document).off('keydown.carousel', handlers.keydown); } if ($elements.prev_btn && $elements.prev_btn.length) { $elements.prev_btn.off('click.carousel'); } if ($elements.next_btn && $elements.next_btn.length) { $elements.next_btn.off('click.carousel'); } $e.remove(); }; init(); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: NI.Carousel = Carousel; NI.Carousel.Generator = generate; });
lib/Carousel.js
/* ============================================================================ >4SESz., _, ,gSEE2zx.,_ .azx ,w. @Sh. "QEE3. JEE3. &ss `*4EEEEE2x.,_ "EEV ,aS5^;dEEEE2x., VEEF _ \E2`_,gF4EEEx.?jF EE5L `*4EEEEE2zpn..ZEEF ;sz. `*EEESzw.w* '|EE. ,dEEF `"?j] _,_ ,_ _, _,. L.EEEF !EEF _,, `"`` EE7 ,,_ :EEE7 ,ws,`|EEL`JEEL`JEE)`JEEL zE5` E3. / [EE3 ,w. zE2` Ek .zE5^JZE3.,6EF [3 {EEE. VEE7.EE2 AE3. EEV ZEEL{EEL ws. ; [EE1 EEEt{E3. JEELEE3. JE5LJEEF ,w, \EEk,,>^ JEEL,@EEF ZE5L,ZE5^ "Q3. V2`. \EEk,,J' "Q[ yE2^ VE[_zEE[,"QEL V5F ,ss :EE7 ;EEF L,szzw.. ,., `` \E5.,E5F EE1. /; ``*4EEEZhw._ EEEL ```` `` JEEE. `"45EEEhw.,,,] From 2010 till ∞ typecode-js v 0.1 */ // this carousel implementation is based on the jQuery Tools "scrollable" implementation: // https://github.com/jquerytools/jquerytools/blob/master/src/scrollable/scrollable.js define(['jquery', 'NIseed'], function($) { var window = this, NI = window.NI, generate, focussed; generate = { carousel: function() { return $('<div class="carousel">\ <div class="viewport" style="overflow:hidden; position:relative;"">\ <div class="scroll" style="position:absolute; width:20000em;"></div>\ </div>\ </div>'); }, prev_btn: function(instance) { var $btn; $btn = $('<a href="#" class="btn btn-prev"><span>Previous</span></a>'); if (instance) { $btn.on('click.carousel', function(e) { e.preventDefault(); instance.prev(); }); } return $btn; }, next_btn: function(instance) { var $btn; $btn = $('<a href="#" class="btn btn-next"><span>Next</span></a>'); if (instance) { $btn.on('click.carousel', function(e) { e.preventDefault(); instance.next(); }); } return $btn; } }; function Carousel(options) { var me, o, $e, selectors, $elements, handlers, touch_info; me = this; // assumes arguments are class selectors specified without a '.' o = $.extend({ $e: null, viewport_dimensions: null, // { width: null, height: null }, viewport_class: 'viewport', scroll_class: 'scroll', panels: [], panel_class: 'panel', active_class: 'state-active', disabled_class: 'state-disabled', clone_class: 'clone', speed: 400, easing: 'swing', vertical: false, circular: true, elastic: false, elastic_delay: 100, keyboard: true, touch: true, on_before_move: function(instance, info) {}, on_move: function(instance, info) {} }, options); function init() { var $viewport; if (o.$e) { if (typeof o.$e === 'string') { o.$e = $(o.$e); } $e = o.$e; } else { $e = generate.carousel(); } selectors = { panel: '.' + o.panel_class, active: '.' + o.active_class, clone: '.' + o.clone_class }; $viewport = $e.find('.' + o.viewport_class); $elements = { viewport: $viewport, scroll: $viewport.find('.' + o.scroll_class), current_target: null, prev_btn: null, next_btn: null }; if (o.viewport_dimensions) { if (o.elastic) { o.viewport_dimensions = null; } else { if (typeof o.viewport_dimensions.width === 'number') { $elements.viewport.width(o.viewport_dimensions.width); } if (typeof o.viewport_dimensions.height === 'number') { $elements.viewport.height(o.viewport_dimensions.height); } } } if (o.keyboard) { $(window.document).on('keydown.carousel', handlers.keydown); } if (o.touch) { touch_info = {}; $elements.scroll[0].ontouchstart = handlers.touchstart; $elements.scroll[0].ontouchmove = handlers.touchmove; } if (o.elastic) { elastic_panel_sync(); $(window).on('resize', handlers.elastic_resize); } if (o.panels && o.panels.length) { $.each(o.panels, function(i, $panel) { me.add($panel); }); } me.set_orientation(o.vertical); me.begin(true); } function current() { return $elements.scroll.find(selectors.panel + selectors.active); } function target_position($panel) { if (o.vertical) { if (o.viewport_dimensions && typeof o.viewport_dimensions.height === 'number') { return {top: -($panel.index()*o.viewport_dimensions.height)}; } return {top: -($panel.position().top)}; } if (o.viewport_dimensions && typeof o.viewport_dimensions.width === 'number') { return {left: -($panel.index()*o.viewport_dimensions.width)}; } return {left: -($panel.position().left)}; } function move_to($panel, no_anim) { var $clone_target = false, info; if (!$panel.length) { return me; } $elements.current_target = $panel; // Determine if the target panel is a clone. // If it is, keep track of the real panel as $clone_target if ($panel.hasClass(o.clone_class)) { $clone_target = $elements.scroll.children(selectors.panel).not(selectors.clone)[$panel.hasClass('head') ? 'last' : 'first'](); $clone_target.addClass(o.active_class).siblings().removeClass(o.active_class); } else { $panel.addClass(o.active_class).siblings().removeClass(o.active_class); } info = me.info(); if ($.isFunction(o.on_before_move)) { if (o.on_before_move(me, info) === false) { return me; } } $elements.scroll.stop(true, false).animate(target_position($panel), (no_anim ? 0 : o.speed), o.easing, function() { $elements.current_target = null; if ($clone_target) { $elements.scroll.css(target_position($clone_target)); } if (!o.circular) { if ($elements.prev_btn.length) { $elements.prev_btn[info.index === 0 ? 'addClass' : 'removeClass'](o.disabled_class); } if ($elements.next_btn.length) { $elements.next_btn[info.index === info.total-1 ? 'addClass' : 'removeClass'](o.disabled_class); } } if ($.isFunction(o.on_move)) { o.on_move(me, info); } } ); return me; } function elastic_panel_sync($panel) { var w, h; w = $e.width(); h = $e.height(); if (!$panel) { $panel = $elements.scroll.children(selectors.panel); } $panel.width(w).height(h); } function sync_current_animation() { if ($elements.current_target) { move_to($elements.current_target, true); } else { move_to(current(), true); } return me; } function register_btn(key) { var $btn; $btn = generate[key](me); if ($elements[key]) { $elements[key].add($btn); } else { $elements[key] = $btn; } return $btn; } handlers = { keydown: function(e) { if (focussed != me) { return; } if (me.info().total < 2) { return; } switch (e.which) { case NI.co.keyboard.LEFT: e.preventDefault(); me.prev(); break; case NI.co.keyboard.RIGHT: e.preventDefault(); me.next(); break; } }, touchstart: function(e) { touch_info.x = e.touches[0].clientX; touch_info.y = e.touches[0].clientY; }, touchmove: function(e) { var dx, dy; if (e.touches.length === 1 && !$elements.scroll.is(':animated')) { e.preventDefault(); dx = touch_info.x - e.touches[0].clientX; dy = touch_info.y - e.touches[0].clientY; me[o.vertical && dy > 0 || !o.vertical && dx > 0 ? 'next' : 'prev'](); } }, elastic_resize: NI.fn.debounce(function(e) { elastic_panel_sync(); sync_current_animation(); }, o.elastic_delay) }; // return an object with a reference to the currently active panel, // the current index, and the total number of panels this.info = function() { var $panels, $current, index; $panels = $elements.scroll.children(selectors.panel).not(selectors.clone); $panels.each(function(i, panel) { var $p = $(panel); if ($p.hasClass(o.active_class)) { $current = $p; index = i; return false; } }); return { $current: $current, index: index, total: $panels.length }; }; // add a panel to the end of the carousel // (chainable) this.add = function($panel) { $panel.addClass(o.panel_class); //if (!o.vertical) { // $panel.css('float', 'left'); //} if (o.elastic) { elastic_panel_sync($panel); } else if (o.viewport_dimensions) { if (typeof o.viewport_dimensions.width === 'number') { $panel.width(o.viewport_dimensions.width); } if (typeof o.viewport_dimensions.height === 'number') { $panel.height(o.viewport_dimensions.height); } } $elements.scroll.append($panel); return this; }; // remove a panel from the carousel, // (return the removed panel) this.remove = function($panel) { var info, panel_index, current_index; if (!($.contains($elements.scroll[0], $panel[0])) || $panel.hasClass(o.clone_class)) { return false; } info = this.info(); if (info.total === 1) { $elements.scroll.children(selectors.clone).remove(); return $panel.detach(); } panel_index = $panel.index(); current_index = info.$current.index(); $panel.detach(); // if the removed panel came before the currently active panel, // update the offset of the scroll element if (panel_index < current_index) { move_to(info.$current, true); } // if the removed panel was the currently active panel, // activate the previous sibling panel else if (panel_index === current_index) { this.to_index(current_index - 1, true); } return $panel; }; // generate a 'previous' button bound to this instance // return a headless jQuery element representing the button this.register_prev_btn = function() { return register_btn('prev_btn'); }; // generate a 'next' button bound to this instance // return a headless jQuery element representing the button this.register_next_btn = function() { return register_btn('next_btn'); }; // return the jQuery element that represents the carousel this.get$e = function() { return $e; }; // Tell the Carousel to check itself before it wr-wr-wrecks itself. // If the Carousel is circular, generate its secret clone elements. // The Carousel should be refreshed after panels have been added to or removed from it. // add() and remove() do not automatically call refresh() (to allow for simultaneous calls // to manipulate the Carousel in row, without consecutively refreshing). // (chainable) this.refresh = function() { var $panels; if (o.circular) { $elements.scroll.children(selectors.clone).remove(); $panels = $elements.scroll.children(selectors.panel); $panels.last().clone(false).addClass(o.clone_class +' head').prependTo($elements.scroll); $panels.first().clone(false).addClass(o.clone_class +' tail').appendTo($elements.scroll); } return this; }; // move to the first panel and automatically refresh // (unless no_refresh is true) // (chainable) this.begin = function(no_anim, no_refresh) { if (!no_refresh) { this.refresh(); } return move_to($elements.scroll.children(selectors.panel).not(selectors.clone).first(), no_anim); }; // move to the last panel // (chainable) this.end = function(no_anim) { return move_to($elements.scroll.children(selectors.panel).not(selectors.clone).last(), no_anim); }; // move to the panel at the specified index // (chainable) this.to_index = function(index, no_anim) { $elements.scroll.children(selectors.panel).not(selectors.clone).each(function(i, panel) { if (i === index) { move_to($(panel), no_anim); return false; } }); return this; }; // move to the next panel // (chainable) this.next = function(no_anim) { return move_to(current().next(selectors.panel), no_anim); }; // move to the previous panel // (chainable) this.prev = function(no_anim) { return move_to(current().prev(selectors.panel), no_anim); }; // set focus on this carousel // (chainable) this.focus = function() { focussed = me; return me; }; // remove focus from this carousel // (chainable) this.blur = function() { if (focussed == me) { focussed = null; } return me; }; // set the carousel to vertical or horizontal // (chainable) this.set_orientation = function(vertical) { if (vertical === true) { o.vertical = true; $e.addClass('orientation-vertical'); $e.removeClass('orientation-horizontal'); } else { o.vertical = false; $e.removeClass('orientation-vertical'); $e.addClass('orientation-horizontal'); } return me; }; // destroy this instance // (the carousel element is automatically removed from the DOM) this.destroy = function() { me.blur(); if (o.elastic) { $(window).off('resize', handlers.elastic_resize); } if (o.keyboard) { $(window.document).off('keydown.carousel', handlers.keydown); } if ($elements.prev_btn && $elements.prev_btn.length) { $elements.prev_btn.off('click.carousel'); } if ($elements.next_btn && $elements.next_btn.length) { $elements.next_btn.off('click.carousel'); } $e.remove(); }; init(); } //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: NI.Carousel = Carousel; NI.Carousel.Generator = generate; });
add offset and other tweaks to Carousel
lib/Carousel.js
add offset and other tweaks to Carousel
<ide><path>ib/Carousel.js <ide> elastic_delay: 100, <ide> keyboard: true, <ide> touch: true, <add> offset: 0, <ide> on_before_move: function(instance, info) {}, <ide> on_move: function(instance, info) {} <ide> }, options); <ide> function target_position($panel) { <ide> if (o.vertical) { <ide> if (o.viewport_dimensions && typeof o.viewport_dimensions.height === 'number') { <add> //return {top: -($panel.index()*o.viewport_dimensions.height) + o.offset}; <ide> return {top: -($panel.index()*o.viewport_dimensions.height)}; <ide> } <add> //return {top: -($panel.position().top) + o.offset}; <ide> return {top: -($panel.position().top)}; <ide> } <ide> if (o.viewport_dimensions && typeof o.viewport_dimensions.width === 'number') { <ide> } <ide> <ide> function move_to($panel, no_anim) { <del> var $clone_target = false, info; <add> var info, $clone_target = false; <ide> <ide> if (!$panel.length) { <ide> return me; <ide> } <ide> <ide> info = me.info(); <add> <add> if ($clone_target) { <add> info.is_clone = true; <add> info.clone_target = $clone_target; <add> } else { <add> info.is_clone = false; <add> info.clone_target = null; <add> } <ide> <ide> if ($.isFunction(o.on_before_move)) { <ide> if (o.on_before_move(me, info) === false) { <ide> // return an object with a reference to the currently active panel, <ide> // the current index, and the total number of panels <ide> this.info = function() { <del> var $panels, $current, index; <add> var $panels, $current, $current_clone, $next, $prev,index; <ide> $panels = $elements.scroll.children(selectors.panel).not(selectors.clone); <add> $panels_with_clones = $elements.scroll.children(selectors.panel); <ide> $panels.each(function(i, panel) { <ide> var $p = $(panel); <ide> if ($p.hasClass(o.active_class)) { <add> $prev = $p.prev(); <add> $next = $p.next(); <ide> $current = $p; <ide> index = i; <ide> return false; <ide> }); <ide> return { <ide> $current: $current, <add> $next: $next, <add> $prev: $prev, <ide> index: index, <del> total: $panels.length <add> total: $panels.length, <add> $panels: $panels, <add> $panels_with_clones: $panels_with_clones <ide> }; <ide> }; <ide>
Java
apache-2.0
9322f8ec7fe6fe991dfe73bc7fe662aed81c7d67
0
evanchooly/morphia,evanchooly/morphia
package com.google.code.morphia.issue148; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.bson.types.ObjectId; import org.junit.Assert; import org.junit.Ignore; import org.junit.Test; import com.google.code.morphia.Datastore; import com.google.code.morphia.Morphia; import com.google.code.morphia.TestBase; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Id; import com.google.code.morphia.mapping.cache.DefaultEntityCache; import com.google.code.morphia.mapping.cache.EntityCache; import com.google.code.morphia.query.Query; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; @Ignore("enable when testing on issue") public class TestAsListPerf extends TestBase { final int addressNb = 2000; final int nbOfTasks = 300; final int threadPool = 10; @Override public void setUp() { super.setUp(); morphia.map(Address.class); for (int i = 0; i < addressNb; i++) { Address address = new Address(i); ds.save(address); } } @Test public void compareDriverAndMorphiaQueryingOnce() throws Exception { double driverAvg = driverQueryAndMorphiaConv(addressNb / 2, ds, morphia); double morphiaAvg = morphiaQueryAndMorphiaConv(addressNb / 2, ds, morphia); System.out.println(String.format("compareDriverAndMorphiaQueryingOnce - driver: %4.2f ms/pojo , morphia: %4.2f ms/pojo ", driverAvg , morphiaAvg)); Assert.assertNotNull(driverAvg); } @Test public void morphiaQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result morphiaQueryThreadsResult = new Result(nbOfTasks); List<MorphiaQueryThread> morphiaThreads = new ArrayList<MorphiaQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { morphiaThreads.add(new MorphiaQueryThread(morphiaQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService morphiaPool = Executors.newFixedThreadPool(threadPool); for (MorphiaQueryThread thread : morphiaThreads) { morphiaPool.execute(thread); } morphiaPool.shutdown(); morphiaPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("morphiaQueryingMultithreaded - %d morphia queries in an average time of %4.2f ms/pojo", morphiaQueryThreadsResult.results.size(), morphiaQueryThreadsResult.getAverageTime())); } @Test public void driverQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result mongoQueryThreadsResult = new Result(nbOfTasks); List<MongoQueryThread> mongoThreads = new ArrayList<MongoQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { mongoThreads.add(new MongoQueryThread(mongoQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService mongoPool = Executors.newFixedThreadPool(threadPool); for (MongoQueryThread mongoQueryThread : mongoThreads) { mongoPool.execute(mongoQueryThread); } mongoPool.shutdown(); mongoPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("driverQueryingMultithreaded - %d driver queries in an average time of %4.2f ms/pojo", mongoQueryThreadsResult.results.size(), mongoQueryThreadsResult.getAverageTime())); } @Test public void compareMorphiaAndDriverQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result morphiaQueryThreadsResult = new Result(nbOfTasks); List<MorphiaQueryThread> morphiaThreads = new ArrayList<MorphiaQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { morphiaThreads.add(new MorphiaQueryThread(morphiaQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService morphiaPool = Executors.newFixedThreadPool(threadPool); for (MorphiaQueryThread thread : morphiaThreads) { morphiaPool.execute(thread); } morphiaPool.shutdown(); morphiaPool.awaitTermination(30, TimeUnit.SECONDS); Result mongoQueryThreadsResult = new Result(nbOfTasks); List<MongoQueryThread> mongoThreads = new ArrayList<MongoQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { mongoThreads.add(new MongoQueryThread(mongoQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService mongoPool = Executors.newFixedThreadPool(threadPool); for (MongoQueryThread mongoQueryThread : mongoThreads) { mongoPool.execute(mongoQueryThread); } mongoPool.shutdown(); mongoPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("compareMorphiaAndDriverQueryingMultithreaded (%d queries each) - driver average time: %4.2f ms/pojo, morphia average time %4.2f ms/pojo", mongoQueryThreadsResult.results.size(), mongoQueryThreadsResult.getAverageTime(), morphiaQueryThreadsResult.getAverageTime())); } @Test public void compareDriverAndMorphiaQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result mongoQueryThreadsResult = new Result(nbOfTasks); List<MongoQueryThread> mongoThreads = new ArrayList<MongoQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { mongoThreads.add(new MongoQueryThread(mongoQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService mongoPool = Executors.newFixedThreadPool(threadPool); for (MongoQueryThread mongoQueryThread : mongoThreads) { mongoPool.execute(mongoQueryThread); } mongoPool.shutdown(); mongoPool.awaitTermination(30, TimeUnit.SECONDS); Result morphiaQueryThreadsResult = new Result(nbOfTasks); List<MorphiaQueryThread> morphiaThreads = new ArrayList<MorphiaQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { morphiaThreads.add(new MorphiaQueryThread(morphiaQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService morphiaPool = Executors.newFixedThreadPool(threadPool); for (MorphiaQueryThread thread : morphiaThreads) { morphiaPool.execute(thread); } morphiaPool.shutdown(); morphiaPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("compareDriverAndMorphiaQueryingMultithreaded (%d queries each) - driver average time: %4.2f ms/pojo, morphia average time %4.2f ms/pojo", mongoQueryThreadsResult.results.size(), mongoQueryThreadsResult.getAverageTime(), morphiaQueryThreadsResult.getAverageTime())); } static class Result { private final Vector<Double> results; public Result(final int nbOfHits) { results = new Vector<Double>(nbOfHits); } public double getAverageTime() { Double total = 0d; for (Double duration : results) { total += duration; } return total / results.size(); } } static class MorphiaQueryThread implements Runnable { private final Result result; private final int nbOfHits; private final Datastore ds; private final Morphia morphia; public MorphiaQueryThread(final Result result, final int nbOfHits, final Datastore ds, final Morphia morphia) { this.result = result; this.nbOfHits = nbOfHits; this.ds = ds; this.morphia = morphia; } public void run() { result.results.add(morphiaQueryAndMorphiaConv(nbOfHits, ds, morphia)); } } static class MongoQueryThread implements Runnable { private final Result result; private final int nbOfHits; private final Datastore ds; private final Morphia morphia; public MongoQueryThread(final Result result, final int nbOfHits, final Datastore ds, final Morphia morphia) { this.result = result; this.nbOfHits = nbOfHits; this.ds = ds; this.morphia = morphia; } public void run() { result.results.add(driverQueryAndMorphiaConv(nbOfHits, ds, morphia)); } } public static double morphiaQueryAndMorphiaConv(final int nbOfHits, final Datastore ds, final Morphia morphia) { Query<Address> query = ds.createQuery(Address.class); query.field("parity").equal(0); long start = System.nanoTime(); List<Address> resultList = query.asList(); long duration = (System.nanoTime() - start) / 1000000; //ns -> ms Assert.assertEquals(nbOfHits, resultList.size()); return (double)duration/nbOfHits; } public static double driverQueryAndMorphiaConv(final int nbOfHits, final Datastore ds, final Morphia morphia) { BasicDBObject query = new BasicDBObject(); query.append("parity", 0); long start = System.nanoTime(); List<DBObject> list = ds.getDB().getCollection("Address").find(query).toArray(); EntityCache entityCache = new DefaultEntityCache(); List<Address> resultList = new LinkedList<Address>(); for (DBObject dbObject : list) { Address address = morphia.fromDBObject(Address.class, dbObject, entityCache); resultList.add(address); } long duration = (System.nanoTime() - start) / 1000000; //ns -> ms Assert.assertEquals(nbOfHits, resultList.size()); return (double)duration/nbOfHits; } @Entity private static class Address { public Address() { } public Address(final int i) { parity = i % 2 == 0 ? 1 : 0; name += i; street += i; city += i; state += i; zip += i; } @Id ObjectId id; int parity; String name = "Scott"; String street = "3400 Maple"; String city = "Manhattan Beach"; String state = "CA"; int zip = 94114; Date added = new Date(); } }
morphia/src/test/java/com/google/code/morphia/issue148/TestAsListPerf.java
package com.google.code.morphia.issue148; import java.util.ArrayList; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.bson.types.ObjectId; import org.junit.Assert; import org.junit.Test; import com.google.code.morphia.Datastore; import com.google.code.morphia.Morphia; import com.google.code.morphia.TestBase; import com.google.code.morphia.annotations.Entity; import com.google.code.morphia.annotations.Id; import com.google.code.morphia.mapping.cache.DefaultEntityCache; import com.google.code.morphia.mapping.cache.EntityCache; import com.google.code.morphia.query.Query; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; //@Ignore("enable when testing on issue") public class TestAsListPerf extends TestBase { final int addressNb = 2000; final int nbOfTasks = 300; final int threadPool = 10; @Override public void setUp() { super.setUp(); morphia.map(Address.class); for (int i = 0; i < addressNb; i++) { Address address = new Address(i); ds.save(address); } } @Test public void compareDriverAndMorphiaQueryingOnce() throws Exception { double driverAvg = driverQueryAndMorphiaConv(addressNb / 2, ds, morphia); double morphiaAvg = morphiaQueryAndMorphiaConv(addressNb / 2, ds, morphia); System.out.println(String.format("compareDriverAndMorphiaQueryingOnce - driver: %4.2f ms/pojo , morphia: %4.2f ms/pojo ", driverAvg , morphiaAvg)); Assert.assertNotNull(driverAvg); } @Test public void morphiaQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result morphiaQueryThreadsResult = new Result(nbOfTasks); List<MorphiaQueryThread> morphiaThreads = new ArrayList<MorphiaQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { morphiaThreads.add(new MorphiaQueryThread(morphiaQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService morphiaPool = Executors.newFixedThreadPool(threadPool); for (MorphiaQueryThread thread : morphiaThreads) { morphiaPool.execute(thread); } morphiaPool.shutdown(); morphiaPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("morphiaQueryingMultithreaded - %d morphia queries in an average time of %4.2f ms/pojo", morphiaQueryThreadsResult.results.size(), morphiaQueryThreadsResult.getAverageTime())); } @Test public void driverQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result mongoQueryThreadsResult = new Result(nbOfTasks); List<MongoQueryThread> mongoThreads = new ArrayList<MongoQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { mongoThreads.add(new MongoQueryThread(mongoQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService mongoPool = Executors.newFixedThreadPool(threadPool); for (MongoQueryThread mongoQueryThread : mongoThreads) { mongoPool.execute(mongoQueryThread); } mongoPool.shutdown(); mongoPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("driverQueryingMultithreaded - %d driver queries in an average time of %4.2f ms/pojo", mongoQueryThreadsResult.results.size(), mongoQueryThreadsResult.getAverageTime())); } @Test public void compareMorphiaAndDriverQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result morphiaQueryThreadsResult = new Result(nbOfTasks); List<MorphiaQueryThread> morphiaThreads = new ArrayList<MorphiaQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { morphiaThreads.add(new MorphiaQueryThread(morphiaQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService morphiaPool = Executors.newFixedThreadPool(threadPool); for (MorphiaQueryThread thread : morphiaThreads) { morphiaPool.execute(thread); } morphiaPool.shutdown(); morphiaPool.awaitTermination(30, TimeUnit.SECONDS); Result mongoQueryThreadsResult = new Result(nbOfTasks); List<MongoQueryThread> mongoThreads = new ArrayList<MongoQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { mongoThreads.add(new MongoQueryThread(mongoQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService mongoPool = Executors.newFixedThreadPool(threadPool); for (MongoQueryThread mongoQueryThread : mongoThreads) { mongoPool.execute(mongoQueryThread); } mongoPool.shutdown(); mongoPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("compareMorphiaAndDriverQueryingMultithreaded (%d queries each) - driver average time: %4.2f ms/pojo, morphia average time %4.2f ms/pojo", mongoQueryThreadsResult.results.size(), mongoQueryThreadsResult.getAverageTime(), morphiaQueryThreadsResult.getAverageTime())); } @Test public void compareDriverAndMorphiaQueryingMultithreaded() throws InterruptedException { int nbOfHits = addressNb / 2; Result mongoQueryThreadsResult = new Result(nbOfTasks); List<MongoQueryThread> mongoThreads = new ArrayList<MongoQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { mongoThreads.add(new MongoQueryThread(mongoQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService mongoPool = Executors.newFixedThreadPool(threadPool); for (MongoQueryThread mongoQueryThread : mongoThreads) { mongoPool.execute(mongoQueryThread); } mongoPool.shutdown(); mongoPool.awaitTermination(30, TimeUnit.SECONDS); Result morphiaQueryThreadsResult = new Result(nbOfTasks); List<MorphiaQueryThread> morphiaThreads = new ArrayList<MorphiaQueryThread>(nbOfTasks); for (int i = 0; i < nbOfTasks; i++) { morphiaThreads.add(new MorphiaQueryThread(morphiaQueryThreadsResult, nbOfHits, ds, morphia)); } ExecutorService morphiaPool = Executors.newFixedThreadPool(threadPool); for (MorphiaQueryThread thread : morphiaThreads) { morphiaPool.execute(thread); } morphiaPool.shutdown(); morphiaPool.awaitTermination(30, TimeUnit.SECONDS); System.out.println(String.format("compareDriverAndMorphiaQueryingMultithreaded (%d queries each) - driver average time: %4.2f ms/pojo, morphia average time %4.2f ms/pojo", mongoQueryThreadsResult.results.size(), mongoQueryThreadsResult.getAverageTime(), morphiaQueryThreadsResult.getAverageTime())); } static class Result { private final Vector<Double> results; public Result(final int nbOfHits) { results = new Vector<Double>(nbOfHits); } public double getAverageTime() { Double total = 0d; for (Double duration : results) { total += duration; } return total / results.size(); } } static class MorphiaQueryThread implements Runnable { private final Result result; private final int nbOfHits; private final Datastore ds; private final Morphia morphia; public MorphiaQueryThread(final Result result, final int nbOfHits, final Datastore ds, final Morphia morphia) { this.result = result; this.nbOfHits = nbOfHits; this.ds = ds; this.morphia = morphia; } public void run() { result.results.add(morphiaQueryAndMorphiaConv(nbOfHits, ds, morphia)); } } static class MongoQueryThread implements Runnable { private final Result result; private final int nbOfHits; private final Datastore ds; private final Morphia morphia; public MongoQueryThread(final Result result, final int nbOfHits, final Datastore ds, final Morphia morphia) { this.result = result; this.nbOfHits = nbOfHits; this.ds = ds; this.morphia = morphia; } public void run() { result.results.add(driverQueryAndMorphiaConv(nbOfHits, ds, morphia)); } } public static double morphiaQueryAndMorphiaConv(final int nbOfHits, final Datastore ds, final Morphia morphia) { Query<Address> query = ds.createQuery(Address.class); query.field("parity").equal(0); long start = System.nanoTime(); List<Address> resultList = query.asList(); long duration = (System.nanoTime() - start) / 1000000; //ns -> ms Assert.assertEquals(nbOfHits, resultList.size()); return (double)duration/nbOfHits; } public static double driverQueryAndMorphiaConv(final int nbOfHits, final Datastore ds, final Morphia morphia) { BasicDBObject query = new BasicDBObject(); query.append("parity", 0); long start = System.nanoTime(); List<DBObject> list = ds.getDB().getCollection("Address").find(query).toArray(); EntityCache entityCache = new DefaultEntityCache(); List<Address> resultList = new LinkedList<Address>(); for (DBObject dbObject : list) { Address address = morphia.fromDBObject(Address.class, dbObject, entityCache); resultList.add(address); } long duration = (System.nanoTime() - start) / 1000000; //ns -> ms Assert.assertEquals(nbOfHits, resultList.size()); return (double)duration/nbOfHits; } @Entity private static class Address { public Address() { } public Address(final int i) { parity = i % 2 == 0 ? 1 : 0; name += i; street += i; city += i; state += i; zip += i; } @Id ObjectId id; int parity; String name = "Scott"; String street = "3400 Maple"; String city = "Manhattan Beach"; String state = "CA"; int zip = 94114; Date added = new Date(); } }
ignore by default ...
morphia/src/test/java/com/google/code/morphia/issue148/TestAsListPerf.java
ignore by default ...
<ide><path>orphia/src/test/java/com/google/code/morphia/issue148/TestAsListPerf.java <ide> <ide> import org.bson.types.ObjectId; <ide> import org.junit.Assert; <add>import org.junit.Ignore; <ide> import org.junit.Test; <ide> <ide> import com.google.code.morphia.Datastore; <ide> import com.mongodb.BasicDBObject; <ide> import com.mongodb.DBObject; <ide> <del>//@Ignore("enable when testing on issue") <add>@Ignore("enable when testing on issue") <ide> public class TestAsListPerf extends TestBase { <ide> final int addressNb = 2000; <ide> final int nbOfTasks = 300;
Java
apache-2.0
1f172318ad1cc55026049cac08ffa56f8b4c2ea2
0
akosyakov/intellij-community,amith01994/intellij-community,robovm/robovm-studio,ThiagoGarciaAlves/intellij-community,fitermay/intellij-community,fitermay/intellij-community,asedunov/intellij-community,slisson/intellij-community,apixandru/intellij-community,clumsy/intellij-community,gnuhub/intellij-community,semonte/intellij-community,supersven/intellij-community,adedayo/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,slisson/intellij-community,mglukhikh/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,amith01994/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,diorcety/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,fnouama/intellij-community,Lekanich/intellij-community,supersven/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,samthor/intellij-community,apixandru/intellij-community,kdwink/intellij-community,apixandru/intellij-community,fnouama/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,petteyg/intellij-community,adedayo/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,jagguli/intellij-community,allotria/intellij-community,nicolargo/intellij-community,salguarnieri/intellij-community,diorcety/intellij-community,semonte/intellij-community,suncycheng/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,retomerz/intellij-community,fnouama/intellij-community,fnouama/intellij-community,asedunov/intellij-community,semonte/intellij-community,MER-GROUP/intellij-community,clumsy/intellij-community,jagguli/intellij-community,vladmm/intellij-community,signed/intellij-community,supersven/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,muntasirsyed/intellij-community,fnouama/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,da1z/intellij-community,holmes/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,da1z/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,signed/intellij-community,fitermay/intellij-community,youdonghai/intellij-community,caot/intellij-community,semonte/intellij-community,apixandru/intellij-community,robovm/robovm-studio,salguarnieri/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,caot/intellij-community,lucafavatella/intellij-community,pwoodworth/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,alphafoobar/intellij-community,fnouama/intellij-community,ahb0327/intellij-community,Lekanich/intellij-community,samthor/intellij-community,vladmm/intellij-community,ThiagoGarciaAlves/intellij-community,nicolargo/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,tmpgit/intellij-community,da1z/intellij-community,samthor/intellij-community,ryano144/intellij-community,adedayo/intellij-community,allotria/intellij-community,vladmm/intellij-community,adedayo/intellij-community,asedunov/intellij-community,holmes/intellij-community,tmpgit/intellij-community,ryano144/intellij-community,muntasirsyed/intellij-community,ryano144/intellij-community,asedunov/intellij-community,akosyakov/intellij-community,ahb0327/intellij-community,petteyg/intellij-community,da1z/intellij-community,izonder/intellij-community,MichaelNedzelsky/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,signed/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,blademainer/intellij-community,clumsy/intellij-community,slisson/intellij-community,amith01994/intellij-community,allotria/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,wreckJ/intellij-community,ol-loginov/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,Lekanich/intellij-community,kool79/intellij-community,alphafoobar/intellij-community,diorcety/intellij-community,xfournet/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,alphafoobar/intellij-community,ivan-fedorov/intellij-community,slisson/intellij-community,samthor/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,TangHao1987/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,kdwink/intellij-community,caot/intellij-community,xfournet/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,caot/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,signed/intellij-community,wreckJ/intellij-community,hurricup/intellij-community,diorcety/intellij-community,robovm/robovm-studio,TangHao1987/intellij-community,SerCeMan/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,holmes/intellij-community,da1z/intellij-community,lucafavatella/intellij-community,holmes/intellij-community,adedayo/intellij-community,retomerz/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,wreckJ/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ol-loginov/intellij-community,fengbaicanhe/intellij-community,slisson/intellij-community,jagguli/intellij-community,Distrotech/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,blademainer/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,semonte/intellij-community,ryano144/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,robovm/robovm-studio,gnuhub/intellij-community,SerCeMan/intellij-community,Distrotech/intellij-community,samthor/intellij-community,fnouama/intellij-community,lucafavatella/intellij-community,semonte/intellij-community,samthor/intellij-community,signed/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,kdwink/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,diorcety/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,fengbaicanhe/intellij-community,hurricup/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,petteyg/intellij-community,MichaelNedzelsky/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,retomerz/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,samthor/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,apixandru/intellij-community,pwoodworth/intellij-community,xfournet/intellij-community,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,samthor/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,izonder/intellij-community,diorcety/intellij-community,jagguli/intellij-community,samthor/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,hurricup/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,pwoodworth/intellij-community,orekyuu/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,retomerz/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,nicolargo/intellij-community,tmpgit/intellij-community,robovm/robovm-studio,amith01994/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,vvv1559/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,alphafoobar/intellij-community,adedayo/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,suncycheng/intellij-community,vvv1559/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,blademainer/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,izonder/intellij-community,clumsy/intellij-community,xfournet/intellij-community,izonder/intellij-community,caot/intellij-community,robovm/robovm-studio,petteyg/intellij-community,diorcety/intellij-community,apixandru/intellij-community,signed/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,wreckJ/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,apixandru/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,da1z/intellij-community,adedayo/intellij-community,kool79/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,ryano144/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,apixandru/intellij-community,petteyg/intellij-community,hurricup/intellij-community,samthor/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,kdwink/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,samthor/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,fnouama/intellij-community,adedayo/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,Lekanich/intellij-community,asedunov/intellij-community,xfournet/intellij-community,holmes/intellij-community,ibinti/intellij-community,FHannes/intellij-community,akosyakov/intellij-community,robovm/robovm-studio,Lekanich/intellij-community,MER-GROUP/intellij-community,tmpgit/intellij-community,signed/intellij-community,ryano144/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,adedayo/intellij-community,holmes/intellij-community,nicolargo/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,ibinti/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,jagguli/intellij-community,fitermay/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,fengbaicanhe/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,youdonghai/intellij-community,izonder/intellij-community,clumsy/intellij-community,da1z/intellij-community,kool79/intellij-community,petteyg/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,youdonghai/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,fitermay/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,dslomov/intellij-community,supersven/intellij-community,retomerz/intellij-community,youdonghai/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,MER-GROUP/intellij-community,da1z/intellij-community,allotria/intellij-community,izonder/intellij-community,apixandru/intellij-community,alphafoobar/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,wreckJ/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,ryano144/intellij-community,TangHao1987/intellij-community,ol-loginov/intellij-community,lucafavatella/intellij-community,SerCeMan/intellij-community,alphafoobar/intellij-community,TangHao1987/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,slisson/intellij-community,ivan-fedorov/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,orekyuu/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,supersven/intellij-community,Lekanich/intellij-community,signed/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,xfournet/intellij-community,slisson/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,Distrotech/intellij-community,signed/intellij-community,FHannes/intellij-community,xfournet/intellij-community,signed/intellij-community,ibinti/intellij-community,asedunov/intellij-community,michaelgallacher/intellij-community,fitermay/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,ibinti/intellij-community,retomerz/intellij-community,robovm/robovm-studio,asedunov/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,supersven/intellij-community,vvv1559/intellij-community,akosyakov/intellij-community,da1z/intellij-community,ftomassetti/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,allotria/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,samthor/intellij-community,FHannes/intellij-community,signed/intellij-community,alphafoobar/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,tmpgit/intellij-community,petteyg/intellij-community,kool79/intellij-community,jagguli/intellij-community,allotria/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,diorcety/intellij-community,amith01994/intellij-community,holmes/intellij-community,caot/intellij-community,signed/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,vladmm/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,izonder/intellij-community,ibinti/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,petteyg/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,kdwink/intellij-community,izonder/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,hurricup/intellij-community,ivan-fedorov/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,pwoodworth/intellij-community,SerCeMan/intellij-community,kdwink/intellij-community,diorcety/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,FHannes/intellij-community,holmes/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,akosyakov/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,MER-GROUP/intellij-community,salguarnieri/intellij-community,gnuhub/intellij-community,lucafavatella/intellij-community,clumsy/intellij-community,lucafavatella/intellij-community,amith01994/intellij-community,jagguli/intellij-community,petteyg/intellij-community,pwoodworth/intellij-community,ThiagoGarciaAlves/intellij-community,vladmm/intellij-community,robovm/robovm-studio,caot/intellij-community,muntasirsyed/intellij-community,supersven/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,diorcety/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,vladmm/intellij-community,dslomov/intellij-community,orekyuu/intellij-community,robovm/robovm-studio,adedayo/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,xfournet/intellij-community,jagguli/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,clumsy/intellij-community,semonte/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,allotria/intellij-community,MER-GROUP/intellij-community,xfournet/intellij-community,hurricup/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,tmpgit/intellij-community,apixandru/intellij-community,diorcety/intellij-community,mglukhikh/intellij-community,ol-loginov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,mglukhikh/intellij-community,ivan-fedorov/intellij-community,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,fitermay/intellij-community,dslomov/intellij-community,FHannes/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,kool79/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,slisson/intellij-community,gnuhub/intellij-community,izonder/intellij-community,izonder/intellij-community,asedunov/intellij-community,kool79/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,salguarnieri/intellij-community,ryano144/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,muntasirsyed/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,clumsy/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,kool79/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ryano144/intellij-community,nicolargo/intellij-community,holmes/intellij-community,petteyg/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,kdwink/intellij-community,fnouama/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,supersven/intellij-community,fengbaicanhe/intellij-community,ibinti/intellij-community,retomerz/intellij-community,slisson/intellij-community,MER-GROUP/intellij-community,fengbaicanhe/intellij-community,ftomassetti/intellij-community,fitermay/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,MichaelNedzelsky/intellij-community,ibinti/intellij-community,ahb0327/intellij-community,allotria/intellij-community,semonte/intellij-community,amith01994/intellij-community,ibinti/intellij-community,kdwink/intellij-community,kdwink/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,caot/intellij-community,amith01994/intellij-community,Distrotech/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,Lekanich/intellij-community,suncycheng/intellij-community,caot/intellij-community,blademainer/intellij-community
package com.jetbrains.python.codeInsight.imports; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiReference; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyBundle; import com.jetbrains.python.codeInsight.PyCodeInsightSettings; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.psi.PyImportElement; import com.jetbrains.python.psi.PyQualifiedExpression; import com.jetbrains.python.psi.impl.PyQualifiedName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * The object contains a list of import candidates and serves only to show the initial hint; * the actual work is done in ImportFromExistingAction.. * * @author dcheryasov */ public class AutoImportQuickFix implements LocalQuickFix, HighPriorityAction { private final PyElement myNode; private final PsiReference myReference; private final List<ImportCandidateHolder> myImports; // from where and what to import String myName; boolean myUseQualifiedImport; private boolean myExpended; /** * Creates a new, empty fix object. * @param node to which the fix applies. * @param name the unresolved identifier portion of node's text * @param qualify if true, add an "import ..." statement and qualify the name; else use "from ... import name" */ public AutoImportQuickFix(PyElement node, PsiReference reference, String name, boolean qualify) { myNode = node; myReference = reference; myImports = new ArrayList<ImportCandidateHolder>(); myName = name; myUseQualifiedImport = qualify; myExpended = false; } /** * Adds another import source. * @param importable an element that could be imported either from import element or from file. * @param file the file which is the source of the importable * @param importElement an existing import element that can be a source for the importable. */ public void addImport(@NotNull PsiElement importable, @NotNull PsiFile file, @Nullable PyImportElement importElement) { myImports.add(new ImportCandidateHolder(importable, file, importElement, null, null)); } /** * Adds another import source. * @param importable an element that could be imported either from import element or from file. * @param file the file which is the source of the importable * @param path import path for the file, as a qualified name (a.b.c) * @param asName name to use to import the path as: "import path as asName" */ public void addImport(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file, @Nullable PyQualifiedName path, @Nullable String asName) { myImports.add(new ImportCandidateHolder(importable, file, null, path, asName)); } @NotNull public String getText() { if (myUseQualifiedImport) return PyBundle.message("ACT.qualify.with.module"); else return PyBundle.message("ACT.NAME.use.import"); } @NotNull public String getName() { return getText(); } @NotNull public String getFamilyName() { return PyBundle.message("ACT.FAMILY.import"); } public boolean showHint(Editor editor) { if (!PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP) { return false; } if (myNode == null || !myNode.isValid() || myNode.getName() == null || myImports.size() <= 0) { return false; // TODO: also return false if an on-the-fly unambiguous fix is possible? } if (ImportFromExistingAction.isResolved(myReference)) { return false; } if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) { return false; } if ((myNode instanceof PyQualifiedExpression) && ((((PyQualifiedExpression)myNode).getQualifier() != null))) return false; // we cannot be qualified final String message = ShowAutoImportPass.getMessage( myImports.size() > 1, ImportCandidateHolder.getQualifiedName(myName, myImports.get(0).getPath(), myImports.get(0).getImportElement()) ); final ImportFromExistingAction action = new ImportFromExistingAction(myNode, myImports, myName, myUseQualifiedImport); action.onDone(new Runnable() { public void run() { myExpended = true; } }); HintManager.getInstance().showQuestionHint( editor, message, myNode.getTextOffset(), myNode.getTextRange().getEndOffset(), action); return true; } public boolean isAvailable() { return !myExpended && myNode != null && myNode.isValid() && myImports.size() > 0; } public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { invoke(descriptor.getPsiElement().getContainingFile()); myExpended = true; } public void invoke(PsiFile file) throws IncorrectOperationException { // make sure file is committed, writable, etc if (!myReference.getElement().isValid()) return; if (!CodeInsightUtilBase.prepareFileForWrite(file)) return; if (ImportFromExistingAction.isResolved(myReference)) return; // act ImportFromExistingAction action = new ImportFromExistingAction(myNode, myImports, myName, myUseQualifiedImport); action.execute(); // assume that action runs in WriteAction on its own behalf myExpended = true; } public void sortCandidates() { Collections.sort(myImports); } public int getCandidatesCount() { return myImports.size(); } public boolean hasOnlyFunctions() { for (ImportCandidateHolder holder : myImports) { if (!(holder.getImportable() instanceof PyFunction)) { return false; } } return true; } }
python/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java
package com.jetbrains.python.codeInsight.imports; import com.intellij.codeInsight.CodeInsightUtilBase; import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass; import com.intellij.codeInsight.hint.HintManager; import com.intellij.codeInsight.intention.HighPriorityAction; import com.intellij.codeInspection.LocalQuickFix; import com.intellij.codeInspection.ProblemDescriptor; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiReference; import com.intellij.util.IncorrectOperationException; import com.jetbrains.python.PyBundle; import com.jetbrains.python.codeInsight.PyCodeInsightSettings; import com.jetbrains.python.psi.PyElement; import com.jetbrains.python.psi.PyFunction; import com.jetbrains.python.psi.PyImportElement; import com.jetbrains.python.psi.PyQualifiedExpression; import com.jetbrains.python.psi.impl.PyQualifiedName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.List; /** * The object contains a list of import candidates and serves only to show the initial hint; * the actual work is done in ImportFromExistingAction.. * * @author dcheryasov */ public class AutoImportQuickFix implements LocalQuickFix, HighPriorityAction { private final PyElement myNode; private final PsiReference myReference; private final List<ImportCandidateHolder> myImports; // from where and what to import String myName; boolean myUseQualifiedImport; private boolean myExpended; /** * Creates a new, empty fix object. * @param node to which the fix applies. * @param name the unresolved identifier portion of node's text * @param qualify if true, add an "import ..." statement and qualify the name; else use "from ... import name" */ public AutoImportQuickFix(PyElement node, PsiReference reference, String name, boolean qualify) { myNode = node; myReference = reference; myImports = new ArrayList<ImportCandidateHolder>(); myName = name; myUseQualifiedImport = qualify; myExpended = false; } /** * Adds another import source. * @param importable an element that could be imported either from import element or from file. * @param file the file which is the source of the importable * @param importElement an existing import element that can be a source for the importable. */ public void addImport(@NotNull PsiElement importable, @NotNull PsiFile file, @Nullable PyImportElement importElement) { myImports.add(new ImportCandidateHolder(importable, file, importElement, null, null)); } /** * Adds another import source. * @param importable an element that could be imported either from import element or from file. * @param file the file which is the source of the importable * @param path import path for the file, as a qualified name (a.b.c) * @param asName name to use to import the path as: "import path as asName" */ public void addImport(@NotNull PsiElement importable, @NotNull PsiFileSystemItem file, @Nullable PyQualifiedName path, @Nullable String asName) { myImports.add(new ImportCandidateHolder(importable, file, null, path, asName)); } @NotNull public String getText() { if (myUseQualifiedImport) return PyBundle.message("ACT.qualify.with.module"); else return PyBundle.message("ACT.NAME.use.import"); } @NotNull public String getName() { return getText(); } @NotNull public String getFamilyName() { return PyBundle.message("ACT.FAMILY.import"); } public boolean showHint(Editor editor) { if (!PyCodeInsightSettings.getInstance().SHOW_IMPORT_POPUP) { return false; } if (myNode == null || !myNode.isValid() || myNode.getName() == null || myImports.size() <= 0) { return false; // TODO: also return false if an on-the-fly unambiguous fix is possible? } if (ImportFromExistingAction.isResolved(myReference)) { return false; } if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint()) { return false; } if ((myNode instanceof PyQualifiedExpression) && ((((PyQualifiedExpression)myNode).getQualifier() != null))) return false; // we cannot be qualified final String message = ShowAutoImportPass.getMessage( myImports.size() > 1, ImportCandidateHolder.getQualifiedName(myName, myImports.get(0).getPath(), myImports.get(0).getImportElement()) ); final ImportFromExistingAction action = new ImportFromExistingAction(myNode, myImports, myName, myUseQualifiedImport); action.onDone(new Runnable() { public void run() { myExpended = true; } }); HintManager.getInstance().showQuestionHint( editor, message, myNode.getTextOffset(), myNode.getTextRange().getEndOffset(), action); return true; } public boolean isAvailable() { return !myExpended && myNode != null && myNode.isValid() && myImports.size() > 0; } public void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) { invoke(descriptor.getPsiElement().getContainingFile()); myExpended = true; } public void invoke(PsiFile file) throws IncorrectOperationException { // make sure file is committed, writable, etc if (!myReference.getElement().isValid()) return; if (!CodeInsightUtilBase.prepareFileForWrite(file)) return; if (ImportFromExistingAction.isResolved(myReference)) return; // act ImportFromExistingAction action = new ImportFromExistingAction(myNode, myImports, myName, myUseQualifiedImport); action.execute(); // assume that action runs in WriteAction on its own behalf myExpended = true; } public void sortCandidates() { Collections.sort(myImports); } public int getCandidatesCount() { return myImports.size(); } public boolean hasOnlyFunctions() { for (ImportCandidateHolder holder : myImports) { if (!(holder.getImportable() instanceof PyFunction)) { return false; } } return true; } }
auto-import doesn't hide parameter info (PY-5764)
python/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java
auto-import doesn't hide parameter info (PY-5764)
<ide><path>ython/src/com/jetbrains/python/codeInsight/imports/AutoImportQuickFix.java <ide> if (ImportFromExistingAction.isResolved(myReference)) { <ide> return false; <ide> } <del> if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint()) { <add> if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) { <ide> return false; <ide> } <ide> if ((myNode instanceof PyQualifiedExpression) && ((((PyQualifiedExpression)myNode).getQualifier() != null))) return false; // we cannot be qualified
JavaScript
mit
b11c9d35c63548cd1c35828e779e677a1b84452b
0
puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway,puuu/MQTT433gateway
$(function () { 'strict mode'; var CONFIG_ITEMS = [ new GroupItem("General Config", legendFactory), new ConfigItem("deviceName", deviceNameInputFactory, inputApply, inputGet, "The general name of the device"), new ConfigItem("configPassword", devicePasswordInputFactory, inputApply, inputGet, "The admin password for the web UI (min. 8 characters)"), new GroupItem("MQTT Config", legendFactory), new ConfigItem("mqttBroker", hostNameInputFactory, inputApply, inputGet, "MQTT Broker host"), new ConfigItem("mqttBrokerPort", portNumberInputFactory, inputApply, inputGetInt, "MQTT Broker port"), new ConfigItem("mqttUser", inputFieldFactory, inputApply, inputGet, "MQTT username (optional)"), new ConfigItem("mqttPassword", passwordFieldFactory, inputApply, inputGet, "MQTT password (optional)"), new ConfigItem("mqttRetain", checkboxFactory, checkboxApply, checkboxGet, "Retain MQTT messages"), new GroupItem("MQTT Topic Config", legendFactory), new ConfigItem("mqttReceiveTopic", mqttTopicInputFactory, inputApply, inputGet, "Topic to publish received signal"), new ConfigItem("mqttSendTopic", mqttTopicInputFactory, inputApply, inputGet, "Topic to get signals to send from"), new GroupItem("433MHz RF Config", legendFactory), new ConfigItem("rfEchoMessages", checkboxFactory, checkboxApply, checkboxGet, "Echo sent rf messages back"), new ConfigItem("rfReceiverPin", pinNumberInputFactory, inputApply, inputGetInt, "The GPIO pin used for the rf receiver"), new ConfigItem("rfReceiverPinPullUp", checkboxFactory, checkboxApply, checkboxGet, "Activate pullup on rf receiver pin (required for 5V protection with reverse diode)"), new ConfigItem("rfTransmitterPin", pinNumberInputFactory, inputApply, inputGetInt, "The GPIO pin used for the RF transmitter"), new GroupItem("Enabled RF protocols", legendFactory), new ConfigItem("rfProtocols", protocolInputField, protocolApply, protocolGet, ""), new GroupItem("Log Config", legendFactory), new ConfigItem("serialLogLevel", logLevelInputFactory, inputApply, inputGet, "Level for serial logging"), new ConfigItem("webLogLevel", logLevelInputFactory, inputApply, inputGet, "Level for logging to the web UI"), new ConfigItem("syslogLevel", logLevelInputFactory, inputApply, inputGet, "Level for syslog logging"), new ConfigItem("syslogHost", hostNameInputFactory, inputApply, inputGet, "Syslog server (optional)"), new ConfigItem("syslogPort", portNumberInputFactory, inputApply, inputGetInt, "Syslog port (optional)"), new GroupItem("Status LED", legendFactory), new ConfigItem("ledPin", pinNumberInputFactory, inputApply, inputGetInt, "The GPIO pin used for the status LED"), new ConfigItem("ledActiveHigh", checkboxFactory, checkboxApply, checkboxGet, "The way how the LED is connected to the pin (false for built-in led)") ]; var DEBUG_FLAGS = { protocolRaw: "Enable Raw RF message logging", systemLoad: "Show the processed loop() iterations for each second", freeHeap: "Show the free heap memory every second" }; var SystemCommandActions = { restart: function () { var body = $("body"); body.empty(); body.append("<p>Device will reboot!</p><p>Try to reconnect in 15 seconds.</p>"); setTimeout(function () { window.location.reload(true); }, 15000); }, reset_wifi: function () { var body = $("body"); body.empty(); body.append("<p>Devices WIFI settings where cleared!</p><p>Please reconfigure it.</p>"); }, reset_config: function () { var body = $("body"); body.empty(); body.append("<p>Devices Config was reset - reboot device!</p>" + "<p>You might have to reconfigure the wifi!</p>" + "<p>Reload page in 10 seconds...</p>"); setTimeout(function () { window.location.reload(true); }, 10000); } }; function ConfigItem(name, factory, apply, fetch, help) { this.name = name; this.factory = factory; this.apply = apply; this.fetch = fetch; this.help = help; } function GroupItem(name, factory) { this.name = name; this.factory = factory; } function inputLabelFactory(item) { return $('<label>', { text: item.name, for: 'cfg-' + item.name, }); } function inputHelpFactory(item) { return $('<span>', { class: 'pure-form-message', text: item.help, }); } function logLevelInputFactory(item) { var element = $('<select>', { class: 'config-item', id: 'cfg-' + item.name, name: item.name, }).append([ $('<option>', {value: '', text: "None"}), $('<option>', {value: 'error', text: 'Error'}), $('<option>', {value: 'warning', text: 'Warning'}), $('<option>', {value: 'info', text: 'Info'}), $('<option>', {value: 'debug', text: 'Debug'}), ]); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function inputFieldFactory(item, pattern, required) { var element = $('<input>', { type: 'text', class: 'pure-input-1 config-item', id: 'cfg-' + item.name, pattern: pattern, required: required, name: item.name, }); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function deviceNameInputFactory(item) { return inputFieldFactory(item, '[.-_A-Za-z0-9]+', true); } function hostNameInputFactory(item) { return inputFieldFactory(item, '[.-_A-Za-z0-9]*'); } function mqttTopicInputFactory(item) { return inputFieldFactory(item, undefined, true); } function inputFieldNumberFactory(item, min, max) { var element = $('<input>', { type: 'number', class: 'pure-input-1 config-item', id: 'cfg-' + item.name, name: item.name, min: min, max: max, }); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function portNumberInputFactory(item) { return inputFieldNumberFactory(item, 1, 65535); } function pinNumberInputFactory(item) { return inputFieldNumberFactory(item, 0, 16); } function passwordFieldFactory(item, minlength) { var element = $('<input>', { type: 'password', class: 'pure-input-1 config-item', id: 'cfg-' + item.name, name: item.name, minlength: minlength, }); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function devicePasswordInputFactory(item) { return passwordFieldFactory(item, 8); } function checkboxFactory(item) { var element = $('<input>', { type: 'checkbox', class: 'config-item', id: 'cfg-' + item.name, name: item.name, }); registerConfigUi(element, item); return $('<label>', { class: 'pure-checkbox', }).append([ element, ' ' + item.name, inputHelpFactory(item), ]); } function legendFactory(item) { return $('<legend>', { text: item.name }); } var protocols; function protocolInputField(item) { var container = $('<div>', { id: 'cfg-' + item.name, class: 'pure-g', }); registerConfigUi(container, item); function protocolListFactory(protos) { protos.forEach(function (value) { var element = $('<input>', { type: 'checkbox', class: 'config-item protocols-item', id: 'cfg-' + item.name + '-' + value, name: item.name, value: value, }); container.append($('<div>', { class: 'pure-u-1 pure-u-md-1-2 pure-u-lg-1-3 pure-u-xl-1-4', }).append($('<label>', { class: 'pure-checkbox', }).append([ element, ' Protocol ' + value, ]))); }); protocols = protos; } $.ajax({ url: "/protocols", type: "GET", contentType: 'application/json', success: protocolListFactory }); return container; } function inputApply(itemName, data) { $('#cfg-' + itemName).val(data); } function checkboxApply(itemName, data) { $('#cfg-' + itemName).prop("checked", data); } function protocolApply(itemName, data) { if (protocols === undefined) { setTimeout(protocolApply(itemName, data), 100); return; } if (data.length == 0) { data = protocols; } data.forEach(function (value) { $('#cfg-' + itemName + '-' + value).prop('checked', true); }); } function inputGet(element) { if (! element.get(0).checkValidity()) { return undefined; } return element.val(); } function inputGetInt(element) { return parseInt(inputGet(element)); } function checkboxGet(element) { return element.prop("checked"); } function protocolGet(element) { var checked = $('.protocols-item:checked'); if ($('.protocols-item').length === checked.length) { return []; } return $.map(checked, function (x) { return $(x).val(); }); } var lastConfig = {}; var changes = {}; function registerConfigUi(element, item) { element.change(function (event) { var newData = item.fetch(element); if (newData !== undefined) { if (JSON.stringify(lastConfig[item.name]) !== JSON.stringify(newData)) { changes[item.name] = newData; } else { delete changes[item.name]; } } }); } function throttle(callback, limit) { var wait = false; return function () { if (!wait) { callback.apply(this, arguments); wait = true; setTimeout(function () { wait = false; }, limit); } }; } function initConfigUi() { function applyConfig(data) { CONFIG_ITEMS.forEach(function (item) { if (item.apply) { item.apply(item.name, data[item.name]); } }); changes = {}; lastConfig = data; } function loadConfig() { $.ajax({ url: '/config', type: 'GET', contentType: 'application/json', success: applyConfig }); } var settings = $("#settings"); CONFIG_ITEMS.forEach(function (item) { settings.append(item.factory(item)); }); loadConfig(); $('#settings-form').submit(function (event) { event.preventDefault(); $.ajax({ url: "/config", type: 'PUT', contentType: 'application/json', data: JSON.stringify(changes), success: applyConfig }); return false; }); $('#cfg-form-reset').click(function (event) { event.preventDefault(); loadConfig(); return false; }); } function initDebugUi(debugFlags, container) { function create(debugFlag, helpText) { var checkbox = $('<input>', { type: 'checkbox', class: 'debug-item', id: 'debug-' + debugFlag, name: debugFlag, }); checkbox.change(function (event) { submit(this); }); return $('<div>', { class: 'pure-u-1 pure-u-md-1-3' }).append($('<label>', {class: 'pure-checkbox'}).append([ checkbox, ' ' + debugFlag, $('<span>', { class: 'pure-form-message', text: helpText, }), ])); } function apply(data) { $.each(data, function (key, value) { $('#debug-' + key).prop("checked", value); }); } function submit(item) { var data = {}; data[item.name] = item.checked; $.ajax({ url: '/debug', type: "PUT", data: JSON.stringify(data), contentType: 'application/json', success: apply }); } $.each(debugFlags, function(debugFlag, helpText) { container.append(create(debugFlag, helpText)); }); $.ajax({ url: "/debug", type: "GET", contentType: 'application/json', success: apply }); } var sendCommand = throttle( function (params) { $.ajax({ url: '/system', type: 'POST', data: JSON.stringify(params), contentType: 'application/json', success: function () { SystemCommandActions[params.command](); } }); }, 1000 ); $('.system-btn').click(function (event) { sendCommand({command: $(this).data('command')}); }); function loadFwVersion() { $.ajax({ url: "/firmware", type: "GET", contentType: 'application/json', success: function (data) { $('#current-fw-version').append('Current version: ' + data.version); } }); } function openWebSocket() { var container = $('#log-container'); var pre = container.find('pre'); var webSocket = new WebSocket("ws://" + location.hostname + ":81"); var tm; function ping() { clearTimeout(tm); tm = setTimeout(function () { webSocket.send("__PING__"); tm = setTimeout(function () { webSocket.close(); openWebSocket(); }, 2000); }, 5000); } webSocket.onmessage = function (event) { var message = event.data; if (message === "__PONG__") { ping(); return; } pre.append(message); if (message === '\n' || (typeof message === "string" && message.indexOf('\n') !== -1)) { container.scrollTop(pre.get(0).scrollHeight); } }; webSocket.onerror = function (event) { webSocket.close(); if (tm === undefined) { openWebSocket(); } }; webSocket.onopen = function (event) { ping(); }; } // Clear log $('#btn-clear-log').click(function (event) { $('#log-container').find('pre').empty(); }); initConfigUi(); initDebugUi(DEBUG_FLAGS, $("#debugflags")); loadFwVersion(); openWebSocket(); });
web/src/js/script.js
$(function () { 'strict mode'; var CONFIG_ITEMS = [ new GroupItem("General Config", legendFactory), new ConfigItem("deviceName", inputFieldFactory, inputApply, inputGet, "The general name of the device"), new ConfigItem("configPassword", passwordFieldFactory, inputApply, passwordGet, "The admin password for the web UI (min. 8 characters)"), new GroupItem("MQTT Config", legendFactory), new ConfigItem("mqttBroker", inputFieldFactory, inputApply, inputGet, "MQTT Broker host"), new ConfigItem("mqttBrokerPort", inputFieldFactory, inputApply, inputGetInt, "MQTT Broker port"), new ConfigItem("mqttUser", inputFieldFactory, inputApply, inputGet, "MQTT username (optional)"), new ConfigItem("mqttPassword", passwordFieldFactory, inputApply, inputGet, "MQTT password (optional)"), new ConfigItem("mqttRetain", checkboxFactory, checkboxApply, checkboxGet, "Retain MQTT messages"), new GroupItem("MQTT Topic Config", legendFactory), new ConfigItem("mqttReceiveTopic", inputFieldFactory, inputApply, inputGet, "Topic to publish received signal"), new ConfigItem("mqttSendTopic", inputFieldFactory, inputApply, inputGet, "Topic to get signals to send from"), new GroupItem("433MHz RF Config", legendFactory), new ConfigItem("rfEchoMessages", checkboxFactory, checkboxApply, checkboxGet, "Echo sent rf messages back"), new ConfigItem("rfReceiverPin", inputFieldFactory, inputApply, inputGetInt, "The GPIO pin used for the rf receiver"), new ConfigItem("rfReceiverPinPullUp", checkboxFactory, checkboxApply, checkboxGet, "Activate pullup on rf receiver pin (required for 5V protection with reverse diode)"), new ConfigItem("rfTransmitterPin", inputFieldFactory, inputApply, inputGetInt, "The GPIO pin used for the RF transmitter"), new GroupItem("Enabled RF protocols", legendFactory), new ConfigItem("rfProtocols", protocolInputField, protocolApply, protocolGet, ""), new GroupItem("Log Config", legendFactory), new ConfigItem("serialLogLevel", logLevelInputFactory, inputApply, inputGet, "Level for serial logging"), new ConfigItem("webLogLevel", logLevelInputFactory, inputApply, inputGet, "Level for logging to the web UI"), new ConfigItem("syslogLevel", logLevelInputFactory, inputApply, inputGet, "Level for syslog logging"), new ConfigItem("syslogHost", inputFieldFactory, inputApply, inputGet, "Syslog server (optional)"), new ConfigItem("syslogPort", inputFieldFactory, inputApply, inputGetInt, "Syslog port (optional)"), new GroupItem("Status LED", legendFactory), new ConfigItem("ledPin", inputFieldFactory, inputApply, inputGetInt, "The GPIO pin used for the status LED"), new ConfigItem("ledActiveHigh", checkboxFactory, checkboxApply, checkboxGet, "The way how the LED is connected to the pin (false for built-in led)") ]; var DEBUG_FLAGS = { protocolRaw: "Enable Raw RF message logging", systemLoad: "Show the processed loop() iterations for each second", freeHeap: "Show the free heap memory every second" }; var SystemCommandActions = { restart: function () { var body = $("body"); body.empty(); body.append("<p>Device will reboot!</p><p>Try to reconnect in 15 seconds.</p>"); setTimeout(function () { window.location.reload(true); }, 15000); }, reset_wifi: function () { var body = $("body"); body.empty(); body.append("<p>Devices WIFI settings where cleared!</p><p>Please reconfigure it.</p>"); }, reset_config: function () { var body = $("body"); body.empty(); body.append("<p>Devices Config was reset - reboot device!</p>" + "<p>You might have to reconfigure the wifi!</p>" + "<p>Reload page in 10 seconds...</p>"); setTimeout(function () { window.location.reload(true); }, 10000); } }; function ConfigItem(name, factory, apply, fetch, help) { this.name = name; this.factory = factory; this.apply = apply; this.fetch = fetch; this.help = help; } function GroupItem(name, factory) { this.name = name; this.factory = factory; } function inputLabelFactory(item) { return $('<label>', { text: item.name, for: 'cfg-' + item.name, }); } function inputHelpFactory(item) { return $('<span>', { class: 'pure-form-message', text: item.help, }); } function logLevelInputFactory(item) { var element = $('<select>', { class: 'config-item', id: 'cfg-' + item.name, name: item.name, }).append([ $('<option>', {value: '', text: "None"}), $('<option>', {value: 'error', text: 'Error'}), $('<option>', {value: 'warning', text: 'Warning'}), $('<option>', {value: 'info', text: 'Info'}), $('<option>', {value: 'debug', text: 'Debug'}), ]); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function inputFieldFactory(item) { var element = $('<input>', { type: 'text', class: 'pure-input-1 config-item', id: 'cfg-' + item.name, name: item.name, }); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function passwordFieldFactory(item) { var element = $('<input>', { type: 'password', class: 'pure-input-1 config-item', id: 'cfg-' + item.name, name: item.name, }); registerConfigUi(element, item); return [ inputLabelFactory(item), element, inputHelpFactory(item), ]; } function checkboxFactory(item) { var element = $('<input>', { type: 'checkbox', class: 'config-item', id: 'cfg-' + item.name, name: item.name, }); registerConfigUi(element, item); return $('<label>', { class: 'pure-checkbox', }).append([ element, ' ' + item.name, inputHelpFactory(item), ]); } function legendFactory(item) { return $('<legend>', { text: item.name }); } var protocols; function protocolInputField(item) { var container = $('<div>', { id: 'cfg-' + item.name, class: 'pure-g', }); registerConfigUi(container, item); function protocolListFactory(protos) { protos.forEach(function (value) { var element = $('<input>', { type: 'checkbox', class: 'config-item protocols-item', id: 'cfg-' + item.name + '-' + value, name: item.name, value: value, }); container.append($('<div>', { class: 'pure-u-1 pure-u-md-1-2 pure-u-lg-1-3 pure-u-xl-1-4', }).append($('<label>', { class: 'pure-checkbox', }).append([ element, ' Protocol ' + value, ]))); }); protocols = protos; } $.ajax({ url: "/protocols", type: "GET", contentType: 'application/json', success: protocolListFactory }); return container; } function inputApply(itemName, data) { $('#cfg-' + itemName).val(data); } function checkboxApply(itemName, data) { $('#cfg-' + itemName).prop("checked", data); } function protocolApply(itemName, data) { if (protocols === undefined) { setTimeout(protocolApply(itemName, data), 100); return; } if (data.length == 0) { data = protocols; } data.forEach(function (value) { $('#cfg-' + itemName + '-' + value).prop('checked', true); }); } function inputGet(element) { return element.val(); } function passwordGet(element) { var pwd = element.val(); if (pwd.length < 8) { alert("Password must have at least 8 characters"); return undefined; } return pwd; } function inputGetInt(element) { return parseInt(inputGet(element)); } function checkboxGet(element) { return element.prop("checked"); } function protocolGet(element) { var checked = $('.protocols-item:checked'); if ($('.protocols-item').length === checked.length) { return []; } return $.map(checked, function (x) { return $(x).val(); }); } var lastConfig = {}; var changes = {}; function registerConfigUi(element, item) { element.change(function (event) { var newData = item.fetch(element); if (newData !== undefined) { if (JSON.stringify(lastConfig[item.name]) !== JSON.stringify(newData)) { changes[item.name] = newData; } else { delete changes[item.name]; } } }); } function throttle(callback, limit) { var wait = false; return function () { if (!wait) { callback.apply(this, arguments); wait = true; setTimeout(function () { wait = false; }, limit); } }; } function initConfigUi() { function applyConfig(data) { CONFIG_ITEMS.forEach(function (item) { if (item.apply) { item.apply(item.name, data[item.name]); } }); changes = {}; lastConfig = data; } function loadConfig() { $.ajax({ url: '/config', type: 'GET', contentType: 'application/json', success: applyConfig }); } var settings = $("#settings"); CONFIG_ITEMS.forEach(function (item) { settings.append(item.factory(item)); }); loadConfig(); $('#settings-form').submit(function (event) { event.preventDefault(); $.ajax({ url: "/config", type: 'PUT', contentType: 'application/json', data: JSON.stringify(changes), success: applyConfig }); return false; }); $('#cfg-form-reset').click(function (event) { event.preventDefault(); loadConfig(); return false; }); } function initDebugUi(debugFlags, container) { function create(debugFlag, helpText) { var checkbox = $('<input>', { type: 'checkbox', class: 'debug-item', id: 'debug-' + debugFlag, name: debugFlag, }); checkbox.change(function (event) { submit(this); }); return $('<div>', { class: 'pure-u-1 pure-u-md-1-3' }).append($('<label>', {class: 'pure-checkbox'}).append([ checkbox, ' ' + debugFlag, $('<span>', { class: 'pure-form-message', text: helpText, }), ])); } function apply(data) { $.each(data, function (key, value) { $('#debug-' + key).prop("checked", value); }); } function submit(item) { var data = {}; data[item.name] = item.checked; $.ajax({ url: '/debug', type: "PUT", data: JSON.stringify(data), contentType: 'application/json', success: apply }); } $.each(debugFlags, function(debugFlag, helpText) { container.append(create(debugFlag, helpText)); }); $.ajax({ url: "/debug", type: "GET", contentType: 'application/json', success: apply }); } var sendCommand = throttle( function (params) { $.ajax({ url: '/system', type: 'POST', data: JSON.stringify(params), contentType: 'application/json', success: function () { SystemCommandActions[params.command](); } }); }, 1000 ); $('.system-btn').click(function (event) { sendCommand({command: $(this).data('command')}); }); function loadFwVersion() { $.ajax({ url: "/firmware", type: "GET", contentType: 'application/json', success: function (data) { $('#current-fw-version').append('Current version: ' + data.version); } }); } function openWebSocket() { var container = $('#log-container'); var pre = container.find('pre'); var webSocket = new WebSocket("ws://" + location.hostname + ":81"); var tm; function ping() { clearTimeout(tm); tm = setTimeout(function () { webSocket.send("__PING__"); tm = setTimeout(function () { webSocket.close(); openWebSocket(); }, 2000); }, 5000); } webSocket.onmessage = function (event) { var message = event.data; if (message === "__PONG__") { ping(); return; } pre.append(message); if (message === '\n' || (typeof message === "string" && message.indexOf('\n') !== -1)) { container.scrollTop(pre.get(0).scrollHeight); } }; webSocket.onerror = function (event) { webSocket.close(); if (tm === undefined) { openWebSocket(); } }; webSocket.onopen = function (event) { ping(); }; } // Clear log $('#btn-clear-log').click(function (event) { $('#log-container').find('pre').empty(); }); initConfigUi(); initDebugUi(DEBUG_FLAGS, $("#debugflags")); loadFwVersion(); openWebSocket(); });
Frontend: use html5 form data validation
web/src/js/script.js
Frontend: use html5 form data validation
<ide><path>eb/src/js/script.js <ide> <ide> var CONFIG_ITEMS = [ <ide> new GroupItem("General Config", legendFactory), <del> new ConfigItem("deviceName", inputFieldFactory, inputApply, inputGet, "The general name of the device"), <del> new ConfigItem("configPassword", passwordFieldFactory, inputApply, passwordGet, "The admin password for the web UI (min. 8 characters)"), <add> new ConfigItem("deviceName", deviceNameInputFactory, inputApply, inputGet, "The general name of the device"), <add> new ConfigItem("configPassword", devicePasswordInputFactory, inputApply, inputGet, "The admin password for the web UI (min. 8 characters)"), <ide> <ide> new GroupItem("MQTT Config", legendFactory), <del> new ConfigItem("mqttBroker", inputFieldFactory, inputApply, inputGet, "MQTT Broker host"), <del> new ConfigItem("mqttBrokerPort", inputFieldFactory, inputApply, inputGetInt, "MQTT Broker port"), <add> new ConfigItem("mqttBroker", hostNameInputFactory, inputApply, inputGet, "MQTT Broker host"), <add> new ConfigItem("mqttBrokerPort", portNumberInputFactory, inputApply, inputGetInt, "MQTT Broker port"), <ide> new ConfigItem("mqttUser", inputFieldFactory, inputApply, inputGet, "MQTT username (optional)"), <ide> new ConfigItem("mqttPassword", passwordFieldFactory, inputApply, inputGet, "MQTT password (optional)"), <ide> new ConfigItem("mqttRetain", checkboxFactory, checkboxApply, checkboxGet, "Retain MQTT messages"), <ide> <ide> new GroupItem("MQTT Topic Config", legendFactory), <del> new ConfigItem("mqttReceiveTopic", inputFieldFactory, inputApply, inputGet, "Topic to publish received signal"), <del> new ConfigItem("mqttSendTopic", inputFieldFactory, inputApply, inputGet, "Topic to get signals to send from"), <add> new ConfigItem("mqttReceiveTopic", mqttTopicInputFactory, inputApply, inputGet, "Topic to publish received signal"), <add> new ConfigItem("mqttSendTopic", mqttTopicInputFactory, inputApply, inputGet, "Topic to get signals to send from"), <ide> <ide> new GroupItem("433MHz RF Config", legendFactory), <ide> new ConfigItem("rfEchoMessages", checkboxFactory, checkboxApply, checkboxGet, "Echo sent rf messages back"), <del> new ConfigItem("rfReceiverPin", inputFieldFactory, inputApply, inputGetInt, "The GPIO pin used for the rf receiver"), <add> new ConfigItem("rfReceiverPin", pinNumberInputFactory, inputApply, inputGetInt, "The GPIO pin used for the rf receiver"), <ide> new ConfigItem("rfReceiverPinPullUp", checkboxFactory, checkboxApply, checkboxGet, "Activate pullup on rf receiver pin (required for 5V protection with reverse diode)"), <del> new ConfigItem("rfTransmitterPin", inputFieldFactory, inputApply, inputGetInt, "The GPIO pin used for the RF transmitter"), <add> new ConfigItem("rfTransmitterPin", pinNumberInputFactory, inputApply, inputGetInt, "The GPIO pin used for the RF transmitter"), <ide> <ide> new GroupItem("Enabled RF protocols", legendFactory), <ide> new ConfigItem("rfProtocols", protocolInputField, protocolApply, protocolGet, ""), <ide> new ConfigItem("serialLogLevel", logLevelInputFactory, inputApply, inputGet, "Level for serial logging"), <ide> new ConfigItem("webLogLevel", logLevelInputFactory, inputApply, inputGet, "Level for logging to the web UI"), <ide> new ConfigItem("syslogLevel", logLevelInputFactory, inputApply, inputGet, "Level for syslog logging"), <del> new ConfigItem("syslogHost", inputFieldFactory, inputApply, inputGet, "Syslog server (optional)"), <del> new ConfigItem("syslogPort", inputFieldFactory, inputApply, inputGetInt, "Syslog port (optional)"), <add> new ConfigItem("syslogHost", hostNameInputFactory, inputApply, inputGet, "Syslog server (optional)"), <add> new ConfigItem("syslogPort", portNumberInputFactory, inputApply, inputGetInt, "Syslog port (optional)"), <ide> <ide> new GroupItem("Status LED", legendFactory), <del> new ConfigItem("ledPin", inputFieldFactory, inputApply, inputGetInt, "The GPIO pin used for the status LED"), <add> new ConfigItem("ledPin", pinNumberInputFactory, inputApply, inputGetInt, "The GPIO pin used for the status LED"), <ide> new ConfigItem("ledActiveHigh", checkboxFactory, checkboxApply, checkboxGet, "The way how the LED is connected to the pin (false for built-in led)") <ide> ]; <ide> <ide> ]; <ide> } <ide> <del> function inputFieldFactory(item) { <add> function inputFieldFactory(item, pattern, required) { <ide> var element = $('<input>', { <ide> type: 'text', <ide> class: 'pure-input-1 config-item', <ide> id: 'cfg-' + item.name, <add> pattern: pattern, <add> required: required, <ide> name: item.name, <ide> }); <ide> registerConfigUi(element, item); <ide> ]; <ide> } <ide> <del> function passwordFieldFactory(item) { <add> function deviceNameInputFactory(item) { <add> return inputFieldFactory(item, '[.-_A-Za-z0-9]+', true); <add> } <add> <add> function hostNameInputFactory(item) { <add> return inputFieldFactory(item, '[.-_A-Za-z0-9]*'); <add> } <add> <add> function mqttTopicInputFactory(item) { <add> return inputFieldFactory(item, undefined, true); <add> } <add> <add> function inputFieldNumberFactory(item, min, max) { <ide> var element = $('<input>', { <del> type: 'password', <add> type: 'number', <ide> class: 'pure-input-1 config-item', <ide> id: 'cfg-' + item.name, <ide> name: item.name, <add> min: min, <add> max: max, <ide> }); <ide> registerConfigUi(element, item); <ide> return [ <ide> element, <ide> inputHelpFactory(item), <ide> ]; <add> } <add> <add> function portNumberInputFactory(item) { <add> return inputFieldNumberFactory(item, 1, 65535); <add> } <add> <add> function pinNumberInputFactory(item) { <add> return inputFieldNumberFactory(item, 0, 16); <add> } <add> <add> function passwordFieldFactory(item, minlength) { <add> var element = $('<input>', { <add> type: 'password', <add> class: 'pure-input-1 config-item', <add> id: 'cfg-' + item.name, <add> name: item.name, <add> minlength: minlength, <add> }); <add> registerConfigUi(element, item); <add> return [ <add> inputLabelFactory(item), <add> element, <add> inputHelpFactory(item), <add> ]; <add> } <add> <add> function devicePasswordInputFactory(item) { <add> return passwordFieldFactory(item, 8); <ide> } <ide> <ide> function checkboxFactory(item) { <ide> } <ide> <ide> function inputGet(element) { <add> if (! element.get(0).checkValidity()) { <add> return undefined; <add> } <ide> return element.val(); <del> } <del> <del> function passwordGet(element) { <del> var pwd = element.val(); <del> if (pwd.length < 8) { <del> alert("Password must have at least 8 characters"); <del> return undefined; <del> } <del> return pwd; <ide> } <ide> <ide> function inputGetInt(element) {
JavaScript
mit
cd09857bff09820a1bbee0a9464a6217edf9e442
0
cofacts/rumors-site,cofacts/rumors-site
import { useRef, useEffect } from 'react'; import { makeStyles, withStyles } from '@material-ui/core/styles'; import { Tabs, Tab, Box, Container } from '@material-ui/core'; import SearchIcon from '@material-ui/icons/Search'; import { useRouter } from 'next/router'; import Head from 'next/head'; import getConfig from 'next/config'; import { t } from 'ttag'; import querystring from 'querystring'; import ArticlePageLayout from 'components/ArticlePageLayout'; import ReplySearchPageLayout from 'components/ReplySearchPageLayout'; import AppLayout from 'components/AppLayout'; import withApollo from 'lib/apollo'; const { publicRuntimeConfig: { PUBLIC_URL }, } = getConfig(); const useStyles = makeStyles(theme => ({ jumbotron: { position: 'absolute', background: '#202020', left: 0, right: 0, }, search: { color: theme.palette.common.white, paddingRight: theme.spacing(3), }, content: { paddingTop: 230, }, form: { padding: '56px 0', display: 'flex', alignItems: 'baseline', }, inputArea: { position: 'relative', background: theme.palette.secondary[400], border: `1px dashed ${theme.palette.secondary[200]}`, borderRadius: 8, padding: theme.spacing(1), '&:before, &:after': { display: 'block', position: 'absolute', color: '#B9B9B9', fontSize: '2rem', }, '&:before': { content: '"“"', top: -theme.spacing(1), left: -theme.spacing(2), }, '&:after': { content: '"”"', bottom: -theme.spacing(3), right: -theme.spacing(2), }, '&:focus-within': { border: `1px solid ${theme.palette.primary[500]}`, '& $submit': { display: 'block', }, }, }, input: { width: '100%', border: 'none', outline: 'none', color: theme.palette.common.white, background: 'transparent', }, submit: { display: 'none', outline: 'none', cursor: 'pointer', height: '100%', position: 'absolute', border: `1px solid ${theme.palette.primary[500]}`, top: 0, right: 0, borderTopRightRadius: 8, borderBottomRightRadius: 8, background: theme.palette.primary[500], color: theme.palette.common.white, '& > svg': { verticalAlign: 'middle', }, }, })); const CustomTab = withStyles(theme => ({ root: { color: theme.palette.common.white, fontSize: theme.typography.htmlFontSize, '&$selected': { color: theme.palette.primary, }, }, }))(Tab); function SearchPage() { const router = useRouter(); const queryString = querystring.stringify(router.query); const { query } = router; const textareaRef = useRef(null); const classes = useStyles(); const navigate = type => router.push({ pathname: '/search', query: { ...query, type } }); const onSearch = e => { e.preventDefault(); router.push({ pathname: '/search', query: { ...query, q: e.target.search.value }, }); }; const { q } = query; useEffect(() => { textareaRef.current.value = q; }, [q]); return ( <AppLayout> <Head> <title>{t`Search`}</title> <link rel="alternate" type="application/rss+xml" href={`${PUBLIC_URL}/api/articles/rss2?${queryString}`} /> <link rel="alternate" type="application/atom+xml" href={`${PUBLIC_URL}/api/articles/atom1?${queryString}`} /> </Head> <div className={classes.jumbotron}> <Container> <form onSubmit={onSearch} className={classes.form}> <h2 className={classes.search}>{t`Searching`}</h2> <Box flex={1} className={classes.inputArea}> <textarea ref={textareaRef} name="search" className={classes.input} rows={1} /> <button type="submit" className={classes.submit}> <SearchIcon /> </button> </Box> </form> </Container> <Container> <Tabs value={query.type} onChange={(e, page) => navigate(page)} indicatorColor="primary" textColor="primary" aria-label="tabs" > <CustomTab value="messages" label={t`Messages`} /> <CustomTab value="replies" label={t`Replies`} /> </Tabs> </Container> </div> <div className={classes.content}> {query.type === 'messages' && ( <ArticlePageLayout displayHeader={false} /> )} {query.type === 'replies' && <ReplySearchPageLayout />} </div> </AppLayout> ); } export default withApollo({ /** * Although this page is mostly not server-rendered, we need this so that publicRuntimeConfig works. * @see https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration * */ ssr: true, })(SearchPage);
pages/search.js
import { useRef, useEffect } from 'react'; import { makeStyles, withStyles } from '@material-ui/core/styles'; import { Tabs, Tab, Box, Container } from '@material-ui/core'; import SearchIcon from '@material-ui/icons/Search'; import { useRouter } from 'next/router'; import Head from 'next/head'; import getConfig from 'next/config'; import { t } from 'ttag'; import querystring from 'querystring'; import ArticlePageLayout from 'components/ArticlePageLayout'; import ReplySearchPageLayout from 'components/ReplySearchPageLayout'; import AppLayout from 'components/AppLayout'; import withApollo from 'lib/apollo'; const { publicRuntimeConfig: { PUBLIC_URL }, } = getConfig(); const useStyles = makeStyles(theme => ({ jumbotron: { position: 'absolute', background: '#202020', left: 0, right: 0, }, search: { color: theme.palette.common.white, paddingRight: theme.spacing(3), }, content: { paddingTop: 230, }, form: { padding: '56px 0', display: 'flex', alignItems: 'baseline', }, inputArea: { position: 'relative', background: theme.palette.secondary[400], border: `1px dashed ${theme.palette.secondary[200]}`, borderRadius: 8, padding: theme.spacing(1), '&:before, &:after': { display: 'block', position: 'absolute', color: '#B9B9B9', fontSize: '2rem', }, '&:before': { content: '"“"', top: -theme.spacing(1), left: -theme.spacing(2), }, '&:after': { content: '"”"', bottom: -theme.spacing(3), right: -theme.spacing(2), }, '&:focus-within': { border: `1px solid ${theme.palette.primary[500]}`, '& $submit': { display: 'block', }, }, }, input: { width: '100%', border: 'none', outline: 'none', color: theme.palette.common.white, background: 'transparent', }, submit: { display: 'none', outline: 'none', cursor: 'pointer', height: '100%', position: 'absolute', border: `1px solid ${theme.palette.primary[500]}`, top: 0, right: 0, borderTopRightRadius: 8, borderBottomRightRadius: 8, background: theme.palette.primary[500], color: theme.palette.common.white, '& > svg': { verticalAlign: 'middle', }, }, })); const CustomTab = withStyles(theme => ({ root: { color: theme.palette.common.white, fontSize: theme.typography.htmlFontSize, '&$selected': { color: theme.palette.primary, }, }, }))(Tab); function SearchPage() { const router = useRouter(); const queryString = querystring.stringify(router.query); const { query } = router; const textareaRef = useRef(null); const classes = useStyles(); const navigate = type => router.push({ pathname: '/search', query: { ...query, type } }); const onSearch = e => { e.preventDefault(); router.push({ pathname: '/search', query: { ...query, q: e.target.search.value }, }); }; const { q } = query; useEffect(() => { textareaRef.current.value = q; }, [q]); return ( <AppLayout> <Head> <title>{t`Search`}</title> <link rel="alternate" type="application/rss+xml" href={`${PUBLIC_URL}/api/articles/rss2?${queryString}`} /> <link rel="alternate" type="application/atom+xml" href={`${PUBLIC_URL}/api/articles/atom1?${queryString}`} /> </Head> <div className={classes.jumbotron}> <Container> <form onSubmit={onSearch} className={classes.form}> <h2 className={classes.search}>{t`Searching`}</h2> <Box flex={1} className={classes.inputArea}> <textarea ref={textareaRef} name="search" className={classes.input} rows={1} /> <button type="submit" className={classes.submit}> <SearchIcon /> </button> </Box> </form> </Container> <Container> <Tabs value={query.type} onChange={(e, page) => navigate(page)} indicatorColor="primary" textColor="primary" aria-label="tabs" > <CustomTab value="messages" label={t`Messages`} /> <CustomTab value="replies" label={t`Replies`} /> </Tabs> </Container> </div> <div className={classes.content}> {query.type === 'messages' && ( <ArticlePageLayout displayHeader={false} /> )} {query.type === 'replies' && <ReplySearchPageLayout />} </div> </AppLayout> ); } export default withApollo()(SearchPage);
Make production build works by opt-out static build for search pages
pages/search.js
Make production build works by opt-out static build for search pages
<ide><path>ages/search.js <ide> ); <ide> } <ide> <del>export default withApollo()(SearchPage); <add>export default withApollo({ <add> /** <add> * Although this page is mostly not server-rendered, we need this so that publicRuntimeConfig works. <add> * @see https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration <add> * */ <add> ssr: true, <add>})(SearchPage);
Java
apache-2.0
1f5e82ec3b9063f41f24f24c4b8aac58e14b2f6b
0
retomerz/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,clumsy/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,ibinti/intellij-community,retomerz/intellij-community,asedunov/intellij-community,MichaelNedzelsky/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,signed/intellij-community,xfournet/intellij-community,xfournet/intellij-community,holmes/intellij-community,diorcety/intellij-community,diorcety/intellij-community,slisson/intellij-community,fnouama/intellij-community,dslomov/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,MER-GROUP/intellij-community,mglukhikh/intellij-community,vvv1559/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,muntasirsyed/intellij-community,samthor/intellij-community,allotria/intellij-community,ibinti/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,caot/intellij-community,FHannes/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,petteyg/intellij-community,fitermay/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,wreckJ/intellij-community,holmes/intellij-community,xfournet/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,ftomassetti/intellij-community,caot/intellij-community,supersven/intellij-community,allotria/intellij-community,asedunov/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,wreckJ/intellij-community,mglukhikh/intellij-community,retomerz/intellij-community,amith01994/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,tmpgit/intellij-community,allotria/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,fnouama/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,ernestp/consulo,vladmm/intellij-community,TangHao1987/intellij-community,xfournet/intellij-community,ibinti/intellij-community,kool79/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,signed/intellij-community,apixandru/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,gnuhub/intellij-community,allotria/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,apixandru/intellij-community,supersven/intellij-community,ryano144/intellij-community,fitermay/intellij-community,blademainer/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,allotria/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,supersven/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,blademainer/intellij-community,kool79/intellij-community,da1z/intellij-community,apixandru/intellij-community,hurricup/intellij-community,blademainer/intellij-community,lucafavatella/intellij-community,ahb0327/intellij-community,samthor/intellij-community,suncycheng/intellij-community,samthor/intellij-community,tmpgit/intellij-community,FHannes/intellij-community,signed/intellij-community,semonte/intellij-community,petteyg/intellij-community,kdwink/intellij-community,xfournet/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,vladmm/intellij-community,samthor/intellij-community,akosyakov/intellij-community,FHannes/intellij-community,signed/intellij-community,diorcety/intellij-community,tmpgit/intellij-community,alphafoobar/intellij-community,idea4bsd/idea4bsd,ernestp/consulo,fitermay/intellij-community,mglukhikh/intellij-community,jagguli/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,ryano144/intellij-community,slisson/intellij-community,samthor/intellij-community,Distrotech/intellij-community,samthor/intellij-community,xfournet/intellij-community,izonder/intellij-community,ftomassetti/intellij-community,ol-loginov/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,vladmm/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,SerCeMan/intellij-community,orekyuu/intellij-community,Distrotech/intellij-community,fitermay/intellij-community,ryano144/intellij-community,fitermay/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,Lekanich/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,allotria/intellij-community,asedunov/intellij-community,apixandru/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,hurricup/intellij-community,adedayo/intellij-community,Distrotech/intellij-community,Distrotech/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,kool79/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,salguarnieri/intellij-community,xfournet/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,caot/intellij-community,apixandru/intellij-community,signed/intellij-community,SerCeMan/intellij-community,asedunov/intellij-community,slisson/intellij-community,Distrotech/intellij-community,caot/intellij-community,ryano144/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,slisson/intellij-community,ernestp/consulo,akosyakov/intellij-community,da1z/intellij-community,ahb0327/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,lucafavatella/intellij-community,ol-loginov/intellij-community,vladmm/intellij-community,amith01994/intellij-community,signed/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,semonte/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,TangHao1987/intellij-community,adedayo/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,consulo/consulo,kool79/intellij-community,MER-GROUP/intellij-community,blademainer/intellij-community,supersven/intellij-community,allotria/intellij-community,semonte/intellij-community,alphafoobar/intellij-community,supersven/intellij-community,blademainer/intellij-community,clumsy/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,fengbaicanhe/intellij-community,alphafoobar/intellij-community,signed/intellij-community,youdonghai/intellij-community,robovm/robovm-studio,semonte/intellij-community,ThiagoGarciaAlves/intellij-community,tmpgit/intellij-community,vvv1559/intellij-community,Lekanich/intellij-community,MichaelNedzelsky/intellij-community,consulo/consulo,ahb0327/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,idea4bsd/idea4bsd,TangHao1987/intellij-community,petteyg/intellij-community,MER-GROUP/intellij-community,ryano144/intellij-community,idea4bsd/idea4bsd,kool79/intellij-community,youdonghai/intellij-community,dslomov/intellij-community,nicolargo/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,michaelgallacher/intellij-community,SerCeMan/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,signed/intellij-community,da1z/intellij-community,michaelgallacher/intellij-community,MER-GROUP/intellij-community,idea4bsd/idea4bsd,nicolargo/intellij-community,ol-loginov/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,slisson/intellij-community,blademainer/intellij-community,semonte/intellij-community,izonder/intellij-community,michaelgallacher/intellij-community,FHannes/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,retomerz/intellij-community,suncycheng/intellij-community,robovm/robovm-studio,jagguli/intellij-community,ahb0327/intellij-community,vladmm/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,supersven/intellij-community,slisson/intellij-community,robovm/robovm-studio,da1z/intellij-community,akosyakov/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,holmes/intellij-community,vladmm/intellij-community,MER-GROUP/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,robovm/robovm-studio,asedunov/intellij-community,SerCeMan/intellij-community,consulo/consulo,youdonghai/intellij-community,holmes/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,kdwink/intellij-community,signed/intellij-community,amith01994/intellij-community,kdwink/intellij-community,kdwink/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,slisson/intellij-community,ibinti/intellij-community,orekyuu/intellij-community,semonte/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,MichaelNedzelsky/intellij-community,izonder/intellij-community,allotria/intellij-community,fnouama/intellij-community,youdonghai/intellij-community,ernestp/consulo,robovm/robovm-studio,ryano144/intellij-community,orekyuu/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,robovm/robovm-studio,asedunov/intellij-community,xfournet/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,fnouama/intellij-community,ivan-fedorov/intellij-community,SerCeMan/intellij-community,ol-loginov/intellij-community,michaelgallacher/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,petteyg/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,izonder/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,asedunov/intellij-community,fnouama/intellij-community,apixandru/intellij-community,hurricup/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,suncycheng/intellij-community,lucafavatella/intellij-community,da1z/intellij-community,supersven/intellij-community,consulo/consulo,nicolargo/intellij-community,kdwink/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,robovm/robovm-studio,da1z/intellij-community,fnouama/intellij-community,kool79/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,lucafavatella/intellij-community,nicolargo/intellij-community,ahb0327/intellij-community,izonder/intellij-community,gnuhub/intellij-community,da1z/intellij-community,jagguli/intellij-community,caot/intellij-community,xfournet/intellij-community,akosyakov/intellij-community,holmes/intellij-community,orekyuu/intellij-community,ibinti/intellij-community,caot/intellij-community,retomerz/intellij-community,kool79/intellij-community,fitermay/intellij-community,muntasirsyed/intellij-community,consulo/consulo,da1z/intellij-community,apixandru/intellij-community,fnouama/intellij-community,consulo/consulo,kdwink/intellij-community,pwoodworth/intellij-community,retomerz/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,MER-GROUP/intellij-community,ftomassetti/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,signed/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,supersven/intellij-community,supersven/intellij-community,clumsy/intellij-community,da1z/intellij-community,izonder/intellij-community,Lekanich/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,vvv1559/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,kdwink/intellij-community,clumsy/intellij-community,fengbaicanhe/intellij-community,dslomov/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,samthor/intellij-community,semonte/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,holmes/intellij-community,tmpgit/intellij-community,adedayo/intellij-community,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,adedayo/intellij-community,ernestp/consulo,pwoodworth/intellij-community,petteyg/intellij-community,blademainer/intellij-community,nicolargo/intellij-community,wreckJ/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,supersven/intellij-community,petteyg/intellij-community,retomerz/intellij-community,FHannes/intellij-community,TangHao1987/intellij-community,caot/intellij-community,adedayo/intellij-community,samthor/intellij-community,ryano144/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,ThiagoGarciaAlves/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,wreckJ/intellij-community,ernestp/consulo,fitermay/intellij-community,TangHao1987/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,blademainer/intellij-community,dslomov/intellij-community,robovm/robovm-studio,Distrotech/intellij-community,da1z/intellij-community,kdwink/intellij-community,dslomov/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,orekyuu/intellij-community,tmpgit/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,muntasirsyed/intellij-community,vladmm/intellij-community,caot/intellij-community,ryano144/intellij-community,kool79/intellij-community,ryano144/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,alphafoobar/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,fitermay/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,fnouama/intellij-community,jagguli/intellij-community,MichaelNedzelsky/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,wreckJ/intellij-community,orekyuu/intellij-community,jagguli/intellij-community,retomerz/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,FHannes/intellij-community,fengbaicanhe/intellij-community,semonte/intellij-community,fengbaicanhe/intellij-community,caot/intellij-community,tmpgit/intellij-community,suncycheng/intellij-community,samthor/intellij-community,blademainer/intellij-community,izonder/intellij-community,da1z/intellij-community,petteyg/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,slisson/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,clumsy/intellij-community,izonder/intellij-community,kool79/intellij-community,holmes/intellij-community,allotria/intellij-community,ftomassetti/intellij-community,holmes/intellij-community,alphafoobar/intellij-community,amith01994/intellij-community,akosyakov/intellij-community,nicolargo/intellij-community,diorcety/intellij-community,youdonghai/intellij-community,pwoodworth/intellij-community,izonder/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,FHannes/intellij-community,asedunov/intellij-community,orekyuu/intellij-community,muntasirsyed/intellij-community,ol-loginov/intellij-community,hurricup/intellij-community,tmpgit/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,ryano144/intellij-community,da1z/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,TangHao1987/intellij-community,mglukhikh/intellij-community,ahb0327/intellij-community,hurricup/intellij-community,Distrotech/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,ol-loginov/intellij-community,signed/intellij-community,FHannes/intellij-community,diorcety/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,idea4bsd/idea4bsd,petteyg/intellij-community,salguarnieri/intellij-community,amith01994/intellij-community,gnuhub/intellij-community,adedayo/intellij-community,apixandru/intellij-community,ftomassetti/intellij-community,wreckJ/intellij-community,SerCeMan/intellij-community,TangHao1987/intellij-community,caot/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,lucafavatella/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,clumsy/intellij-community,vvv1559/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,ftomassetti/intellij-community,ftomassetti/intellij-community,SerCeMan/intellij-community,fitermay/intellij-community,ThiagoGarciaAlves/intellij-community,ol-loginov/intellij-community,jagguli/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,clumsy/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,kool79/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,adedayo/intellij-community,diorcety/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,lucafavatella/intellij-community,apixandru/intellij-community,MER-GROUP/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,clumsy/intellij-community,akosyakov/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,kdwink/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,diorcety/intellij-community,jagguli/intellij-community,kool79/intellij-community,ibinti/intellij-community,semonte/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,slisson/intellij-community,Distrotech/intellij-community,holmes/intellij-community,slisson/intellij-community,dslomov/intellij-community,xfournet/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,holmes/intellij-community,retomerz/intellij-community,gnuhub/intellij-community,FHannes/intellij-community,amith01994/intellij-community,kdwink/intellij-community,ibinti/intellij-community,samthor/intellij-community,slisson/intellij-community,dslomov/intellij-community,amith01994/intellij-community,hurricup/intellij-community,dslomov/intellij-community,suncycheng/intellij-community,slisson/intellij-community,TangHao1987/intellij-community,ivan-fedorov/intellij-community,allotria/intellij-community,jagguli/intellij-community,ivan-fedorov/intellij-community,tmpgit/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,diorcety/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,youdonghai/intellij-community,blademainer/intellij-community,xfournet/intellij-community,diorcety/intellij-community,izonder/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,caot/intellij-community,retomerz/intellij-community,ahb0327/intellij-community
/* * Copyright 2000-2012 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.xdebugger.impl.breakpoints.ui.tree; import com.intellij.ide.util.treeView.TreeState; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.MultiValuesMap; import com.intellij.ui.CheckedTreeNode; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroup; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointItem; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.util.*; /** * @author nik, zajac */ public class BreakpointItemsTreeController implements BreakpointsCheckboxTree.Delegate { private final TreeNodeComparator myComparator = new TreeNodeComparator(); private final CheckedTreeNode myRoot; private final Map<BreakpointItem, BreakpointItemNode> myNodes = new HashMap<BreakpointItem, BreakpointItemNode>(); private List<XBreakpointGroupingRule> myGroupingRules; private final Map<XBreakpointGroup, BreakpointsGroupNode> myGroupNodes = new HashMap<XBreakpointGroup, BreakpointsGroupNode>(); private final MultiValuesMap<XBreakpointGroupingRule, XBreakpointGroup> myGroups = new MultiValuesMap<XBreakpointGroupingRule, XBreakpointGroup>(); private JTree myTreeView; public BreakpointItemsTreeController(Collection<XBreakpointGroupingRule> groupingRules) { myRoot = new CheckedTreeNode("root"); setGroupingRulesInternal(groupingRules); } public void setTreeView(JTree treeView) { myTreeView = treeView; if (treeView instanceof BreakpointsCheckboxTree) { ((BreakpointsCheckboxTree)treeView).setDelegate(this); } myTreeView.setShowsRootHandles(!myGroupingRules.isEmpty()); } private void setGroupingRulesInternal(final Collection<XBreakpointGroupingRule> groupingRules) { myGroupingRules = new ArrayList<XBreakpointGroupingRule>(groupingRules); } public void buildTree(@NotNull Collection<? extends BreakpointItem> breakpoints) { final TreeState state = TreeState.createOn(myTreeView, myRoot); myRoot.removeAllChildren(); myNodes.clear(); myGroupNodes.clear(); myGroups.clear(); for (BreakpointItem breakpoint : breakpoints) { BreakpointItemNode node = new BreakpointItemNode(breakpoint); CheckedTreeNode parent = getParentNode(breakpoint); parent.add(node); myNodes.put(breakpoint, node); } TreeUtil.sort(myRoot, myComparator); ((DefaultTreeModel)(myTreeView.getModel())).nodeStructureChanged(myRoot); state.applyTo(myTreeView, myRoot); TreeUtil.expandAll(myTreeView); } @NotNull private CheckedTreeNode getParentNode(final BreakpointItem breakpoint) { CheckedTreeNode parent = myRoot; XBreakpointGroup parentGroup = null; for (int i = 0; i < myGroupingRules.size(); i++) { XBreakpointGroup group = getGroup(parentGroup, breakpoint, myGroupingRules.get(i)); if (group != null) { parent = getOrCreateGroupNode(parent, group, i); parentGroup = group; } } return parent; } @Nullable private XBreakpointGroup getGroup(XBreakpointGroup parentGroup, final BreakpointItem breakpoint, final XBreakpointGroupingRule groupingRule) { //noinspection unchecked Collection<XBreakpointGroup> groups = myGroups.get(groupingRule); if (groups == null) { groups = Collections.emptyList(); } XBreakpointGroup group = groupingRule.getGroup(breakpoint.getBreakpoint(), filterByParent(parentGroup, groups)); if (group != null) { myGroups.put(groupingRule, group); } return group; } private Collection<XBreakpointGroup> filterByParent(XBreakpointGroup parentGroup, Collection<XBreakpointGroup> groups) { Collection<XBreakpointGroup> filtered = new ArrayList<XBreakpointGroup>(); for (XBreakpointGroup group : groups) { TreeNode parentNode = myGroupNodes.get(group).getParent(); BreakpointsGroupNode parent = parentNode instanceof BreakpointsGroupNode ? (BreakpointsGroupNode)parentNode : null; if ((parentGroup == null && parentNode == myRoot) || (parent != null && parent.getGroup() == parentGroup)) { filtered.add(group); } } return filtered; } private <G extends XBreakpointGroup> BreakpointsGroupNode<G> getOrCreateGroupNode(CheckedTreeNode parent, final G group, final int level) { //noinspection unchecked BreakpointsGroupNode<G> groupNode = (BreakpointsGroupNode<G>)myGroupNodes.get(group); if (groupNode == null) { groupNode = new BreakpointsGroupNode<G>(group, level); myGroupNodes.put(group, groupNode); parent.add(groupNode); } return groupNode; } @Override public void nodeStateChanged(CheckedTreeNode node) { if (node instanceof BreakpointItemNode) { ((BreakpointItemNode)node).getBreakpointItem().setEnabled(node.isChecked()); } } public void setGroupingRules(Collection<XBreakpointGroupingRule> groupingRules) { setGroupingRulesInternal(groupingRules); rebuildTree(new ArrayList<BreakpointItem>(myNodes.keySet())); } public void rebuildTree(Collection<BreakpointItem> items) { List<BreakpointItem> selectedBreakpoints = getSelectedBreakpoints(); TreePath path = myTreeView.getSelectionPath(); buildTree(items); if (selectedBreakpoints.size() > 0) { selectBreakpointItem(selectedBreakpoints.get(0), path); } } public List<BreakpointItem> getSelectedBreakpoints() { TreePath[] selectionPaths = myTreeView.getSelectionPaths(); if (selectionPaths == null || selectionPaths.length == 0) return Collections.emptyList(); final ArrayList<BreakpointItem> list = new ArrayList<BreakpointItem>(); for (TreePath selectionPath : selectionPaths) { TreeUtil.traverseDepth((TreeNode)selectionPath.getLastPathComponent(), new TreeUtil.Traverse() { public boolean accept(final Object node) { if (node instanceof BreakpointItemNode) { list.add(((BreakpointItemNode)node).getBreakpointItem()); } return true; } }); } return list; } public void selectBreakpointItem(@Nullable final BreakpointItem breakpoint, TreePath path) { BreakpointItemNode node = myNodes.get(breakpoint); if (node != null) { TreeUtil.selectNode(myTreeView, node); } else { TreeUtil.selectPath(myTreeView, path); } } public CheckedTreeNode getRoot() { return myRoot; } public void selectFirstBreakpointItem() { TreeUtil.selectPath(myTreeView, TreeUtil.getFirstLeafNodePath(myTreeView)); } public void removeSelectedBreakpoints(Project project) { final TreePath[] paths = myTreeView.getSelectionPaths(); if (paths == null) return; final List<BreakpointItem> breakpoints = getSelectedBreakpoints(); for (TreePath path : paths) { final Object node = path.getLastPathComponent(); if (node instanceof BreakpointItemNode) { final BreakpointItem item = ((BreakpointItemNode)node).getBreakpointItem(); if (!item.allowedToRemove()) { TreeUtil.unselect(myTreeView, (DefaultMutableTreeNode)node); breakpoints.remove(item); } } } if (breakpoints.isEmpty()) return; TreeUtil.removeSelected(myTreeView); for (BreakpointItem breakpoint : breakpoints) { breakpoint.removed(project); } } private static class TreeNodeComparator implements Comparator<TreeNode> { public int compare(final TreeNode o1, final TreeNode o2) { if (o1 instanceof BreakpointItemNode && o2 instanceof BreakpointItemNode) { //noinspection unchecked BreakpointItem b1 = ((BreakpointItemNode)o1).getBreakpointItem(); //noinspection unchecked BreakpointItem b2 = ((BreakpointItemNode)o2).getBreakpointItem(); boolean default1 = b1.isDefaultBreakpoint(); boolean default2 = b2.isDefaultBreakpoint(); if (default1 && !default2) return -1; if (!default1 && default2) return 1; return b1.compareTo(b2); } if (o1 instanceof BreakpointsGroupNode && o2 instanceof BreakpointsGroupNode) { final BreakpointsGroupNode group1 = (BreakpointsGroupNode)o1; final BreakpointsGroupNode group2 = (BreakpointsGroupNode)o2; if (group1.getLevel() != group2.getLevel()) { return group1.getLevel() - group2.getLevel(); } return group1.getGroup().compareTo(group2.getGroup()); } return o1 instanceof BreakpointsGroupNode ? -1 : 1; } } public interface BreakpointItemsTreeDelegate { void execute(BreakpointItem item); } }
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointItemsTreeController.java
/* * Copyright 2000-2012 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.xdebugger.impl.breakpoints.ui.tree; import com.intellij.ide.util.treeView.TreeState; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.MultiValuesMap; import com.intellij.ui.CheckedTreeNode; import com.intellij.util.ui.tree.TreeUtil; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroup; import com.intellij.xdebugger.breakpoints.ui.XBreakpointGroupingRule; import com.intellij.xdebugger.impl.breakpoints.ui.BreakpointItem; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import java.util.*; /** * @author nik, zajac */ public class BreakpointItemsTreeController implements BreakpointsCheckboxTree.Delegate { private final TreeNodeComparator myComparator = new TreeNodeComparator(); private final CheckedTreeNode myRoot; private final Map<BreakpointItem, BreakpointItemNode> myNodes = new HashMap<BreakpointItem, BreakpointItemNode>(); private List<XBreakpointGroupingRule> myGroupingRules; private final Map<XBreakpointGroup, BreakpointsGroupNode> myGroupNodes = new HashMap<XBreakpointGroup, BreakpointsGroupNode>(); private final MultiValuesMap<XBreakpointGroupingRule, XBreakpointGroup> myGroups = new MultiValuesMap<XBreakpointGroupingRule, XBreakpointGroup>(); private JTree myTreeView; public BreakpointItemsTreeController(Collection<XBreakpointGroupingRule> groupingRules) { myRoot = new CheckedTreeNode("root"); setGroupingRulesInternal(groupingRules); } public void setTreeView(JTree treeView) { myTreeView = treeView; if (treeView instanceof BreakpointsCheckboxTree) { ((BreakpointsCheckboxTree)treeView).setDelegate(this); } myTreeView.setShowsRootHandles(!myGroupingRules.isEmpty()); } private void setGroupingRulesInternal(final Collection<XBreakpointGroupingRule> groupingRules) { myGroupingRules = new ArrayList<XBreakpointGroupingRule>(groupingRules); } public void buildTree(@NotNull Collection<? extends BreakpointItem> breakpoints) { final TreeState state = TreeState.createOn(myTreeView, myRoot); myRoot.removeAllChildren(); myNodes.clear(); myGroupNodes.clear(); myGroups.clear(); for (BreakpointItem breakpoint : breakpoints) { BreakpointItemNode node = new BreakpointItemNode(breakpoint); CheckedTreeNode parent = getParentNode(breakpoint); parent.add(node); myNodes.put(breakpoint, node); } TreeUtil.sort(myRoot, myComparator); ((DefaultTreeModel)(myTreeView.getModel())).nodeStructureChanged(myRoot); state.applyTo(myTreeView, myRoot); TreeUtil.expandAll(myTreeView); } @NotNull private CheckedTreeNode getParentNode(final BreakpointItem breakpoint) { CheckedTreeNode parent = myRoot; XBreakpointGroup parentGroup = null; for (int i = 0; i < myGroupingRules.size(); i++) { XBreakpointGroup group = getGroup(parentGroup, breakpoint, myGroupingRules.get(i)); if (group != null) { parent = getOrCreateGroupNode(parent, group, i); parentGroup = group; } } return parent; } @Nullable private XBreakpointGroup getGroup(XBreakpointGroup parentGroup, final BreakpointItem breakpoint, final XBreakpointGroupingRule groupingRule) { //noinspection unchecked Collection<XBreakpointGroup> groups = myGroups.get(groupingRule); if (groups == null) { groups = Collections.emptyList(); } XBreakpointGroup group = groupingRule.getGroup(breakpoint.getBreakpoint(), filterByParent(parentGroup, groups)); if (group != null) { myGroups.put(groupingRule, group); } return group; } private Collection<XBreakpointGroup> filterByParent(XBreakpointGroup parentGroup, Collection<XBreakpointGroup> groups) { Collection<XBreakpointGroup> filtered = new ArrayList<XBreakpointGroup>(); for (XBreakpointGroup group : groups) { TreeNode parentNode = myGroupNodes.get(group).getParent(); BreakpointsGroupNode parent = parentNode instanceof BreakpointsGroupNode ? (BreakpointsGroupNode)parentNode : null; if ((parentGroup == null && parentNode == myRoot) || (parent != null && parent.getGroup() == parentGroup)) { filtered.add(group); } } return filtered; } private <G extends XBreakpointGroup> BreakpointsGroupNode<G> getOrCreateGroupNode(CheckedTreeNode parent, final G group, final int level) { //noinspection unchecked BreakpointsGroupNode<G> groupNode = (BreakpointsGroupNode<G>)myGroupNodes.get(group); if (groupNode == null) { groupNode = new BreakpointsGroupNode<G>(group, level); myGroupNodes.put(group, groupNode); parent.add(groupNode); } return groupNode; } @Override public void nodeStateChanged(CheckedTreeNode node) { if (node instanceof BreakpointItemNode) { ((BreakpointItemNode)node).getBreakpointItem().setEnabled(node.isChecked()); } } public void setGroupingRules(Collection<XBreakpointGroupingRule> groupingRules) { setGroupingRulesInternal(groupingRules); rebuildTree(new ArrayList<BreakpointItem>(myNodes.keySet())); } public void rebuildTree(Collection<BreakpointItem> items) { List<BreakpointItem> selectedBreakpoints = getSelectedBreakpoints(); TreePath path = myTreeView.getSelectionPath(); buildTree(items); if (selectedBreakpoints.size() > 0) { selectBreakpointItem(selectedBreakpoints.get(0), path); } } public List<BreakpointItem> getSelectedBreakpoints() { TreePath[] selectionPaths = myTreeView.getSelectionPaths(); if (selectionPaths == null || selectionPaths.length == 0) return Collections.emptyList(); final ArrayList<BreakpointItem> list = new ArrayList<BreakpointItem>(); for (TreePath selectionPath : selectionPaths) { TreeUtil.traverseDepth((TreeNode)selectionPath.getLastPathComponent(), new TreeUtil.Traverse() { public boolean accept(final Object node) { if (node instanceof BreakpointItemNode) { list.add(((BreakpointItemNode)node).getBreakpointItem()); } return true; } }); } return list; } public void selectBreakpointItem(@Nullable final BreakpointItem breakpoint, TreePath path) { BreakpointItemNode node = myNodes.get(breakpoint); if (node != null) { TreeUtil.selectNode(myTreeView, node); } else { TreeUtil.selectPath(myTreeView, path); } } public CheckedTreeNode getRoot() { return myRoot; } public void selectFirstBreakpointItem() { TreeUtil.selectPath(myTreeView, TreeUtil.getFirstLeafNodePath(myTreeView)); } public void removeSelectedBreakpoints(Project project) { final TreePath[] paths = myTreeView.getSelectionPaths(); final List<BreakpointItem> breakpoints = getSelectedBreakpoints(); for (TreePath path : paths) { final Object node = path.getLastPathComponent(); if (node instanceof BreakpointItemNode) { final BreakpointItem item = ((BreakpointItemNode)node).getBreakpointItem(); if (!item.allowedToRemove()) { TreeUtil.unselect(myTreeView, (DefaultMutableTreeNode)node); breakpoints.remove(item); } } } if (breakpoints.isEmpty()) return; TreeUtil.removeSelected(myTreeView); for (BreakpointItem breakpoint : breakpoints) { breakpoint.removed(project); } } private static class TreeNodeComparator implements Comparator<TreeNode> { public int compare(final TreeNode o1, final TreeNode o2) { if (o1 instanceof BreakpointItemNode && o2 instanceof BreakpointItemNode) { //noinspection unchecked BreakpointItem b1 = ((BreakpointItemNode)o1).getBreakpointItem(); //noinspection unchecked BreakpointItem b2 = ((BreakpointItemNode)o2).getBreakpointItem(); boolean default1 = b1.isDefaultBreakpoint(); boolean default2 = b2.isDefaultBreakpoint(); if (default1 && !default2) return -1; if (!default1 && default2) return 1; return b1.compareTo(b2); } if (o1 instanceof BreakpointsGroupNode && o2 instanceof BreakpointsGroupNode) { final BreakpointsGroupNode group1 = (BreakpointsGroupNode)o1; final BreakpointsGroupNode group2 = (BreakpointsGroupNode)o2; if (group1.getLevel() != group2.getLevel()) { return group1.getLevel() - group2.getLevel(); } return group1.getGroup().compareTo(group2.getGroup()); } return o1 instanceof BreakpointsGroupNode ? -1 : 1; } } public interface BreakpointItemsTreeDelegate { void execute(BreakpointItem item); } }
http://ea.jetbrains.com/browser/ea_problems/43930
platform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointItemsTreeController.java
http://ea.jetbrains.com/browser/ea_problems/43930
<ide><path>latform/xdebugger-impl/src/com/intellij/xdebugger/impl/breakpoints/ui/tree/BreakpointItemsTreeController.java <ide> <ide> public void removeSelectedBreakpoints(Project project) { <ide> final TreePath[] paths = myTreeView.getSelectionPaths(); <add> if (paths == null) return; <ide> final List<BreakpointItem> breakpoints = getSelectedBreakpoints(); <ide> for (TreePath path : paths) { <ide> final Object node = path.getLastPathComponent();
Java
mit
error: pathspec 'src/exception/MultiCatch.java' did not match any file(s) known to git
ab0b9215aba54cb17ad40e0b1968eead730a9ad6
1
ubbn/CoreJava,tugul/CoreJava
package exception; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.FileSystemException; import java.sql.SQLException; /** * - MultiCatch block * introduced in Java 7 * multiple exceptions can be caught in same catch block * those must be unrelated class * * Note: * It is illegal to reassign the exception inside multi-catch * while it is allowed in single exception catch block * * */ public class MultiCatch { private static void throwsExceptions() throws Exception { } public static void main(String[] args) { try { throwsExceptions(); } catch(IllegalArgumentException | SQLException e){ e.printStackTrace(); } catch(FileNotFoundException | IOException e){ // DOES NOT COMPILE, must be unrelated exceptions // FileNotFoundException extends IOException } catch (ArithmeticException | ClassNotFoundException e){ e = new RuntimeException(); // DOES NOT COMPILE, reassign not allowed in multi-catch } catch (Exception e) { e = new RuntimeException("Re-assigned exception"); // reassigning exception is allowed in single catch } } }
src/exception/MultiCatch.java
Mult-catch is introduced in Java 7
src/exception/MultiCatch.java
Mult-catch is introduced in Java 7
<ide><path>rc/exception/MultiCatch.java <add>package exception; <add> <add>import java.io.FileNotFoundException; <add>import java.io.IOException; <add>import java.nio.file.FileSystemException; <add>import java.sql.SQLException; <add> <add>/** <add> * - MultiCatch block <add> * introduced in Java 7 <add> * multiple exceptions can be caught in same catch block <add> * those must be unrelated class <add> * <add> * Note: <add> * It is illegal to reassign the exception inside multi-catch <add> * while it is allowed in single exception catch block <add> * <add> * <add> */ <add>public class MultiCatch { <add> private static void throwsExceptions() throws Exception { } <add> <add> public static void main(String[] args) { <add> try { <add> throwsExceptions(); <add> } <add> catch(IllegalArgumentException | SQLException e){ <add> e.printStackTrace(); <add> } <add> catch(FileNotFoundException | IOException e){ // DOES NOT COMPILE, must be unrelated exceptions <add> // FileNotFoundException extends IOException <add> } <add> catch (ArithmeticException | ClassNotFoundException e){ <add> e = new RuntimeException(); // DOES NOT COMPILE, reassign not allowed in multi-catch <add> } <add> catch (Exception e) <add> { <add> e = new RuntimeException("Re-assigned exception"); // reassigning exception is allowed in single catch <add> } <add> } <add>}
Java
apache-2.0
54fd3895f1d3c694db67bf2b2acd0ceccb57e43e
0
henrichg/PhoneProfiles
package sk.henrichg.phoneprofiles; import android.annotation.SuppressLint; import android.app.Application; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.support.multidex.MultiDex; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.util.Pair; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import com.evernote.android.job.JobConfig; import com.evernote.android.job.JobManager; import com.github.anrwatchdog.ANRError; import com.github.anrwatchdog.ANRWatchDog; import com.samsung.android.sdk.SsdkUnsupportedException; import com.samsung.android.sdk.look.Slook; import com.stericson.RootShell.RootShell; import com.stericson.RootShell.execution.Command; import com.stericson.RootTools.RootTools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.fabric.sdk.android.Fabric; public class PPApplication extends Application { static final String romManufacturer = getROMManufacturer(); static String PACKAGE_NAME; static final int VERSION_CODE_EXTENDER_1_0_4 = 60; static final int VERSION_CODE_EXTENDER_2_0 = 80; static final int VERSION_CODE_EXTENDER_LATEST = VERSION_CODE_EXTENDER_2_0; public static final String EXPORT_PATH = "/PhoneProfiles"; private static final String LOG_FILENAME = "log.txt"; private static final boolean logIntoLogCat = true; private static final boolean logIntoFile = false; private static final boolean rootToolsDebug = false; private static final String logFilterTags = "##### PPApplication.onCreate" +"|PhoneProfilesService.onCreate" //+"|PhoneProfilesService.onStartCommand" +"|PhoneProfilesService.doForFirstStart" //+"|PhoneProfilesService.showProfileNotification" +"|PhoneProfilesService.onDestroy" +"|BootUpReceiver" +"|PackageReplacedReceiver" +"|ShutdownBroadcastReceiver" //+"|ProfileDurationAlarmBroadcastReceiver" //+"|ActivateProfilesHelper.executeForForceStopApplications" +"|DataWrapper.setDynamicLauncherShortcuts" ; static final String EXTRA_PROFILE_ID = "profile_id"; static final String EXTRA_STARTUP_SOURCE = "startup_source"; static final int STARTUP_SOURCE_NOTIFICATION = 1; static final int STARTUP_SOURCE_WIDGET = 2; static final int STARTUP_SOURCE_SHORTCUT = 3; static final int STARTUP_SOURCE_BOOT = 4; static final int STARTUP_SOURCE_ACTIVATOR = 5; static final int STARTUP_SOURCE_SERVICE = 6; static final int STARTUP_SOURCE_EDITOR = 8; static final int STARTUP_SOURCE_ACTIVATOR_START = 9; static final int STARTUP_SOURCE_EXTERNAL_APP = 10; static final int STARTUP_SOURCE_SERVICE_MANUAL = 11; static final int PREFERENCES_STARTUP_SOURCE_ACTIVITY = 1; //static final int PREFERENCES_STARTUP_SOURCE_FRAGMENT = 2; static final int PREFERENCES_STARTUP_SOURCE_SHARED_PROFILE = 3; static final String PROFILE_NOTIFICATION_CHANNEL = "phoneProfiles_activated_profile"; static final String INFORMATION_NOTIFICATION_CHANNEL = "phoneProfiles_information"; static final String EXCLAMATION_NOTIFICATION_CHANNEL = "phoneProfiles_exclamation"; static final String GRANT_PERMISSION_NOTIFICATION_CHANNEL = "phoneProfiles_grant_permission"; static final int PROFILE_NOTIFICATION_ID = 700420; static final int IMPORTANT_INFO_NOTIFICATION_ID = 700422; static final int GRANT_PROFILE_PERMISSIONS_NOTIFICATION_ID = 700423; static final int GRANT_INSTALL_TONE_PERMISSIONS_NOTIFICATION_ID = 700424; static final int ACTION_FOR_EXTERNAL_APPLICATION_NOTIFICATION_ID = 700425; static final int PROFILE_ACTIVATION_MOBILE_DATA_PREFS_NOTIFICATION_ID = 700426; static final int PROFILE_ACTIVATION_LOCATION_PREFS_NOTIFICATION_ID = 700427; static final int PROFILE_ACTIVATION_WIFI_AP_PREFS_NOTIFICATION_ID = 700428; static final int ABOUT_APPLICATION_DONATE_NOTIFICATION_ID = 700429; static final int PROFILE_ACTIVATION_NETWORK_TYPE_PREFS_NOTIFICATION_ID = 700430; static final String APPLICATION_PREFS_NAME = "phone_profile_preferences"; static final String SHARED_PROFILE_PREFS_NAME = "profile_preferences_default_profile"; static final String PERMISSIONS_PREFS_NAME = "permissions_list"; static final String PERMISSIONS_STATUS_PREFS_NAME = "permissions_status"; static final String WIFI_CONFIGURATION_LIST_PREFS_NAME = "wifi_configuration_list"; public static final int PREFERENCE_NOT_ALLOWED = 0; public static final int PREFERENCE_ALLOWED = 1; public static final int PREFERENCE_NOT_ALLOWED_NO_HARDWARE = 0; public static final int PREFERENCE_NOT_ALLOWED_NOT_ROOTED = 1; public static final int PREFERENCE_NOT_ALLOWED_SETTINGS_NOT_FOUND = 2; public static final int PREFERENCE_NOT_ALLOWED_SERVICE_NOT_FOUND = 3; public static final int PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_SYSTEM = 4; private static final int PREFERENCE_NOT_ALLOWED_NOT_CONFIGURED_IN_SYSTEM_SETTINGS = 5; public static final int PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_APPLICATION = 6; private static final int PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_ANDROID_VERSION = 7; private static final String PREF_APPLICATION_STARTED = "applicationStarted"; private static final String PREF_SAVED_VERSION_CODE = "saved_version_code"; private static final String PREF_DAYS_AFTER_FIRST_START = "days_after_first_start"; private static final String PREF_DONATION_NOTIFICATION_COUNT = "donation_notification_count"; private static final String PREF_DONATION_DONATED = "donation_donated"; static final String EXTENDER_ACCESSIBILITY_SERVICE_ID = "sk.henrichg.phoneprofilesplusextender/.PPPEAccessibilityService"; static final String ACTION_ACCESSIBILITY_SERVICE_UNBIND = "sk.henrichg.phoneprofilesplusextender.ACTION_ACCESSIBILITY_SERVICE_UNBIND"; static final String ACTION_FORCE_STOP_APPLICATIONS_START = "sk.henrichg.phoneprofilesplusextender.ACTION_FORCE_STOP_APPLICATIONS_START"; static final String ACTION_FORCE_STOP_APPLICATIONS_END = "sk.henrichg.phoneprofilesplusextender.ACTION_FORCE_STOP_APPLICATIONS_END"; static final String ACCESSIBILITY_SERVICE_PERMISSION = "sk.henrichg.phoneprofilesplusextender.ACCESSIBILITY_SERVICE_PERMISSION"; static final String EXTRA_APPLICATIONS = "extra_applications"; public static HandlerThread handlerThread = null; public static HandlerThread handlerThreadVolumes = null; public static HandlerThread handlerThreadRadios = null; public static HandlerThread handlerThreadAdaptiveBrightness = null; public static HandlerThread handlerThreadWallpaper = null; public static HandlerThread handlerThreadPowerSaveMode = null; public static HandlerThread handlerThreadLockDevice = null; public static HandlerThread handlerThreadRunApplication = null; public static HandlerThread handlerThreadHeadsUpNotifications = null; public static Handler brightnessHandler; public static Handler toastHandler; public static Handler screenTimeoutHandler; public static Handler widgetHandler; public static int notAllowedReason; public static String notAllowedReasonDetail; public static final RootMutex rootMutex = new RootMutex(); public static final ScanResultsMutex scanResultsMutex = new ScanResultsMutex(); public static boolean startedOnBoot = false; public static LockDeviceActivity lockDeviceActivity = null; public static int screenTimeoutBeforeDeviceLock = 0; //public static final RootMutex rootMutex = new RootMutex(); // Samsung Look instance public static Slook sLook = null; public static boolean sLookCocktailPanelEnabled = false; //public static boolean sLookCocktailBarEnabled = false; private static final RefreshGUIBroadcastReceiver refreshGUIBroadcastReceiver = new RefreshGUIBroadcastReceiver(); private static final DashClockBroadcastReceiver dashClockBroadcastReceiver = new DashClockBroadcastReceiver(); @Override public void onCreate() { super.onCreate(); if (checkAppReplacingState()) return; // Set up Crashlytics, disabled for debug builds Crashlytics crashlyticsKit = new Crashlytics.Builder() .core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()) .build(); Fabric.with(getApplicationContext(), crashlyticsKit); // Crashlytics.getInstance().core.logException(exception); -- this log will be associated with crash log. // set up ANR-WatchDog ANRWatchDog anrWatchDog = new ANRWatchDog(); //anrWatchDog.setReportMainThreadOnly(); anrWatchDog.setANRListener(new ANRWatchDog.ANRListener() { @Override public void onAppNotResponding(ANRError error) { Crashlytics.getInstance().core.logException(error); } }); anrWatchDog.start(); try { Crashlytics.setBool("DEBUG", BuildConfig.DEBUG); } catch (Exception ignored) {} //if (BuildConfig.DEBUG) { int actualVersionCode = 0; try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); actualVersionCode = pInfo.versionCode; } catch (Exception ignored) { } Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(getApplicationContext(), actualVersionCode)); //} // Debug.startMethodTracing("phoneprofiles"); //long nanoTimeStart = startMeasuringRunTime(); PACKAGE_NAME = getPackageName(); LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(PPApplication.dashClockBroadcastReceiver, new IntentFilter("DashClockBroadcastReceiver")); LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(PPApplication.refreshGUIBroadcastReceiver, new IntentFilter("RefreshGUIBroadcastReceiver")); startHandlerThread(); startHandlerThreadVolumes(); startHandlerThreadRadios(); startHandlerThreadAdaptiveBrightness(); startHandlerThreadWallpaper(); startHandlerThreadPowerSaveMode(); startHandlerThreadLockDevice(); startHandlerThreadRunApplication(); startHandlerThreadHeadsUpNotifications(); toastHandler = new Handler(getMainLooper()); brightnessHandler = new Handler(getMainLooper()); screenTimeoutHandler = new Handler(getMainLooper()); widgetHandler = new Handler(getMainLooper()); // initialization //loadPreferences(this); PPApplication.initRoot(); JobConfig.setForceAllowApi14(true); // https://github.com/evernote/android-job/issues/197 JobManager.create(this).addJobCreator(new PPJobsCreator()); //Log.d("PPApplication.onCreate", "memory usage (after create activateProfileHelper)=" + Debug.getNativeHeapAllocatedSize()); //Log.d("PPApplication.onCreate","xxx"); //getMeasuredRunTime(nanoTimeStart, "PPApplication.onCreate"); // Samsung Look initialization sLook = new Slook(); try { sLook.initialize(this); // true = The Device supports Edge Single Mode, Edge Single Plus Mode, and Edge Feeds Mode. sLookCocktailPanelEnabled = sLook.isFeatureEnabled(Slook.COCKTAIL_PANEL); // true = The Device supports Edge Immersive Mode feature. //sLookCocktailBarEnabled = sLook.isFeatureEnabled(Slook.COCKTAIL_BAR); } catch (SsdkUnsupportedException e) { sLook = null; } } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } // workaround for: java.lang.NullPointerException: Attempt to invoke virtual method // 'android.content.res.AssetManager android.content.res.Resources.getAssets()' on a null object reference // https://issuetracker.google.com/issues/36972466 private boolean checkAppReplacingState() { if (getResources() == null) { Log.w("PPApplication.onCreate", "app is replacing...kill"); android.os.Process.killProcess(android.os.Process.myPid()); return true; } return false; } //-------------------------------------------------------------- static void startPPService(Context context, Intent serviceIntent) { if (Build.VERSION.SDK_INT < 26) context.getApplicationContext().startService(serviceIntent); else context.getApplicationContext().startForegroundService(serviceIntent); } //-------------------------------------------------------------- static public boolean getApplicationStarted(Context context, boolean testService) { ApplicationPreferences.getSharedPreferences(context); if (testService) return ApplicationPreferences.preferences.getBoolean(PREF_APPLICATION_STARTED, false) && (PhoneProfilesService.instance != null); else return ApplicationPreferences.preferences.getBoolean(PREF_APPLICATION_STARTED, false); } static public void setApplicationStarted(Context context, boolean appStarted) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_APPLICATION_STARTED, appStarted); editor.apply(); } static public int getSavedVersionCode(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getInt(PREF_SAVED_VERSION_CODE, 0); } static public void setSavedVersionCode(Context context, int version) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(PREF_SAVED_VERSION_CODE, version); editor.apply(); } public static String getNotAllowedPreferenceReasonString(Context context) { switch (notAllowedReason) { case PREFERENCE_NOT_ALLOWED_NO_HARDWARE: return context.getString(R.string.preference_not_allowed_reason_no_hardware); case PREFERENCE_NOT_ALLOWED_NOT_ROOTED: return context.getString(R.string.preference_not_allowed_reason_not_rooted); case PREFERENCE_NOT_ALLOWED_SETTINGS_NOT_FOUND: return context.getString(R.string.preference_not_allowed_reason_settings_not_found); case PREFERENCE_NOT_ALLOWED_SERVICE_NOT_FOUND: return context.getString(R.string.preference_not_allowed_reason_service_not_found); case PREFERENCE_NOT_ALLOWED_NOT_CONFIGURED_IN_SYSTEM_SETTINGS: return context.getString(R.string.preference_not_allowed_reason_not_configured_in_system_settings); case PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_SYSTEM: return context.getString(R.string.preference_not_allowed_reason_not_supported) + " (" + notAllowedReasonDetail + ")"; case PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_APPLICATION: return context.getString(R.string.preference_not_allowed_reason_not_supported_by_application) + " (" + notAllowedReasonDetail + ")"; case PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_ANDROID_VERSION: return context.getString(R.string.preference_not_allowed_reason_not_supported_android_version) + " (" + notAllowedReasonDetail + ")"; default: return context.getString(R.string.empty_string); } } //------------------------------------- // log ---------------------------------------------------------- static private void resetLog() { File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) //noinspection ResultOfMethodCallIgnored exportDir.mkdirs(); File logFile = new File(sd, EXPORT_PATH + "/" + LOG_FILENAME); //noinspection ResultOfMethodCallIgnored logFile.delete(); } @SuppressWarnings("UnusedAssignment") @SuppressLint("SimpleDateFormat") static private void logIntoFile(String type, String tag, String text) { if (!logIntoFile) return; try { // warnings when logIntoFile == false File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) //noinspection ResultOfMethodCallIgnored exportDir.mkdirs(); File logFile = new File(sd, EXPORT_PATH + "/" + LOG_FILENAME); if (logFile.length() > 1024 * 10000) resetLog(); if (!logFile.exists()) { //noinspection ResultOfMethodCallIgnored logFile.createNewFile(); } //BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); String log = ""; SimpleDateFormat sdf = new SimpleDateFormat("d.MM.yy HH:mm:ss:S"); String time = sdf.format(Calendar.getInstance().getTimeInMillis()); log = log + time + "--" + type + "-----" + tag + "------" + text; buf.append(log); buf.newLine(); buf.flush(); buf.close(); } catch (IOException ignored) { } } private static boolean logContainsFilterTag(String tag) { boolean contains = false; String[] splits = logFilterTags.split("\\|"); for (String split : splits) { if (tag.contains(split)) { contains = true; break; } } return contains; } static public boolean logEnabled() { //noinspection ConstantConditions return (logIntoLogCat || logIntoFile); } @SuppressWarnings("unused") static public void logI(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.i(tag, text); logIntoFile("I", tag, text); } } @SuppressWarnings("unused") static public void logW(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.w(tag, text); logIntoFile("W", tag, text); } } @SuppressWarnings("unused") static public void logE(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.e(tag, text); logIntoFile("E", tag, text); } } @SuppressWarnings("unused") static public void logD(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.d(tag, text); logIntoFile("D", tag, text); } } static public int getDaysAfterFirstStart(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getInt(PREF_DAYS_AFTER_FIRST_START, 0); } static public void setDaysAfterFirstStart(Context context, int days) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(PREF_DAYS_AFTER_FIRST_START, days); editor.apply(); } static public int getDonationNotificationCount(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getInt(PREF_DONATION_NOTIFICATION_COUNT, 0); } static public void setDonationNotificationCount(Context context, int days) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(PREF_DONATION_NOTIFICATION_COUNT, days); editor.apply(); } static public boolean getDonationDonated(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_DONATION_DONATED, false); } static public void setDonationDonated(Context context) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_DONATION_DONATED, true); editor.apply(); } //-------------------------------------------------------------- // notification channels ------------------------- static void createProfileNotificationChannel(/*Profile profile, */Context context) { if (Build.VERSION.SDK_INT >= 26) { int importance; if (ApplicationPreferences.notificationShowInStatusBar(context)) { /*KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); if (myKM != null) { //boolean screenUnlocked = !myKM.inKeyguardRestrictedInputMode(); //boolean screenUnlocked = getScreenUnlocked(context); boolean screenUnlocked = !myKM.isKeyguardLocked(); if ((ApplicationPreferences.notificationHideInLockScreen(context) && (!screenUnlocked)) || ((profile != null) && profile._hideStatusBarIcon)) importance = NotificationManager.IMPORTANCE_MIN; else importance = NotificationManager.IMPORTANCE_LOW; } else*/ importance = NotificationManager.IMPORTANCE_LOW; } else importance = NotificationManager.IMPORTANCE_MIN; // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_activated_profile); // The user-visible description of the channel. String description = context.getString(R.string.notification_channel_activated_profile_description_pp); NotificationChannel channel = new NotificationChannel(PROFILE_NOTIFICATION_CHANNEL, name, importance); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createInformationNotificationChannel(Context context) { if (Build.VERSION.SDK_INT >= 26) { // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_information); // The user-visible description of the channel. String description = context.getString(R.string.empty_string); NotificationChannel channel = new NotificationChannel(INFORMATION_NOTIFICATION_CHANNEL, name, NotificationManager.IMPORTANCE_LOW); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createExclamationNotificationChannel(Context context) { if (Build.VERSION.SDK_INT >= 26) { // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_exclamation); // The user-visible description of the channel. String description = context.getString(R.string.empty_string); NotificationChannel channel = new NotificationChannel(EXCLAMATION_NOTIFICATION_CHANNEL, name, NotificationManager.IMPORTANCE_DEFAULT); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createGrantPermissionNotificationChannel(Context context) { if (Build.VERSION.SDK_INT >= 26) { // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_grant_permission); // The user-visible description of the channel. String description = context.getString(R.string.notification_channel_grant_permission_description); NotificationChannel channel = new NotificationChannel(GRANT_PERMISSION_NOTIFICATION_CHANNEL, name, NotificationManager.IMPORTANCE_DEFAULT); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createNotificationChannels(Context appContext) { PPApplication.createProfileNotificationChannel(appContext); PPApplication.createInformationNotificationChannel(appContext); PPApplication.createExclamationNotificationChannel(appContext); PPApplication.createGrantPermissionNotificationChannel(appContext); } // ----------------------------------------------- // root ----------------------------------------------------- static synchronized void initRoot() { synchronized (PPApplication.rootMutex) { rootMutex.rootChecked = false; rootMutex.rooted = false; rootMutex.settingsBinaryChecked = false; rootMutex.settingsBinaryExists = false; //rootMutex.isSELinuxEnforcingChecked = false; //rootMutex.isSELinuxEnforcing = false; //rootMutex.suVersion = null; //rootMutex.suVersionChecked = false; rootMutex.serviceBinaryChecked = false; rootMutex.serviceBinaryExists = false; } } private static boolean _isRooted() { RootShell.debugMode = rootToolsDebug; if (rootMutex.rootChecked) return rootMutex.rooted; try { PPApplication.logE("PPApplication._isRooted", "start isRootAvailable"); //if (RootTools.isRootAvailable()) { if (RootToolsSmall.isRooted()) { // device is rooted PPApplication.logE("PPApplication._isRooted", "root available"); rootMutex.rooted = true; } else { PPApplication.logE("PPApplication._isRooted", "root NOT available"); rootMutex.rooted = false; //rootMutex.settingsBinaryExists = false; //rootMutex.settingsBinaryChecked = false; //rootMutex.isSELinuxEnforcingChecked = false; //rootMutex.isSELinuxEnforcing = false; //rootMutex.suVersionChecked = false; //rootMutex.suVersion = null; //rootMutex.serviceBinaryExists = false; //rootMutex.serviceBinaryChecked = false; } rootMutex.rootChecked = true; } catch (Exception e) { Log.e("PPApplication._isRooted", Log.getStackTraceString(e)); } //if (rooted) // getSUVersion(); return rootMutex.rooted; } static boolean isRooted() { if (rootMutex.rootChecked) return rootMutex.rooted; synchronized (PPApplication.rootMutex) { return _isRooted(); } } static boolean isRootGranted() { RootShell.debugMode = rootToolsDebug; if (isRooted()) { try { PPApplication.logE("PPApplication.isRootGranted", "start isAccessGiven"); if (RootTools.isAccessGiven()) { // root is granted PPApplication.logE("PPApplication.isRootGranted", "root granted"); return true; } else { // grant declined PPApplication.logE("PPApplication.isRootGranted", "root NOT granted"); return false; } } catch (Exception e) { Log.e("PPApplication.isRootGranted", Log.getStackTraceString(e)); return false; } } else { PPApplication.logE("PPApplication.isRootGranted", "not rooted"); return false; } } static boolean settingsBinaryExists() { RootShell.debugMode = rootToolsDebug; if (rootMutex.settingsBinaryChecked) return rootMutex.settingsBinaryExists; synchronized (PPApplication.rootMutex) { if (!rootMutex.settingsBinaryChecked) { PPApplication.logE("PPApplication.settingsBinaryExists", "start"); rootMutex.settingsBinaryExists = RootToolsSmall.hasSettingBin(); rootMutex.settingsBinaryChecked = true; } PPApplication.logE("PPApplication.settingsBinaryExists", "settingsBinaryExists=" + rootMutex.settingsBinaryExists); return rootMutex.settingsBinaryExists; } } static boolean serviceBinaryExists() { RootShell.debugMode = rootToolsDebug; if (rootMutex.serviceBinaryChecked) return rootMutex.serviceBinaryExists; synchronized (PPApplication.rootMutex) { if (!rootMutex.serviceBinaryChecked) { PPApplication.logE("PPApplication.serviceBinaryExists", "start"); rootMutex.serviceBinaryExists = RootToolsSmall.hasServiceBin(); rootMutex.serviceBinaryChecked = true; } PPApplication.logE("PPApplication.serviceBinaryExists", "serviceBinaryExists=" + rootMutex.serviceBinaryExists); return rootMutex.serviceBinaryExists; } } /** * Detect if SELinux is set to enforcing, caches result * * @return true if SELinux set to enforcing, or false in the case of * permissive or not present */ /*public static boolean isSELinuxEnforcing() { RootShell.debugMode = rootToolsDebug; synchronized (PPApplication.rootMutex) { if (!isSELinuxEnforcingChecked) { boolean enforcing = false; // First known firmware with SELinux built-in was a 4.2 (17) // leak //if (android.os.Build.VERSION.SDK_INT >= 17) { // Detect enforcing through sysfs, not always present File f = new File("/sys/fs/selinux/enforce"); if (f.exists()) { try { InputStream is = new FileInputStream("/sys/fs/selinux/enforce"); //noinspection TryFinallyCanBeTryWithResources try { enforcing = (is.read() == '1'); } finally { is.close(); } } catch (Exception ignored) { } } //} isSELinuxEnforcing = enforcing; isSELinuxEnforcingChecked = true; } PPApplication.logE("PPApplication.isSELinuxEnforcing", "isSELinuxEnforcing="+isSELinuxEnforcing); return isSELinuxEnforcing; } }*/ /* public static String getSELinuxEnforceCommand(String command, Shell.ShellContext context) { if ((suVersion != null) && suVersion.contains("SUPERSU")) return "su --context " + context.getValue() + " -c \"" + command + "\" < /dev/null"; else return command; } public static String getSUVersion() { if (!suVersionChecked) { Command command = new Command(0, false, "su -v") { @Override public void commandOutput(int id, String line) { suVersion = line; super.commandOutput(id, line); } } ; try { RootTools.getShell(false).add(command); commandWait(command); suVersionChecked = true; } catch (Exception e) { Log.e("PPApplication.getSUVersion", Log.getStackTraceString(e)); } } return suVersion; } */ public static String getJavaCommandFile(Class<?> mainClass, String name, Context context, Object cmdParam) { try { String cmd = "#!/system/bin/sh\n" + "base=/system\n" + "export CLASSPATH=" + context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.sourceDir + "\n" + "exec app_process $base/bin " + mainClass.getName() + " " + cmdParam + " \"$@\"\n"; FileOutputStream fos = context.openFileOutput(name, Context.MODE_PRIVATE); fos.write(cmd.getBytes()); fos.close(); File file = context.getFileStreamPath(name); if (!file.setExecutable(true)) return null; /* File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) exportDir.mkdirs(); File outFile = new File(sd, PPApplication.EXPORT_PATH + "/" + name); OutputStream out = new FileOutputStream(outFile); out.write(cmd.getBytes()); out.close(); outFile.setExecutable(true); */ return file.getAbsolutePath(); } catch (Exception e) { return null; } } static void getServicesList() { synchronized (PPApplication.rootMutex) { if (rootMutex.serviceList == null) rootMutex.serviceList = new ArrayList<>(); else rootMutex.serviceList.clear(); //noinspection RegExpRedundantEscape final Pattern compile = Pattern.compile("^[0-9]+\\s+([a-zA-Z0-9_\\-\\.]+): \\[(.*)\\]$"); Command command = new Command(0, false, "service list") { @Override public void commandOutput(int id, String line) { Matcher matcher = compile.matcher(line); if (matcher.find()) { //noinspection unchecked rootMutex.serviceList.add(new Pair(matcher.group(1), matcher.group(2))); } super.commandOutput(id, line); } }; try { RootTools.getShell(false).add(command); commandWait(command); } catch (Exception e) { Log.e("PPApplication.getServicesList", Log.getStackTraceString(e)); } } } static Object getServiceManager(String serviceType) { synchronized (PPApplication.rootMutex) { if (rootMutex.serviceList != null) { for (Pair pair : rootMutex.serviceList) { if (serviceType.equals(pair.first)) { return pair.second; } } } return null; } } static int getTransactionCode(String serviceManager, String method) { int code = -1; try { for (Class declaredFields : Class.forName(serviceManager).getDeclaredClasses()) { Field[] declaredFields2 = declaredFields.getDeclaredFields(); int length = declaredFields2.length; int iField = 0; while (iField < length) { Field field = declaredFields2[iField]; String name = field.getName(); if (name == null || !name.equals("TRANSACTION_" + method)) { iField++; } else { try { field.setAccessible(true); code = field.getInt(field); break; } catch (Exception e) { Log.e("PPApplication.getTransactionCode", Log.getStackTraceString(e)); } } } } } catch (ClassNotFoundException e) { Log.e("PPApplication.getTransactionCode", Log.getStackTraceString(e)); } return code; } static String getServiceCommand(String serviceType, int transactionCode, Object... params) { if (params.length > 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("service").append(" ").append("call").append(" ").append(serviceType).append(" ").append(transactionCode); for (Object param : params) { if (param != null) { stringBuilder.append(" "); if (param instanceof Integer) { stringBuilder.append("i32").append(" ").append(param); } else if (param instanceof String) { stringBuilder.append("s16").append(" ").append("'").append(((String) param).replace("'", "'\\''")).append("'"); } } } return stringBuilder.toString(); } else return null; } static void commandWait(Command cmd) { int waitTill = 50; int waitTillMultiplier = 2; int waitTillLimit = 3200; // 6350 msec (3200 * 2 - 50) //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (cmd) { while (!cmd.isFinished() && waitTill<=waitTillLimit) { try { if (!cmd.isFinished()) { cmd.wait(waitTill); waitTill *= waitTillMultiplier; } } catch (InterruptedException e) { Log.e("PPApplication.commandWait", Log.getStackTraceString(e)); } } } if (!cmd.isFinished()){ Log.e("PPApplication.commandWait", "Could not finish root command in " + (waitTill/waitTillMultiplier)); } } // Debug ----------------------------------------------------------------- /* public static long startMeasuringRunTime() { return System.nanoTime(); } public static void getMeasuredRunTime(long nanoTimeStart, String log) { long nanoTimeEnd = System.nanoTime(); long measuredTime = (nanoTimeEnd - nanoTimeStart) / 1000000; Log.d(log, "MEASURED TIME=" + measuredTime); } */ // others ------------------------------------------------------------------ public static void sleep(long ms) { /*long start = SystemClock.uptimeMillis(); do { SystemClock.sleep(100); } while (SystemClock.uptimeMillis() - start < ms);*/ //SystemClock.sleep(ms); try{ Thread.sleep(ms); }catch(InterruptedException ignored){ } } private static String getROMManufacturer() { String line; BufferedReader input = null; try { java.lang.Process p = Runtime.getRuntime().exec("getprop ro.product.brand"); input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024); line = input.readLine(); input.close(); } catch (IOException ex) { Log.e("PPApplication.getROMManufacturer", "Unable to read sysprop ro.product.brand", ex); return null; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e("PPApplication.getROMManufacturer", "Exception while closing InputStream", e); } } } return line; } static boolean hasSystemFeature(Context context, String feature) { try { PackageManager packageManager = context.getPackageManager(); return packageManager.hasSystemFeature(feature); } catch (Exception e) { return false; } } static void startHandlerThread() { if (handlerThread == null) { handlerThread = new HandlerThread("PPHandlerThread"); handlerThread.start(); } } static void startHandlerThreadVolumes() { if (handlerThreadVolumes == null) { handlerThreadVolumes = new HandlerThread("handlerThreadVolumes"); handlerThreadVolumes.start(); } } static void startHandlerThreadRadios() { if (handlerThreadRadios == null) { handlerThreadRadios = new HandlerThread("handlerThreadRadios"); handlerThreadRadios.start(); } } static void startHandlerThreadAdaptiveBrightness() { if (handlerThreadAdaptiveBrightness == null) { handlerThreadAdaptiveBrightness = new HandlerThread("handlerThreadAdaptiveBrightness"); handlerThreadAdaptiveBrightness.start(); } } static void startHandlerThreadWallpaper() { if (handlerThreadWallpaper == null) { handlerThreadWallpaper = new HandlerThread("handlerThreadWallpaper"); handlerThreadWallpaper.start(); } } static void startHandlerThreadPowerSaveMode() { if (handlerThreadPowerSaveMode == null) { handlerThreadPowerSaveMode = new HandlerThread("handlerThreadPowerSaveMode"); handlerThreadPowerSaveMode.start(); } } static void startHandlerThreadLockDevice() { if (handlerThreadLockDevice == null) { handlerThreadLockDevice = new HandlerThread("handlerThreadLockDevice"); handlerThreadLockDevice.start(); } } static void startHandlerThreadRunApplication() { if (handlerThreadRunApplication == null) { handlerThreadRunApplication = new HandlerThread("handlerThreadRunApplication"); handlerThreadRunApplication.start(); } } static void startHandlerThreadHeadsUpNotifications() { if (handlerThreadHeadsUpNotifications == null) { handlerThreadHeadsUpNotifications = new HandlerThread("handlerThreadHeadsUpNotifications"); handlerThreadHeadsUpNotifications.start(); } } }
phoneProfiles/src/main/java/sk/henrichg/phoneprofiles/PPApplication.java
package sk.henrichg.phoneprofiles; import android.annotation.SuppressLint; import android.app.Application; import android.app.NotificationChannel; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.Environment; import android.os.Handler; import android.os.HandlerThread; import android.support.multidex.MultiDex; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.util.Pair; import com.crashlytics.android.Crashlytics; import com.crashlytics.android.core.CrashlyticsCore; import com.evernote.android.job.JobConfig; import com.evernote.android.job.JobManager; import com.github.anrwatchdog.ANRError; import com.github.anrwatchdog.ANRWatchDog; import com.samsung.android.sdk.SsdkUnsupportedException; import com.samsung.android.sdk.look.Slook; import com.stericson.RootShell.RootShell; import com.stericson.RootShell.execution.Command; import com.stericson.RootTools.RootTools; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Field; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.fabric.sdk.android.Fabric; public class PPApplication extends Application { static final String romManufacturer = getROMManufacturer(); static String PACKAGE_NAME; static final int VERSION_CODE_EXTENDER_1_0_4 = 60; static final int VERSION_CODE_EXTENDER_2_0 = 70; static final int VERSION_CODE_EXTENDER_LATEST = VERSION_CODE_EXTENDER_2_0; public static final String EXPORT_PATH = "/PhoneProfiles"; private static final String LOG_FILENAME = "log.txt"; private static final boolean logIntoLogCat = true; private static final boolean logIntoFile = false; private static final boolean rootToolsDebug = false; private static final String logFilterTags = "##### PPApplication.onCreate" +"|PhoneProfilesService.onCreate" //+"|PhoneProfilesService.onStartCommand" +"|PhoneProfilesService.doForFirstStart" //+"|PhoneProfilesService.showProfileNotification" +"|PhoneProfilesService.onDestroy" +"|BootUpReceiver" +"|PackageReplacedReceiver" +"|ShutdownBroadcastReceiver" //+"|ProfileDurationAlarmBroadcastReceiver" //+"|ActivateProfilesHelper.executeForForceStopApplications" +"|DataWrapper.setDynamicLauncherShortcuts" ; static final String EXTRA_PROFILE_ID = "profile_id"; static final String EXTRA_STARTUP_SOURCE = "startup_source"; static final int STARTUP_SOURCE_NOTIFICATION = 1; static final int STARTUP_SOURCE_WIDGET = 2; static final int STARTUP_SOURCE_SHORTCUT = 3; static final int STARTUP_SOURCE_BOOT = 4; static final int STARTUP_SOURCE_ACTIVATOR = 5; static final int STARTUP_SOURCE_SERVICE = 6; static final int STARTUP_SOURCE_EDITOR = 8; static final int STARTUP_SOURCE_ACTIVATOR_START = 9; static final int STARTUP_SOURCE_EXTERNAL_APP = 10; static final int STARTUP_SOURCE_SERVICE_MANUAL = 11; static final int PREFERENCES_STARTUP_SOURCE_ACTIVITY = 1; //static final int PREFERENCES_STARTUP_SOURCE_FRAGMENT = 2; static final int PREFERENCES_STARTUP_SOURCE_SHARED_PROFILE = 3; static final String PROFILE_NOTIFICATION_CHANNEL = "phoneProfiles_activated_profile"; static final String INFORMATION_NOTIFICATION_CHANNEL = "phoneProfiles_information"; static final String EXCLAMATION_NOTIFICATION_CHANNEL = "phoneProfiles_exclamation"; static final String GRANT_PERMISSION_NOTIFICATION_CHANNEL = "phoneProfiles_grant_permission"; static final int PROFILE_NOTIFICATION_ID = 700420; static final int IMPORTANT_INFO_NOTIFICATION_ID = 700422; static final int GRANT_PROFILE_PERMISSIONS_NOTIFICATION_ID = 700423; static final int GRANT_INSTALL_TONE_PERMISSIONS_NOTIFICATION_ID = 700424; static final int ACTION_FOR_EXTERNAL_APPLICATION_NOTIFICATION_ID = 700425; static final int PROFILE_ACTIVATION_MOBILE_DATA_PREFS_NOTIFICATION_ID = 700426; static final int PROFILE_ACTIVATION_LOCATION_PREFS_NOTIFICATION_ID = 700427; static final int PROFILE_ACTIVATION_WIFI_AP_PREFS_NOTIFICATION_ID = 700428; static final int ABOUT_APPLICATION_DONATE_NOTIFICATION_ID = 700429; static final int PROFILE_ACTIVATION_NETWORK_TYPE_PREFS_NOTIFICATION_ID = 700430; static final String APPLICATION_PREFS_NAME = "phone_profile_preferences"; static final String SHARED_PROFILE_PREFS_NAME = "profile_preferences_default_profile"; static final String PERMISSIONS_PREFS_NAME = "permissions_list"; static final String PERMISSIONS_STATUS_PREFS_NAME = "permissions_status"; static final String WIFI_CONFIGURATION_LIST_PREFS_NAME = "wifi_configuration_list"; public static final int PREFERENCE_NOT_ALLOWED = 0; public static final int PREFERENCE_ALLOWED = 1; public static final int PREFERENCE_NOT_ALLOWED_NO_HARDWARE = 0; public static final int PREFERENCE_NOT_ALLOWED_NOT_ROOTED = 1; public static final int PREFERENCE_NOT_ALLOWED_SETTINGS_NOT_FOUND = 2; public static final int PREFERENCE_NOT_ALLOWED_SERVICE_NOT_FOUND = 3; public static final int PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_SYSTEM = 4; private static final int PREFERENCE_NOT_ALLOWED_NOT_CONFIGURED_IN_SYSTEM_SETTINGS = 5; public static final int PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_APPLICATION = 6; private static final int PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_ANDROID_VERSION = 7; private static final String PREF_APPLICATION_STARTED = "applicationStarted"; private static final String PREF_SAVED_VERSION_CODE = "saved_version_code"; private static final String PREF_DAYS_AFTER_FIRST_START = "days_after_first_start"; private static final String PREF_DONATION_NOTIFICATION_COUNT = "donation_notification_count"; private static final String PREF_DONATION_DONATED = "donation_donated"; static final String EXTENDER_ACCESSIBILITY_SERVICE_ID = "sk.henrichg.phoneprofilesplusextender/.PPPEAccessibilityService"; static final String ACTION_ACCESSIBILITY_SERVICE_UNBIND = "sk.henrichg.phoneprofilesplusextender.ACTION_ACCESSIBILITY_SERVICE_UNBIND"; static final String ACTION_FORCE_STOP_APPLICATIONS_START = "sk.henrichg.phoneprofilesplusextender.ACTION_FORCE_STOP_APPLICATIONS_START"; static final String ACTION_FORCE_STOP_APPLICATIONS_END = "sk.henrichg.phoneprofilesplusextender.ACTION_FORCE_STOP_APPLICATIONS_END"; static final String ACCESSIBILITY_SERVICE_PERMISSION = "sk.henrichg.phoneprofilesplusextender.ACCESSIBILITY_SERVICE_PERMISSION"; static final String EXTRA_APPLICATIONS = "extra_applications"; public static HandlerThread handlerThread = null; public static HandlerThread handlerThreadVolumes = null; public static HandlerThread handlerThreadRadios = null; public static HandlerThread handlerThreadAdaptiveBrightness = null; public static HandlerThread handlerThreadWallpaper = null; public static HandlerThread handlerThreadPowerSaveMode = null; public static HandlerThread handlerThreadLockDevice = null; public static HandlerThread handlerThreadRunApplication = null; public static HandlerThread handlerThreadHeadsUpNotifications = null; public static Handler brightnessHandler; public static Handler toastHandler; public static Handler screenTimeoutHandler; public static Handler widgetHandler; public static int notAllowedReason; public static String notAllowedReasonDetail; public static final RootMutex rootMutex = new RootMutex(); public static final ScanResultsMutex scanResultsMutex = new ScanResultsMutex(); public static boolean startedOnBoot = false; public static LockDeviceActivity lockDeviceActivity = null; public static int screenTimeoutBeforeDeviceLock = 0; //public static final RootMutex rootMutex = new RootMutex(); // Samsung Look instance public static Slook sLook = null; public static boolean sLookCocktailPanelEnabled = false; //public static boolean sLookCocktailBarEnabled = false; private static final RefreshGUIBroadcastReceiver refreshGUIBroadcastReceiver = new RefreshGUIBroadcastReceiver(); private static final DashClockBroadcastReceiver dashClockBroadcastReceiver = new DashClockBroadcastReceiver(); @Override public void onCreate() { super.onCreate(); if (checkAppReplacingState()) return; // Set up Crashlytics, disabled for debug builds Crashlytics crashlyticsKit = new Crashlytics.Builder() .core(new CrashlyticsCore.Builder().disabled(BuildConfig.DEBUG).build()) .build(); Fabric.with(getApplicationContext(), crashlyticsKit); // Crashlytics.getInstance().core.logException(exception); -- this log will be associated with crash log. // set up ANR-WatchDog ANRWatchDog anrWatchDog = new ANRWatchDog(); //anrWatchDog.setReportMainThreadOnly(); anrWatchDog.setANRListener(new ANRWatchDog.ANRListener() { @Override public void onAppNotResponding(ANRError error) { Crashlytics.getInstance().core.logException(error); } }); anrWatchDog.start(); try { Crashlytics.setBool("DEBUG", BuildConfig.DEBUG); } catch (Exception ignored) {} //if (BuildConfig.DEBUG) { int actualVersionCode = 0; try { PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0); actualVersionCode = pInfo.versionCode; } catch (Exception ignored) { } Thread.setDefaultUncaughtExceptionHandler(new TopExceptionHandler(getApplicationContext(), actualVersionCode)); //} // Debug.startMethodTracing("phoneprofiles"); //long nanoTimeStart = startMeasuringRunTime(); PACKAGE_NAME = getPackageName(); LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(PPApplication.dashClockBroadcastReceiver, new IntentFilter("DashClockBroadcastReceiver")); LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(PPApplication.refreshGUIBroadcastReceiver, new IntentFilter("RefreshGUIBroadcastReceiver")); startHandlerThread(); startHandlerThreadVolumes(); startHandlerThreadRadios(); startHandlerThreadAdaptiveBrightness(); startHandlerThreadWallpaper(); startHandlerThreadPowerSaveMode(); startHandlerThreadLockDevice(); startHandlerThreadRunApplication(); startHandlerThreadHeadsUpNotifications(); toastHandler = new Handler(getMainLooper()); brightnessHandler = new Handler(getMainLooper()); screenTimeoutHandler = new Handler(getMainLooper()); widgetHandler = new Handler(getMainLooper()); // initialization //loadPreferences(this); PPApplication.initRoot(); JobConfig.setForceAllowApi14(true); // https://github.com/evernote/android-job/issues/197 JobManager.create(this).addJobCreator(new PPJobsCreator()); //Log.d("PPApplication.onCreate", "memory usage (after create activateProfileHelper)=" + Debug.getNativeHeapAllocatedSize()); //Log.d("PPApplication.onCreate","xxx"); //getMeasuredRunTime(nanoTimeStart, "PPApplication.onCreate"); // Samsung Look initialization sLook = new Slook(); try { sLook.initialize(this); // true = The Device supports Edge Single Mode, Edge Single Plus Mode, and Edge Feeds Mode. sLookCocktailPanelEnabled = sLook.isFeatureEnabled(Slook.COCKTAIL_PANEL); // true = The Device supports Edge Immersive Mode feature. //sLookCocktailBarEnabled = sLook.isFeatureEnabled(Slook.COCKTAIL_BAR); } catch (SsdkUnsupportedException e) { sLook = null; } } @Override protected void attachBaseContext(Context base) { super.attachBaseContext(base); MultiDex.install(this); } // workaround for: java.lang.NullPointerException: Attempt to invoke virtual method // 'android.content.res.AssetManager android.content.res.Resources.getAssets()' on a null object reference // https://issuetracker.google.com/issues/36972466 private boolean checkAppReplacingState() { if (getResources() == null) { Log.w("PPApplication.onCreate", "app is replacing...kill"); android.os.Process.killProcess(android.os.Process.myPid()); return true; } return false; } //-------------------------------------------------------------- static void startPPService(Context context, Intent serviceIntent) { if (Build.VERSION.SDK_INT < 26) context.getApplicationContext().startService(serviceIntent); else context.getApplicationContext().startForegroundService(serviceIntent); } //-------------------------------------------------------------- static public boolean getApplicationStarted(Context context, boolean testService) { ApplicationPreferences.getSharedPreferences(context); if (testService) return ApplicationPreferences.preferences.getBoolean(PREF_APPLICATION_STARTED, false) && (PhoneProfilesService.instance != null); else return ApplicationPreferences.preferences.getBoolean(PREF_APPLICATION_STARTED, false); } static public void setApplicationStarted(Context context, boolean appStarted) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_APPLICATION_STARTED, appStarted); editor.apply(); } static public int getSavedVersionCode(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getInt(PREF_SAVED_VERSION_CODE, 0); } static public void setSavedVersionCode(Context context, int version) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(PREF_SAVED_VERSION_CODE, version); editor.apply(); } public static String getNotAllowedPreferenceReasonString(Context context) { switch (notAllowedReason) { case PREFERENCE_NOT_ALLOWED_NO_HARDWARE: return context.getString(R.string.preference_not_allowed_reason_no_hardware); case PREFERENCE_NOT_ALLOWED_NOT_ROOTED: return context.getString(R.string.preference_not_allowed_reason_not_rooted); case PREFERENCE_NOT_ALLOWED_SETTINGS_NOT_FOUND: return context.getString(R.string.preference_not_allowed_reason_settings_not_found); case PREFERENCE_NOT_ALLOWED_SERVICE_NOT_FOUND: return context.getString(R.string.preference_not_allowed_reason_service_not_found); case PREFERENCE_NOT_ALLOWED_NOT_CONFIGURED_IN_SYSTEM_SETTINGS: return context.getString(R.string.preference_not_allowed_reason_not_configured_in_system_settings); case PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_SYSTEM: return context.getString(R.string.preference_not_allowed_reason_not_supported) + " (" + notAllowedReasonDetail + ")"; case PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_BY_APPLICATION: return context.getString(R.string.preference_not_allowed_reason_not_supported_by_application) + " (" + notAllowedReasonDetail + ")"; case PREFERENCE_NOT_ALLOWED_NOT_SUPPORTED_ANDROID_VERSION: return context.getString(R.string.preference_not_allowed_reason_not_supported_android_version) + " (" + notAllowedReasonDetail + ")"; default: return context.getString(R.string.empty_string); } } //------------------------------------- // log ---------------------------------------------------------- static private void resetLog() { File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) //noinspection ResultOfMethodCallIgnored exportDir.mkdirs(); File logFile = new File(sd, EXPORT_PATH + "/" + LOG_FILENAME); //noinspection ResultOfMethodCallIgnored logFile.delete(); } @SuppressWarnings("UnusedAssignment") @SuppressLint("SimpleDateFormat") static private void logIntoFile(String type, String tag, String text) { if (!logIntoFile) return; try { // warnings when logIntoFile == false File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) //noinspection ResultOfMethodCallIgnored exportDir.mkdirs(); File logFile = new File(sd, EXPORT_PATH + "/" + LOG_FILENAME); if (logFile.length() > 1024 * 10000) resetLog(); if (!logFile.exists()) { //noinspection ResultOfMethodCallIgnored logFile.createNewFile(); } //BufferedWriter for performance, true to set append to file flag BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); String log = ""; SimpleDateFormat sdf = new SimpleDateFormat("d.MM.yy HH:mm:ss:S"); String time = sdf.format(Calendar.getInstance().getTimeInMillis()); log = log + time + "--" + type + "-----" + tag + "------" + text; buf.append(log); buf.newLine(); buf.flush(); buf.close(); } catch (IOException ignored) { } } private static boolean logContainsFilterTag(String tag) { boolean contains = false; String[] splits = logFilterTags.split("\\|"); for (String split : splits) { if (tag.contains(split)) { contains = true; break; } } return contains; } static public boolean logEnabled() { //noinspection ConstantConditions return (logIntoLogCat || logIntoFile); } @SuppressWarnings("unused") static public void logI(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.i(tag, text); logIntoFile("I", tag, text); } } @SuppressWarnings("unused") static public void logW(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.w(tag, text); logIntoFile("W", tag, text); } } @SuppressWarnings("unused") static public void logE(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.e(tag, text); logIntoFile("E", tag, text); } } @SuppressWarnings("unused") static public void logD(String tag, String text) { if (!logEnabled()) return; if (logContainsFilterTag(tag)) { if (logIntoLogCat) Log.d(tag, text); logIntoFile("D", tag, text); } } static public int getDaysAfterFirstStart(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getInt(PREF_DAYS_AFTER_FIRST_START, 0); } static public void setDaysAfterFirstStart(Context context, int days) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(PREF_DAYS_AFTER_FIRST_START, days); editor.apply(); } static public int getDonationNotificationCount(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getInt(PREF_DONATION_NOTIFICATION_COUNT, 0); } static public void setDonationNotificationCount(Context context, int days) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putInt(PREF_DONATION_NOTIFICATION_COUNT, days); editor.apply(); } static public boolean getDonationDonated(Context context) { ApplicationPreferences.getSharedPreferences(context); return ApplicationPreferences.preferences.getBoolean(PREF_DONATION_DONATED, false); } static public void setDonationDonated(Context context) { ApplicationPreferences.getSharedPreferences(context); Editor editor = ApplicationPreferences.preferences.edit(); editor.putBoolean(PREF_DONATION_DONATED, true); editor.apply(); } //-------------------------------------------------------------- // notification channels ------------------------- static void createProfileNotificationChannel(/*Profile profile, */Context context) { if (Build.VERSION.SDK_INT >= 26) { int importance; if (ApplicationPreferences.notificationShowInStatusBar(context)) { /*KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE); if (myKM != null) { //boolean screenUnlocked = !myKM.inKeyguardRestrictedInputMode(); //boolean screenUnlocked = getScreenUnlocked(context); boolean screenUnlocked = !myKM.isKeyguardLocked(); if ((ApplicationPreferences.notificationHideInLockScreen(context) && (!screenUnlocked)) || ((profile != null) && profile._hideStatusBarIcon)) importance = NotificationManager.IMPORTANCE_MIN; else importance = NotificationManager.IMPORTANCE_LOW; } else*/ importance = NotificationManager.IMPORTANCE_LOW; } else importance = NotificationManager.IMPORTANCE_MIN; // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_activated_profile); // The user-visible description of the channel. String description = context.getString(R.string.notification_channel_activated_profile_description_pp); NotificationChannel channel = new NotificationChannel(PROFILE_NOTIFICATION_CHANNEL, name, importance); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createInformationNotificationChannel(Context context) { if (Build.VERSION.SDK_INT >= 26) { // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_information); // The user-visible description of the channel. String description = context.getString(R.string.empty_string); NotificationChannel channel = new NotificationChannel(INFORMATION_NOTIFICATION_CHANNEL, name, NotificationManager.IMPORTANCE_LOW); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createExclamationNotificationChannel(Context context) { if (Build.VERSION.SDK_INT >= 26) { // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_exclamation); // The user-visible description of the channel. String description = context.getString(R.string.empty_string); NotificationChannel channel = new NotificationChannel(EXCLAMATION_NOTIFICATION_CHANNEL, name, NotificationManager.IMPORTANCE_DEFAULT); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createGrantPermissionNotificationChannel(Context context) { if (Build.VERSION.SDK_INT >= 26) { // The user-visible name of the channel. CharSequence name = context.getString(R.string.notification_channel_grant_permission); // The user-visible description of the channel. String description = context.getString(R.string.notification_channel_grant_permission_description); NotificationChannel channel = new NotificationChannel(GRANT_PERMISSION_NOTIFICATION_CHANNEL, name, NotificationManager.IMPORTANCE_DEFAULT); // Configure the notification channel. //channel.setImportance(importance); channel.setDescription(description); channel.enableLights(false); // Sets the notification light color for notifications posted to this // channel, if the device supports this feature. //channel.setLightColor(Color.RED); channel.enableVibration(false); //channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE); if (notificationManager != null) notificationManager.createNotificationChannel(channel); } } static void createNotificationChannels(Context appContext) { PPApplication.createProfileNotificationChannel(appContext); PPApplication.createInformationNotificationChannel(appContext); PPApplication.createExclamationNotificationChannel(appContext); PPApplication.createGrantPermissionNotificationChannel(appContext); } // ----------------------------------------------- // root ----------------------------------------------------- static synchronized void initRoot() { synchronized (PPApplication.rootMutex) { rootMutex.rootChecked = false; rootMutex.rooted = false; rootMutex.settingsBinaryChecked = false; rootMutex.settingsBinaryExists = false; //rootMutex.isSELinuxEnforcingChecked = false; //rootMutex.isSELinuxEnforcing = false; //rootMutex.suVersion = null; //rootMutex.suVersionChecked = false; rootMutex.serviceBinaryChecked = false; rootMutex.serviceBinaryExists = false; } } private static boolean _isRooted() { RootShell.debugMode = rootToolsDebug; if (rootMutex.rootChecked) return rootMutex.rooted; try { PPApplication.logE("PPApplication._isRooted", "start isRootAvailable"); //if (RootTools.isRootAvailable()) { if (RootToolsSmall.isRooted()) { // device is rooted PPApplication.logE("PPApplication._isRooted", "root available"); rootMutex.rooted = true; } else { PPApplication.logE("PPApplication._isRooted", "root NOT available"); rootMutex.rooted = false; //rootMutex.settingsBinaryExists = false; //rootMutex.settingsBinaryChecked = false; //rootMutex.isSELinuxEnforcingChecked = false; //rootMutex.isSELinuxEnforcing = false; //rootMutex.suVersionChecked = false; //rootMutex.suVersion = null; //rootMutex.serviceBinaryExists = false; //rootMutex.serviceBinaryChecked = false; } rootMutex.rootChecked = true; } catch (Exception e) { Log.e("PPApplication._isRooted", Log.getStackTraceString(e)); } //if (rooted) // getSUVersion(); return rootMutex.rooted; } static boolean isRooted() { if (rootMutex.rootChecked) return rootMutex.rooted; synchronized (PPApplication.rootMutex) { return _isRooted(); } } static boolean isRootGranted() { RootShell.debugMode = rootToolsDebug; if (isRooted()) { try { PPApplication.logE("PPApplication.isRootGranted", "start isAccessGiven"); if (RootTools.isAccessGiven()) { // root is granted PPApplication.logE("PPApplication.isRootGranted", "root granted"); return true; } else { // grant declined PPApplication.logE("PPApplication.isRootGranted", "root NOT granted"); return false; } } catch (Exception e) { Log.e("PPApplication.isRootGranted", Log.getStackTraceString(e)); return false; } } else { PPApplication.logE("PPApplication.isRootGranted", "not rooted"); return false; } } static boolean settingsBinaryExists() { RootShell.debugMode = rootToolsDebug; if (rootMutex.settingsBinaryChecked) return rootMutex.settingsBinaryExists; synchronized (PPApplication.rootMutex) { if (!rootMutex.settingsBinaryChecked) { PPApplication.logE("PPApplication.settingsBinaryExists", "start"); rootMutex.settingsBinaryExists = RootToolsSmall.hasSettingBin(); rootMutex.settingsBinaryChecked = true; } PPApplication.logE("PPApplication.settingsBinaryExists", "settingsBinaryExists=" + rootMutex.settingsBinaryExists); return rootMutex.settingsBinaryExists; } } static boolean serviceBinaryExists() { RootShell.debugMode = rootToolsDebug; if (rootMutex.serviceBinaryChecked) return rootMutex.serviceBinaryExists; synchronized (PPApplication.rootMutex) { if (!rootMutex.serviceBinaryChecked) { PPApplication.logE("PPApplication.serviceBinaryExists", "start"); rootMutex.serviceBinaryExists = RootToolsSmall.hasServiceBin(); rootMutex.serviceBinaryChecked = true; } PPApplication.logE("PPApplication.serviceBinaryExists", "serviceBinaryExists=" + rootMutex.serviceBinaryExists); return rootMutex.serviceBinaryExists; } } /** * Detect if SELinux is set to enforcing, caches result * * @return true if SELinux set to enforcing, or false in the case of * permissive or not present */ /*public static boolean isSELinuxEnforcing() { RootShell.debugMode = rootToolsDebug; synchronized (PPApplication.rootMutex) { if (!isSELinuxEnforcingChecked) { boolean enforcing = false; // First known firmware with SELinux built-in was a 4.2 (17) // leak //if (android.os.Build.VERSION.SDK_INT >= 17) { // Detect enforcing through sysfs, not always present File f = new File("/sys/fs/selinux/enforce"); if (f.exists()) { try { InputStream is = new FileInputStream("/sys/fs/selinux/enforce"); //noinspection TryFinallyCanBeTryWithResources try { enforcing = (is.read() == '1'); } finally { is.close(); } } catch (Exception ignored) { } } //} isSELinuxEnforcing = enforcing; isSELinuxEnforcingChecked = true; } PPApplication.logE("PPApplication.isSELinuxEnforcing", "isSELinuxEnforcing="+isSELinuxEnforcing); return isSELinuxEnforcing; } }*/ /* public static String getSELinuxEnforceCommand(String command, Shell.ShellContext context) { if ((suVersion != null) && suVersion.contains("SUPERSU")) return "su --context " + context.getValue() + " -c \"" + command + "\" < /dev/null"; else return command; } public static String getSUVersion() { if (!suVersionChecked) { Command command = new Command(0, false, "su -v") { @Override public void commandOutput(int id, String line) { suVersion = line; super.commandOutput(id, line); } } ; try { RootTools.getShell(false).add(command); commandWait(command); suVersionChecked = true; } catch (Exception e) { Log.e("PPApplication.getSUVersion", Log.getStackTraceString(e)); } } return suVersion; } */ public static String getJavaCommandFile(Class<?> mainClass, String name, Context context, Object cmdParam) { try { String cmd = "#!/system/bin/sh\n" + "base=/system\n" + "export CLASSPATH=" + context.getPackageManager().getPackageInfo(context.getPackageName(), 0).applicationInfo.sourceDir + "\n" + "exec app_process $base/bin " + mainClass.getName() + " " + cmdParam + " \"$@\"\n"; FileOutputStream fos = context.openFileOutput(name, Context.MODE_PRIVATE); fos.write(cmd.getBytes()); fos.close(); File file = context.getFileStreamPath(name); if (!file.setExecutable(true)) return null; /* File sd = Environment.getExternalStorageDirectory(); File exportDir = new File(sd, PPApplication.EXPORT_PATH); if (!(exportDir.exists() && exportDir.isDirectory())) exportDir.mkdirs(); File outFile = new File(sd, PPApplication.EXPORT_PATH + "/" + name); OutputStream out = new FileOutputStream(outFile); out.write(cmd.getBytes()); out.close(); outFile.setExecutable(true); */ return file.getAbsolutePath(); } catch (Exception e) { return null; } } static void getServicesList() { synchronized (PPApplication.rootMutex) { if (rootMutex.serviceList == null) rootMutex.serviceList = new ArrayList<>(); else rootMutex.serviceList.clear(); //noinspection RegExpRedundantEscape final Pattern compile = Pattern.compile("^[0-9]+\\s+([a-zA-Z0-9_\\-\\.]+): \\[(.*)\\]$"); Command command = new Command(0, false, "service list") { @Override public void commandOutput(int id, String line) { Matcher matcher = compile.matcher(line); if (matcher.find()) { //noinspection unchecked rootMutex.serviceList.add(new Pair(matcher.group(1), matcher.group(2))); } super.commandOutput(id, line); } }; try { RootTools.getShell(false).add(command); commandWait(command); } catch (Exception e) { Log.e("PPApplication.getServicesList", Log.getStackTraceString(e)); } } } static Object getServiceManager(String serviceType) { synchronized (PPApplication.rootMutex) { if (rootMutex.serviceList != null) { for (Pair pair : rootMutex.serviceList) { if (serviceType.equals(pair.first)) { return pair.second; } } } return null; } } static int getTransactionCode(String serviceManager, String method) { int code = -1; try { for (Class declaredFields : Class.forName(serviceManager).getDeclaredClasses()) { Field[] declaredFields2 = declaredFields.getDeclaredFields(); int length = declaredFields2.length; int iField = 0; while (iField < length) { Field field = declaredFields2[iField]; String name = field.getName(); if (name == null || !name.equals("TRANSACTION_" + method)) { iField++; } else { try { field.setAccessible(true); code = field.getInt(field); break; } catch (Exception e) { Log.e("PPApplication.getTransactionCode", Log.getStackTraceString(e)); } } } } } catch (ClassNotFoundException e) { Log.e("PPApplication.getTransactionCode", Log.getStackTraceString(e)); } return code; } static String getServiceCommand(String serviceType, int transactionCode, Object... params) { if (params.length > 0) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("service").append(" ").append("call").append(" ").append(serviceType).append(" ").append(transactionCode); for (Object param : params) { if (param != null) { stringBuilder.append(" "); if (param instanceof Integer) { stringBuilder.append("i32").append(" ").append(param); } else if (param instanceof String) { stringBuilder.append("s16").append(" ").append("'").append(((String) param).replace("'", "'\\''")).append("'"); } } } return stringBuilder.toString(); } else return null; } static void commandWait(Command cmd) { int waitTill = 50; int waitTillMultiplier = 2; int waitTillLimit = 3200; // 6350 msec (3200 * 2 - 50) //noinspection SynchronizationOnLocalVariableOrMethodParameter synchronized (cmd) { while (!cmd.isFinished() && waitTill<=waitTillLimit) { try { if (!cmd.isFinished()) { cmd.wait(waitTill); waitTill *= waitTillMultiplier; } } catch (InterruptedException e) { Log.e("PPApplication.commandWait", Log.getStackTraceString(e)); } } } if (!cmd.isFinished()){ Log.e("PPApplication.commandWait", "Could not finish root command in " + (waitTill/waitTillMultiplier)); } } // Debug ----------------------------------------------------------------- /* public static long startMeasuringRunTime() { return System.nanoTime(); } public static void getMeasuredRunTime(long nanoTimeStart, String log) { long nanoTimeEnd = System.nanoTime(); long measuredTime = (nanoTimeEnd - nanoTimeStart) / 1000000; Log.d(log, "MEASURED TIME=" + measuredTime); } */ // others ------------------------------------------------------------------ public static void sleep(long ms) { /*long start = SystemClock.uptimeMillis(); do { SystemClock.sleep(100); } while (SystemClock.uptimeMillis() - start < ms);*/ //SystemClock.sleep(ms); try{ Thread.sleep(ms); }catch(InterruptedException ignored){ } } private static String getROMManufacturer() { String line; BufferedReader input = null; try { java.lang.Process p = Runtime.getRuntime().exec("getprop ro.product.brand"); input = new BufferedReader(new InputStreamReader(p.getInputStream()), 1024); line = input.readLine(); input.close(); } catch (IOException ex) { Log.e("PPApplication.getROMManufacturer", "Unable to read sysprop ro.product.brand", ex); return null; } finally { if (input != null) { try { input.close(); } catch (IOException e) { Log.e("PPApplication.getROMManufacturer", "Exception while closing InputStream", e); } } } return line; } static boolean hasSystemFeature(Context context, String feature) { try { PackageManager packageManager = context.getPackageManager(); return packageManager.hasSystemFeature(feature); } catch (Exception e) { return false; } } static void startHandlerThread() { if (handlerThread == null) { handlerThread = new HandlerThread("PPHandlerThread"); handlerThread.start(); } } static void startHandlerThreadVolumes() { if (handlerThreadVolumes == null) { handlerThreadVolumes = new HandlerThread("handlerThreadVolumes"); handlerThreadVolumes.start(); } } static void startHandlerThreadRadios() { if (handlerThreadRadios == null) { handlerThreadRadios = new HandlerThread("handlerThreadRadios"); handlerThreadRadios.start(); } } static void startHandlerThreadAdaptiveBrightness() { if (handlerThreadAdaptiveBrightness == null) { handlerThreadAdaptiveBrightness = new HandlerThread("handlerThreadAdaptiveBrightness"); handlerThreadAdaptiveBrightness.start(); } } static void startHandlerThreadWallpaper() { if (handlerThreadWallpaper == null) { handlerThreadWallpaper = new HandlerThread("handlerThreadWallpaper"); handlerThreadWallpaper.start(); } } static void startHandlerThreadPowerSaveMode() { if (handlerThreadPowerSaveMode == null) { handlerThreadPowerSaveMode = new HandlerThread("handlerThreadPowerSaveMode"); handlerThreadPowerSaveMode.start(); } } static void startHandlerThreadLockDevice() { if (handlerThreadLockDevice == null) { handlerThreadLockDevice = new HandlerThread("handlerThreadLockDevice"); handlerThreadLockDevice.start(); } } static void startHandlerThreadRunApplication() { if (handlerThreadRunApplication == null) { handlerThreadRunApplication = new HandlerThread("handlerThreadRunApplication"); handlerThreadRunApplication.start(); } } static void startHandlerThreadHeadsUpNotifications() { if (handlerThreadHeadsUpNotifications == null) { handlerThreadHeadsUpNotifications = new HandlerThread("handlerThreadHeadsUpNotifications"); handlerThreadHeadsUpNotifications.start(); } } }
Changed latest extender version code.
phoneProfiles/src/main/java/sk/henrichg/phoneprofiles/PPApplication.java
Changed latest extender version code.
<ide><path>honeProfiles/src/main/java/sk/henrichg/phoneprofiles/PPApplication.java <ide> static String PACKAGE_NAME; <ide> <ide> static final int VERSION_CODE_EXTENDER_1_0_4 = 60; <del> static final int VERSION_CODE_EXTENDER_2_0 = 70; <add> static final int VERSION_CODE_EXTENDER_2_0 = 80; <ide> static final int VERSION_CODE_EXTENDER_LATEST = VERSION_CODE_EXTENDER_2_0; <ide> <ide> public static final String EXPORT_PATH = "/PhoneProfiles";
Java
apache-2.0
6c254989ce5177c80f788424be6deb0e01009d38
0
apache/commons-functor,apache/commons-functor
/* * 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.functor.core; import java.io.Serializable; import org.apache.commons.functor.BinaryPredicate; import org.apache.commons.functor.UnaryPredicate; import org.apache.commons.functor.adapter.IgnoreLeftPredicate; import org.apache.commons.functor.adapter.IgnoreRightPredicate; /** * {@link #test Tests} * <code>false</code> iff its argument * is <code>null</code>. * * @param <T> the argument type. * @version $Revision$ $Date$ * @author Rodney Waldhoff */ public final class IsNotNull<T> implements UnaryPredicate<T>, Serializable { // static attributes // ------------------------------------------------------------------------ /** * Basic IsNotNull instance. */ public static final IsNotNull<Object> INSTANCE = IsNotNull.<Object>instance(); /** * Left-handed BinaryPredicate. */ public static final BinaryPredicate<Object, Object> LEFT = IsNotNull.<Object>left(); /** * Right-handed BinaryPredicate. */ public static final BinaryPredicate<Object, Object> RIGHT = IsNotNull.<Object>right(); /** * serialVersionUID declaration. */ private static final long serialVersionUID = -6856387958371590330L; // constructor // ------------------------------------------------------------------------ /** * Create a new IsNotNull. */ public IsNotNull() { } // predicate interface // ------------------------------------------------------------------------ /** * {@inheritDoc} */ public boolean test(Object obj) { return (null != obj); } /** * {@inheritDoc} */ public boolean equals(Object that) { return that instanceof IsNotNull<?>; } /** * {@inheritDoc} */ public int hashCode() { return "IsNotNull".hashCode(); } /** * {@inheritDoc} */ public String toString() { return "IsNotNull"; } // static methods // ------------------------------------------------------------------------ /** * Get an IsNotNull instance. * @return IsNotNull */ public static <T> IsNotNull<T> instance() { return new IsNotNull<T>(); } /** * Get a BinaryPredicate that matches if the left argument is not null. * @return BinaryPredicate<A, Object> */ public static <A> BinaryPredicate<A, Object> left() { return IgnoreRightPredicate.adapt(new IsNotNull<A>()); } /** * Get a BinaryPredicate that matches if the right argument is null. * @return BinaryPredicate<Object, A> */ public static <A> BinaryPredicate<Object, A> right() { return IgnoreLeftPredicate.adapt(new IsNotNull<A>()); } }
src/main/java/org/apache/commons/functor/core/IsNotNull.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.functor.core; import java.io.Serializable; import org.apache.commons.functor.BinaryPredicate; import org.apache.commons.functor.UnaryPredicate; import org.apache.commons.functor.adapter.IgnoreLeftPredicate; import org.apache.commons.functor.adapter.IgnoreRightPredicate; /** * {@link #test Tests} * <code>false</code> iff its argument * is <code>null</code>. * * @version $Revision$ $Date$ * @author Rodney Waldhoff */ public final class IsNotNull<T> implements UnaryPredicate<T>, Serializable { // static attributes // ------------------------------------------------------------------------ /** * Basic IsNotNull instance. */ public static final IsNotNull<Object> INSTANCE = IsNotNull.<Object>instance(); /** * Left-handed BinaryPredicate. */ public static final BinaryPredicate<Object, Object> LEFT = IsNotNull.<Object>left(); /** * Right-handed BinaryPredicate. */ public static final BinaryPredicate<Object, Object> RIGHT = IsNotNull.<Object>right(); /** * serialVersionUID declaration. */ private static final long serialVersionUID = -6856387958371590330L; // constructor // ------------------------------------------------------------------------ /** * Create a new IsNotNull. */ public IsNotNull() { } // predicate interface // ------------------------------------------------------------------------ /** * {@inheritDoc} */ public boolean test(Object obj) { return (null != obj); } /** * {@inheritDoc} */ public boolean equals(Object that) { return that instanceof IsNotNull<?>; } /** * {@inheritDoc} */ public int hashCode() { return "IsNotNull".hashCode(); } /** * {@inheritDoc} */ public String toString() { return "IsNotNull"; } // static methods // ------------------------------------------------------------------------ /** * Get an IsNotNull instance. * @return IsNotNull */ public static <T> IsNotNull<T> instance() { return new IsNotNull<T>(); } /** * Get a BinaryPredicate that matches if the left argument is not null. * @return BinaryPredicate<A, Object> */ public static <A> BinaryPredicate<A, Object> left() { return IgnoreRightPredicate.adapt(new IsNotNull<A>()); } /** * Get a BinaryPredicate that matches if the right argument is null. * @return BinaryPredicate<Object, A> */ public static <A> BinaryPredicate<Object, A> right() { return IgnoreLeftPredicate.adapt(new IsNotNull<A>()); } }
fixed checkstyle violations: Type Javadoc comment is missing an @param <T> tag git-svn-id: 7e88b6689c675bf212a536fca2a3ed2c50d982c1@1160398 13f79535-47bb-0310-9956-ffa450edef68
src/main/java/org/apache/commons/functor/core/IsNotNull.java
fixed checkstyle violations: Type Javadoc comment is missing an @param <T> tag
<ide><path>rc/main/java/org/apache/commons/functor/core/IsNotNull.java <ide> * <code>false</code> iff its argument <ide> * is <code>null</code>. <ide> * <add> * @param <T> the argument type. <ide> * @version $Revision$ $Date$ <ide> * @author Rodney Waldhoff <ide> */
Java
mit
16de4b2ad3011f06495adfd70b31865c2c47543e
0
navinpai/OSMT2013
package org.iiitb.os.os_proj.shell; import org.iiitb.os.os_proj.User; import org.iiitb.os.os_proj.commands.ICommand; import org.iiitb.os.os_proj.controller.Controller; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Shell extends JFrame { public static final int WIDTH = 500; public static final int HEIGHT = 500; public static final int ROWS = 26; public static final int COLUMNS = 43; public static final int LINE_LENGTH = 407; public static String userString = ""; private static String SHELLTEXT = "\t Welcome to KanchuFS Shell \n\nEnter Username:"; private static String SHELLTEXTINCORRECTLOGIN = "\t Welcome to KanchuFS Shell \n\nIncorrect Login...Try again \nEnter Username:"; private boolean isLoginUserName = true; private boolean isLoginPassword = false; private boolean firstcommand = false; private String sudopassword=""; private boolean isRoot=false; private boolean sudoProcedureOngoing=false; private String receivedString = null; private String username; private String password; private JTextArea shellArea; private JTextArea command; private Border border; private String sudocommand; private Controller controller; public Shell() { controller = new Controller("", new User()); JPanel shellPanel = new JPanel(); shellPanel.setBackground(new Color(0, 0, 0)); border = BorderFactory.createLineBorder(Color.BLACK); shellArea = new JTextArea(ROWS, COLUMNS); shellArea.setText(SHELLTEXT); shellArea.setVisible(true); shellArea.setLineWrap(true); shellArea.setWrapStyleWord(true); shellArea.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(5, 10, 0, 10))); shellArea.setEditable(false); shellArea.setBackground(new Color(0, 0, 0)); shellArea.setForeground(new Color(255, 255, 255)); command = new JTextArea(COLUMNS - ROWS, COLUMNS); command.setForeground(new Color(255, 255, 255)); command.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(0, 10, 5, 10))); command.setBackground(new Color(0, 0, 0)); command.setCaretColor(new Color(255, 255, 255)); command.requestFocus(); command.setLineWrap(true); command.setWrapStyleWord(true); shellPanel.setLayout(new BorderLayout()); shellPanel.add(shellArea, BorderLayout.NORTH); shellPanel.add(command, BorderLayout.AFTER_LINE_ENDS); shellPanel.setSize(WIDTH, HEIGHT); Font font = new Font("Arial", Font.PLAIN, 12); Canvas c = new Canvas(); FontMetrics fm = c.getFontMetrics(font); int lines = fm.stringWidth(shellArea.getText()) / LINE_LENGTH; shellArea.setRows(lines); //revalidate(); this.addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e) { command.requestFocusInWindow(); } }); command.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (isLoginPassword) { command.setForeground(new Color(0, 0, 0)); command.setCaretPosition(0); } if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { if (command.getText().length() > userString.length()) { callRobotBackspace(); } else { e.consume(); } } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { System.out.println(command.getText()); if(command.getText().length()>userString.length()+4 && command.getText().substring(userString.length(),userString.length()+4).equals("sudo")){ if(!isRoot){ sudoProcedureOngoing=true; sudocommand=command.getText().substring(userString.length()+4); updateShell("\nEnter root password:"); command.setText(""); command.setCaretColor(new Color(0,0,0)); command.setForeground(new Color(0,0,0)); } else{ receivedString = controller.call(sudocommand); updateShell(receivedString); } } else if(sudoProcedureOngoing){ sudopassword = command.getText(); if(sudopassword.substring(1, command.getText().length()).equals(Controller.CURRENT_USER.getPasswordHash())){ command.setCaretColor(new Color(255,255,255)); command.setForeground(new Color(255,255,255)); command.setText(""); sudoProcedureOngoing=false; isRoot=true; receivedString = controller.call(sudocommand); updateShell(receivedString); } else{ command.setText(""); shellArea.append("\nIncorrect Password : Try Again\n"); } } else if (command.getText().substring(userString.length()).equals("logout")) { logout(); } else if (isLoginUserName) { username = command.getText(); command.setText(""); shellArea.append("\n" + username); shellArea.append("\nEnter Password:"); command.setCaretColor(new Color(0, 0, 0)); isLoginUserName = false; isLoginPassword = true; } else if (isLoginPassword) { password = command.getText(); command.setText(""); command.setCaretColor(new Color(255, 255, 255)); isLoginPassword = false; isLoginUserName = false; password=new StringBuffer(password).reverse().deleteCharAt(0).toString(); login(username, password); command.setForeground(new Color(255, 255, 255)); } else { if (firstcommand) { shellArea.setVisible(true); firstcommand = false; } receivedString = controller.call(command.getText().substring(userString.length())); updateShell(receivedString); } if(!sudoProcedureOngoing||!isLoginUserName) command.setCaretPosition(userString.length()); } } }); JScrollPane scrollPane = new JScrollPane(shellPanel); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum()); this.add(scrollPane); } private void updateShell(String receivedString) { shellArea.append("\n" + command.getText() + receivedString); command.setText(userString); callRobotBackspace(); } private void callRobotBackspace() { Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } robot.keyPress(KeyEvent.VK_BACK_SPACE); robot.keyRelease(KeyEvent.VK_BACK_SPACE); } public void login(String username, String password) { ArrayList<User> userDetails; Map<String, String> constraints = new HashMap<String, String>(); constraints.put("username", username); constraints.put("passwordhash", password); userDetails = ICommand.mongoConnect.getUsers(constraints); if (userDetails.size() != 0) { controller = new Controller(userDetails.get(0).getUsername(), userDetails.get(0)); userString=userDetails.get(0).getUsername()+" $:"; Controller.CURRENT_PATH=userDetails.get(0).getHome(); shellArea.setText(""); firstcommand = true; command.setText(""); showUserString(); callRobotBackspace(); } else{ shellArea.setText(SHELLTEXTINCORRECTLOGIN); callRobotBackspace(); isLoginUserName = true; isLoginPassword = false; } } private void showUserString() { shellArea.append("Logged in successfully"); command.append(userString); callRobotBackspace(); } public ArrayList<String> logout() { Controller.CURRENT_PATH = ""; shellArea.setText(SHELLTEXT); command.setText(""); isLoginUserName=true; isLoginPassword=false; userString=""; //Controller.CURRENT_USER = new User(); //check username/pass and login return null; } }
src/main/java/org/iiitb/os/os_proj/shell/Shell.java
package org.iiitb.os.os_proj.shell; import org.iiitb.os.os_proj.User; import org.iiitb.os.os_proj.commands.ICommand; import org.iiitb.os.os_proj.controller.Controller; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class Shell extends JFrame { public static final int WIDTH = 500; public static final int HEIGHT = 500; public static final int ROWS = 26; public static final int COLUMNS = 43; public static final int LINE_LENGTH = 407; public static String userString = ""; private static String SHELLTEXT = "\t Welcome to KanchuFS Shell \n\nEnter Username:"; private static String SHELLTEXTINCORRECTLOGIN = "\t Welcome to KanchuFS Shell \n\nIncorrect Login...Try again \nEnter Username:"; private boolean isLoginUserName = true; private boolean isLoginPassword = false; private boolean firstcommand = false; private String sudopassword=""; private boolean isRoot=false; private boolean sudoProcedureOngoing=false; private String receivedString = null; private String username; private String password; private JTextArea shellArea; private JTextArea command; private Border border; private String sudocommand; private Controller controller; public Shell() { controller = new Controller("", new User()); JPanel shellPanel = new JPanel(); shellPanel.setBackground(new Color(0, 0, 0)); border = BorderFactory.createLineBorder(Color.BLACK); shellArea = new JTextArea(ROWS, COLUMNS); shellArea.setText(SHELLTEXT); shellArea.setVisible(true); shellArea.setLineWrap(true); shellArea.setWrapStyleWord(true); shellArea.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(5, 10, 0, 10))); shellArea.setEditable(false); shellArea.setBackground(new Color(0, 0, 0)); shellArea.setForeground(new Color(255, 255, 255)); command = new JTextArea(COLUMNS - ROWS, COLUMNS); command.setForeground(new Color(255, 255, 255)); command.setBorder(BorderFactory.createCompoundBorder(border, BorderFactory.createEmptyBorder(0, 10, 5, 10))); command.setBackground(new Color(0, 0, 0)); command.setCaretColor(new Color(255, 255, 255)); command.requestFocus(); command.setLineWrap(true); command.setWrapStyleWord(true); shellPanel.setLayout(new BorderLayout()); shellPanel.add(shellArea, BorderLayout.NORTH); shellPanel.add(command, BorderLayout.AFTER_LINE_ENDS); shellPanel.setSize(WIDTH, HEIGHT); Font font = new Font("Arial", Font.PLAIN, 12); Canvas c = new Canvas(); FontMetrics fm = c.getFontMetrics(font); int lines = fm.stringWidth(shellArea.getText()) / LINE_LENGTH; shellArea.setRows(lines); //revalidate(); this.addWindowFocusListener(new WindowAdapter() { @Override public void windowGainedFocus(WindowEvent e) { command.requestFocusInWindow(); } }); command.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (isLoginPassword) { command.setForeground(new Color(0, 0, 0)); command.setCaretPosition(0); } if (e.getKeyCode() == KeyEvent.VK_BACK_SPACE) { if (command.getText().length() > userString.length()) { callRobotBackspace(); } else { e.consume(); } } else if (e.getKeyCode() == KeyEvent.VK_ENTER) { System.out.println(command.getText()); if(command.getText().length()>userString.length()+4 && command.getText().substring(userString.length(),userString.length()+4).equals("sudo")){ if(!isRoot){ sudoProcedureOngoing=true; sudocommand=command.getText().substring(userString.length()+4); updateShell("\nEnter root password:"); command.setText(""); command.setCaretColor(new Color(0,0,0)); command.setForeground(new Color(0,0,0)); } else{ receivedString = controller.call(sudocommand); updateShell(receivedString); } } else if(sudoProcedureOngoing){ sudopassword = command.getText(); if(sudopassword.substring(1, command.getText().length()).equals(Controller.CURRENT_USER.getPasswordHash())){ command.setCaretColor(new Color(255,255,255)); command.setForeground(new Color(255,255,255)); command.setText(""); sudoProcedureOngoing=false; receivedString = controller.call(sudocommand); updateShell(receivedString); } else{ command.setText(""); shellArea.append("\nIncorrect Password : Try Again\n"); } } else if (command.getText().equals("logout")) { logout(); } else if (isLoginUserName) { username = command.getText(); command.setText(""); shellArea.append("\n" + username); shellArea.append("\nEnter Password:"); command.setCaretColor(new Color(0, 0, 0)); isLoginUserName = false; isLoginPassword = true; } else if (isLoginPassword) { password = command.getText(); command.setText(""); command.setCaretColor(new Color(255, 255, 255)); isLoginPassword = false; isLoginUserName = false; password=new StringBuffer(password).reverse().deleteCharAt(0).toString(); login(username, password); command.setForeground(new Color(255, 255, 255)); } else { if (firstcommand) { shellArea.setVisible(true); firstcommand = false; } receivedString = controller.call(command.getText().substring(userString.length())); updateShell(receivedString); } if(!sudoProcedureOngoing) command.setCaretPosition(userString.length()); } } }); JScrollPane scrollPane = new JScrollPane(shellPanel); scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); JScrollBar vertical = scrollPane.getVerticalScrollBar(); vertical.setValue(vertical.getMaximum()); this.add(scrollPane); } private void updateShell(String receivedString) { shellArea.append("\n" + command.getText() + receivedString); command.setText(userString); callRobotBackspace(); } private void callRobotBackspace() { Robot robot = null; try { robot = new Robot(); } catch (AWTException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } robot.keyPress(KeyEvent.VK_BACK_SPACE); robot.keyRelease(KeyEvent.VK_BACK_SPACE); } public void login(String username, String password) { ArrayList<User> userDetails; Map<String, String> constraints = new HashMap<String, String>(); constraints.put("username", username); constraints.put("passwordhash", password); userDetails = ICommand.mongoConnect.getUsers(constraints); if (userDetails.size() != 0) { controller = new Controller(userDetails.get(0).getUsername(), userDetails.get(0)); userString=userDetails.get(0).getUsername()+" $:"; Controller.CURRENT_PATH=userDetails.get(0).getHome(); shellArea.setText(""); firstcommand = true; command.setText(""); showUserString(); callRobotBackspace(); } else{ shellArea.setText(SHELLTEXTINCORRECTLOGIN); callRobotBackspace(); isLoginUserName = true; isLoginPassword = false; } } private void showUserString() { shellArea.append("Logged in successfully"); command.append(userString); callRobotBackspace(); } public ArrayList<String> logout() { Controller.CURRENT_PATH = ""; //Controller.CURRENT_USER = new User(); //check username/pass and login return null; } }
Fixed logout
src/main/java/org/iiitb/os/os_proj/shell/Shell.java
Fixed logout
<ide><path>rc/main/java/org/iiitb/os/os_proj/shell/Shell.java <ide> command.setForeground(new Color(255,255,255)); <ide> command.setText(""); <ide> sudoProcedureOngoing=false; <add> isRoot=true; <ide> receivedString = controller.call(sudocommand); <ide> updateShell(receivedString); <ide> <ide> shellArea.append("\nIncorrect Password : Try Again\n"); <ide> } <ide> } <del> else if (command.getText().equals("logout")) { <add> else if (command.getText().substring(userString.length()).equals("logout")) { <ide> logout(); <ide> } else if (isLoginUserName) { <ide> username = command.getText(); <ide> receivedString = controller.call(command.getText().substring(userString.length())); <ide> updateShell(receivedString); <ide> } <del> if(!sudoProcedureOngoing) <add> if(!sudoProcedureOngoing||!isLoginUserName) <ide> command.setCaretPosition(userString.length()); <ide> <ide> } <ide> <ide> public ArrayList<String> logout() { <ide> Controller.CURRENT_PATH = ""; <add> shellArea.setText(SHELLTEXT); <add> command.setText(""); <add> isLoginUserName=true; <add> isLoginPassword=false; <add> userString=""; <ide> //Controller.CURRENT_USER = new User(); <ide> //check username/pass and login <ide>
Java
apache-2.0
38d118bcb3fee683326c8fe2d40958fd5f2ee8fd
0
bazaarvoice/emodb,bazaarvoice/emodb
package com.bazaarvoice.emodb.blob.db.astyanax; import com.bazaarvoice.emodb.blob.BlobReadConsistency; import com.bazaarvoice.emodb.blob.api.Names; import com.bazaarvoice.emodb.blob.db.MetadataProvider; import com.bazaarvoice.emodb.blob.db.StorageProvider; import com.bazaarvoice.emodb.blob.db.StorageSummary; import com.bazaarvoice.emodb.common.api.impl.LimitCounter; import com.bazaarvoice.emodb.common.cassandra.CassandraKeyspace; import com.bazaarvoice.emodb.common.cassandra.nio.BufferUtils; import com.bazaarvoice.emodb.common.dropwizard.metrics.ParameterizedTimed; import com.bazaarvoice.emodb.common.json.JsonHelper; import com.bazaarvoice.emodb.table.db.Table; import com.bazaarvoice.emodb.table.db.astyanax.AstyanaxStorage; import com.bazaarvoice.emodb.table.db.astyanax.AstyanaxTable; import com.bazaarvoice.emodb.table.db.astyanax.DataCopyDAO; import com.bazaarvoice.emodb.table.db.astyanax.DataPurgeDAO; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.google.common.base.Throwables; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.Execution; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.NotFoundException; import com.netflix.astyanax.model.ByteBufferRange; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.Composite; import com.netflix.astyanax.model.ConsistencyLevel; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.model.Rows; import com.netflix.astyanax.query.ColumnQuery; import com.netflix.astyanax.serializers.AsciiSerializer; import com.netflix.astyanax.serializers.CompositeSerializer; import com.netflix.astyanax.serializers.IntegerSerializer; import com.netflix.astyanax.util.RangeBuilder; import org.apache.cassandra.dht.ByteOrderedPartitioner; import org.apache.cassandra.dht.Token; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; /** * A single row Cassandra implementation of {@link com.bazaarvoice.emodb.blob.db.StorageProvider}. * <p/> * Storing blobs in a single row means blobs can't be bigger than what a single Cassandra server can handle. This is * unlikely to be a problem as long as it's not used to store large videos. It also means that reads of a single large * blob can't be distributed across all servers in the ring but instead just N servers, where N is the replication * factor. * <p/> * The storage strategy is to chunk up the blob into smallish columns where each chunk can fit easily in memory. To do * this, there it uses 3 classes of columns: * - A single metadata column with a {@link StorageSummary} object encoded as JSON. * - N "presence" columns, one per chunk. These have no data, but are written at the same time as each chunk. A * reader can quickly read the presence columns and verify that, if all presence columns exist, all the chunk columns * must also exist and be available (unless a concurrent writer re-writes the blob before the chunks can be retrieved). * - N chunk columns, sized so that each chunk can be transferred in a single thrift call without consuming too much * memory. * <p/> * The Astyanax com.netflix.astyanax.recipes.storage.CassandraChunkedStorageProvider implementation has a few * deficiencies that this avoids: * - The Astyanax v1.0.1 ChunkedStorage recipe has minor bugs: it ignores its * configured ConsistencyLevel, it doesn't have a way to set some ObjectMetadata attributes. * - The consistency story seems weak. There's no way to test whether all chunks are available * before starting to stream back the results, and as a result the algorithm relies heavily * on retry to wait for replication. If the retry algorithm waits too long (seconds) it * impacts the client, and if too many threads get stuck in retry loops it will DOS the * BlobStore service. * - If two different blobs are stored using the same IDs, we may end up with orphaned chunks * that never get cleaned up. We'd have to write a M/R job that looks for them. * - If a blob is overwritten with new data, there is a period of time when readers could see * mixed results where part of the returned data is from the old blob and part is from the * new blob. * <p/> * On the other hand, the Astyanax recipes com.netflix.astyanax.recipes.storage.ObjectReader and * com.netflix.astyanax.recipes.storage.ObjectWriter are much more aggressive about retries and concurrency, so they * likely have better performance than this does. */ public class AstyanaxStorageProvider implements StorageProvider, MetadataProvider, DataCopyDAO, DataPurgeDAO { private enum ColumnGroup { A, // Metadata encoded as JSON B, // Chunk presence markers Z, // Chunk bytes } private static final int DEFAULT_CHUNK_SIZE = 0x10000; // 64kb private static final ConsistencyLevel CONSISTENCY_STRONG = ConsistencyLevel.CL_LOCAL_QUORUM; private static final int MAX_SCAN_METADATA_BATCH_SIZE = 250; private final ConsistencyLevel _readConsistency; private final Token.TokenFactory _tokenFactory; private final Meter _blobReadMeter; private final Meter _blobMetadataReadMeter; private final Meter _blobWriteMeter; private final Meter _blobMetadataWriteMeter; private final Meter _blobDeleteMeter; private final Meter _blobMetadataDeleteMeter; private final Meter _blobCopyMeter; private final Meter _blobMetadataCopyMeter; private final Timer _scanBatchTimer; private final Meter _scanReadMeter; @Inject public AstyanaxStorageProvider(@BlobReadConsistency ConsistencyLevel readConsistency, MetricRegistry metricRegistry) { _readConsistency = Objects.requireNonNull(readConsistency, "readConsistency"); _tokenFactory = new ByteOrderedPartitioner().getTokenFactory(); _blobReadMeter = metricRegistry.meter(getMetricName("blob-read")); _blobWriteMeter = metricRegistry.meter(getMetricName("blob-write")); _blobDeleteMeter = metricRegistry.meter(getMetricName("blob-delete")); _blobCopyMeter = metricRegistry.meter(getMetricName("blob-copy")); _blobMetadataReadMeter = metricRegistry.meter(getMetricName("blob-metadata-read")); _blobMetadataWriteMeter = metricRegistry.meter(getMetricName("blob-metadata-write")); _blobMetadataDeleteMeter = metricRegistry.meter(getMetricName("blob-metadata-delete")); _blobMetadataCopyMeter = metricRegistry.meter(getMetricName("blob-metadata-copy")); _scanBatchTimer = metricRegistry.timer(getMetricName("scan-batch")); _scanReadMeter = metricRegistry.meter(getMetricName("scan-reads")); } private static String getMetricName(String name) { return MetricRegistry.name("bv.emodb.blob", "AstyanaxStorageProvider", name); } @Override public long getCurrentTimestamp(Table tbl) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); AstyanaxStorage storage = table.getReadStorage(); CassandraKeyspace keyspace = storage.getPlacement().getKeyspace(); return keyspace.getAstyanaxKeyspace().getConfig().getClock().getCurrentTime(); } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void writeChunk(Table tbl, String blobId, int chunkId, ByteBuffer data, long timestamp) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Write two columns: one small one and one big one with the binary data. Readers can query on // the presence of the small one to be confident that the big column has replicated and is available. MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(CONSISTENCY_STRONG) .setTimestamp(timestamp); mutation.withRow(placement.getBlobColumnFamily(), storage.getRowKey(blobId)) .putEmptyColumn(getColumn(ColumnGroup.B, chunkId)) .putColumn(getColumn(ColumnGroup.Z, chunkId), data); execute(mutation); _blobWriteMeter.mark(data.remaining()); } } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public ByteBuffer readChunk(Table tbl, String blobId, int chunkId, long timestamp) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); AstyanaxStorage storage = table.getReadStorage(); BlobPlacement placement = (BlobPlacement) storage.getPlacement(); CassandraKeyspace keyspace = placement.getKeyspace(); ColumnQuery<Composite> query = keyspace.prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKey(storage.getRowKey(blobId)) .getColumn(getColumn(ColumnGroup.Z, chunkId)); OperationResult<Column<Composite>> operationResult; try { operationResult = query.execute(); } catch (NotFoundException e) { return null; } catch (ConnectionException e) { throw Throwables.propagate(e); } Column<Composite> column = operationResult.getResult(); if (column.getTimestamp() != timestamp) { return null; } ByteBuffer data = column.getByteBufferValue(); _blobReadMeter.mark(data.remaining()); return data; } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void deleteObject(Table tbl, String blobId) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Do a column range query on all the B and Z columns. Don't get the A columns with the metadata. Composite start = getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.LESS_THAN_EQUAL); Composite end = getColumnPrefix(ColumnGroup.Z, Composite.ComponentEquality.GREATER_THAN_EQUAL); ColumnList<Composite> columns = execute(placement.getKeyspace() .prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKey(storage.getRowKey(blobId)) .withColumnRange(start, end, false, Integer.MAX_VALUE)); deleteDataColumns(table, blobId, columns, CONSISTENCY_STRONG, null); _blobDeleteMeter.mark(); } } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void writeMetadata(Table tbl, String blobId, StorageSummary summary) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(CONSISTENCY_STRONG) .setTimestamp(summary.getTimestamp()); mutation.withRow(placement.getBlobColumnFamily(), storage.getRowKey(blobId)) .putColumn(getColumn(ColumnGroup.A, 0), JsonHelper.asJson(summary)); execute(mutation); } _blobMetadataWriteMeter.mark(); } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public StorageSummary readMetadata(Table tbl, String blobId) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); Objects.requireNonNull(blobId, "blobId"); AstyanaxStorage storage = table.getReadStorage(); BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Do a column range query on all the A and B columns. Don't get the Z columns with the binary data. Composite start = getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL); Composite end = getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.GREATER_THAN_EQUAL); ColumnList<Composite> columns = execute(placement.getKeyspace() .prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKey(storage.getRowKey(blobId)) .withColumnRange(start, end, false, Integer.MAX_VALUE)); StorageSummary summary = toStorageSummary(columns, true); _blobMetadataReadMeter.mark(); if (summary == null) { return null; } // TODO should be removed for blob s3 migration // Cleanup older versions of the blob, if any (unlikely). deleteDataColumns(table, blobId, columns, ConsistencyLevel.CL_ANY, summary.getTimestamp()); return summary; } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void deleteMetadata(Table tbl, String blobId) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); Objects.requireNonNull(blobId); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(CONSISTENCY_STRONG); mutation.withRow(placement.getBlobColumnFamily(), storage.getRowKey(blobId)) .deleteColumn(getColumn(ColumnGroup.A, 0)); execute(mutation); _blobMetadataDeleteMeter.mark(mutation.getRowCount()); } } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public long countMetadata(Table tbl) { return countRowsInColumn(tbl, ColumnGroup.A); } private static StorageSummary toStorageSummary(ColumnList<Composite> columns, boolean checkChunks) { if (columns.size() == 0) { return null; } // Read the summary column with the attributes, length etc. Column<Composite> summaryColumn = columns.getColumnByIndex(0); if (summaryColumn == null || !matches(summaryColumn.getName(), ColumnGroup.A, 0)) { return null; } StorageSummary summary = JsonHelper.fromJson(summaryColumn.getStringValue(), StorageSummary.class); if (checkChunks) { // Check that all the chunks are available. Some may still be in the process of being written or replicated. if (columns.size() < 1 + summary.getChunkCount()) { return null; } for (int chunkId = 0; chunkId < summary.getChunkCount(); chunkId++) { Column<Composite> presence = columns.getColumnByIndex(chunkId + 1); if (presence == null || !matches(presence.getName(), ColumnGroup.B, chunkId) || presence.getTimestamp() != summary.getTimestamp()) { return null; } } } return summary; } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public Iterator<Map.Entry<String, StorageSummary>> scanMetadata(Table tbl, @Nullable String fromBlobIdExclusive, final LimitCounter limit) { Objects.requireNonNull(tbl, "table"); checkArgument(fromBlobIdExclusive == null || Names.isLegalBlobId(fromBlobIdExclusive), "fromBlobIdExclusive"); checkArgument(limit.remaining() > 0, "Limit must be >0"); final AstyanaxTable table = (AstyanaxTable) tbl; AstyanaxStorage storage = table.getReadStorage(); final BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Do a column range query on all the A and B columns. Don't get the Z columns with the binary data. CompositeSerializer colSerializer = CompositeSerializer.get(); final ByteBufferRange columnRange = new RangeBuilder() .setStart(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) .setEnd(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) .setLimit(1) .build(); // Loop over all the range prefixes (256 of them) and, for each, execute Cassandra queries to page through the // records with that prefix. final Iterator<ByteBufferRange> scanIter = storage.scanIterator(fromBlobIdExclusive); return touch(Iterators.concat(new AbstractIterator<Iterator<Map.Entry<String, StorageSummary>>>() { @Override protected Iterator<Map.Entry<String, StorageSummary>> computeNext() { if (scanIter.hasNext()) { ByteBufferRange keyRange = scanIter.next(); Iterator<Row<ByteBuffer, Composite>> rowIter = scanInternal(placement, keyRange, columnRange, limit); return decodeMetadataRows(rowIter, table); } return endOfData(); } })); } private static Iterator<Map.Entry<String, StorageSummary>> decodeMetadataRows( final Iterator<Row<ByteBuffer, Composite>> rowIter, final AstyanaxTable table) { return new AbstractIterator<Map.Entry<String, StorageSummary>>() { @Override protected Map.Entry<String, StorageSummary> computeNext() { while (rowIter.hasNext()) { Row<ByteBuffer, Composite> row = rowIter.next(); ByteBuffer key = row.getKey(); ColumnList<Composite> columns = row.getColumns(); String blobId = AstyanaxStorage.getContentKey(key); StorageSummary summary = toStorageSummary(columns, false); if (summary == null) { continue; // Partial blob, parts may still be replicating. } // TODO should be removed for blob s3 migration // Cleanup older versions of the blob, if any (unlikely). deleteDataColumns(table, blobId, columns, ConsistencyLevel.CL_ANY, summary.getTimestamp()); return Maps.immutableEntry(blobId, summary); } return endOfData(); } }; } private long countRowsInColumn(Table tbl, ColumnGroup column) { Objects.requireNonNull(tbl, "table"); AstyanaxTable table = (AstyanaxTable) tbl; AstyanaxStorage storage = table.getReadStorage(); BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Limit the # of columns to retrieve since we just want to count rows, but we need one column to ignore range // ghosts. CompositeSerializer colSerializer = CompositeSerializer.get(); ByteBufferRange columnRange = new RangeBuilder() .setStart(getColumnPrefix(column, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) .setEnd(getColumnPrefix(column, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) .setLimit(1) .build(); LimitCounter unlimited = LimitCounter.max(); // Range query all the shards and count the number of rows in each. long count = 0; Iterator<ByteBufferRange> scanIter = storage.scanIterator(null); while (scanIter.hasNext()) { ByteBufferRange keyRange = scanIter.next(); Iterator<Row<ByteBuffer, Composite>> rowIter = scanInternal(placement, keyRange, columnRange, unlimited); while (rowIter.hasNext()) { if (!rowIter.next().getColumns().isEmpty()) { count++; } } } return count; } // DataCopyDAO @Override public void copy(AstyanaxStorage source, AstyanaxStorage dest, Runnable progress) { Objects.requireNonNull(source, "source"); Objects.requireNonNull(dest, "dest"); Iterator<ByteBufferRange> scanIter = source.scanIterator(null); while (scanIter.hasNext()) { ByteBufferRange range = scanIter.next(); // metadata copy will be conditional for s3 migration copyRange(range, source, dest, true, true, progress); } } private void copyRange(ByteBufferRange keyRange, AstyanaxStorage source, AstyanaxStorage dest, boolean copyMetadata, boolean copyData, Runnable progress) { BlobPlacement sourcePlacement = (BlobPlacement) source.getPlacement(); BlobPlacement destPlacement = (BlobPlacement) dest.getPlacement(); ConsistencyLevel consistency = CONSISTENCY_STRONG; // Scan through the row metadata, skipping the chunk columns for now. CompositeSerializer colSerializer = CompositeSerializer.get(); ByteBufferRange metadataColumnRange = new RangeBuilder() .setStart(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) .setEnd(getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) .build(); Iterator<List<Row<ByteBuffer, Composite>>> rowsIter = Iterators.partition( scanInternal(sourcePlacement, keyRange, metadataColumnRange, LimitCounter.max()), MAX_SCAN_METADATA_BATCH_SIZE); while (rowsIter.hasNext()) { List<Row<ByteBuffer, Composite>> rows = rowsIter.next(); MutationBatch summaryMutation = destPlacement.getKeyspace().prepareMutationBatch(consistency); for (Row<ByteBuffer, Composite> row : rows) { // Map the source row key to the destination row key. Its table uuid and shard key will be different. ByteBuffer newRowKey = dest.getRowKey(AstyanaxStorage.getContentKey(row.getRawKey())); for (Column<Composite> column : row.getColumns()) { Composite name = column.getName(); ColumnGroup group = ColumnGroup.valueOf(name.get(0, AsciiSerializer.get())); int chunkId = name.get(1, IntegerSerializer.get()); if (copyMetadata && group == ColumnGroup.A) { // Found a blob summary. Copy the summaries for multiple rows together in a batch. summaryMutation.withRow(destPlacement.getBlobColumnFamily(), newRowKey) .setTimestamp(column.getTimestamp()) .putColumn(name, column.getByteBufferValue(), column.getTtl()); } else if (copyData && group == ColumnGroup.B) { // Found a chunk presence column. Fetch and copy the chunk data, one chunk at a time. // Make sure chunk presence columns and data columns are paired together at all times. ColumnQuery<Composite> query = sourcePlacement.getKeyspace() .prepareQuery(sourcePlacement.getBlobColumnFamily(), consistency) .getKey(row.getRawKey()) .getColumn(getColumn(ColumnGroup.Z, chunkId)); Column<Composite> chunk; try { chunk = query.execute().getResult(); } catch (NotFoundException e) { continue; // Unusual, but possible if racing a delete. } catch (ConnectionException e) { throw Throwables.propagate(e); } // Write two columns: one small one and one big one with the binary data. Readers can query on // the presence of the small one to be confident that the big column has replicated and is available. MutationBatch chunkMutation = destPlacement.getKeyspace().prepareMutationBatch(consistency); chunkMutation.withRow(destPlacement.getBlobColumnFamily(), newRowKey) .setTimestamp(chunk.getTimestamp()) .putEmptyColumn(getColumn(ColumnGroup.B, chunkId), chunk.getTtl()) .putColumn(getColumn(ColumnGroup.Z, chunkId), chunk.getByteBufferValue(), chunk.getTtl()); progress.run(); execute(chunkMutation); } } } if (!summaryMutation.isEmpty()) { progress.run(); execute(summaryMutation); _blobMetadataCopyMeter.mark(summaryMutation.getRowCount()); } _blobCopyMeter.mark(rows.size()); } } // DataPurgeDAO @Override public void purge(AstyanaxStorage storage, Runnable progress) { // metadata purge will be conditional for s3 migration purge(storage, true, true, progress); } private void purge(AstyanaxStorage storage, boolean deleteMetadata, boolean deleteData, Runnable progress) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); CassandraKeyspace keyspace = placement.getKeyspace(); ColumnFamily<ByteBuffer, Composite> cf = placement.getBlobColumnFamily(); // Limit the query to a single column since we mainly just want the row keys (but not zero columns because // then we couldn't distinguish a live row from a row that has been deleted already). ByteBufferRange columnRange = new RangeBuilder().setLimit(1).build(); MutationBatch mutation = keyspace.prepareMutationBatch(CONSISTENCY_STRONG); LimitCounter unlimited = LimitCounter.max(); // Range query all the shards and delete all the rows we find. Iterator<ByteBufferRange> scanIter = storage.scanIterator(null); while (scanIter.hasNext()) { ByteBufferRange keyRange = scanIter.next(); Iterator<Row<ByteBuffer, Composite>> rowIter = scanInternal(placement, keyRange, columnRange, unlimited); while (rowIter.hasNext()) { Row<ByteBuffer, Composite> row = rowIter.next(); if (row.getColumns().isEmpty()) { continue; // don't bother deleting range ghosts } if (deleteMetadata && deleteData) { mutation.withRow(cf, row.getKey()).delete(); } else { if (deleteMetadata) { mutation.withRow(cf, row.getKey()) .deleteColumn(getColumn(ColumnGroup.A, 0)); } if (deleteData) { mutation.withRow(cf, row.getKey()) .deleteColumn(getColumn(ColumnGroup.B, 1)) .deleteColumn(getColumn(ColumnGroup.Z, 2)); } } if (mutation.getRowCount() >= 100) { progress.run(); execute(mutation); mutation.discardMutations(); } } } if (!mutation.isEmpty()) { progress.run(); execute(mutation); } } /** * Queries for rows within the specified range, exclusive on start and inclusive on end. */ private Iterator<Row<ByteBuffer, Composite>> scanInternal(final BlobPlacement placement, final ByteBufferRange keyRange, final ByteBufferRange columnRange, final LimitCounter limit) { return Iterators.concat(new AbstractIterator<Iterator<Row<ByteBuffer, Composite>>>() { private ByteBuffer _rangeStart = keyRange.getStart(); private final ByteBuffer _rangeEnd = keyRange.getEnd(); private int _minimumLimit = 1; private boolean _done; @Override protected Iterator<Row<ByteBuffer, Composite>> computeNext() { // Note: if Cassandra is asked to perform a token range query where start >= end it will wrap // around which is absolutely *not* what we want since it could return data for another table. if (_done || BufferUtils.compareUnsigned(_rangeStart, _rangeEnd) >= 0) { return endOfData(); } Timer.Context timer = _scanBatchTimer.time(); try { int batchSize = (int) Math.min(Math.max(limit.remaining(), _minimumLimit), MAX_SCAN_METADATA_BATCH_SIZE); // Increase the minimum limit a bit each time around so if we start encountering lots of range // ghosts we eventually scan through them at a reasonable rate. _minimumLimit = Math.min(_minimumLimit + 3, MAX_SCAN_METADATA_BATCH_SIZE); // Pass token strings to get exclusive start behavior, to support 'fromBlobIdExclusive'. Rows<ByteBuffer, Composite> rows = execute(placement.getKeyspace() .prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKeyRange(null, null, toTokenString(_rangeStart), toTokenString(_rangeEnd), batchSize) .withColumnRange(columnRange)); if (rows.size() >= batchSize) { // Save the last row key so we can use it as the start (exclusive) if we must query to get more data. _rangeStart = rows.getRowByIndex(rows.size() - 1).getKey(); } else { // If we got fewer rows than we asked for, another query won't find more rows. _done = true; } // Track metrics _scanReadMeter.mark(rows.size()); // Return the rows. Filter out range ghosts (deleted rows with no columns) final Iterator<Row<ByteBuffer, Composite>> rowIter = rows.iterator(); return new AbstractIterator<Row<ByteBuffer, Composite>>() { @Override protected Row<ByteBuffer, Composite> computeNext() { while (rowIter.hasNext()) { Row<ByteBuffer, Composite> row = rowIter.next(); if (!row.getColumns().isEmpty()) { return row; } } return endOfData(); } }; } finally { timer.stop(); } } }); } @Override public int getDefaultChunkSize() { return DEFAULT_CHUNK_SIZE; } private static void deleteDataColumns(AstyanaxTable table, String blobId, ColumnList<Composite> columns, ConsistencyLevel consistency, Long timestamp) { for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Any columns with a timestamp older than the one we expect must be from an old version // of the blob. This should be rare, but if it happens clean up and delete the old data. MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(consistency); ColumnListMutation<Composite> row = mutation.withRow( placement.getBlobColumnFamily(), storage.getRowKey(blobId)); boolean found = false; for (Column<Composite> column : columns) { if (null != timestamp && column.getTimestamp() < timestamp) { if (ColumnGroup.B.name().equals(column.getName().get(0, AsciiSerializer.get()))) { int chunkId = column.getName().get(1, IntegerSerializer.get()); row.deleteColumn(getColumn(ColumnGroup.B, chunkId)) .deleteColumn(getColumn(ColumnGroup.Z, chunkId)); found = true; } } } if (found) { execute(mutation); } } } private static Composite getColumn(ColumnGroup group, int index) { Composite column = new Composite(); column.addComponent(group.name(), AsciiSerializer.get()); column.addComponent(index, IntegerSerializer.get()); return column; } private static Composite getColumnPrefix(ColumnGroup group, Composite.ComponentEquality equality) { Composite column = new Composite(); column.addComponent(group.name(), AsciiSerializer.get(), equality); return column; } /** * The Astyanax Composite behavior is broken in that a deserialized Composite is not .equal() to a normally * created Composite because the serializers aren't used correctly. This function works around the problem. */ private static boolean matches(Composite column, ColumnGroup group, int index) { return column.size() == 2 && column.get(0, AsciiSerializer.get()).equals(group.name()) && column.get(1, IntegerSerializer.get()).equals(index); } private String toTokenString(ByteBuffer bytes) { return _tokenFactory.toString(_tokenFactory.fromByteArray(bytes)); } private static <R> R execute(Execution<R> execution) { OperationResult<R> operationResult; try { operationResult = execution.execute(); } catch (ConnectionException e) { throw Throwables.propagate(e); } return operationResult.getResult(); } /** * Force computation of the first item in an iterator so metrics calculations for a method reflect the cost of * the first batch of results. */ private static <T> Iterator<T> touch(Iterator<T> iter) { // Could return a Guava PeekingIterator after "if (iter.hasNext()) iter.peek()", but simply calling hasNext() // is sufficient for the iterator implementations used by this DAO class... iter.hasNext(); return iter; } }
blob/src/main/java/com/bazaarvoice/emodb/blob/db/astyanax/AstyanaxStorageProvider.java
package com.bazaarvoice.emodb.blob.db.astyanax; import com.bazaarvoice.emodb.blob.BlobReadConsistency; import com.bazaarvoice.emodb.blob.api.Names; import com.bazaarvoice.emodb.blob.db.MetadataProvider; import com.bazaarvoice.emodb.blob.db.StorageProvider; import com.bazaarvoice.emodb.blob.db.StorageSummary; import com.bazaarvoice.emodb.common.api.impl.LimitCounter; import com.bazaarvoice.emodb.common.cassandra.CassandraKeyspace; import com.bazaarvoice.emodb.common.cassandra.nio.BufferUtils; import com.bazaarvoice.emodb.common.dropwizard.metrics.ParameterizedTimed; import com.bazaarvoice.emodb.common.json.JsonHelper; import com.bazaarvoice.emodb.table.db.Table; import com.bazaarvoice.emodb.table.db.astyanax.AstyanaxStorage; import com.bazaarvoice.emodb.table.db.astyanax.AstyanaxTable; import com.bazaarvoice.emodb.table.db.astyanax.DataCopyDAO; import com.bazaarvoice.emodb.table.db.astyanax.DataPurgeDAO; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.Timer; import com.google.common.base.Throwables; import com.google.common.collect.AbstractIterator; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.netflix.astyanax.ColumnListMutation; import com.netflix.astyanax.Execution; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.OperationResult; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.netflix.astyanax.connectionpool.exceptions.NotFoundException; import com.netflix.astyanax.model.ByteBufferRange; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.Composite; import com.netflix.astyanax.model.ConsistencyLevel; import com.netflix.astyanax.model.Row; import com.netflix.astyanax.model.Rows; import com.netflix.astyanax.query.ColumnQuery; import com.netflix.astyanax.serializers.AsciiSerializer; import com.netflix.astyanax.serializers.CompositeSerializer; import com.netflix.astyanax.serializers.IntegerSerializer; import com.netflix.astyanax.util.RangeBuilder; import org.apache.cassandra.dht.ByteOrderedPartitioner; import org.apache.cassandra.dht.Token; import javax.annotation.Nullable; import java.nio.ByteBuffer; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import static com.google.common.base.Preconditions.checkArgument; /** * A single row Cassandra implementation of {@link com.bazaarvoice.emodb.blob.db.StorageProvider}. * <p/> * Storing blobs in a single row means blobs can't be bigger than what a single Cassandra server can handle. This is * unlikely to be a problem as long as it's not used to store large videos. It also means that reads of a single large * blob can't be distributed across all servers in the ring but instead just N servers, where N is the replication * factor. * <p/> * The storage strategy is to chunk up the blob into smallish columns where each chunk can fit easily in memory. To do * this, there it uses 3 classes of columns: * - A single metadata column with a {@link StorageSummary} object encoded as JSON. * - N "presence" columns, one per chunk. These have no data, but are written at the same time as each chunk. A * reader can quickly read the presence columns and verify that, if all presence columns exist, all the chunk columns * must also exist and be available (unless a concurrent writer re-writes the blob before the chunks can be retrieved). * - N chunk columns, sized so that each chunk can be transferred in a single thrift call without consuming too much * memory. * <p/> * The Astyanax com.netflix.astyanax.recipes.storage.CassandraChunkedStorageProvider implementation has a few * deficiencies that this avoids: * - The Astyanax v1.0.1 ChunkedStorage recipe has minor bugs: it ignores its * configured ConsistencyLevel, it doesn't have a way to set some ObjectMetadata attributes. * - The consistency story seems weak. There's no way to test whether all chunks are available * before starting to stream back the results, and as a result the algorithm relies heavily * on retry to wait for replication. If the retry algorithm waits too long (seconds) it * impacts the client, and if too many threads get stuck in retry loops it will DOS the * BlobStore service. * - If two different blobs are stored using the same IDs, we may end up with orphaned chunks * that never get cleaned up. We'd have to write a M/R job that looks for them. * - If a blob is overwritten with new data, there is a period of time when readers could see * mixed results where part of the returned data is from the old blob and part is from the * new blob. * <p/> * On the other hand, the Astyanax recipes com.netflix.astyanax.recipes.storage.ObjectReader and * com.netflix.astyanax.recipes.storage.ObjectWriter are much more aggressive about retries and concurrency, so they * likely have better performance than this does. */ public class AstyanaxStorageProvider implements StorageProvider, MetadataProvider, DataCopyDAO, DataPurgeDAO { private enum ColumnGroup { A, // Metadata encoded as JSON B, // Chunk presence markers Z, // Chunk bytes } private static final int DEFAULT_CHUNK_SIZE = 0x10000; // 64kb private static final ConsistencyLevel CONSISTENCY_STRONG = ConsistencyLevel.CL_LOCAL_QUORUM; private static final int MAX_SCAN_METADATA_BATCH_SIZE = 250; private final ConsistencyLevel _readConsistency; private final Token.TokenFactory _tokenFactory; private final Meter _blobReadMeter; private final Meter _blobMetadataReadMeter; private final Meter _blobWriteMeter; private final Meter _blobMetadataWriteMeter; private final Meter _blobDeleteMeter; private final Meter _blobMetadataDeleteMeter; private final Meter _blobCopyMeter; private final Meter _blobMetadataCopyMeter; private final Timer _scanBatchTimer; private final Meter _scanReadMeter; @Inject public AstyanaxStorageProvider(@BlobReadConsistency ConsistencyLevel readConsistency, MetricRegistry metricRegistry) { _readConsistency = Objects.requireNonNull(readConsistency, "readConsistency"); _tokenFactory = new ByteOrderedPartitioner().getTokenFactory(); _blobReadMeter = metricRegistry.meter(getMetricName("blob-read")); _blobWriteMeter = metricRegistry.meter(getMetricName("blob-write")); _blobDeleteMeter = metricRegistry.meter(getMetricName("blob-delete")); _blobCopyMeter = metricRegistry.meter(getMetricName("blob-copy")); _blobMetadataReadMeter = metricRegistry.meter(getMetricName("blob-metadata-read")); _blobMetadataWriteMeter = metricRegistry.meter(getMetricName("blob-metadata-write")); _blobMetadataDeleteMeter = metricRegistry.meter(getMetricName("blob-metadata-delete")); _blobMetadataCopyMeter = metricRegistry.meter(getMetricName("blob-metadata-copy")); _scanBatchTimer = metricRegistry.timer(getMetricName("scan-batch")); _scanReadMeter = metricRegistry.meter(getMetricName("scan-reads")); } private static String getMetricName(String name) { return MetricRegistry.name("bv.emodb.blob", "AstyanaxStorageProvider", name); } @Override public long getCurrentTimestamp(Table tbl) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); AstyanaxStorage storage = table.getReadStorage(); CassandraKeyspace keyspace = storage.getPlacement().getKeyspace(); return keyspace.getAstyanaxKeyspace().getConfig().getClock().getCurrentTime(); } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void writeChunk(Table tbl, String blobId, int chunkId, ByteBuffer data, long timestamp) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Write two columns: one small one and one big one with the binary data. Readers can query on // the presence of the small one to be confident that the big column has replicated and is available. MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(CONSISTENCY_STRONG) .setTimestamp(timestamp); mutation.withRow(placement.getBlobColumnFamily(), storage.getRowKey(blobId)) .putEmptyColumn(getColumn(ColumnGroup.B, chunkId)) .putColumn(getColumn(ColumnGroup.Z, chunkId), data); execute(mutation); _blobWriteMeter.mark(data.remaining()); } } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public ByteBuffer readChunk(Table tbl, String blobId, int chunkId, long timestamp) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); AstyanaxStorage storage = table.getReadStorage(); BlobPlacement placement = (BlobPlacement) storage.getPlacement(); CassandraKeyspace keyspace = placement.getKeyspace(); ColumnQuery<Composite> query = keyspace.prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKey(storage.getRowKey(blobId)) .getColumn(getColumn(ColumnGroup.Z, chunkId)); OperationResult<Column<Composite>> operationResult; try { operationResult = query.execute(); } catch (NotFoundException e) { return null; } catch (ConnectionException e) { throw Throwables.propagate(e); } Column<Composite> column = operationResult.getResult(); if (column.getTimestamp() != timestamp) { return null; } ByteBuffer data = column.getByteBufferValue(); _blobReadMeter.mark(data.remaining()); return data; } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void deleteObject(Table tbl, String blobId) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Do a column range query on all the B and Z columns. Don't get the A columns with the metadata. Composite start = getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.LESS_THAN_EQUAL); Composite end = getColumnPrefix(ColumnGroup.Z, Composite.ComponentEquality.GREATER_THAN_EQUAL); ColumnList<Composite> columns = execute(placement.getKeyspace() .prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKey(storage.getRowKey(blobId)) .withColumnRange(start, end, false, Integer.MAX_VALUE)); deleteDataColumns(table, blobId, columns, CONSISTENCY_STRONG, null); _blobDeleteMeter.mark(); } } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void writeMetadata(Table tbl, String blobId, StorageSummary summary) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(CONSISTENCY_STRONG) .setTimestamp(summary.getTimestamp()); mutation.withRow(placement.getBlobColumnFamily(), storage.getRowKey(blobId)) .putColumn(getColumn(ColumnGroup.A, 0), JsonHelper.asJson(summary)); execute(mutation); } _blobMetadataWriteMeter.mark(); } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public StorageSummary readMetadata(Table tbl, String blobId) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); Objects.requireNonNull(blobId, "blobId"); AstyanaxStorage storage = table.getReadStorage(); BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Do a column range query on all the A and B columns. Don't get the Z columns with the binary data. Composite start = getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL); Composite end = getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.GREATER_THAN_EQUAL); ColumnList<Composite> columns = execute(placement.getKeyspace() .prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKey(storage.getRowKey(blobId)) .withColumnRange(start, end, false, Integer.MAX_VALUE)); StorageSummary summary = toStorageSummary(columns); if (summary == null) { return null; } // TODO should be removed for blob s3 migration // Cleanup older versions of the blob, if any (unlikely). deleteDataColumns(table, blobId, columns, ConsistencyLevel.CL_ANY, summary.getTimestamp()); _blobMetadataReadMeter.mark(); return summary; } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public void deleteMetadata(Table tbl, String blobId) { AstyanaxTable table = (AstyanaxTable) Objects.requireNonNull(tbl, "table"); Objects.requireNonNull(blobId); for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(CONSISTENCY_STRONG); mutation.withRow(placement.getBlobColumnFamily(), storage.getRowKey(blobId)) .deleteColumn(getColumn(ColumnGroup.A, 0)); execute(mutation); _blobMetadataDeleteMeter.mark(mutation.getRowCount()); } } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public long countMetadata(Table tbl) { return countRowsInColumn(tbl, ColumnGroup.A); } private static StorageSummary toStorageSummary(ColumnList<Composite> columns) { if (columns.size() == 0) { return null; } // Read the summary column with the attributes, length etc. Column<Composite> summaryColumn = columns.getColumnByIndex(0); if (summaryColumn == null || !matches(summaryColumn.getName(), ColumnGroup.A, 0)) { return null; } StorageSummary summary = JsonHelper.fromJson(summaryColumn.getStringValue(), StorageSummary.class); // Check that all the chunks are available. Some may still be in the process of being written or replicated. if (columns.size() < 1 + summary.getChunkCount()) { return null; } for (int chunkId = 0; chunkId < summary.getChunkCount(); chunkId++) { Column<Composite> presence = columns.getColumnByIndex(chunkId + 1); if (presence == null || !matches(presence.getName(), ColumnGroup.B, chunkId) || presence.getTimestamp() != summary.getTimestamp()) { return null; } } return summary; } @ParameterizedTimed(type = "AstyanaxStorageProvider") @Override public Iterator<Map.Entry<String, StorageSummary>> scanMetadata(Table tbl, @Nullable String fromBlobIdExclusive, final LimitCounter limit) { Objects.requireNonNull(tbl, "table"); checkArgument(fromBlobIdExclusive == null || Names.isLegalBlobId(fromBlobIdExclusive), "fromBlobIdExclusive"); checkArgument(limit.remaining() > 0, "Limit must be >0"); final AstyanaxTable table = (AstyanaxTable) tbl; AstyanaxStorage storage = table.getReadStorage(); final BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Do a column range query on all the A and B columns. Don't get the Z columns with the binary data. CompositeSerializer colSerializer = CompositeSerializer.get(); final ByteBufferRange columnRange = new RangeBuilder() .setStart(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) .setEnd(getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) .build(); // Loop over all the range prefixes (256 of them) and, for each, execute Cassandra queries to page through the // records with that prefix. final Iterator<ByteBufferRange> scanIter = storage.scanIterator(fromBlobIdExclusive); return touch(Iterators.concat(new AbstractIterator<Iterator<Map.Entry<String, StorageSummary>>>() { @Override protected Iterator<Map.Entry<String, StorageSummary>> computeNext() { if (scanIter.hasNext()) { ByteBufferRange keyRange = scanIter.next(); return decodeMetadataRows(scanInternal(placement, keyRange, columnRange, limit), table); } return endOfData(); } })); } private static Iterator<Map.Entry<String, StorageSummary>> decodeMetadataRows( final Iterator<Row<ByteBuffer, Composite>> rowIter, final AstyanaxTable table) { return new AbstractIterator<Map.Entry<String, StorageSummary>>() { @Override protected Map.Entry<String, StorageSummary> computeNext() { while (rowIter.hasNext()) { Row<ByteBuffer, Composite> row = rowIter.next(); ByteBuffer key = row.getKey(); ColumnList<Composite> columns = row.getColumns(); String blobId = AstyanaxStorage.getContentKey(key); StorageSummary summary = toStorageSummary(columns); if (summary == null) { continue; // Partial blob, parts may still be replicating. } // TODO should be removed for blob s3 migration // Cleanup older versions of the blob, if any (unlikely). deleteDataColumns(table, blobId, columns, ConsistencyLevel.CL_ANY, summary.getTimestamp()); return Maps.immutableEntry(blobId, summary); } return endOfData(); } }; } private long countRowsInColumn(Table tbl, ColumnGroup column) { Objects.requireNonNull(tbl, "table"); AstyanaxTable table = (AstyanaxTable) tbl; AstyanaxStorage storage = table.getReadStorage(); BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Limit the # of columns to retrieve since we just want to count rows, but we need one column to ignore range // ghosts. CompositeSerializer colSerializer = CompositeSerializer.get(); ByteBufferRange columnRange = new RangeBuilder() .setStart(getColumnPrefix(column, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) .setEnd(getColumnPrefix(column, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) .setLimit(1) .build(); LimitCounter unlimited = LimitCounter.max(); // Range query all the shards and count the number of rows in each. long count = 0; Iterator<ByteBufferRange> scanIter = storage.scanIterator(null); while (scanIter.hasNext()) { ByteBufferRange keyRange = scanIter.next(); Iterator<Row<ByteBuffer, Composite>> rowIter = scanInternal(placement, keyRange, columnRange, unlimited); while (rowIter.hasNext()) { if (!rowIter.next().getColumns().isEmpty()) { count++; } } } return count; } // DataCopyDAO @Override public void copy(AstyanaxStorage source, AstyanaxStorage dest, Runnable progress) { Objects.requireNonNull(source, "source"); Objects.requireNonNull(dest, "dest"); Iterator<ByteBufferRange> scanIter = source.scanIterator(null); while (scanIter.hasNext()) { ByteBufferRange range = scanIter.next(); // metadata copy will be conditional for s3 migration copyRange(range, source, dest, true, true, progress); } } private void copyRange(ByteBufferRange keyRange, AstyanaxStorage source, AstyanaxStorage dest, boolean copyMetadata, boolean copyData, Runnable progress) { BlobPlacement sourcePlacement = (BlobPlacement) source.getPlacement(); BlobPlacement destPlacement = (BlobPlacement) dest.getPlacement(); ConsistencyLevel consistency = CONSISTENCY_STRONG; // Scan through the row metadata, skipping the chunk columns for now. CompositeSerializer colSerializer = CompositeSerializer.get(); ByteBufferRange metadataColumnRange = new RangeBuilder() .setStart(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) .setEnd(getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) .build(); Iterator<List<Row<ByteBuffer, Composite>>> rowsIter = Iterators.partition( scanInternal(sourcePlacement, keyRange, metadataColumnRange, LimitCounter.max()), MAX_SCAN_METADATA_BATCH_SIZE); while (rowsIter.hasNext()) { List<Row<ByteBuffer, Composite>> rows = rowsIter.next(); MutationBatch summaryMutation = destPlacement.getKeyspace().prepareMutationBatch(consistency); for (Row<ByteBuffer, Composite> row : rows) { // Map the source row key to the destination row key. Its table uuid and shard key will be different. ByteBuffer newRowKey = dest.getRowKey(AstyanaxStorage.getContentKey(row.getRawKey())); for (Column<Composite> column : row.getColumns()) { Composite name = column.getName(); ColumnGroup group = ColumnGroup.valueOf(name.get(0, AsciiSerializer.get())); int chunkId = name.get(1, IntegerSerializer.get()); if (copyMetadata && group == ColumnGroup.A) { // Found a blob summary. Copy the summaries for multiple rows together in a batch. summaryMutation.withRow(destPlacement.getBlobColumnFamily(), newRowKey) .setTimestamp(column.getTimestamp()) .putColumn(name, column.getByteBufferValue(), column.getTtl()); } else if (copyData && group == ColumnGroup.B) { // Found a chunk presence column. Fetch and copy the chunk data, one chunk at a time. // Make sure chunk presence columns and data columns are paired together at all times. ColumnQuery<Composite> query = sourcePlacement.getKeyspace() .prepareQuery(sourcePlacement.getBlobColumnFamily(), consistency) .getKey(row.getRawKey()) .getColumn(getColumn(ColumnGroup.Z, chunkId)); Column<Composite> chunk; try { chunk = query.execute().getResult(); } catch (NotFoundException e) { continue; // Unusual, but possible if racing a delete. } catch (ConnectionException e) { throw Throwables.propagate(e); } // Write two columns: one small one and one big one with the binary data. Readers can query on // the presence of the small one to be confident that the big column has replicated and is available. MutationBatch chunkMutation = destPlacement.getKeyspace().prepareMutationBatch(consistency); chunkMutation.withRow(destPlacement.getBlobColumnFamily(), newRowKey) .setTimestamp(chunk.getTimestamp()) .putEmptyColumn(getColumn(ColumnGroup.B, chunkId), chunk.getTtl()) .putColumn(getColumn(ColumnGroup.Z, chunkId), chunk.getByteBufferValue(), chunk.getTtl()); progress.run(); execute(chunkMutation); } } } if (!summaryMutation.isEmpty()) { progress.run(); execute(summaryMutation); _blobMetadataCopyMeter.mark(summaryMutation.getRowCount()); } _blobCopyMeter.mark(rows.size()); } } // DataPurgeDAO @Override public void purge(AstyanaxStorage storage, Runnable progress) { // metadata purge will be conditional for s3 migration purge(storage, true, true, progress); } private void purge(AstyanaxStorage storage, boolean deleteMetadata, boolean deleteData, Runnable progress) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); CassandraKeyspace keyspace = placement.getKeyspace(); ColumnFamily<ByteBuffer, Composite> cf = placement.getBlobColumnFamily(); // Limit the query to a single column since we mainly just want the row keys (but not zero columns because // then we couldn't distinguish a live row from a row that has been deleted already). ByteBufferRange columnRange = new RangeBuilder().setLimit(1).build(); MutationBatch mutation = keyspace.prepareMutationBatch(CONSISTENCY_STRONG); LimitCounter unlimited = LimitCounter.max(); // Range query all the shards and delete all the rows we find. Iterator<ByteBufferRange> scanIter = storage.scanIterator(null); while (scanIter.hasNext()) { ByteBufferRange keyRange = scanIter.next(); Iterator<Row<ByteBuffer, Composite>> rowIter = scanInternal(placement, keyRange, columnRange, unlimited); while (rowIter.hasNext()) { Row<ByteBuffer, Composite> row = rowIter.next(); if (row.getColumns().isEmpty()) { continue; // don't bother deleting range ghosts } if (deleteMetadata && deleteData) { mutation.withRow(cf, row.getKey()).delete(); } else { if (deleteMetadata) { mutation.withRow(cf, row.getKey()) .deleteColumn(getColumn(ColumnGroup.A, 0)); } if (deleteData) { mutation.withRow(cf, row.getKey()) .deleteColumn(getColumn(ColumnGroup.B, 1)) .deleteColumn(getColumn(ColumnGroup.Z, 2)); } } if (mutation.getRowCount() >= 100) { progress.run(); execute(mutation); mutation.discardMutations(); } } } if (!mutation.isEmpty()) { progress.run(); execute(mutation); } } /** * Queries for rows within the specified range, exclusive on start and inclusive on end. */ private Iterator<Row<ByteBuffer, Composite>> scanInternal(final BlobPlacement placement, final ByteBufferRange keyRange, final ByteBufferRange columnRange, final LimitCounter limit) { return Iterators.concat(new AbstractIterator<Iterator<Row<ByteBuffer, Composite>>>() { private ByteBuffer _rangeStart = keyRange.getStart(); private final ByteBuffer _rangeEnd = keyRange.getEnd(); private int _minimumLimit = 1; private boolean _done; @Override protected Iterator<Row<ByteBuffer, Composite>> computeNext() { // Note: if Cassandra is asked to perform a token range query where start >= end it will wrap // around which is absolutely *not* what we want since it could return data for another table. if (_done || BufferUtils.compareUnsigned(_rangeStart, _rangeEnd) >= 0) { return endOfData(); } Timer.Context timer = _scanBatchTimer.time(); try { int batchSize = (int) Math.min(Math.max(limit.remaining(), _minimumLimit), MAX_SCAN_METADATA_BATCH_SIZE); // Increase the minimum limit a bit each time around so if we start encountering lots of range // ghosts we eventually scan through them at a reasonable rate. _minimumLimit = Math.min(_minimumLimit + 3, MAX_SCAN_METADATA_BATCH_SIZE); // Pass token strings to get exclusive start behavior, to support 'fromBlobIdExclusive'. Rows<ByteBuffer, Composite> rows = execute(placement.getKeyspace() .prepareQuery(placement.getBlobColumnFamily(), _readConsistency) .getKeyRange(null, null, toTokenString(_rangeStart), toTokenString(_rangeEnd), batchSize) .withColumnRange(columnRange)); if (rows.size() >= batchSize) { // Save the last row key so we can use it as the start (exclusive) if we must query to get more data. _rangeStart = rows.getRowByIndex(rows.size() - 1).getKey(); } else { // If we got fewer rows than we asked for, another query won't find more rows. _done = true; } // Track metrics _scanReadMeter.mark(rows.size()); // Return the rows. Filter out range ghosts (deleted rows with no columns) final Iterator<Row<ByteBuffer, Composite>> rowIter = rows.iterator(); return new AbstractIterator<Row<ByteBuffer, Composite>>() { @Override protected Row<ByteBuffer, Composite> computeNext() { while (rowIter.hasNext()) { Row<ByteBuffer, Composite> row = rowIter.next(); if (!row.getColumns().isEmpty()) { return row; } } return endOfData(); } }; } finally { timer.stop(); } } }); } @Override public int getDefaultChunkSize() { return DEFAULT_CHUNK_SIZE; } private static void deleteDataColumns(AstyanaxTable table, String blobId, ColumnList<Composite> columns, ConsistencyLevel consistency, Long timestamp) { for (AstyanaxStorage storage : table.getWriteStorage()) { BlobPlacement placement = (BlobPlacement) storage.getPlacement(); // Any columns with a timestamp older than the one we expect must be from an old version // of the blob. This should be rare, but if it happens clean up and delete the old data. MutationBatch mutation = placement.getKeyspace().prepareMutationBatch(consistency); ColumnListMutation<Composite> row = mutation.withRow( placement.getBlobColumnFamily(), storage.getRowKey(blobId)); boolean found = false; for (Column<Composite> column : columns) { if (null != timestamp && column.getTimestamp() < timestamp) { if (ColumnGroup.B.name().equals(column.getName().get(0, AsciiSerializer.get()))) { int chunkId = column.getName().get(1, IntegerSerializer.get()); row.deleteColumn(getColumn(ColumnGroup.B, chunkId)) .deleteColumn(getColumn(ColumnGroup.Z, chunkId)); found = true; } } } if (found) { execute(mutation); } } } private static Composite getColumn(ColumnGroup group, int index) { Composite column = new Composite(); column.addComponent(group.name(), AsciiSerializer.get()); column.addComponent(index, IntegerSerializer.get()); return column; } private static Composite getColumnPrefix(ColumnGroup group, Composite.ComponentEquality equality) { Composite column = new Composite(); column.addComponent(group.name(), AsciiSerializer.get(), equality); return column; } /** * The Astyanax Composite behavior is broken in that a deserialized Composite is not .equal() to a normally * created Composite because the serializers aren't used correctly. This function works around the problem. */ private static boolean matches(Composite column, ColumnGroup group, int index) { return column.size() == 2 && column.get(0, AsciiSerializer.get()).equals(group.name()) && column.get(1, IntegerSerializer.get()).equals(index); } private String toTokenString(ByteBuffer bytes) { return _tokenFactory.toString(_tokenFactory.fromByteArray(bytes)); } private static <R> R execute(Execution<R> execution) { OperationResult<R> operationResult; try { operationResult = execution.execute(); } catch (ConnectionException e) { throw Throwables.propagate(e); } return operationResult.getResult(); } /** * Force computation of the first item in an iterator so metrics calculations for a method reflect the cost of * the first batch of results. */ private static <T> Iterator<T> touch(Iterator<T> iter) { // Could return a Guava PeekingIterator after "if (iter.hasNext()) iter.peek()", but simply calling hasNext() // is sufficient for the iterator implementations used by this DAO class... iter.hasNext(); return iter; } }
PD-183114 tune scan blob metadata logic (#443)
blob/src/main/java/com/bazaarvoice/emodb/blob/db/astyanax/AstyanaxStorageProvider.java
PD-183114 tune scan blob metadata logic (#443)
<ide><path>lob/src/main/java/com/bazaarvoice/emodb/blob/db/astyanax/AstyanaxStorageProvider.java <ide> .getKey(storage.getRowKey(blobId)) <ide> .withColumnRange(start, end, false, Integer.MAX_VALUE)); <ide> <del> StorageSummary summary = toStorageSummary(columns); <add> StorageSummary summary = toStorageSummary(columns, true); <add> _blobMetadataReadMeter.mark(); <add> <ide> if (summary == null) { <ide> return null; <ide> } <ide> // Cleanup older versions of the blob, if any (unlikely). <ide> deleteDataColumns(table, blobId, columns, ConsistencyLevel.CL_ANY, summary.getTimestamp()); <ide> <del> _blobMetadataReadMeter.mark(); <ide> return summary; <ide> } <ide> <ide> return countRowsInColumn(tbl, ColumnGroup.A); <ide> } <ide> <del> private static StorageSummary toStorageSummary(ColumnList<Composite> columns) { <add> private static StorageSummary toStorageSummary(ColumnList<Composite> columns, boolean checkChunks) { <ide> if (columns.size() == 0) { <ide> return null; <ide> } <ide> } <ide> StorageSummary summary = JsonHelper.fromJson(summaryColumn.getStringValue(), StorageSummary.class); <ide> <del> // Check that all the chunks are available. Some may still be in the process of being written or replicated. <del> if (columns.size() < 1 + summary.getChunkCount()) { <del> return null; <del> } <del> for (int chunkId = 0; chunkId < summary.getChunkCount(); chunkId++) { <del> Column<Composite> presence = columns.getColumnByIndex(chunkId + 1); <del> if (presence == null || <del> !matches(presence.getName(), ColumnGroup.B, chunkId) || <del> presence.getTimestamp() != summary.getTimestamp()) { <add> if (checkChunks) { <add> // Check that all the chunks are available. Some may still be in the process of being written or replicated. <add> if (columns.size() < 1 + summary.getChunkCount()) { <ide> return null; <add> } <add> for (int chunkId = 0; chunkId < summary.getChunkCount(); chunkId++) { <add> Column<Composite> presence = columns.getColumnByIndex(chunkId + 1); <add> if (presence == null || <add> !matches(presence.getName(), ColumnGroup.B, chunkId) || <add> presence.getTimestamp() != summary.getTimestamp()) { <add> return null; <add> } <ide> } <ide> } <ide> return summary; <ide> CompositeSerializer colSerializer = CompositeSerializer.get(); <ide> final ByteBufferRange columnRange = new RangeBuilder() <ide> .setStart(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.LESS_THAN_EQUAL), colSerializer) <del> .setEnd(getColumnPrefix(ColumnGroup.B, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) <add> .setEnd(getColumnPrefix(ColumnGroup.A, Composite.ComponentEquality.GREATER_THAN_EQUAL), colSerializer) <add> .setLimit(1) <ide> .build(); <ide> <ide> // Loop over all the range prefixes (256 of them) and, for each, execute Cassandra queries to page through the <ide> protected Iterator<Map.Entry<String, StorageSummary>> computeNext() { <ide> if (scanIter.hasNext()) { <ide> ByteBufferRange keyRange = scanIter.next(); <del> return decodeMetadataRows(scanInternal(placement, keyRange, columnRange, limit), table); <add> Iterator<Row<ByteBuffer, Composite>> rowIter = scanInternal(placement, keyRange, columnRange, limit); <add> return decodeMetadataRows(rowIter, table); <ide> } <ide> return endOfData(); <ide> } <ide> <ide> String blobId = AstyanaxStorage.getContentKey(key); <ide> <del> StorageSummary summary = toStorageSummary(columns); <add> StorageSummary summary = toStorageSummary(columns, false); <ide> if (summary == null) { <ide> continue; // Partial blob, parts may still be replicating. <ide> }
Java
mit
1673452d30038e7d94722d8441b9b51d7b473739
0
OpenMods/OpenData
package openeye.logic; import java.lang.Thread.UncaughtExceptionHandler; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import openeye.Log; import openeye.net.GenericSender.FailedToReceive; import openeye.net.GenericSender.FailedToSend; import openeye.net.ReportSender; import openeye.reports.FileSignature; import openeye.reports.ReportCrash; import openeye.reports.ReportPing; import openeye.responses.IResponse; import openeye.storage.IDataSource; import openeye.storage.IWorkingStorage; import openeye.struct.ITypedStruct; import openeye.struct.TypedCollections.ReportsList; import openeye.struct.TypedCollections.ResponseList; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class SenderWorker implements Runnable { private static final String URL = "http://openeye.openmods.info/api/v1/data"; private final Future<ModMetaCollector> collector; private final ModState state; private final CountDownLatch firstMessageReceived = new CountDownLatch(1); private final Set<String> dangerousSignatures = Sets.newHashSet(); public SenderWorker(Future<ModMetaCollector> collector, ModState state) { this.collector = collector; this.state = state; } private static void logException(Throwable throwable, String msg, Object... args) { ThrowableLogger.processThrowable(throwable, "openeye"); Log.warn(throwable, msg, args); } private static void store(Object report, String name) { try { IDataSource<Object> list = Storages.instance().sessionArchive.createNew(name); list.store(report); } catch (Exception e) { Log.warn(e, "Failed to store " + name); } } private static void filterStructs(Collection<? extends ITypedStruct> structs, Set<String> blacklist) { Iterator<? extends ITypedStruct> it = structs.iterator(); while (it.hasNext()) { final ITypedStruct struct = it.next(); final String type = struct.getType(); if (blacklist.contains(type)) { Log.info("Filtered type %s(%s) from list, since it's on blacklist", type, struct); it.remove(); } } } private ReportsList executeResponses(ModMetaCollector collector, ResponseList requests) { Preconditions.checkState(!requests.isEmpty()); final ReportContext context = new ReportContext(collector); for (IResponse request : requests) request.execute(context); dangerousSignatures.addAll(context.dangerousSignatures()); return context.reports(); } private static Collection<ReportCrash> listPendingCrashes() { final IWorkingStorage<ReportCrash> pendingCrashes = Storages.instance().pendingCrashes; Map<CrashId, ReportCrash> crashes = Maps.newHashMap(); for (IDataSource<ReportCrash> crash : pendingCrashes.listAll()) { try { ReportCrash report = crash.retrieve(); if (report != null) { ReportCrash prev = crashes.put(new CrashId(report.timestamp, report.random), report); if (prev != null) Log.warn("Found duplicated crash report %s", crash.getId()); } } catch (Exception e) { // no point of sending those to server Log.warn(e, "Failed to read crash %s, removing", crash.getId()); crash.delete(); } } return crashes.values(); } private static void removePendingCrashes() { final IWorkingStorage<ReportCrash> pendingCrashes = Storages.instance().pendingCrashes; for (IDataSource<ReportCrash> crash : pendingCrashes.listAll()) crash.delete(); } protected ReportsList createInitialReport(ModMetaCollector collector) { final ReportsList result = new ReportsList(); try { createAnalyticsReport(collector, result); result.addAll(listPendingCrashes()); } catch (Exception e) { logException(e, "Failed to create initial report"); } return result; } protected void createAnalyticsReport(ModMetaCollector collector, final ReportsList result) { try { if (Config.scanOnly) { result.add(ReportBuilders.buildKnownFilesReport(collector)); } else { result.add(ReportBuilders.buildAnalyticsReport(collector, state.installedMods)); } if (Config.pingOnInitialReport) result.add(new ReportPing()); } catch (Exception e) { logException(e, "Failed to create analytics report"); } } private void sendReports(ModMetaCollector collector) { ReportsList currentReports = createInitialReport(collector); try { ReportSender sender = new ReportSender(URL); while (!currentReports.isEmpty()) { filterStructs(currentReports, Config.reportsBlacklist); store(currentReports, "request"); ResponseList response = Config.dontSend? null : sender.sendAndReceive(currentReports); if (response == null || response.isEmpty()) break; filterStructs(response, Config.responseBlacklist); store(response, "response"); currentReports.clear(); try { currentReports = executeResponses(collector, response); } catch (Exception e) { logException(e, "Failed to execute responses"); break; } firstMessageReceived.countDown(); // early release - notes send in next packets are ignored } removePendingCrashes(); } catch (FailedToSend e) { Log.warn(e, "Failed to send report to %s", URL); } catch (FailedToReceive e) { Log.warn(e, "Failed to receive response from %s", URL); } catch (Exception e) { Log.warn(e, "Failed to send report to %s", URL); } } @Override public void run() { try { ModMetaCollector collector = this.collector.get(); sendReports(collector); } catch (Throwable t) { logException(t, "Failed to send data to server OpenEye"); } finally { firstMessageReceived.countDown(); // can't do much more, releasing lock } } public void start() { Thread senderThread = new Thread(this); senderThread.setName("OpenEye sender thread"); senderThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logException(e, "Uncaught exception in data collector thread, report will not be send"); firstMessageReceived.countDown(); // oh well, better luck next time } }); senderThread.start(); } public void waitForFirstMsg() { try { if (!firstMessageReceived.await(30, TimeUnit.SECONDS)) Log.warn("OpenEye timeouted while waiting for worker thread, data will be incomplete"); } catch (InterruptedException e) { Log.warn("Thread interrupted while waiting for msg"); } } public Collection<FileSignature> listDangerousFiles() { List<FileSignature> result = Lists.newArrayList(); try { ModMetaCollector collector = this.collector.get(); for (String signature : dangerousSignatures) { FileSignature file = collector.getFileForSignature(signature); if (signature != null) result.add(file); } } catch (Throwable t) { Log.warn(t, "Failed to list dangerous files"); } return result; } }
src/openeye/logic/SenderWorker.java
package openeye.logic; import java.lang.Thread.UncaughtExceptionHandler; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import openeye.Log; import openeye.net.GenericSender.FailedToReceive; import openeye.net.GenericSender.FailedToSend; import openeye.net.ReportSender; import openeye.reports.FileSignature; import openeye.reports.ReportCrash; import openeye.reports.ReportPing; import openeye.responses.IResponse; import openeye.storage.IDataSource; import openeye.storage.IWorkingStorage; import openeye.struct.ITypedStruct; import openeye.struct.TypedCollections.ReportsList; import openeye.struct.TypedCollections.ResponseList; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class SenderWorker implements Runnable { private static final String URL = "http://openeye.openmods.info/api/v1/data"; private final Future<ModMetaCollector> collector; private final ModState state; private final CountDownLatch firstMessageReceived = new CountDownLatch(1); private final Set<String> dangerousSignatures = Sets.newHashSet(); public SenderWorker(Future<ModMetaCollector> collector, ModState state) { this.collector = collector; this.state = state; } private static void logException(Throwable throwable, String msg, Object... args) { ThrowableLogger.processThrowable(throwable, "openeye"); Log.warn(throwable, msg, args); } private static void store(Object report, String name) { try { IDataSource<Object> list = Storages.instance().sessionArchive.createNew(name); list.store(report); } catch (Exception e) { Log.warn(e, "Failed to store " + name); } } private static void filterStructs(Collection<? extends ITypedStruct> structs, Set<String> blacklist) { Iterator<? extends ITypedStruct> it = structs.iterator(); while (it.hasNext()) { final ITypedStruct struct = it.next(); final String type = struct.getType(); if (blacklist.contains(type)) { Log.info("Filtered type %s(%s) from list, since it's on blacklist", type, struct); it.remove(); } } } private ReportsList executeResponses(ModMetaCollector collector, ResponseList requests) { Preconditions.checkState(!requests.isEmpty()); final ReportContext context = new ReportContext(collector); for (IResponse request : requests) request.execute(context); dangerousSignatures.addAll(context.dangerousSignatures()); return context.reports(); } private static Collection<ReportCrash> listPendingCrashes() { final IWorkingStorage<ReportCrash> pendingCrashes = Storages.instance().pendingCrashes; Map<CrashId, ReportCrash> crashes = Maps.newHashMap(); for (IDataSource<ReportCrash> crash : pendingCrashes.listAll()) { try { ReportCrash report = crash.retrieve(); if (report != null) { ReportCrash prev = crashes.put(new CrashId(report.timestamp, report.random), report); if (prev != null) Log.warn("Found duplicated crash report %s", crash.getId()); } } catch (Exception e) { // no point of sending those to server Log.warn(e, "Failed to read crash %s", crash.getId()); } } return crashes.values(); } private static void removePendingCrashes() { final IWorkingStorage<ReportCrash> pendingCrashes = Storages.instance().pendingCrashes; for (IDataSource<ReportCrash> crash : pendingCrashes.listAll()) crash.delete(); } protected ReportsList createInitialReport(ModMetaCollector collector) { final ReportsList result = new ReportsList(); try { createAnalyticsReport(collector, result); result.addAll(listPendingCrashes()); } catch (Exception e) { logException(e, "Failed to create initial report"); } return result; } protected void createAnalyticsReport(ModMetaCollector collector, final ReportsList result) { try { if (Config.scanOnly) { result.add(ReportBuilders.buildKnownFilesReport(collector)); } else { result.add(ReportBuilders.buildAnalyticsReport(collector, state.installedMods)); } if (Config.pingOnInitialReport) result.add(new ReportPing()); } catch (Exception e) { logException(e, "Failed to create analytics report"); } } private void sendReports(ModMetaCollector collector) { ReportsList currentReports = createInitialReport(collector); try { ReportSender sender = new ReportSender(URL); while (!currentReports.isEmpty()) { filterStructs(currentReports, Config.reportsBlacklist); store(currentReports, "request"); ResponseList response = Config.dontSend? null : sender.sendAndReceive(currentReports); if (response == null || response.isEmpty()) break; filterStructs(response, Config.responseBlacklist); store(response, "response"); currentReports.clear(); try { currentReports = executeResponses(collector, response); } catch (Exception e) { logException(e, "Failed to execute responses"); break; } firstMessageReceived.countDown(); // early release - notes send in next packets are ignored } removePendingCrashes(); } catch (FailedToSend e) { Log.warn(e, "Failed to send report to %s", URL); } catch (FailedToReceive e) { Log.warn(e, "Failed to receive response from %s", URL); } catch (Exception e) { Log.warn(e, "Failed to send report to %s", URL); } } @Override public void run() { try { ModMetaCollector collector = this.collector.get(); sendReports(collector); } catch (Throwable t) { logException(t, "Failed to send data to server OpenEye"); } finally { firstMessageReceived.countDown(); // can't do much more, releasing lock } } public void start() { Thread senderThread = new Thread(this); senderThread.setName("OpenEye sender thread"); senderThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { logException(e, "Uncaught exception in data collector thread, report will not be send"); firstMessageReceived.countDown(); // oh well, better luck next time } }); senderThread.start(); } public void waitForFirstMsg() { try { if (!firstMessageReceived.await(30, TimeUnit.SECONDS)) Log.warn("OpenEye timeouted while waiting for worker thread, data will be incomplete"); } catch (InterruptedException e) { Log.warn("Thread interrupted while waiting for msg"); } } public Collection<FileSignature> listDangerousFiles() { List<FileSignature> result = Lists.newArrayList(); try { ModMetaCollector collector = this.collector.get(); for (String signature : dangerousSignatures) { FileSignature file = collector.getFileForSignature(signature); if (signature != null) result.add(file); } } catch (Throwable t) { Log.warn(t, "Failed to list dangerous files"); } return result; } }
Remove malformed reports
src/openeye/logic/SenderWorker.java
Remove malformed reports
<ide><path>rc/openeye/logic/SenderWorker.java <ide> } <ide> } catch (Exception e) { <ide> // no point of sending those to server <del> Log.warn(e, "Failed to read crash %s", crash.getId()); <add> Log.warn(e, "Failed to read crash %s, removing", crash.getId()); <add> crash.delete(); <ide> } <ide> } <ide> return crashes.values();
Java
apache-2.0
2ce246afec10003cfafe83111073094366134fb8
0
mcxiaoke/Android-Next,mcxiaoke/Android-Next
package com.mcxiaoke.next.http; import android.os.Bundle; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mcxiaoke.next.http.callback.BitmapCallback; import com.mcxiaoke.next.http.callback.FileCallback; import com.mcxiaoke.next.http.callback.HttpCallback; import com.mcxiaoke.next.http.callback.JsonCallback; import com.mcxiaoke.next.http.callback.ResponseCallback; import com.mcxiaoke.next.http.callback.StringCallback; import com.mcxiaoke.next.http.job.HttpJob; import com.mcxiaoke.next.http.processor.HttpProcessor; import com.mcxiaoke.next.http.transformer.BitmapTransformer; import com.mcxiaoke.next.http.transformer.FileTransformer; import com.mcxiaoke.next.http.transformer.HttpTransformer; import com.mcxiaoke.next.http.transformer.JsonTransformer; import com.mcxiaoke.next.http.transformer.ResponseTransformer; import com.mcxiaoke.next.http.transformer.StringTransformer; import com.mcxiaoke.next.task.SimpleTaskCallback; import com.mcxiaoke.next.task.TaskCallable; import com.mcxiaoke.next.task.TaskCallback; import com.mcxiaoke.next.task.TaskQueue; import com.mcxiaoke.next.utils.LogUtils; import com.squareup.okhttp.OkHttpClient; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** * User: mcxiaoke * Date: 15/8/21 * Time: 10:42 */ public class HttpQueue { static class SingletonHolder { public static final HttpQueue INSTANCE = new HttpQueue(); } public static HttpQueue getDefault() { return SingletonHolder.INSTANCE; } private static final String TAG = HttpQueue.class.getSimpleName(); private static final int NUM_THREADS_DEFAULT = 0; private final Map<Integer, String> mJobs; private final List<String> mRequests; private TaskQueue mQueue; private NextClient mClient; private Gson mGson; private boolean mDebug; public HttpQueue() { this(createQueue(), new NextClient()); } public HttpQueue(final OkHttpClient client) { this(createQueue(), new NextClient(client)); } public HttpQueue(final NextClient client) { this(createQueue(), client); } public HttpQueue(final TaskQueue queue) { this(queue, new NextClient()); } public HttpQueue(final TaskQueue queue, final NextClient client) { mJobs = new ConcurrentHashMap<Integer, String>(); mRequests = new CopyOnWriteArrayList<String>(); mGson = new GsonBuilder().setPrettyPrinting().create(); mQueue = queue; mClient = client; } public void setDebug(final boolean debug) { mDebug = debug; mClient.setDebug(debug); } public void setQueue(final TaskQueue queue) { mQueue = queue; } public void setClient(final NextClient client) { mClient = client; } public void setGson(final Gson gson) { mGson = gson; } public NextClient getClient() { return mClient; } public TaskQueue getQueue() { return mQueue; } public Gson getGson() { return mGson; } public void cancelAll(Object caller) { mQueue.cancelAll(caller); } public void cancel(String name) { if (name != null) { mQueue.cancel(name); } } public void cancelAll() { mQueue.cancelAll(); synchronized (mJobs) { mRequests.clear(); mJobs.clear(); } } public List<String> getRequests() { return new ArrayList<>(mRequests); } public <T> String add(final HttpJob<T> job) { return enqueue(job); } public <T> String add(final NextRequest request, final HttpTransformer<T> transformer, final HttpCallback<T> callback, final Object caller, final HttpProcessor<NextRequest> requestProcessor, final HttpProcessor<NextResponse> preProcessor, final HttpProcessor<T> postProcessor) { final HttpJob<T> job = new HttpJob<T>(request, transformer, callback, caller); job.addRequestProcessor(requestProcessor) .addPreProcessor(preProcessor) .addPostProcessor(postProcessor); return enqueue(job); } public <T> String add(final NextRequest request, final HttpTransformer<T> transformer, final HttpCallback<T> callback, final Object caller) { final HttpJob<T> job = new HttpJob<T>(request, transformer, callback, caller); return enqueue(job); } public String add(final NextRequest request, final ResponseCallback callback, final Object caller) { return add(request, new ResponseTransformer(), callback, caller); } public <T> String add(final NextRequest request, final JsonCallback<T> callback, Object caller) { return add(request, new JsonTransformer<T>(mGson, callback.getType()), callback, caller); } public String add(final NextRequest request, final StringCallback callback, final Object caller) { return add(request, new StringTransformer(), callback, caller); } public String add(final NextRequest request, final BitmapCallback callback, final Object caller) { return add(request, new BitmapTransformer(), callback, caller); } public String add(final NextRequest request, final File file, final FileCallback callback, final Object caller) { return add(request, new FileTransformer(file), callback, caller); } private <T> String enqueue(final HttpJob<T> job) { final NextRequest request = job.request; final HttpTransformer<T> transformer = job.transformer; final HttpCallback<T> callback = job.callback; final Object caller = job.caller; final String url = String.valueOf(request.url()); if (mDebug) { logHttpJob(TAG, "[Enqueue] " + url + " from " + caller); } ensureClient(); ensureQueue(); final int hashCode = System.identityHashCode(request); final TaskCallable<T> callable = new TaskCallable<T>() { @Override public T call() throws Exception { // request interceptors // NextRequest aReq = request; final List<HttpProcessor<NextRequest>> requestProcessors = job.getRequestProcessors(); if (requestProcessors != null) { for (HttpProcessor<NextRequest> pr : requestProcessors) { pr.process(request); // pr.process(aReq); // aReq = pr.process(aReq); // if (pr.process(aReq)) { // break; // } } } // response interceptors final NextResponse nextResponse = mClient.execute(request); final List<HttpProcessor<NextResponse>> preProcessors = job.getPreProcessors(); if (preProcessors != null) { for (HttpProcessor<NextResponse> pr : preProcessors) { pr.process(nextResponse); // pr.process(aRes); // aRes = pr.process(aRes); // if (pr.process(aRes)) { // break; // } } } // model interceptors final T response = transformer.transform(nextResponse); final List<HttpProcessor<T>> postProcessors = job.getPostProcessors(); if (postProcessors != null) { for (HttpProcessor<T> pr : postProcessors) { pr.process(response); // pr.process(model); // model = pr.process(model); // if (pr.process(model)) { // break; // } } } return response; } }; final TaskCallback<T> taskCallback = new SimpleTaskCallback<T>() { @Override public void onTaskCancelled(final String name, final Bundle extras) { if (mDebug) { logHttpJob(TAG, "[Cancelled] (" + name + ") " + url); } } @Override public void onTaskFinished(final String name, final Bundle extras) { super.onTaskFinished(name, extras); synchronized (mJobs) { mJobs.remove(hashCode); mRequests.remove(url); } } @Override public void onTaskSuccess(final T t, final Bundle extras) { if (mDebug) { logHttpJob(TAG, "[Success] Type:" + t.getClass() + " " + url); } if (callback != null) { callback.onSuccess(t); } } @Override public void onTaskFailure(final Throwable ex, final Bundle extras) { if (mDebug) { logHttpJob(TAG, "[Failure] Error:" + ex + " " + url); } if (callback != null) { callback.onError(ex); } } }; final String tag = mQueue.add(callable, taskCallback, caller); synchronized (mJobs) { mJobs.put(hashCode, tag); mRequests.add(url); } return tag; } private synchronized void ensureClient() { if (mClient == null) { mClient = new NextClient(); } } private synchronized void ensureQueue() { if (mQueue == null) { mQueue = createQueue(); } } private static TaskQueue createQueue() { return TaskQueue.concurrent(NUM_THREADS_DEFAULT); } private void logHttpJob(final String tag, final String message) { LogUtils.v(tag, "[HttpJob]" + message + " thread:" + Thread.currentThread().getName()); } }
http/src/main/java/com/mcxiaoke/next/http/HttpQueue.java
package com.mcxiaoke.next.http; import android.os.Bundle; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mcxiaoke.next.http.callback.BitmapCallback; import com.mcxiaoke.next.http.callback.FileCallback; import com.mcxiaoke.next.http.callback.HttpCallback; import com.mcxiaoke.next.http.callback.JsonCallback; import com.mcxiaoke.next.http.callback.ResponseCallback; import com.mcxiaoke.next.http.callback.StringCallback; import com.mcxiaoke.next.http.job.HttpJob; import com.mcxiaoke.next.http.processor.HttpProcessor; import com.mcxiaoke.next.http.transformer.BitmapTransformer; import com.mcxiaoke.next.http.transformer.FileTransformer; import com.mcxiaoke.next.http.transformer.HttpTransformer; import com.mcxiaoke.next.http.transformer.JsonTransformer; import com.mcxiaoke.next.http.transformer.ResponseTransformer; import com.mcxiaoke.next.http.transformer.StringTransformer; import com.mcxiaoke.next.task.SimpleTaskCallback; import com.mcxiaoke.next.task.TaskCallable; import com.mcxiaoke.next.task.TaskCallback; import com.mcxiaoke.next.task.TaskQueue; import com.mcxiaoke.next.utils.LogUtils; import com.squareup.okhttp.OkHttpClient; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; /** * User: mcxiaoke * Date: 15/8/21 * Time: 10:42 */ public class HttpQueue { static class SingletonHolder { public static final HttpQueue INSTANCE = new HttpQueue(); } public static HttpQueue getDefault() { return SingletonHolder.INSTANCE; } private static final String TAG = HttpQueue.class.getSimpleName(); private static final int NUM_THREADS_DEFAULT = 0; private final Map<Integer, String> mJobs; private final List<String> mRequests; private TaskQueue mQueue; private NextClient mClient; private Gson mGson; private boolean mDebug; public HttpQueue() { this(createQueue(), new NextClient()); } public HttpQueue(final OkHttpClient client) { this(createQueue(), new NextClient(client)); } public HttpQueue(final NextClient client) { this(createQueue(), client); } public HttpQueue(final TaskQueue queue) { this(queue, new NextClient()); } public HttpQueue(final TaskQueue queue, final NextClient client) { mJobs = new ConcurrentHashMap<Integer, String>(); mRequests = new CopyOnWriteArrayList<String>(); mGson = new GsonBuilder().setPrettyPrinting().create(); mQueue = queue; mClient = client; } public void setDebug(final boolean debug) { mDebug = debug; mClient.setDebug(debug); } public void setQueue(final TaskQueue queue) { mQueue = queue; } public void setClient(final NextClient client) { mClient = client; } public void setGson(final Gson gson) { mGson = gson; } public NextClient getClient() { return mClient; } public TaskQueue getQueue() { return mQueue; } public Gson getGson() { return mGson; } public void cancelAll(Object caller) { mQueue.cancelAll(caller); } public void cancel(String name) { if (name != null) { mQueue.cancel(name); } } public void cancelAll() { mQueue.cancelAll(); synchronized (mJobs) { mRequests.clear(); mJobs.clear(); } } public List<String> getRequests() { return new ArrayList<>(mRequests); } public <T> String add(final HttpJob<T> job) { return enqueue(job); } public <T> String add(final NextRequest request, final HttpTransformer<T> transformer, final HttpCallback<T> callback, Object caller, final HttpProcessor<NextRequest> requestProcessor, final HttpProcessor<NextResponse> preProcessor, final HttpProcessor<T> postProcessor) { final HttpJob<T> job = new HttpJob<T>(request, transformer, callback, caller); job.addRequestProcessor(requestProcessor) .addPreProcessor(preProcessor) .addPostProcessor(postProcessor); return enqueue(job); } public <T> String add(final NextRequest request, final HttpTransformer<T> transformer, final HttpCallback<T> callback, Object caller) { final HttpJob<T> job = new HttpJob<T>(request, transformer, callback, caller); return enqueue(job); } public String add(final NextRequest request, final ResponseCallback callback, Object caller) { return add(request, new ResponseTransformer(), callback, caller); } public <T> String add(final NextRequest request, final JsonCallback<T> callback, Object caller) { return add(request, new JsonTransformer<T>(mGson, callback.getType()), callback, caller); } public String add(final NextRequest request, final StringCallback callback, Object caller) { return add(request, new StringTransformer(), callback, caller); } public String add(final NextRequest request, final BitmapCallback callback, Object caller) { return add(request, new BitmapTransformer(), callback, caller); } public String add(final NextRequest request, final File file, final FileCallback callback, Object caller) { return add(request, new FileTransformer(file), callback, caller); } private <T> String enqueue(final HttpJob<T> job) { final NextRequest request = job.request; final HttpTransformer<T> transformer = job.transformer; final HttpCallback<T> callback = job.callback; final Object caller = job.caller; final String url = String.valueOf(request.url()); if (mDebug) { logHttpJob(TAG, "[Enqueue] " + url + " from " + caller); } ensureClient(); ensureQueue(); final int hashCode = System.identityHashCode(request); final TaskCallable<T> callable = new TaskCallable<T>() { @Override public T call() throws Exception { // request interceptors // NextRequest aReq = request; final List<HttpProcessor<NextRequest>> requestProcessors = job.getRequestProcessors(); if (requestProcessors != null) { for (HttpProcessor<NextRequest> pr : requestProcessors) { pr.process(request); // pr.process(aReq); // aReq = pr.process(aReq); // if (pr.process(aReq)) { // break; // } } } // response interceptors final NextResponse nextResponse = mClient.execute(request); final List<HttpProcessor<NextResponse>> preProcessors = job.getPreProcessors(); if (preProcessors != null) { for (HttpProcessor<NextResponse> pr : preProcessors) { pr.process(nextResponse); // pr.process(aRes); // aRes = pr.process(aRes); // if (pr.process(aRes)) { // break; // } } } // model interceptors final T response = transformer.transform(nextResponse); final List<HttpProcessor<T>> postProcessors = job.getPostProcessors(); if (postProcessors != null) { for (HttpProcessor<T> pr : postProcessors) { pr.process(response); // pr.process(model); // model = pr.process(model); // if (pr.process(model)) { // break; // } } } return response; } }; final TaskCallback<T> taskCallback = new SimpleTaskCallback<T>() { @Override public void onTaskCancelled(final String name, final Bundle extras) { if (mDebug) { logHttpJob(TAG, "[Cancelled] (" + name + ") " + url); } } @Override public void onTaskFinished(final String name, final Bundle extras) { super.onTaskFinished(name, extras); synchronized (mJobs) { mJobs.remove(hashCode); mRequests.remove(url); } } @Override public void onTaskSuccess(final T t, final Bundle extras) { if (mDebug) { logHttpJob(TAG, "[Success] Type:" + t.getClass() + " " + url); } if (callback != null) { callback.onSuccess(t); } } @Override public void onTaskFailure(final Throwable ex, final Bundle extras) { if (mDebug) { logHttpJob(TAG, "[Failure] Error:" + ex + " " + url); } if (callback != null) { callback.onError(ex); } } }; final String tag = mQueue.add(callable, taskCallback, caller); synchronized (mJobs) { mJobs.put(hashCode, tag); mRequests.add(url); } return tag; } private synchronized void ensureClient() { if (mClient == null) { mClient = new NextClient(); } } private synchronized void ensureQueue() { if (mQueue == null) { mQueue = createQueue(); } } private static TaskQueue createQueue() { return TaskQueue.concurrent(NUM_THREADS_DEFAULT); } private void logHttpJob(final String tag, final String message) { LogUtils.v(tag, "[HttpJob]" + message + " thread:" + Thread.currentThread().getName()); } }
add missing final
http/src/main/java/com/mcxiaoke/next/http/HttpQueue.java
add missing final
<ide><path>ttp/src/main/java/com/mcxiaoke/next/http/HttpQueue.java <ide> public <T> String add(final NextRequest request, <ide> final HttpTransformer<T> transformer, <ide> final HttpCallback<T> callback, <del> Object caller, <add> final Object caller, <ide> final HttpProcessor<NextRequest> requestProcessor, <ide> final HttpProcessor<NextResponse> preProcessor, <ide> final HttpProcessor<T> postProcessor) { <ide> public <T> String add(final NextRequest request, <ide> final HttpTransformer<T> transformer, <ide> final HttpCallback<T> callback, <del> Object caller) { <add> final Object caller) { <ide> final HttpJob<T> job = new HttpJob<T>(request, transformer, callback, caller); <ide> return enqueue(job); <ide> } <ide> <ide> public String add(final NextRequest request, <ide> final ResponseCallback callback, <del> Object caller) { <add> final Object caller) { <ide> return add(request, new ResponseTransformer(), callback, caller); <ide> } <ide> <ide> <ide> public String add(final NextRequest request, <ide> final StringCallback callback, <del> Object caller) { <add> final Object caller) { <ide> return add(request, new StringTransformer(), callback, caller); <ide> } <ide> <ide> public String add(final NextRequest request, <ide> final BitmapCallback callback, <del> Object caller) { <add> final Object caller) { <ide> return add(request, new BitmapTransformer(), callback, caller); <ide> } <ide> <ide> public String add(final NextRequest request, final File file, <ide> final FileCallback callback, <del> Object caller) { <add> final Object caller) { <ide> return add(request, new FileTransformer(file), callback, caller); <ide> } <ide>
Java
mit
f709c1956f578bb6ee443066acfd4096f544bd6f
0
mkrause/gx,mkrause/gx
package gx.realtime; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Model implements EventTarget { private Document document; private CollaborativeMap<CollaborativeObject> root; private boolean initialized; private boolean canRedo; private boolean canUndo; private boolean readOnly; protected Model(Document document){ this.document = document; this.root = new CollaborativeMap<CollaborativeObject>(this); initialized = true; canRedo = false; canUndo = false; readOnly = false; addDocumentEventHandlers(); } private void addDocumentEventHandlers() { document.addEventListener(EventType.OBJECT_CHANGED, (ObjectChangedEvent e) -> { System.out.println("OBJECT_CHANGED"); }); } public void beginCompoundOperation(String opt_name){ //TODO } public void beginCompoundOperation(){ //TODO } public Object create(/*TODO*/){ //TODO return null; } public <E> CollaborativeList<E> createList(){ return new CollaborativeList<E>(this); } public <E> CollaborativeList<E> createList(E[] opt_initialValue){ CollaborativeList<E> result = createList(); result.pushAll(opt_initialValue); return result; } public <E> CollaborativeMap<E> createMap(){ return new CollaborativeMap<E>(this); } public <E> CollaborativeMap<E> createMap(Map<String, E> opt_initialValue){ CollaborativeMap<E> result = createMap(); Set<Entry<String, E>> entries = opt_initialValue.entrySet(); for(Entry<String, E> entry : entries){ result.set(entry.getKey(), entry.getValue()); } return result; } public CollaborativeString createString(){ return new CollaborativeString(this); } public CollaborativeString createString(String opt_initialValue){ CollaborativeString result = createString(); result.setText(opt_initialValue); return result; } public void endCompoundOperation(){ //TODO } public CollaborativeMap<CollaborativeObject> getRoot(){ //TODO: make sure that the documents in this root element are updated return root; } public boolean isInitialized(){ return initialized; } public void redo(){ //TODO } public void undo(){ //TODO } public boolean canRedo(){ return canRedo; } public boolean canUndo(){ return canUndo; } public boolean isReadOnly(){ return readOnly; } public void addEventListener(EventType type, EventHandler handler) { //TODO } public void removeEventListener(EventType type, EventHandler handler) { //TODO } }
src/gx/realtime/Model.java
package gx.realtime; import java.util.Map; import java.util.Map.Entry; import java.util.Set; public class Model implements EventTarget { private Document document; private CollaborativeMap<CollaborativeObject> root; private boolean initialized; private boolean canRedo; private boolean canUndo; private boolean readOnly; protected Model(Document document){ this.document = document; this.root = new CollaborativeMap<CollaborativeObject>(this); initialized = true; canRedo = false; canUndo = false; readOnly = false; addDocumentEventHandlers(); } private void addDocumentEventHandlers() { document.addEventListener(EventType.OBJECT_CHANGED, (ObjectChangedEvent e) -> { System.out.println("OBJECT_CHANGED"); }); } public void beginCompoundOperation(String opt_name){ //TODO } public void beginCompoundOperation(){ //TODO } public Object create(/*TODO*/){ //TODO return null; } public <E> CollaborativeList<E> createList(){ return new CollaborativeList<E>(this); } public <E> CollaborativeList<E> createList(E[] opt_initialValue){ CollaborativeList<E> result = createList(); result.pushAll(opt_initialValue); return result; } public <E> CollaborativeMap<E> createMap(){ return new CollaborativeMap<E>(this); } public <E> CollaborativeMap<E> createMap(Map<String, E> opt_initialValue){ CollaborativeMap<E> result = createMap(); Set<Entry<String, E>> entries = opt_initialValue.entrySet(); for(Entry<String, E> entry : entries){ result.set(entry.getKey(), entry.getValue()); } return result; } public CollaborativeString createString(){ return new CollaborativeString(this); } public CollaborativeString createString(String opt_initialValue){ CollaborativeString result = createString(); result.setText(opt_initialValue); return result; } public void endCompoundOperation(){ //TODO } public CollaborativeMap<CollaborativeObject> getRoot(){ //TODO: make sure that the documents in this root element are updated return root; } public boolean isInitialized(){ return initialized; } public void redo(){ //TODO } public void undo(){ //TODO } public boolean canRedo(){ return canRedo; } public boolean canUndo(){ return canUndo; } public boolean isReadOnly(){ return readOnly; } public void addEventListener(EventType type, EventHandler handler) { //TODO } public void removeEventListener(EventType type, EventHandler handler) { //TODO } }
Tabs -> spaces.
src/gx/realtime/Model.java
Tabs -> spaces.
<ide><path>rc/gx/realtime/Model.java <ide> import java.util.Set; <ide> <ide> public class Model implements EventTarget { <del> <del> private Document document; <del> private CollaborativeMap<CollaborativeObject> root; <del> private boolean initialized; <del> private boolean canRedo; <del> private boolean canUndo; <del> private boolean readOnly; <del> <del> protected Model(Document document){ <del> this.document = document; <del> this.root = new CollaborativeMap<CollaborativeObject>(this); <del> initialized = true; <del> canRedo = false; <del> canUndo = false; <del> readOnly = false; <add> <add> private Document document; <add> private CollaborativeMap<CollaborativeObject> root; <add> private boolean initialized; <add> private boolean canRedo; <add> private boolean canUndo; <add> private boolean readOnly; <add> <add> protected Model(Document document){ <add> this.document = document; <add> this.root = new CollaborativeMap<CollaborativeObject>(this); <add> initialized = true; <add> canRedo = false; <add> canUndo = false; <add> readOnly = false; <ide> <ide> addDocumentEventHandlers(); <del> } <add> } <ide> <ide> private void addDocumentEventHandlers() { <ide> document.addEventListener(EventType.OBJECT_CHANGED, (ObjectChangedEvent e) -> { <ide> System.out.println("OBJECT_CHANGED"); <ide> }); <ide> } <del> <del> public void beginCompoundOperation(String opt_name){ <del> //TODO <del> } <del> <del> public void beginCompoundOperation(){ <del> //TODO <del> } <del> <del> public Object create(/*TODO*/){ <del> //TODO <del> return null; <del> } <del> <del> public <E> CollaborativeList<E> createList(){ <del> return new CollaborativeList<E>(this); <del> } <del> <del> public <E> CollaborativeList<E> createList(E[] opt_initialValue){ <del> CollaborativeList<E> result = createList(); <del> result.pushAll(opt_initialValue); <del> return result; <del> } <del> <del> public <E> CollaborativeMap<E> createMap(){ <del> return new CollaborativeMap<E>(this); <del> } <del> <del> public <E> CollaborativeMap<E> createMap(Map<String, E> opt_initialValue){ <del> CollaborativeMap<E> result = createMap(); <del> Set<Entry<String, E>> entries = opt_initialValue.entrySet(); <del> for(Entry<String, E> entry : entries){ <del> result.set(entry.getKey(), entry.getValue()); <del> } <del> return result; <del> } <del> <del> public CollaborativeString createString(){ <del> return new CollaborativeString(this); <del> } <del> <del> public CollaborativeString createString(String opt_initialValue){ <del> CollaborativeString result = createString(); <del> result.setText(opt_initialValue); <del> return result; <del> } <del> <del> public void endCompoundOperation(){ <del> //TODO <del> } <del> <del> public CollaborativeMap<CollaborativeObject> getRoot(){ <del> //TODO: make sure that the documents in this root element are updated <del> return root; <del> } <del> <del> public boolean isInitialized(){ <del> return initialized; <del> } <del> <del> public void redo(){ <del> //TODO <del> } <del> <del> public void undo(){ <del> //TODO <del> } <del> <del> public boolean canRedo(){ <del> return canRedo; <del> } <del> <del> public boolean canUndo(){ <del> return canUndo; <del> } <del> <del> public boolean isReadOnly(){ <del> return readOnly; <del> } <add> <add> public void beginCompoundOperation(String opt_name){ <add> //TODO <add> } <add> <add> public void beginCompoundOperation(){ <add> //TODO <add> } <add> <add> public Object create(/*TODO*/){ <add> //TODO <add> return null; <add> } <add> <add> public <E> CollaborativeList<E> createList(){ <add> return new CollaborativeList<E>(this); <add> } <add> <add> public <E> CollaborativeList<E> createList(E[] opt_initialValue){ <add> CollaborativeList<E> result = createList(); <add> result.pushAll(opt_initialValue); <add> return result; <add> } <add> <add> public <E> CollaborativeMap<E> createMap(){ <add> return new CollaborativeMap<E>(this); <add> } <add> <add> public <E> CollaborativeMap<E> createMap(Map<String, E> opt_initialValue){ <add> CollaborativeMap<E> result = createMap(); <add> Set<Entry<String, E>> entries = opt_initialValue.entrySet(); <add> for(Entry<String, E> entry : entries){ <add> result.set(entry.getKey(), entry.getValue()); <add> } <add> return result; <add> } <add> <add> public CollaborativeString createString(){ <add> return new CollaborativeString(this); <add> } <add> <add> public CollaborativeString createString(String opt_initialValue){ <add> CollaborativeString result = createString(); <add> result.setText(opt_initialValue); <add> return result; <add> } <add> <add> public void endCompoundOperation(){ <add> //TODO <add> } <add> <add> public CollaborativeMap<CollaborativeObject> getRoot(){ <add> //TODO: make sure that the documents in this root element are updated <add> return root; <add> } <add> <add> public boolean isInitialized(){ <add> return initialized; <add> } <add> <add> public void redo(){ <add> //TODO <add> } <add> <add> public void undo(){ <add> //TODO <add> } <add> <add> public boolean canRedo(){ <add> return canRedo; <add> } <add> <add> public boolean canUndo(){ <add> return canUndo; <add> } <add> <add> public boolean isReadOnly(){ <add> return readOnly; <add> } <ide> <ide> public void addEventListener(EventType type, EventHandler handler) { <ide> //TODO
Java
apache-2.0
eecde0df7d4c89b8300705e023e207b69cba8162
0
shivawu/topcoder-greed,shivawu/topcoder-greed,fries1/topcoder-greed,fries1/topcoder-greed
package greed.util; import java.io.*; /** * Greed is good! Cheers! */ public class FileSystem { private static final int NUM_BACKUPS = 3; private static final String BUILTIN_PREFIX = "builtin "; public static InputStream getInputStream(String resourcePath) throws FileNotFoundException { Log.i("Getting resource: " + resourcePath); if (resourcePath.startsWith(BUILTIN_PREFIX)) { resourcePath = Configuration.TEMPLATE_PATH + "/" + resourcePath.substring(BUILTIN_PREFIX.length()); if (Debug.developmentMode) { resourcePath = Debug.getResourceDirectory() + resourcePath; return new FileInputStream(resourcePath); } else return FileSystem.class.getResourceAsStream(resourcePath); } else { return new FileInputStream(Configuration.getWorkspace() + "/" + resourcePath); } } /* Log is relied on this method, hence Log cannot be used in here */ public static PrintWriter createWriter(String relativePath, boolean append) throws IOException { return new PrintWriter(new FileWriter(Configuration.getWorkspace() + "/" + relativePath, append)); } /* Log is relied on this method, hence Log cannot be used in here */ public static void createFolder(String relativePath) { File folder = new File(Configuration.getWorkspace() + "/" + relativePath); if (!folder.exists()) folder.mkdirs(); } public static void writeFile(String relativePath, String content) { PrintWriter writer; try { writer = new PrintWriter(Configuration.getWorkspace() + "/" + relativePath); writer.print(content); writer.flush(); writer.close(); } catch (FileNotFoundException e) { Log.e("Write file error", e); } } public static boolean exists(String relativePath) { return new File(Configuration.getWorkspace() + "/" + relativePath).exists(); } public static String getParentPath(String relativePath) { File f = new File(relativePath); return f.getParent(); } public static File getRawFile(String relativePath) { File f = new File(Configuration.getWorkspace() + "/" + relativePath); try { File f2 = f.getCanonicalFile(); f = f2; } catch (IOException e) { // leave f untouched, possibly the file path does not exist, so // fixing the non-canonical path is not important } return f; } public static long getSize(String resourcePath) { File f = new File(Configuration.getWorkspace() + "/" + resourcePath); if (f.exists() && f.isFile()) return f.length(); return -1; } public static void backup(String relativePath) { String absolutePath = Configuration.getWorkspace() + "/" + relativePath; File file = new File(absolutePath); if (!file.exists()) return; Log.i("Backing up file " + relativePath); int i; for (i = 0; i < NUM_BACKUPS; ++i) if (!new File(absolutePath + ".bak." + i).exists()) break; if (i == NUM_BACKUPS) { new File(absolutePath + ".bak.0").delete(); for (int j = 1; j < i; ++j) new File(absolutePath + ".bak." + j).renameTo(new File(absolutePath + ".bak." + (j - 1))); i = NUM_BACKUPS - 1; } Log.i("Renamed to " + relativePath + ".bak." + i); file.renameTo(new File(absolutePath + ".bak." + i)); } }
src/main/java/greed/util/FileSystem.java
package greed.util; import java.io.*; /** * Greed is good! Cheers! */ public class FileSystem { private static final int NUM_BACKUPS = 3; private static final String BUILTIN_PREFIX = "builtin "; public static InputStream getInputStream(String resourcePath) throws FileNotFoundException { Log.i("Getting resource: " + resourcePath); if (resourcePath.startsWith(BUILTIN_PREFIX)) { resourcePath = Configuration.TEMPLATE_PATH + "/" + resourcePath.substring(BUILTIN_PREFIX.length()); if (Debug.developmentMode) { resourcePath = Debug.getResourceDirectory() + resourcePath; return new FileInputStream(resourcePath); } else return FileSystem.class.getResourceAsStream(resourcePath); } else { return new FileInputStream(Configuration.getWorkspace() + "/" + resourcePath); } } /* Log is relied on this method, hence Log cannot be used in here */ public static PrintWriter createWriter(String relativePath, boolean append) throws IOException { return new PrintWriter(new FileWriter(Configuration.getWorkspace() + "/" + relativePath, append)); } /* Log is relied on this method, hence Log cannot be used in here */ public static void createFolder(String relativePath) { File folder = new File(Configuration.getWorkspace() + "/" + relativePath); if (!folder.exists()) folder.mkdirs(); } public static void writeFile(String relativePath, String content) { PrintWriter writer; try { writer = new PrintWriter(Configuration.getWorkspace() + "/" + relativePath); writer.print(content); writer.flush(); writer.close(); } catch (FileNotFoundException e) { Log.e("Write file error", e); } } public static boolean exists(String relativePath) { return new File(Configuration.getWorkspace() + "/" + relativePath).exists(); } public static String getParentPath(String relativePath) { File f = new File(relativePath); return f.getParent(); } public static File getRawFile(String relativePath) { return new File(Configuration.getWorkspace() + "/" + relativePath); } public static long getSize(String resourcePath) { File f = new File(Configuration.getWorkspace() + "/" + resourcePath); if (f.exists() && f.isFile()) return f.length(); return -1; } public static void backup(String relativePath) { String absolutePath = Configuration.getWorkspace() + "/" + relativePath; File file = new File(absolutePath); if (!file.exists()) return; Log.i("Backing up file " + relativePath); int i; for (i = 0; i < NUM_BACKUPS; ++i) if (!new File(absolutePath + ".bak." + i).exists()) break; if (i == NUM_BACKUPS) { new File(absolutePath + ".bak.0").delete(); for (int j = 1; j < i; ++j) new File(absolutePath + ".bak." + j).renameTo(new File(absolutePath + ".bak." + (j - 1))); i = NUM_BACKUPS - 1; } Log.i("Renamed to " + relativePath + ".bak." + i); file.renameTo(new File(absolutePath + ".bak." + i)); } }
Makes getRawFile return a canonical path if possible.
src/main/java/greed/util/FileSystem.java
Makes getRawFile return a canonical path if possible.
<ide><path>rc/main/java/greed/util/FileSystem.java <ide> } <ide> <ide> public static File getRawFile(String relativePath) { <del> return new File(Configuration.getWorkspace() + "/" + relativePath); <add> File f = new File(Configuration.getWorkspace() + "/" + relativePath); <add> try { <add> File f2 = f.getCanonicalFile(); <add> f = f2; <add> } catch (IOException e) { <add> // leave f untouched, possibly the file path does not exist, so <add> // fixing the non-canonical path is not important <add> } <add> return f; <ide> } <ide> <ide> public static long getSize(String resourcePath) {
Java
epl-1.0
de0cff3b844dc1bd9ff52d3e851e3ba14008cd9b
0
rrimmana/birt-1,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1
package org.eclipse.birt.report.designer.internal.ui.ide.propertyeditor; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.GroupHyperLinkDescriptorProvider; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.HyperLinkDescriptorProvider; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.dialogs.HyperlinkBuilder; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.ActionHandle; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.ui.PlatformUI; public class IDEHyperLinkDescriptorProvider extends GroupHyperLinkDescriptorProvider { public boolean hyperLinkSelected( ) { boolean flag = true; HyperlinkBuilder dialog = new HyperlinkBuilder( PlatformUI.getWorkbench( ) .getDisplay( ) .getActiveShell( ) ,true ); getActionStack( ).startTrans( Messages.getString( "HyperLinkPage.Menu.Save" ) ); //$NON-NLS-1$ ActionHandle handle = getActionHandle( ); if ( handle == null ) { try { handle = DEUtil.setAction( (ReportItemHandle) DEUtil.getInputFirstElement( input ), StructureFactory.createAction( ) ); } catch ( SemanticException e1 ) { getActionStack( ).rollback( ); ExceptionHandler.handle( e1 ); return false; } } dialog.setInput( handle ); needRefresh = false; boolean isOK = dialog.open( ) == Dialog.OK; needRefresh = true; if ( isOK ) { getActionStack( ).commit( ); flag = true; } else { getActionStack( ).rollback( ); flag = false; } return flag; } private boolean needRefresh = true; protected CommandStack getActionStack( ) { return SessionHandleAdapter.getInstance( ).getCommandStack( ); } protected ActionHandle getActionHandle( ) { return DEUtil.getActionHandle( (ReportItemHandle) DEUtil.getInputFirstElement( input ) ); } }
UI/org.eclipse.birt.report.designer.ui.ide/src/org/eclipse/birt/report/designer/internal/ui/ide/propertyeditor/IDEHyperLinkDescriptorProvider.java
package org.eclipse.birt.report.designer.internal.ui.ide.propertyeditor; import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.HyperLinkDescriptorProvider; import org.eclipse.birt.report.designer.nls.Messages; import org.eclipse.birt.report.designer.ui.dialogs.HyperlinkBuilder; import org.eclipse.birt.report.designer.util.DEUtil; import org.eclipse.birt.report.model.api.ActionHandle; import org.eclipse.birt.report.model.api.CommandStack; import org.eclipse.birt.report.model.api.ReportItemHandle; import org.eclipse.birt.report.model.api.StructureFactory; import org.eclipse.birt.report.model.api.activity.SemanticException; import org.eclipse.jface.dialogs.Dialog; import org.eclipse.ui.PlatformUI; public class IDEHyperLinkDescriptorProvider extends HyperLinkDescriptorProvider { public boolean hyperLinkSelected( ) { boolean flag = true; HyperlinkBuilder dialog = new HyperlinkBuilder( PlatformUI.getWorkbench( ) .getDisplay( ) .getActiveShell( ) ,true ); getActionStack( ).startTrans( Messages.getString( "HyperLinkPage.Menu.Save" ) ); //$NON-NLS-1$ ActionHandle handle = getActionHandle( ); if ( handle == null ) { try { handle = DEUtil.setAction( (ReportItemHandle) DEUtil.getInputFirstElement( input ), StructureFactory.createAction( ) ); } catch ( SemanticException e1 ) { getActionStack( ).rollback( ); ExceptionHandler.handle( e1 ); return false; } } dialog.setInput( handle ); needRefresh = false; boolean isOK = dialog.open( ) == Dialog.OK; needRefresh = true; if ( isOK ) { getActionStack( ).commit( ); flag = true; } else { getActionStack( ).rollback( ); flag = false; } return flag; } private boolean needRefresh = true; private CommandStack getActionStack( ) { return SessionHandleAdapter.getInstance( ).getCommandStack( ); } private ActionHandle getActionHandle( ) { return DEUtil.getActionHandle( (ReportItemHandle) DEUtil.getInputFirstElement( input ) ); } }
Append a group provider to set hyperlink on all selections.
UI/org.eclipse.birt.report.designer.ui.ide/src/org/eclipse/birt/report/designer/internal/ui/ide/propertyeditor/IDEHyperLinkDescriptorProvider.java
Append a group provider to set hyperlink on all selections.
<ide><path>I/org.eclipse.birt.report.designer.ui.ide/src/org/eclipse/birt/report/designer/internal/ui/ide/propertyeditor/IDEHyperLinkDescriptorProvider.java <ide> <ide> import org.eclipse.birt.report.designer.core.model.SessionHandleAdapter; <ide> import org.eclipse.birt.report.designer.internal.ui.util.ExceptionHandler; <add>import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.GroupHyperLinkDescriptorProvider; <ide> import org.eclipse.birt.report.designer.internal.ui.views.attributes.provider.HyperLinkDescriptorProvider; <ide> import org.eclipse.birt.report.designer.nls.Messages; <ide> import org.eclipse.birt.report.designer.ui.dialogs.HyperlinkBuilder; <ide> import org.eclipse.jface.dialogs.Dialog; <ide> import org.eclipse.ui.PlatformUI; <ide> <del>public class IDEHyperLinkDescriptorProvider extends HyperLinkDescriptorProvider <add>public class IDEHyperLinkDescriptorProvider extends GroupHyperLinkDescriptorProvider <ide> { <ide> <ide> public boolean hyperLinkSelected( ) <ide> <ide> private boolean needRefresh = true; <ide> <del> private CommandStack getActionStack( ) <add> protected CommandStack getActionStack( ) <ide> { <ide> return SessionHandleAdapter.getInstance( ).getCommandStack( ); <ide> } <ide> <del> private ActionHandle getActionHandle( ) <add> protected ActionHandle getActionHandle( ) <ide> { <ide> return DEUtil.getActionHandle( (ReportItemHandle) DEUtil.getInputFirstElement( input ) ); <ide> }
Java
mit
b92b03b2f8ba99a95697ca16d490d2d2cd6f3ce7
0
CyclopsMC/CyclopsCore
package org.cyclops.cyclopscore.client.gui; import com.mojang.blaze3d.matrix.MatrixStack; import com.mojang.blaze3d.systems.RenderSystem; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.IRenderTypeBuffer; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.color.ItemColors; import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.client.renderer.model.ModelManager; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.cyclops.cyclopscore.helper.GuiHelpers; import javax.annotation.Nullable; import java.util.Objects; /** * An item renderer that can handle stack sizes larger than 64. * @author rubensworks */ @OnlyIn(Dist.CLIENT) public class RenderItemExtendedSlotCount extends ItemRenderer { private static RenderItemExtendedSlotCount instance; private final ItemRenderer renderItemInner; protected RenderItemExtendedSlotCount(Minecraft mc) { this(mc.getTextureManager(), mc.getItemRenderer().getItemModelMesher().getModelManager(), mc.getItemColors(), mc.getItemRenderer()); } protected RenderItemExtendedSlotCount(TextureManager textureManager, ModelManager modelManager, ItemColors itemColors, ItemRenderer renderItemInner) { super(Objects.requireNonNull(textureManager), Objects.requireNonNull(modelManager), Objects.requireNonNull(itemColors)); this.renderItemInner = renderItemInner; } public static RenderItemExtendedSlotCount getInstance() { return instance; } public static void initialize() { instance = new RenderItemExtendedSlotCount(Minecraft.getInstance()); } public void drawSlotText(FontRenderer fontRenderer, MatrixStack matrixstack, String string, int x, int y) { matrixstack.translate(0.0D, 0.0D, (double)(this.zLevel + 200.0F)); float scale = 0.5f; matrixstack.scale(scale, scale, 1.0f); IRenderTypeBuffer.Impl renderTypeBuffer = IRenderTypeBuffer.getImpl(Tessellator.getInstance().getBuffer()); int width = fontRenderer.getStringWidth(string); fontRenderer.renderString(string, (x + 16) / scale - width, (y + 12) / scale, 16777215, true, matrixstack.getLast().getMatrix(), renderTypeBuffer, false, 0, 15728880); renderTypeBuffer.finish(); } @Override public void renderItemOverlayIntoGUI(FontRenderer fr, ItemStack stack, int xPosition, int yPosition, @Nullable String text) { // ----- Copied and adjusted from super ----- if (!stack.isEmpty()) { MatrixStack matrixstack = new MatrixStack(); if (stack.getCount() != 1 || text != null) { drawSlotText(fr, matrixstack, text == null ? GuiHelpers.quantityToScaledString(stack.getCount()) : text, xPosition, yPosition); } if (stack.getItem().showDurabilityBar(stack)) { RenderSystem.disableDepthTest(); RenderSystem.disableTexture(); RenderSystem.disableAlphaTest(); RenderSystem.disableBlend(); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuffer(); double health = stack.getItem().getDurabilityForDisplay(stack); int i = Math.round(13.0F - (float)health * 13.0F); int j = stack.getItem().getRGBDurabilityForDisplay(stack); this.draw(bufferbuilder, xPosition + 2, yPosition + 13, 13, 2, 0, 0, 0, 255); this.draw(bufferbuilder, xPosition + 2, yPosition + 13, i, 1, j >> 16 & 255, j >> 8 & 255, j & 255, 255); RenderSystem.enableBlend(); RenderSystem.enableAlphaTest(); RenderSystem.enableTexture(); RenderSystem.enableDepthTest(); } ClientPlayerEntity clientplayerentity = Minecraft.getInstance().player; float f3 = clientplayerentity == null ? 0.0F : clientplayerentity.getCooldownTracker().getCooldown(stack.getItem(), Minecraft.getInstance().getRenderPartialTicks()); if (f3 > 0.0F) { RenderSystem.disableDepthTest(); RenderSystem.disableTexture(); RenderSystem.enableBlend(); RenderSystem.defaultBlendFunc(); Tessellator tessellator1 = Tessellator.getInstance(); BufferBuilder bufferbuilder1 = tessellator1.getBuffer(); this.draw(bufferbuilder1, xPosition, yPosition + MathHelper.floor(16.0F * (1.0F - f3)), 16, MathHelper.ceil(16.0F * f3), 255, 255, 255, 127); RenderSystem.enableTexture(); RenderSystem.enableDepthTest(); } } } // Hacks to refer to correct RenderItem's itemModelMesher instance @Override public ItemModelMesher getItemModelMesher() { return renderItemInner.getItemModelMesher(); } @Override public IBakedModel getItemModelWithOverrides(ItemStack stack, @Nullable World worldIn, @Nullable LivingEntity entitylivingbaseIn) { return renderItemInner.getItemModelWithOverrides(stack, worldIn, entitylivingbaseIn); } }
src/main/java/org/cyclops/cyclopscore/client/gui/RenderItemExtendedSlotCount.java
package org.cyclops.cyclopscore.client.gui; import com.mojang.blaze3d.platform.GlStateManager; import net.minecraft.client.Minecraft; import net.minecraft.client.entity.player.ClientPlayerEntity; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.BufferBuilder; import net.minecraft.client.renderer.ItemModelMesher; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.color.ItemColors; import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.client.renderer.model.ModelManager; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.entity.LivingEntity; import net.minecraft.item.ItemStack; import net.minecraft.util.math.MathHelper; import net.minecraft.world.World; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import org.cyclops.cyclopscore.helper.GuiHelpers; import javax.annotation.Nullable; import java.util.Objects; /** * An item renderer that can handle stack sizes larger than 64. * @author rubensworks */ @OnlyIn(Dist.CLIENT) public class RenderItemExtendedSlotCount extends ItemRenderer { private static RenderItemExtendedSlotCount instance; private final ItemRenderer renderItemInner; protected RenderItemExtendedSlotCount(Minecraft mc) { this(mc.getTextureManager(), mc.getItemRenderer().getItemModelMesher().getModelManager(), mc.getItemColors(), mc.getItemRenderer()); } protected RenderItemExtendedSlotCount(TextureManager textureManager, ModelManager modelManager, ItemColors itemColors, ItemRenderer renderItemInner) { super(Objects.requireNonNull(textureManager), Objects.requireNonNull(modelManager), Objects.requireNonNull(itemColors)); this.renderItemInner = renderItemInner; } public static RenderItemExtendedSlotCount getInstance() { return instance; } public static void initialize() { instance = new RenderItemExtendedSlotCount(Minecraft.getInstance()); } public static void drawSlotText(FontRenderer fontRenderer, String string, int x, int y) { GlStateManager.disableLighting(); GlStateManager.disableDepthTest(); GlStateManager.disableBlend(); GlStateManager.pushMatrix(); float scale = 0.5f; GlStateManager.scalef(scale, scale, 1.0f); int width = fontRenderer.getStringWidth(string); fontRenderer.drawStringWithShadow(string, (x + 16) / scale - width, (y + 12) / scale, 16777215); GlStateManager.popMatrix(); GlStateManager.enableLighting(); GlStateManager.enableDepthTest(); GlStateManager.enableBlend(); } @Override public void renderItemOverlayIntoGUI(FontRenderer fr, ItemStack stack, int xPosition, int yPosition, @Nullable String text) { // ----- Copied and adjusted from super ----- if (!stack.isEmpty()) { if (stack.getCount() != 1 || text != null) { drawSlotText(fr, text == null ? GuiHelpers.quantityToScaledString(stack.getCount()) : text, xPosition, yPosition); } if (stack.getItem().showDurabilityBar(stack)) { GlStateManager.disableLighting(); GlStateManager.disableDepthTest(); GlStateManager.disableTexture(); GlStateManager.disableAlphaTest(); GlStateManager.disableBlend(); Tessellator tessellator = Tessellator.getInstance(); BufferBuilder bufferbuilder = tessellator.getBuffer(); double health = stack.getItem().getDurabilityForDisplay(stack); int i = Math.round(13.0F - (float)health * 13.0F); int j = stack.getItem().getRGBDurabilityForDisplay(stack); this.draw(bufferbuilder, xPosition + 2, yPosition + 13, 13, 2, 0, 0, 0, 255); this.draw(bufferbuilder, xPosition + 2, yPosition + 13, i, 1, j >> 16 & 255, j >> 8 & 255, j & 255, 255); GlStateManager.enableBlend(); GlStateManager.enableAlphaTest(); GlStateManager.enableTexture(); GlStateManager.enableLighting(); GlStateManager.enableDepthTest(); } ClientPlayerEntity clientplayerentity = Minecraft.getInstance().player; float f3 = clientplayerentity == null ? 0.0F : clientplayerentity.getCooldownTracker().getCooldown(stack.getItem(), Minecraft.getInstance().getRenderPartialTicks()); if (f3 > 0.0F) { GlStateManager.disableLighting(); GlStateManager.disableDepthTest(); GlStateManager.disableTexture(); Tessellator tessellator1 = Tessellator.getInstance(); BufferBuilder bufferbuilder1 = tessellator1.getBuffer(); this.draw(bufferbuilder1, xPosition, yPosition + MathHelper.floor(16.0F * (1.0F - f3)), 16, MathHelper.ceil(16.0F * f3), 255, 255, 255, 127); GlStateManager.enableTexture(); GlStateManager.enableLighting(); GlStateManager.enableDepthTest(); } } } // Hacks to refer to correct RenderItem's itemModelMesher instance @Override public ItemModelMesher getItemModelMesher() { return renderItemInner.getItemModelMesher(); } @Override public IBakedModel getItemModelWithOverrides(ItemStack stack, @Nullable World worldIn, @Nullable LivingEntity entitylivingbaseIn) { return renderItemInner.getItemModelWithOverrides(stack, worldIn, entitylivingbaseIn); } }
Fix RenderItemExtendedSlotCount rendering amount behind item
src/main/java/org/cyclops/cyclopscore/client/gui/RenderItemExtendedSlotCount.java
Fix RenderItemExtendedSlotCount rendering amount behind item
<ide><path>rc/main/java/org/cyclops/cyclopscore/client/gui/RenderItemExtendedSlotCount.java <ide> package org.cyclops.cyclopscore.client.gui; <ide> <del>import com.mojang.blaze3d.platform.GlStateManager; <add>import com.mojang.blaze3d.matrix.MatrixStack; <add>import com.mojang.blaze3d.systems.RenderSystem; <ide> import net.minecraft.client.Minecraft; <ide> import net.minecraft.client.entity.player.ClientPlayerEntity; <ide> import net.minecraft.client.gui.FontRenderer; <ide> import net.minecraft.client.renderer.BufferBuilder; <add>import net.minecraft.client.renderer.IRenderTypeBuffer; <ide> import net.minecraft.client.renderer.ItemModelMesher; <ide> import net.minecraft.client.renderer.ItemRenderer; <ide> import net.minecraft.client.renderer.Tessellator; <ide> instance = new RenderItemExtendedSlotCount(Minecraft.getInstance()); <ide> } <ide> <del> public static void drawSlotText(FontRenderer fontRenderer, String string, int x, int y) { <del> GlStateManager.disableLighting(); <del> GlStateManager.disableDepthTest(); <del> GlStateManager.disableBlend(); <del> <del> GlStateManager.pushMatrix(); <add> public void drawSlotText(FontRenderer fontRenderer, MatrixStack matrixstack, String string, int x, int y) { <add> matrixstack.translate(0.0D, 0.0D, (double)(this.zLevel + 200.0F)); <ide> float scale = 0.5f; <del> GlStateManager.scalef(scale, scale, 1.0f); <add> matrixstack.scale(scale, scale, 1.0f); <add> IRenderTypeBuffer.Impl renderTypeBuffer = IRenderTypeBuffer.getImpl(Tessellator.getInstance().getBuffer()); <ide> int width = fontRenderer.getStringWidth(string); <del> fontRenderer.drawStringWithShadow(string, (x + 16) / scale - width, (y + 12) / scale, 16777215); <del> GlStateManager.popMatrix(); <del> <del> GlStateManager.enableLighting(); <del> GlStateManager.enableDepthTest(); <del> GlStateManager.enableBlend(); <add> fontRenderer.renderString(string, (x + 16) / scale - width, (y + 12) / scale, 16777215, true, <add> matrixstack.getLast().getMatrix(), renderTypeBuffer, false, 0, 15728880); <add> renderTypeBuffer.finish(); <ide> } <ide> <ide> @Override <ide> public void renderItemOverlayIntoGUI(FontRenderer fr, ItemStack stack, int xPosition, int yPosition, @Nullable String text) { <ide> // ----- Copied and adjusted from super ----- <ide> if (!stack.isEmpty()) { <add> MatrixStack matrixstack = new MatrixStack(); <ide> if (stack.getCount() != 1 || text != null) { <del> drawSlotText(fr, text == null ? GuiHelpers.quantityToScaledString(stack.getCount()) : text, xPosition, yPosition); <add> drawSlotText(fr, matrixstack, text == null ? GuiHelpers.quantityToScaledString(stack.getCount()) : text, xPosition, yPosition); <ide> } <ide> <ide> if (stack.getItem().showDurabilityBar(stack)) { <del> GlStateManager.disableLighting(); <del> GlStateManager.disableDepthTest(); <del> GlStateManager.disableTexture(); <del> GlStateManager.disableAlphaTest(); <del> GlStateManager.disableBlend(); <add> RenderSystem.disableDepthTest(); <add> RenderSystem.disableTexture(); <add> RenderSystem.disableAlphaTest(); <add> RenderSystem.disableBlend(); <ide> Tessellator tessellator = Tessellator.getInstance(); <ide> BufferBuilder bufferbuilder = tessellator.getBuffer(); <ide> double health = stack.getItem().getDurabilityForDisplay(stack); <ide> int j = stack.getItem().getRGBDurabilityForDisplay(stack); <ide> this.draw(bufferbuilder, xPosition + 2, yPosition + 13, 13, 2, 0, 0, 0, 255); <ide> this.draw(bufferbuilder, xPosition + 2, yPosition + 13, i, 1, j >> 16 & 255, j >> 8 & 255, j & 255, 255); <del> GlStateManager.enableBlend(); <del> GlStateManager.enableAlphaTest(); <del> GlStateManager.enableTexture(); <del> GlStateManager.enableLighting(); <del> GlStateManager.enableDepthTest(); <add> RenderSystem.enableBlend(); <add> RenderSystem.enableAlphaTest(); <add> RenderSystem.enableTexture(); <add> RenderSystem.enableDepthTest(); <ide> } <ide> <ide> ClientPlayerEntity clientplayerentity = Minecraft.getInstance().player; <ide> float f3 = clientplayerentity == null ? 0.0F : clientplayerentity.getCooldownTracker().getCooldown(stack.getItem(), Minecraft.getInstance().getRenderPartialTicks()); <ide> if (f3 > 0.0F) { <del> GlStateManager.disableLighting(); <del> GlStateManager.disableDepthTest(); <del> GlStateManager.disableTexture(); <add> RenderSystem.disableDepthTest(); <add> RenderSystem.disableTexture(); <add> RenderSystem.enableBlend(); <add> RenderSystem.defaultBlendFunc(); <ide> Tessellator tessellator1 = Tessellator.getInstance(); <ide> BufferBuilder bufferbuilder1 = tessellator1.getBuffer(); <ide> this.draw(bufferbuilder1, xPosition, yPosition + MathHelper.floor(16.0F * (1.0F - f3)), 16, MathHelper.ceil(16.0F * f3), 255, 255, 255, 127); <del> GlStateManager.enableTexture(); <del> GlStateManager.enableLighting(); <del> GlStateManager.enableDepthTest(); <add> RenderSystem.enableTexture(); <add> RenderSystem.enableDepthTest(); <ide> } <ide> <ide> }
Java
apache-2.0
24d6978ab87e233b46ebb5f07584d3cdf15208ea
0
onyxbits/TextFiction,onyxbits/TextFiction,onyxbits/TextFiction
package de.onyxbits.textfiction; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.widget.Toast; /** * Helper task for the LibraryFragment that takes care of copying games from the * download directory to the library directory. */ class ImportTask extends AsyncTask<Object, Integer, Exception> implements DialogInterface.OnClickListener, DialogInterface.OnMultiChoiceClickListener, FilenameFilter { /** * Supported filename suffixes */ public static final String[] SUFFIXES = { "Z3", "Z5", "Z8", "ZBLORB" }; /** * The import candidates from which the user may choose. */ private File[] toImport; /** * Flags the files in "toImport" that are to be downloaded */ private boolean[] selected; /** * Set if we actually did import something */ private boolean didImport=false; /** * The library fragment, we are working for. */ private LibraryFragment master; private ImportTask() { } @Override public void onPreExecute() { Activity context = master.getActivity(); if (context != null) { context.setProgressBarIndeterminate(false); context.setProgressBarIndeterminateVisibility(false); context.setProgressBarVisibility(false); } } @Override protected Exception doInBackground(Object... params) { for (int i = 0; i < toImport.length; i++) { if (selected[i]) { try { FileUtil.importGame(toImport[i]); } catch (Exception e) { Log.w(getClass().getName(), e); return e; } } } didImport=true; return null; } @Override public void onPostExecute(Exception result) { Activity context = master.getActivity(); if (result != null) { Toast.makeText(context, R.string.msg_failure_import, Toast.LENGTH_SHORT) .show(); } if (context != null) { context.setProgressBarIndeterminate(false); context.setProgressBarIndeterminateVisibility(false); context.setProgressBarVisibility(false); } if (result==null && context!=null && didImport) { Toast.makeText(context,R.string.msg_file_copied_you_may_delete_the_original_now,Toast.LENGTH_LONG).show(); } master.reScan(); } @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { selected[which] = isChecked; } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { execute(new Object()); } } /** * Silently import games without showing a selection dialog * * @param master * callback * @param files * files to import */ public static void importGames(LibraryFragment master, File[] files) { ImportTask task = new ImportTask(); task.master = master; task.toImport = files; task.selected = new boolean[files.length]; Arrays.fill(task.selected, true); task.execute(new Object()); } /** * Shows a list of games that are available in the public downloads directory, * allowing the user to select which ones to import. * * @param master * the fragment to report back to in case something was imported. */ public static void showSelectDialog(LibraryFragment master) { ImportTask task = new ImportTask(); task.toImport = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).listFiles(task); if (task.toImport == null || task.toImport.length == 0) { Toast.makeText(master.getActivity(), R.string.msg_nothing_to_import, Toast.LENGTH_SHORT).show(); return; } Arrays.sort(task.toImport); String[] names = new String[task.toImport.length]; task.selected = new boolean[task.toImport.length]; task.master = master; for (int i = 0; i < task.toImport.length; i++) { names[i] = task.toImport[i].getName(); } AlertDialog.Builder builder = new AlertDialog.Builder(master.getActivity()); builder.setTitle(R.string.title_select_import) .setMultiChoiceItems(names, null, task) .setPositiveButton(android.R.string.ok, task).create().show(); } @Override public boolean accept(File dir, String filename) { boolean ret = false; for (String suffix : SUFFIXES) { if (filename.toUpperCase().endsWith(suffix)) { ret = true; break; } } return ret; } }
src/de/onyxbits/textfiction/ImportTask.java
package de.onyxbits.textfiction; import java.io.File; import java.io.FilenameFilter; import java.util.Arrays; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.AsyncTask; import android.os.Environment; import android.util.Log; import android.widget.Toast; /** * Helper task for the LibraryFragment that takes care of copying games from the * download directory to the library directory. */ class ImportTask extends AsyncTask<Object, Integer, Exception> implements DialogInterface.OnClickListener, DialogInterface.OnMultiChoiceClickListener, FilenameFilter { /** * Supported filename suffixes */ public static final String[] SUFFIXES = { "Z3", "Z5", "Z8", "ZBLORB" }; /** * The import candidates from which the user may choose. */ private File[] toImport; /** * Flags the files in "toImport" that are to be downloaded */ private boolean[] selected; /** * The library fragment, we are working for. */ private LibraryFragment master; private ImportTask() { } @Override public void onPreExecute() { Activity context = master.getActivity(); if (context != null) { context.setProgressBarIndeterminate(false); context.setProgressBarIndeterminateVisibility(false); context.setProgressBarVisibility(false); } } @Override protected Exception doInBackground(Object... params) { for (int i = 0; i < toImport.length; i++) { if (selected[i]) { try { FileUtil.importGame(toImport[i]); } catch (Exception e) { Log.w(getClass().getName(), e); return e; } } } return null; } @Override public void onPostExecute(Exception result) { Activity context = master.getActivity(); if (result != null) { Toast.makeText(context, R.string.msg_failure_import, Toast.LENGTH_SHORT) .show(); } if (context != null) { context.setProgressBarIndeterminate(false); context.setProgressBarIndeterminateVisibility(false); context.setProgressBarVisibility(false); } if (result==null && context!=null) { Toast.makeText(context,R.string.msg_file_copied_you_may_delete_the_original_now,Toast.LENGTH_LONG).show(); } master.reScan(); } @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { selected[which] = isChecked; } @Override public void onClick(DialogInterface dialog, int which) { if (which == DialogInterface.BUTTON_POSITIVE) { execute(new Object()); } } /** * Silently import games without showing a selection dialog * * @param master * callback * @param files * files to import */ public static void importGames(LibraryFragment master, File[] files) { ImportTask task = new ImportTask(); task.master = master; task.toImport = files; task.selected = new boolean[files.length]; Arrays.fill(task.selected, true); task.execute(new Object()); } /** * Shows a list of games that are available in the public downloads directory, * allowing the user to select which ones to import. * * @param master * the fragment to report back to in case something was imported. */ public static void showSelectDialog(LibraryFragment master) { ImportTask task = new ImportTask(); task.toImport = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).listFiles(task); if (task.toImport == null || task.toImport.length == 0) { Toast.makeText(master.getActivity(), R.string.msg_nothing_to_import, Toast.LENGTH_SHORT).show(); return; } Arrays.sort(task.toImport); String[] names = new String[task.toImport.length]; task.selected = new boolean[task.toImport.length]; task.master = master; for (int i = 0; i < task.toImport.length; i++) { names[i] = task.toImport[i].getName(); } AlertDialog.Builder builder = new AlertDialog.Builder(master.getActivity()); builder.setTitle(R.string.title_select_import) .setMultiChoiceItems(names, null, task) .setPositiveButton(android.R.string.ok, task).create().show(); } @Override public boolean accept(File dir, String filename) { boolean ret = false; for (String suffix : SUFFIXES) { if (filename.toUpperCase().endsWith(suffix)) { ret = true; break; } } return ret; } }
Only show the toast if something was succesfully
src/de/onyxbits/textfiction/ImportTask.java
Only show the toast if something was succesfully
<ide><path>rc/de/onyxbits/textfiction/ImportTask.java <ide> * Flags the files in "toImport" that are to be downloaded <ide> */ <ide> private boolean[] selected; <add> <add> /** <add> * Set if we actually did import something <add> */ <add> private boolean didImport=false; <ide> <ide> /** <ide> * The library fragment, we are working for. <ide> } <ide> } <ide> } <add> didImport=true; <ide> return null; <ide> } <ide> <ide> context.setProgressBarIndeterminateVisibility(false); <ide> context.setProgressBarVisibility(false); <ide> } <del> if (result==null && context!=null) { <add> if (result==null && context!=null && didImport) { <ide> Toast.makeText(context,R.string.msg_file_copied_you_may_delete_the_original_now,Toast.LENGTH_LONG).show(); <ide> } <ide> master.reScan();
Java
apache-2.0
7ac66d93f5c353014ef5f307ce5912c6e457dccf
0
wso2/product-apim,wso2/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,chamilaadhi/product-apim,wso2/product-apim,chamilaadhi/product-apim,wso2/product-apim,wso2/product-apim
/* * Copyright (c) 2019, WSO2 Inc. (http://wso2.com) 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 org.wso2.am.integration.test.impl; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.testng.Assert; import org.wso2.am.integration.clients.gateway.api.v2.dto.APIInfoDTO; import org.wso2.am.integration.clients.publisher.api.ApiClient; import org.wso2.am.integration.clients.publisher.api.ApiException; import org.wso2.am.integration.clients.publisher.api.ApiResponse; import org.wso2.am.integration.clients.publisher.api.v1.ApIsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiAuditApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiDocumentsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiLifecycleApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiProductRevisionsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiProductsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiResourcePoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiRevisionsApi; import org.wso2.am.integration.clients.publisher.api.v1.ClientCertificatesApi; import org.wso2.am.integration.clients.publisher.api.v1.CommentsApi; import org.wso2.am.integration.clients.publisher.api.v1.EndpointCertificatesApi; import org.wso2.am.integration.clients.publisher.api.v1.GlobalMediationPoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.GraphQlPoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.GraphQlSchemaApi; import org.wso2.am.integration.clients.publisher.api.v1.GraphQlSchemaIndividualApi; import org.wso2.am.integration.clients.publisher.api.v1.RolesApi; import org.wso2.am.integration.clients.publisher.api.v1.ScopesApi; import org.wso2.am.integration.clients.publisher.api.v1.SubscriptionsApi; import org.wso2.am.integration.clients.publisher.api.v1.ThrottlingPoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.UnifiedSearchApi; import org.wso2.am.integration.clients.publisher.api.v1.ValidationApi; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIBusinessInformationDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APICorsConfigurationDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIKeyDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIProductDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIProductListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIRevisionDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIRevisionDeploymentDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.APIRevisionListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ApiEndpointValidationResponseDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.AsyncAPISpecificationValidationResponseDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.AuditReportDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.CertMetadataDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.CertificatesDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ClientCertMetadataDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.CommentDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.CommentListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.DocumentDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.DocumentListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLQueryComplexityInfoDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLSchemaDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLSchemaTypeListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLValidationResponseDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.LifecycleHistoryDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.LifecycleStateDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.MediationListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.MockResponsePayloadListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.OpenAPIDefinitionValidationResponseDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.PatchRequestBodyDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.PostRequestBodyDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ResourcePolicyInfoDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ResourcePolicyListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ScopeDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ScopeListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.SearchResultListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.SubscriptionListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.SubscriptionPolicyListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.ThrottlingPolicyListDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.WSDLValidationResponseDTO; import org.wso2.am.integration.clients.publisher.api.v1.dto.WorkflowResponseDTO; import org.wso2.am.integration.test.ClientAuthenticator; import org.wso2.am.integration.test.Constants; import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.bean.APIRequest; import org.wso2.am.integration.test.utils.bean.APIResourceBean; import org.wso2.am.integration.test.utils.bean.APIRevisionDeployUndeployRequest; import org.wso2.am.integration.test.utils.bean.APIRevisionRequest; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; /** * This util class performs the actions related to APIDTOobjects. */ public class RestAPIPublisherImpl { public static final String appName = "Integration_Test_App_Publisher"; public static final String callBackURL = "test.com"; public static final String tokenScope = "Production"; public static final String appOwner = "admin"; public static final String grantType = "password"; public static final String username = "admin"; public static final String password = "admin"; public static final String testNameProperty = "testName"; public ApIsApi apIsApi = new ApIsApi(); public ApiDocumentsApi apiDocumentsApi = new ApiDocumentsApi(); public ApiRevisionsApi apiRevisionsApi = new ApiRevisionsApi(); public ApiResourcePoliciesApi apiResourcePoliciesApi = new ApiResourcePoliciesApi(); public ApiProductRevisionsApi apiProductRevisionsApi = new ApiProductRevisionsApi(); public ThrottlingPoliciesApi throttlingPoliciesApi = new ThrottlingPoliciesApi(); public ClientCertificatesApi clientCertificatesApi = new ClientCertificatesApi(); public EndpointCertificatesApi endpointCertificatesApi = new EndpointCertificatesApi(); public GraphQlSchemaApi graphQlSchemaApi = new GraphQlSchemaApi(); public GraphQlSchemaIndividualApi graphQlSchemaIndividualApi = new GraphQlSchemaIndividualApi(); public ApiLifecycleApi apiLifecycleApi = new ApiLifecycleApi(); public CommentsApi commentsApi = new CommentsApi(); public RolesApi rolesApi = new RolesApi(); public ValidationApi validationApi = new ValidationApi(); public SubscriptionsApi subscriptionsApi = new SubscriptionsApi(); public ApiAuditApi apiAuditApi = new ApiAuditApi(); public GraphQlPoliciesApi graphQlPoliciesApi = new GraphQlPoliciesApi(); public UnifiedSearchApi unifiedSearchApi = new UnifiedSearchApi(); public GlobalMediationPoliciesApi globalMediationPoliciesApi = new GlobalMediationPoliciesApi(); public ScopesApi sharedScopesApi = new ScopesApi(); public ApiClient apiPublisherClient = new ApiClient(); public String tenantDomain; private ApiProductsApi apiProductsApi = new ApiProductsApi(); private RestAPIGatewayImpl restAPIGateway; private String disableVerification = System.getProperty("disableVerification"); @Deprecated public RestAPIPublisherImpl() { this(username, password, "", "https://localhost:9943"); } public RestAPIPublisherImpl(String username, String password, String tenantDomain, String publisherURL) { // token/DCR of Publisher node itself will be used String tokenURL = publisherURL + "oauth2/token"; String dcrURL = publisherURL + "client-registration/v0.17/register"; String accessToken = ClientAuthenticator .getAccessToken("openid apim:api_view apim:api_create apim:api_delete apim:api_publish " + "apim:subscription_view apim:subscription_block apim:external_services_discover " + "apim:threat_protection_policy_create apim:threat_protection_policy_manage " + "apim:document_create apim:document_manage apim:mediation_policy_view " + "apim:mediation_policy_create apim:mediation_policy_manage " + "apim:client_certificates_view apim:client_certificates_add " + "apim:client_certificates_update apim:ep_certificates_view " + "apim:ep_certificates_add apim:ep_certificates_update apim:publisher_settings " + "apim:pub_alert_manage apim:shared_scope_manage apim:api_generate_key apim:comment_view " + "apim:comment_write", appName, callBackURL, tokenScope, appOwner, grantType, dcrURL, username, password, tenantDomain, tokenURL); apiPublisherClient.addDefaultHeader("Authorization", "Bearer " + accessToken); apiPublisherClient.setBasePath(publisherURL + "api/am/publisher/v2"); apiPublisherClient.setDebugging(true); apiPublisherClient.setReadTimeout(600000); apiPublisherClient.setConnectTimeout(600000); apiPublisherClient.setWriteTimeout(600000); apIsApi.setApiClient(apiPublisherClient); apiProductsApi.setApiClient(apiPublisherClient); apiRevisionsApi.setApiClient(apiPublisherClient); apiResourcePoliciesApi.setApiClient(apiPublisherClient); apiProductRevisionsApi.setApiClient(apiPublisherClient); graphQlSchemaApi.setApiClient(apiPublisherClient); commentsApi.setApiClient(apiPublisherClient); graphQlSchemaIndividualApi.setApiClient(apiPublisherClient); apiDocumentsApi.setApiClient(apiPublisherClient); throttlingPoliciesApi.setApiClient(apiPublisherClient); apiLifecycleApi.setApiClient(apiPublisherClient); rolesApi.setApiClient(apiPublisherClient); validationApi.setApiClient(apiPublisherClient); clientCertificatesApi.setApiClient(apiPublisherClient); subscriptionsApi.setApiClient(apiPublisherClient); graphQlPoliciesApi.setApiClient(apiPublisherClient); apiAuditApi.setApiClient(apiPublisherClient); unifiedSearchApi.setApiClient(apiPublisherClient); sharedScopesApi.setApiClient(apiPublisherClient); globalMediationPoliciesApi.setApiClient(apiPublisherClient); endpointCertificatesApi.setApiClient(apiPublisherClient); this.tenantDomain = tenantDomain; this.restAPIGateway = new RestAPIGatewayImpl(this.username, this.password, tenantDomain); } /** * \ * This method is used to create an API. * * @param apiRequest * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API. */ public HttpResponse addAPI(APIRequest apiRequest) throws ApiException { String osVersion = "v3"; setActivityID(); APIDTO apidto = this.addAPI(apiRequest, osVersion); HttpResponse response = null; if (apidto != null && StringUtils.isNotEmpty(apidto.getId())) { response = new HttpResponse(apidto.getId(), 201); } return response; } /** * \ * This method is used to create an API. * * @param apiRequest * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API. */ public APIDTO addAPI(APIRequest apiRequest, String osVersion) throws ApiException { APIDTO body = new APIDTO(); body.setName(apiRequest.getName()); body.setContext(apiRequest.getContext()); body.setVersion(apiRequest.getVersion()); if (apiRequest.getVisibility() != null) { body.setVisibility(APIDTO.VisibilityEnum.valueOf(apiRequest.getVisibility().toUpperCase())); if (APIDTO.VisibilityEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getVisibility()) && StringUtils.isNotEmpty(apiRequest.getRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getRoles().split(" , "))); body.setVisibleRoles(roleList); } } else { body.setVisibility(APIDTO.VisibilityEnum.PUBLIC); } if (apiRequest.getAccessControl() != null) { body.setAccessControl(APIDTO.AccessControlEnum.valueOf(apiRequest.getAccessControl().toUpperCase())); if (APIDTO.AccessControlEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getAccessControl()) && StringUtils.isNotEmpty(apiRequest.getAccessControlRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getAccessControlRoles().split(" , "))); body.setAccessControlRoles(roleList); } } else { body.setAccessControl(APIDTO.AccessControlEnum.NONE); } body.setDescription(apiRequest.getDescription()); body.setProvider(apiRequest.getProvider()); ArrayList<String> transports = new ArrayList<>(); if (Constants.PROTOCOL_HTTP.equals(apiRequest.getHttp_checked())) { transports.add(Constants.PROTOCOL_HTTP); } if (Constants.PROTOCOL_HTTPS.equals(apiRequest.getHttps_checked())) { transports.add(Constants.PROTOCOL_HTTPS); } body.setTransport(transports); body.isDefaultVersion(false); body.setCacheTimeout(100); if (apiRequest.getOperationsDTOS() != null) { body.setOperations(apiRequest.getOperationsDTOS()); } else { List<APIOperationsDTO> operations = new ArrayList<>(); APIOperationsDTO apiOperationsDTO = new APIOperationsDTO(); if (isAsyncApi(apiRequest)) { apiOperationsDTO.setVerb("SUBSCRIBE"); } else { apiOperationsDTO.setVerb("GET"); } if ("WEBSUB".equalsIgnoreCase(apiRequest.getType())) { apiOperationsDTO.setTarget("_default"); } else { apiOperationsDTO.setTarget("/*"); } apiOperationsDTO.setAuthType("Application & Application User"); apiOperationsDTO.setThrottlingPolicy("Unlimited"); operations.add(apiOperationsDTO); body.setOperations(operations); } body.setMediationPolicies(apiRequest.getMediationPolicies()); body.setBusinessInformation(new APIBusinessInformationDTO()); body.setCorsConfiguration(new APICorsConfigurationDTO()); body.setTags(Arrays.asList(apiRequest.getTags().split(","))); body.setEndpointConfig(apiRequest.getEndpointConfig()); body.setSecurityScheme(apiRequest.getSecurityScheme()); body.setType(APIDTO.TypeEnum.fromValue(apiRequest.getType())); if (StringUtils.isNotBlank(apiRequest.getApiTier())) { body.setApiThrottlingPolicy(apiRequest.getApiTier()); } List<String> tierList = new ArrayList<>(); tierList.add(Constants.TIERS_UNLIMITED); body.setPolicies(Arrays.asList(apiRequest.getTiersCollection().split(","))); body.isDefaultVersion(Boolean.valueOf(apiRequest.getDefault_version_checked())); APIDTO apidto; try { ApiResponse<APIDTO> httpInfo = apIsApi.createAPIWithHttpInfo(body, osVersion); Assert.assertEquals(201, httpInfo.getStatusCode()); apidto = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } return apidto; } public APIDTO addAPI(APIDTO apidto, String osVersion) throws ApiException { ApiResponse<APIDTO> httpInfo = apIsApi.createAPIWithHttpInfo(apidto, osVersion); Assert.assertEquals(201, httpInfo.getStatusCode()); return httpInfo.getData(); } private boolean isAsyncApi(APIRequest apiRequest) { String type = apiRequest.getType(); return "SSE".equalsIgnoreCase(type) || "WS".equalsIgnoreCase(type) || "WEBSUB".equalsIgnoreCase(type); } /** * This method is used to create a new API of the existing API. * * @param newVersion new API version * @param apiId old API ID * @param defaultVersion is this the * @return apiID of the newly created api version. * @throws ApiException Throws if an error occurs when creating the new API version. */ public String createNewAPIVersion(String newVersion, String apiId, boolean defaultVersion) throws ApiException { String apiLocation = apIsApi.createNewAPIVersionWithHttpInfo(newVersion, apiId, defaultVersion, null).getHeaders() .get("Location").get(0); String[] splitValues = apiLocation.split("/"); return splitValues[splitValues.length - 1]; } /** * This method is used to get the JSON content. * * @return API definition. * @throws IOException throws if an error occurred when creating the API. */ private String getJsonContent(String fileName) throws IOException { if (StringUtils.isNotEmpty(fileName)) { return IOUtils.toString(RestAPIPublisherImpl.class.getClassLoader().getResourceAsStream(fileName), StandardCharsets.UTF_8.name()); } return null; } /** * This method is used to publish the created API. * * @param action API id that need to published. * @param apiId API id that need to published. * return ApiResponse<WorkflowResponseDTO> change response. * @throws ApiException throws if an error occurred when publishing the API. */ public HttpResponse changeAPILifeCycleStatus(String apiId, String action, String lifecycleChecklist) throws ApiException { setActivityID(); WorkflowResponseDTO workflowResponseDTO = this.apiLifecycleApi .changeAPILifecycle(action, apiId, lifecycleChecklist, null); HttpResponse response = null; if (StringUtils.isNotEmpty(workflowResponseDTO.getLifecycleState().getState())) { response = new HttpResponse(workflowResponseDTO.getLifecycleState().getState(), 200); } return response; } public WorkflowResponseDTO changeAPILifeCycleStatus(String apiId, String action) throws ApiException { ApiResponse<WorkflowResponseDTO> workflowResponseDTOApiResponse = this.apiLifecycleApi.changeAPILifecycleWithHttpInfo(action, apiId, null, null); Assert.assertEquals(HttpStatus.SC_OK, workflowResponseDTOApiResponse.getStatusCode()); return workflowResponseDTOApiResponse.getData(); } /** * This method is used to deprecate the created API. * * @param apiId API id that need to published. * @throws ApiException throws if an error occurred when publishing the API. */ public void deprecateAPI(String apiId) throws ApiException { apiLifecycleApi.changeAPILifecycle(Constants.DEPRECATE, apiId, null, null); } /** * This method is used to deploy the api as a prototype. * * @param apiId API id that need to be prototyped. * @throws ApiException throws if an error occurred when publishing the API. */ public void deployPrototypeAPI(String apiId) throws ApiException { apiLifecycleApi.changeAPILifecycle(Constants.DEPLOY_AS_PROTOTYPE, apiId, null, null); } /** * This method is used to block the created API. * * @param apiId API id that need to published. * @throws ApiException throws if an error occurred when publishing the API. */ public void blockAPI(String apiId) throws ApiException { apiLifecycleApi.changeAPILifecycle(Constants.BLOCK, apiId, null, null); } public HttpResponse getLifecycleStatus(String apiId) throws ApiException { LifecycleStateDTO lifecycleStateDTO = this.apiLifecycleApi.getAPILifecycleState(apiId, null); HttpResponse response = null; if (StringUtils.isNotEmpty(lifecycleStateDTO.getState())) { response = new HttpResponse(lifecycleStateDTO.getState(), 200); } return response; } public LifecycleStateDTO getLifecycleStatusDTO(String apiId) throws ApiException { ApiResponse<LifecycleStateDTO> apiResponse = this.apiLifecycleApi.getAPILifecycleStateWithHttpInfo(apiId, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public LifecycleHistoryDTO getLifecycleHistory(String apiId) throws ApiException { ApiResponse<LifecycleHistoryDTO> apiResponse = this.apiLifecycleApi.getAPILifecycleHistoryWithHttpInfo(apiId, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } /** * copy API from existing API * * @param newVersion - new version of the API * @param apiId - existing API Id * @param isDefault - make the default version * @return - http response object * @throws APIManagerIntegrationTestException - Throws if error occurred at API copy operation */ public HttpResponse copyAPI(String newVersion, String apiId, Boolean isDefault) throws ApiException { APIDTO apiDto = apIsApi.createNewAPIVersion(newVersion, apiId, isDefault, null); HttpResponse response = null; if (StringUtils.isNotEmpty(apiDto.getId())) { response = new HttpResponse(apiDto.getId(), 200); } return response; } /** * @param newVersion * @param apiId * @param isDefault * @return * @throws ApiException */ public APIDTO copyAPIWithReturnDTO(String newVersion, String apiId, Boolean isDefault) throws ApiException { ApiResponse<APIDTO> response = apIsApi.createNewAPIVersionWithHttpInfo(newVersion, apiId, isDefault, null); Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); return response.getData(); } /** * Facilitate update API * * @param apiRequest - constructed API request object * @return http response object * @throws APIManagerIntegrationTestException - throws if update API fails */ public HttpResponse updateAPI(APIRequest apiRequest, String apiId) throws ApiException { APIDTO body = new APIDTO(); body.setName(apiRequest.getName()); body.setContext(apiRequest.getContext()); body.setVersion(apiRequest.getVersion()); if (apiRequest.getVisibility() != null) { body.setVisibility(APIDTO.VisibilityEnum.valueOf(apiRequest.getVisibility().toUpperCase())); if (APIDTO.VisibilityEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getVisibility()) && StringUtils.isNotEmpty(apiRequest.getRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getRoles().split(" , "))); body.setVisibleRoles(roleList); } } else { body.setVisibility(APIDTO.VisibilityEnum.PUBLIC); } if (apiRequest.getAccessControl() != null) { body.setAccessControl(APIDTO.AccessControlEnum.valueOf(apiRequest.getAccessControl().toUpperCase())); if (APIDTO.AccessControlEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getAccessControl()) && StringUtils.isNotEmpty(apiRequest.getAccessControlRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getAccessControlRoles().split(" , "))); body.setAccessControlRoles(roleList); } } else { body.setAccessControl(APIDTO.AccessControlEnum.NONE); } body.setDescription(apiRequest.getDescription()); body.setProvider(apiRequest.getProvider()); ArrayList<String> transports = new ArrayList<>(); if (Constants.PROTOCOL_HTTP.equals(apiRequest.getHttp_checked())) { transports.add(Constants.PROTOCOL_HTTP); } if (Constants.PROTOCOL_HTTPS.equals(apiRequest.getHttps_checked())) { transports.add(Constants.PROTOCOL_HTTPS); } body.setTransport(transports); body.isDefaultVersion(false); body.setCacheTimeout(100); body.setMediationPolicies(apiRequest.getMediationPolicies()); if (apiRequest.getOperationsDTOS() != null) { body.setOperations(apiRequest.getOperationsDTOS()); } else { List<APIOperationsDTO> operations = new ArrayList<>(); APIOperationsDTO apiOperationsDTO = new APIOperationsDTO(); apiOperationsDTO.setVerb("GET"); apiOperationsDTO.setTarget("/*"); apiOperationsDTO.setAuthType("Application & Application User"); apiOperationsDTO.setThrottlingPolicy("Unlimited"); operations.add(apiOperationsDTO); body.setOperations(operations); } body.setBusinessInformation(new APIBusinessInformationDTO()); body.setCorsConfiguration(new APICorsConfigurationDTO()); body.setTags(Arrays.asList(apiRequest.getTags().split(","))); body.setEndpointConfig(apiRequest.getEndpointConfig()); if (StringUtils.isNotBlank(apiRequest.getApiTier())) { body.setApiThrottlingPolicy(apiRequest.getApiTier()); } List<String> tierList = new ArrayList<>(); tierList.add(Constants.TIERS_UNLIMITED); body.setPolicies(Arrays.asList(apiRequest.getTiersCollection().split(","))); body.setCategories(apiRequest.getApiCategories()); APIDTO apidto; try { apidto = apIsApi.updateAPI(apiId, body, null); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apidto.getId())) { response = new HttpResponse(apidto.getId(), 200); } return response; } public APIDTO updateAPI(APIDTO apidto, String apiId) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.updateAPIWithHttpInfo(apiId, apidto, null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } /** * Method to get API information * * @param apiId - API id * @return http response object * @throws ApiException - Throws if api information cannot be retrieved. */ public HttpResponse getAPI(String apiId) throws ApiException { setActivityID(); APIDTO apidto = null; HttpResponse response = null; Gson gson = new Gson(); try { apidto = apIsApi.getAPI(apiId, null, null); } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(apidto.getId())) { response = new HttpResponse(gson.toJson(apidto), 200); } return response; } /** * delete API * * @param apiId - API id * @return http response object * @throws ApiException - Throws if API delete fails */ public HttpResponse deleteAPI(String apiId) throws ApiException { ApiResponse<Void> deleteResponse = apIsApi.deleteAPIWithHttpInfo(apiId, null); HttpResponse response = null; if (deleteResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully deleted the API", 200); } return response; } public HttpResponse generateMockScript(String apiId) throws ApiException { ApiResponse<String> mockResponse = apIsApi.generateMockScriptsWithHttpInfo(apiId, null); HttpResponse response = null; if (mockResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully generated MockScript", 200); } return response; } public HttpResponse getGenerateMockScript(String apiId) throws ApiException { ApiResponse<MockResponsePayloadListDTO> mockResponse = apIsApi.getGeneratedMockScriptsOfAPIWithHttpInfo(apiId, null); HttpResponse response = null; if (mockResponse.getStatusCode() == 200) { response = new HttpResponse(mockResponse.getData().toString(), 200); } return response; } /** * Remove document * * @param apiId - API id * @param docId - document id * @return http response object * @throws ApiException - Throws if remove API document fails */ public HttpResponse removeDocumentation(String apiId, String docId) throws ApiException { ApiResponse<Void> deleteResponse = apiDocumentsApi.deleteAPIDocumentWithHttpInfo(apiId, docId, null); HttpResponse response = null; if (deleteResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully removed the documentation", 200); } return response; } /** * revoke access token * * @param accessToken - access token already received * @param consumerKey - consumer key returned * @param authUser - user name * @return http response object * @throws APIManagerIntegrationTestException - throws if access token revoke fails */ public HttpResponse revokeAccessToken(String accessToken, String consumerKey, String authUser) throws APIManagerIntegrationTestException { return null; } /** * update permissions to API access * * @param tierName - name of api throttling tier * @param permissionType - permission type * @param roles - roles of permission * @return http response object * @throws APIManagerIntegrationTestException - throws if permission update fails */ public HttpResponse updatePermissions(String tierName, String permissionType, String roles) throws APIManagerIntegrationTestException { return null; } /** * Update resources of API * * @param apiId - API Id * @return http response object * @throws APIManagerIntegrationTestException - throws if API resource update fails */ public HttpResponse updateResourceOfAPI(String apiId, String api) throws APIManagerIntegrationTestException { return null; } /** * Check whether the Endpoint is valid * * @param endpointUrl url of the endpoint * @param apiId id of the api which the endpoint to be validated * @return HttpResponse - Response of the getAPI request * @throws ApiException - Check for valid endpoint fails. */ public HttpResponse checkValidEndpoint(String endpointUrl, String apiId) throws ApiException { ApiEndpointValidationResponseDTO validationResponseDTO = validationApi.validateEndpoint(endpointUrl, apiId); HttpResponse response = null; if (validationResponseDTO.getStatusCode() == 200) { response = new HttpResponse(validationResponseDTO.getStatusMessage(), 200); } return response; } /** * Change the API Lifecycle status to Publish with the option of Re-subscription is required or not * * @param apiId - API ID * @param isRequireReSubscription - true if Re-subscription is required else false. * @return HttpResponse - Response of the API publish event * @throws APIManagerIntegrationTestException - Exception Throws in checkAuthentication() and when do the REST * service calls to do the lifecycle change. */ public HttpResponse changeAPILifeCycleStatusToPublish(String apiId, boolean isRequireReSubscription) throws ApiException { ApiResponse<WorkflowResponseDTO> responseDTOApiResponse = this.apiLifecycleApi.changeAPILifecycleWithHttpInfo( Constants.PUBLISHED, apiId, "Re-Subscription:" + isRequireReSubscription, null); HttpResponse response = null; if (responseDTOApiResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully changed the lifecycle of the API", 200); } return response; } /** * Retrieve the Tier Permission Page * * @return HttpResponse - Response that contains the Tier Permission Page * @throws APIManagerIntegrationTestException - Exception throws from checkAuthentication() method and * HTTPSClientUtils.doGet() method call */ public HttpResponse getTierPermissionsPage() throws APIManagerIntegrationTestException { return null; } /** * Adding a documentation * * @param apiId - Id of the API. * @param body - document Body. * @return HttpResponse - Response with Document adding result. * @throws ApiException - Exception throws if error occurred when adding document. */ public HttpResponse addDocument(String apiId, DocumentDTO body) throws ApiException { DocumentDTO doc = apiDocumentsApi.addAPIDocument(apiId, body, null); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse(doc.getDocumentId(), 200); } return response; } /** * Adding a content to the document * * @param apiId - Id of the API. * @param docId - document Id. * @param docContent - document content * @return HttpResponse - Response with Document adding result. * @throws ApiException - Exception throws if error occurred when adding document. */ public HttpResponse addContentDocument(String apiId, String docId, String docContent) throws ApiException { DocumentDTO doc = apiDocumentsApi.addAPIDocumentContent(apiId, docId, null, null, docContent); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse("Successfully created the documentation", 200); } return response; } /** * Updating the document content using file * * @param apiId - Id of the API. * @param docId - document Id. * @param docContent - file content * @return HttpResponse - Response with Document adding result. * @throws ApiException - Exception throws if error occurred when adding document. */ public HttpResponse updateContentDocument(String apiId, String docId, File docContent) throws ApiException { DocumentDTO doc = apiDocumentsApi.addAPIDocumentContent(apiId, docId, null, docContent, null); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse("Successfully updated the documentation", 200); } return response; } /** * Update API document. * * @param apiId api Id * @param docId document Id * @param documentDTO documentation object. * @return * @throws ApiException Exception throws if error occurred when updating document. */ public HttpResponse updateDocument(String apiId, String docId, DocumentDTO documentDTO) throws ApiException { DocumentDTO doc = apiDocumentsApi.updateAPIDocument(apiId, docId, documentDTO, null); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse("Successfully created the documentation", 200); } return response; } /** * This method is used to get documents * Get Documents for the given limit and offset values * * @param apiId apiId * @return Documents for the given limit and offset values */ public DocumentListDTO getDocuments(String apiId) throws ApiException { ApiResponse<DocumentListDTO> apiResponse = apiDocumentsApi.getAPIDocumentsWithHttpInfo(apiId, null, null, null); Assert.assertEquals(HttpStatus.SC_OK, apiResponse.getStatusCode()); return apiResponse.getData(); } /** * This method is used to get the content of API documents * * @param apiId UUID of the API * @param documentId UUID of the API document * @return * @throws ApiException */ public HttpResponse getDocumentContent(String apiId, String documentId) throws ApiException { ApiResponse<String> apiResponse = apiDocumentsApi.getAPIDocumentContentByDocumentIdWithHttpInfo(apiId, documentId, null); HttpResponse response = null; if (apiResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully retrieved the Document content", 200); } return response; } /** * delete Document * * @param apiId - API id * @param documentId - API id * @return http response object * @throws ApiException - Throws if API delete fails */ public HttpResponse deleteDocument(String apiId, String documentId) throws ApiException { ApiResponse<Void> deleteResponse = apiDocumentsApi.deleteAPIDocumentWithHttpInfo(apiId, documentId, null); HttpResponse response = null; if (deleteResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully deleted the Document", 200); } return response; } /*** * Add a shared scope * * @param scopeDTO * @return ScopeDTO - Returns the added shared scope * @throws ApiException */ public ScopeDTO addSharedScope(ScopeDTO scopeDTO) throws ApiException { ApiResponse<ScopeDTO> httpInfo = sharedScopesApi.addSharedScopeWithHttpInfo(scopeDTO); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_CREATED); return httpInfo.getData(); } /*** * Remove a shared scope * * @param id id of the scope to delete * @throws ApiException */ public void removeSharedScope(String id) throws ApiException { ApiResponse<Void> httpInfo = sharedScopesApi.deleteSharedScopeWithHttpInfo(id); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); } /*** * Update a shared scopes * * @param uuid * @param scopeDTO * @return ScopeDTO - Returns the updated shared scope * @throws ApiException */ public ScopeDTO updateSharedScope(String uuid, ScopeDTO scopeDTO) throws ApiException { ApiResponse<ScopeDTO> httpInfo = sharedScopesApi.updateSharedScopeWithHttpInfo(uuid, scopeDTO); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); return httpInfo.getData(); } /*** * Get a shared scope * * @param uuid * @return ScopeDTO - Returns the updated shared scope * @throws ApiException */ public ScopeDTO getSharedScopeById(String uuid) throws ApiException { ApiResponse<ScopeDTO> httpInfo = sharedScopesApi.getSharedScopeWithHttpInfo(uuid); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); return httpInfo.getData(); } /*** * Delete a shared scope * * @param uuid * @throws ApiException */ public void deleteSharedScope(String uuid) throws ApiException { ApiResponse<Void> httpInfo = sharedScopesApi.deleteSharedScopeWithHttpInfo(uuid); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); } /*** * Get all shared scopes * * @return ScopeListDTO - Returns all the shared scopes * @throws ApiException */ public ScopeListDTO getAllSharedScopes() throws ApiException { ApiResponse<ScopeListDTO> httpInfo = sharedScopesApi.getSharedScopesWithHttpInfo(null, null); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); return httpInfo.getData(); } /** * Retrieve the All APIs available for the user in Publisher. * * @return HttpResponse - Response that contains all available APIs for the user * @throws APIManagerIntegrationTestException - Exception throws from checkAuthentication() method and * HTTPSClientUtils.doGet() method call */ public APIListDTO getAllAPIs() throws APIManagerIntegrationTestException, ApiException { APIListDTO apis = apIsApi.getAllAPIs(null, null, null, null, null, null, null); if (apis.getCount() > 0) { return apis; } return null; } /** * Retrieve the APIs according to the search query in Publisher. * * @param query - The query on which the APIs needs to be filtered * @return SearchResultListDTO - The search results of the query * @throws ApiException */ public SearchResultListDTO searchAPIs(String query) throws ApiException { ApiResponse<SearchResultListDTO> searchResponse = unifiedSearchApi.searchWithHttpInfo(null, null, query, null); Assert.assertEquals(HttpStatus.SC_OK, searchResponse.getStatusCode()); return searchResponse.getData(); } /** * This method is used to upload endpoint certificates * Get APIs for the given limit and offset values * * @param offset starting position * @param limit maximum number of APIs to return * @return APIs for the given limit and offset values */ public APIListDTO getAPIs(int offset, int limit) throws ApiException { setActivityID(); ApiResponse<APIListDTO> apiResponse = apIsApi.getAllAPIsWithHttpInfo(limit, offset, this.tenantDomain, null, null, false, null); Assert.assertEquals(HttpStatus.SC_OK, apiResponse.getStatusCode()); return apiResponse.getData(); } /** * This method is used to upload certificates * * @param certificate certificate * @param alias alis * @param endpoint endpoint. * @return * @throws ApiException if an error occurred while uploading the certificate. */ public ApiResponse<CertMetadataDTO> uploadEndpointCertificate(File certificate, String alias, String endpoint) throws ApiException { ApiResponse<CertMetadataDTO> certificateDTO = endpointCertificatesApi.addEndpointCertificateWithHttpInfo(certificate, alias, endpoint); return certificateDTO; } /** * This method is used to get all throttling tiers. * * @param - API or resource * @return - Response that contains all the available tiers * @throws ApiException */ public ThrottlingPolicyListDTO getTiers(String policyLevel) throws ApiException { ThrottlingPolicyListDTO policies = throttlingPoliciesApi.getAllThrottlingPolicies(policyLevel, null, null, null); if (policies.getCount() > 0) { return policies; } return null; } public SubscriptionPolicyListDTO getSubscriptionPolicies(String tierQuotaTypes) throws ApiException { SubscriptionPolicyListDTO subscriptionPolicyList = throttlingPoliciesApi.getSubscriptionThrottlingPolicies(null, null, null); if (subscriptionPolicyList.getCount() > 0) { return subscriptionPolicyList; } return null; } /** * This method is used to validate roles. * * @param roleId role Id * @return HttpResponse * @throws APIManagerIntegrationTestException */ public ApiResponse<Void> validateRoles(String roleId) throws ApiException { String encodedRoleName = Base64.getUrlEncoder().encodeToString(roleId.getBytes()); return rolesApi.validateSystemRoleWithHttpInfo(encodedRoleName); } public String getSwaggerByID(String apiId) throws ApiException { ApiResponse<String> response = apIsApi.getAPISwaggerWithHttpInfo(apiId, null); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public String updateSwagger(String apiId, String definition) throws ApiException { ApiResponse<String> apiResponse = apIsApi.updateAPISwaggerWithHttpInfo(apiId, null, definition, null, null); Assert.assertEquals(HttpStatus.SC_OK, apiResponse.getStatusCode()); return apiResponse.getData(); } public OpenAPIDefinitionValidationResponseDTO validateOASDefinition(File oasDefinition) throws ApiException { ApiResponse<OpenAPIDefinitionValidationResponseDTO> response = validationApi.validateOpenAPIDefinitionWithHttpInfo(null, null, oasDefinition, null); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO getAPIByID(String apiId, String tenantDomain) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.getAPIWithHttpInfo(apiId, tenantDomain, null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public APIDTO getAPIByID(String apiId) throws ApiException { return apIsApi.getAPI(apiId, tenantDomain, null); } public APIDTO importOASDefinition(File file, String properties) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importOpenAPIDefinitionWithHttpInfo(file, null, properties, null); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public GraphQLValidationResponseDTO validateGraphqlSchemaDefinition(File schemaDefinition) throws ApiException { ApiResponse<GraphQLValidationResponseDTO> response = validationApi.validateGraphQLSchemaWithHttpInfo(schemaDefinition); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO importGraphqlSchemaDefinition(File file, String properties) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importGraphQLSchemaWithHttpInfo(null, "GRAPHQL", file, properties); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public GraphQLSchemaDTO getGraphqlSchemaDefinition(String apiId) throws ApiException { ApiResponse<GraphQLSchemaDTO> schemaDefinitionDTO = graphQlSchemaIndividualApi. getAPIGraphQLSchemaWithHttpInfo(apiId, "application/json", null); Assert.assertEquals(HttpStatus.SC_OK, schemaDefinitionDTO.getStatusCode()); return schemaDefinitionDTO.getData(); } public void updateGraphqlSchemaDefinition(String apiId, String schemaDefinition) throws ApiException { ApiResponse<Void> schemaDefinitionDTO = graphQlSchemaApi.updateAPIGraphQLSchemaWithHttpInfo (apiId, schemaDefinition, null); Assert.assertEquals(HttpStatus.SC_OK, schemaDefinitionDTO.getStatusCode()); } public WSDLValidationResponseDTO validateWsdlDefinition(String url, File wsdlDefinition) throws ApiException { ApiResponse<WSDLValidationResponseDTO> response = validationApi .validateWSDLDefinitionWithHttpInfo(url, wsdlDefinition); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO importWSDLSchemaDefinition(File file, String url, String properties, String type) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importWSDLDefinitionWithHttpInfo(file, url, properties, type); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public ApiResponse<Void> getWSDLSchemaDefinitionOfAPI(String apiId) throws ApiException { ApiResponse<Void> apiDtoApiResponse = apIsApi.getWSDLOfAPIWithHttpInfo(apiId,null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse; } public ResourcePolicyListDTO getApiResourcePolicies(String apiId, String sequenceType, String resourcePath, String verb) throws ApiException { ApiResponse<ResourcePolicyListDTO> policyListDTOApiResponse = apiResourcePoliciesApi .getAPIResourcePoliciesWithHttpInfo(apiId, sequenceType, resourcePath, verb, null); Assert.assertEquals(policyListDTOApiResponse.getStatusCode(), HttpStatus.SC_OK); return policyListDTOApiResponse.getData(); } public ResourcePolicyInfoDTO updateApiResourcePolicies(String apiId, String resourcePolicyId, String resourcePath, ResourcePolicyInfoDTO resourcePolicyInfoDTO, String verb) throws ApiException { ApiResponse<ResourcePolicyInfoDTO> response = apiResourcePoliciesApi .updateAPIResourcePoliciesByPolicyIdWithHttpInfo(apiId, resourcePolicyId, resourcePolicyInfoDTO, null); Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_OK); return response.getData(); } public AsyncAPISpecificationValidationResponseDTO validateAsyncAPISchemaDefinition(String url, File file) throws ApiException { ApiResponse<AsyncAPISpecificationValidationResponseDTO> response = validationApi .validateAsyncAPISpecificationWithHttpInfo(false, url, file); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO importAsyncAPISchemaDefinition(File file, String url, String properties) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importAsyncAPISpecificationWithHttpInfo(file, url, properties); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public ApiResponse<Void> getAsyncAPIDefinitionOfAPI(String apiId) throws ApiException { ApiResponse<Void> apiDtoApiResponse = apIsApi.getWSDLOfAPIWithHttpInfo(apiId,null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse; } public APIDTO addAPI(APICreationRequestBean apiCreationRequestBean) throws ApiException { APIDTO body = new APIDTO(); body.setName(apiCreationRequestBean.getName()); body.setContext(apiCreationRequestBean.getContext()); body.setVersion(apiCreationRequestBean.getVersion()); if (apiCreationRequestBean.getVisibility() != null) { body.setVisibility(APIDTO.VisibilityEnum.valueOf(apiCreationRequestBean.getVisibility().toUpperCase())); if (APIDTO.VisibilityEnum.RESTRICTED.getValue().equalsIgnoreCase(apiCreationRequestBean.getVisibility()) && StringUtils.isNotEmpty(apiCreationRequestBean.getRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiCreationRequestBean.getRoles().split(" , "))); body.setVisibleRoles(roleList); } } else { body.setVisibility(APIDTO.VisibilityEnum.PUBLIC); } body.setDescription(apiCreationRequestBean.getDescription()); body.setProvider(apiCreationRequestBean.getProvider()); body.setTransport(new ArrayList<String>() {{ add(Constants.PROTOCOL_HTTP); add(Constants.PROTOCOL_HTTPS); }}); body.isDefaultVersion(false); body.setCacheTimeout(100); List<APIOperationsDTO> operations = new ArrayList<>(); for (APIResourceBean resourceBean : apiCreationRequestBean.getResourceBeanList()) { APIOperationsDTO dto = new APIOperationsDTO(); dto.setTarget(resourceBean.getUriTemplate()); dto.setAuthType(resourceBean.getResourceMethodAuthType()); dto.setVerb(resourceBean.getResourceMethod()); dto.setThrottlingPolicy(resourceBean.getResourceMethodThrottlingTier()); operations.add(dto); } body.setOperations(operations); body.setBusinessInformation(new APIBusinessInformationDTO()); body.setCorsConfiguration(new APICorsConfigurationDTO()); body.setTags(Arrays.asList(apiCreationRequestBean.getTags().split(","))); if (apiCreationRequestBean.getSetEndpointSecurityDirectlyToEndpoint()) { try { body.setEndpointConfig(new JSONParser().parse(apiCreationRequestBean.getEndpoint().toString())); } catch (ParseException e) { throw new ApiException(e); } } else { JSONObject jsonObject = new JSONObject(); jsonObject.put("endpoint_type", "http"); JSONObject sandUrl = new JSONObject(); sandUrl.put("url", apiCreationRequestBean.getEndpointUrl().toString()); jsonObject.put("sandbox_endpoints", sandUrl); jsonObject.put("production_endpoints", sandUrl); if ("basic".equalsIgnoreCase(apiCreationRequestBean.getEndpointType())) { JSONObject endpointSecurityGlobal = new JSONObject(); endpointSecurityGlobal.put("enabled", true); endpointSecurityGlobal.put("type", "basic"); endpointSecurityGlobal.put("username", apiCreationRequestBean.getEpUsername()); endpointSecurityGlobal.put("password", apiCreationRequestBean.getEpPassword()); JSONObject endpointSecurity = new JSONObject(); endpointSecurity.put("production", endpointSecurityGlobal); endpointSecurity.put("sandbox", endpointSecurityGlobal); jsonObject.put("endpoint_security", endpointSecurity); } body.setEndpointConfig(jsonObject); } List<String> tierList = new ArrayList<>(); tierList.add(Constants.TIERS_UNLIMITED); if (apiCreationRequestBean.getSubPolicyCollection() != null) { String[] tiers = apiCreationRequestBean.getSubPolicyCollection().split(","); for (String tier : tiers) { tierList.add(tier); } } body.setPolicies(tierList); ApiResponse<APIDTO> httpInfo = apIsApi.createAPIWithHttpInfo(body, "v3"); Assert.assertEquals(201, httpInfo.getStatusCode()); return httpInfo.getData(); } /** * This method is used to upload certificates * * @param certificate certificate * @param alias alis * @return * @throws ApiException if an error occurred while uploading the certificate. */ public HttpResponse uploadCertificate(File certificate, String alias, String apiId, String tier) throws ApiException { ClientCertMetadataDTO certificateDTO = clientCertificatesApi.addAPIClientCertificate(apiId, certificate, alias, tier); HttpResponse response = null; if (StringUtils.isNotEmpty(certificateDTO.getAlias())) { response = new HttpResponse("Successfully uploaded the certificate", 200); } return response; } /** * Update an API * * @param apidto * @return * @throws ApiException */ public APIDTO updateAPI(APIDTO apidto) throws ApiException { ApiResponse<APIDTO> response = apIsApi.updateAPIWithHttpInfo(apidto.getId(), apidto, null); Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_OK); return response.getData(); } /** * Get subscription of an API * * @param apiID * @return * @throws ApiException */ public SubscriptionListDTO getSubscriptionByAPIID(String apiID) throws ApiException { ApiResponse<SubscriptionListDTO> apiResponse = subscriptionsApi.getSubscriptionsWithHttpInfo(apiID, 10, 0, null, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public APIProductListDTO getAllApiProducts() throws ApiException { ApiResponse<APIProductListDTO> apiResponse = apiProductsApi.getAllAPIProductsWithHttpInfo(null, null, null, null, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public APIProductDTO getApiProduct(String apiProductId) throws ApiException { ApiResponse<APIProductDTO> apiResponse = apiProductsApi.getAPIProductWithHttpInfo(apiProductId, null, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public APIProductDTO addApiProduct(APIProductDTO apiProductDTO) throws ApiException { ApiResponse<APIProductDTO> apiResponse = apiProductsApi.createAPIProductWithHttpInfo(apiProductDTO); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_CREATED); return apiResponse.getData(); } public void deleteApiProduct(String apiProductId) throws ApiException { ApiResponse<Void> apiResponse = apiProductsApi.deleteAPIProductWithHttpInfo(apiProductId, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); } /** * Method to retrieve the Audit Report of an API * * @param apiId apiId of the API * @return HttpResponse response * @throws ApiException */ public HttpResponse getAuditApi(String apiId) throws ApiException { HttpResponse response = null; ApiResponse<AuditReportDTO> auditReportResponse = apiAuditApi .getAuditReportOfAPIWithHttpInfo(apiId, "application/json"); if (auditReportResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully audited the report", 200); } return response; } /** * Method to retrieve the GraphQL Schema Type List * * @param apiId apiId of the API * @return HttpResponse response * @throws ApiException */ public HttpResponse getGraphQLSchemaTypeListResponse(String apiId) throws ApiException { HttpResponse response = null; ApiResponse<GraphQLSchemaTypeListDTO> graphQLSchemaTypeListDTOApiResponse = graphQlPoliciesApi .getGraphQLPolicyComplexityTypesOfAPIWithHttpInfo(apiId); if (graphQLSchemaTypeListDTOApiResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully get the GraphQL Schema Type List", 200); } return response; } /** * Method to retrieve the GraphQL Schema Type List * * @param apiId apiId of the API * @return GraphQLSchemaTypeListDTO GraphQLSchemaTypeList object * @throws ApiException */ public GraphQLSchemaTypeListDTO getGraphQLSchemaTypeList(String apiId) throws ApiException { ApiResponse<GraphQLSchemaTypeListDTO> graphQLSchemaTypeListDTOApiResponse = graphQlPoliciesApi .getGraphQLPolicyComplexityTypesOfAPIWithHttpInfo(apiId); Assert.assertEquals(graphQLSchemaTypeListDTOApiResponse.getStatusCode(), HttpStatus.SC_OK); return graphQLSchemaTypeListDTOApiResponse.getData(); } /** * Method to add GraphQL Complexity Info of an API * * @param apiID * @param graphQLQueryComplexityInfoDTO GraphQL Complexity Object * @return * @throws ApiException */ public void addGraphQLComplexityDetails(GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO, String apiID) throws ApiException { ApiResponse<Void> apiResponse = graphQlPoliciesApi.updateGraphQLPolicyComplexityOfAPIWithHttpInfo(apiID, graphQLQueryComplexityInfoDTO); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); } /** * Method to retrieve the GraphQL Complexity Details * * @param apiId apiId of the API * @return HttpResponse response * @throws ApiException */ public HttpResponse getGraphQLComplexityResponse(String apiId) throws ApiException { HttpResponse response = null; ApiResponse<GraphQLQueryComplexityInfoDTO> complexityResponse = graphQlPoliciesApi .getGraphQLPolicyComplexityOfAPIWithHttpInfo(apiId); if (complexityResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully get the GraphQL Complexity Details", 200); } return response; } /** * This method is used to create an API Revision. * * @param apiRevisionRequest API Revision create object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse addAPIRevision(APIRevisionRequest apiRevisionRequest) throws ApiException { setActivityID(); APIRevisionDTO apiRevisionDTO = new APIRevisionDTO(); apiRevisionDTO.setDescription(apiRevisionRequest.getDescription()); Gson gson = new Gson(); try { ApiResponse<APIRevisionDTO> httpInfo = apiRevisionsApi. createAPIRevisionWithHttpInfo(apiRevisionRequest.getApiUUID(), apiRevisionDTO); Assert.assertEquals(201, httpInfo.getStatusCode()); apiRevisionDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; if (apiRevisionDTO != null && StringUtils.isNotEmpty(apiRevisionDTO.getId())) { response = new HttpResponse(gson.toJson(apiRevisionDTO), 201); } return response; } /** * This method is used to create an API Revision. * * @param apiId API Revision create object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public APIRevisionDTO addAPIRevision(String apiId) throws ApiException { APIRevisionDTO apiRevisionDTO = new APIRevisionDTO(); Gson gson = new Gson(); try { ApiResponse<APIRevisionDTO> httpInfo = apiRevisionsApi. createAPIRevisionWithHttpInfo(apiId, apiRevisionDTO); Assert.assertEquals(201, httpInfo.getStatusCode()); return httpInfo.getData(); } catch (ApiException e) { throw new ApiException(e); } } /** * Method to get API Revisions per API * * @param apiUUID - API uuid * @param query - Search query * @return http response object * @throws ApiException - Throws if api information cannot be retrieved. */ public HttpResponse getAPIRevisions(String apiUUID, String query) throws ApiException { APIRevisionListDTO apiRevisionListDTO = null; HttpResponse response = null; Gson gson = new Gson(); try { apiRevisionListDTO = apiRevisionsApi.getAPIRevisions(apiUUID, query); } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(apiRevisionListDTO.getList().toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } /** * This method is used to deploy API Revision to Gateways. * * @param apiRevisionDeployRequestList API Revision deploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deployAPIRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionDeployRequestList, String apiType) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionDeployRequest : apiRevisionDeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionDeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionDeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionDeployRequest.isDisplayOnDevportal()); apiRevisionDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<List<APIRevisionDeploymentDTO>> httpInfo = apiRevisionsApi.deployAPIRevisionWithHttpInfo(apiUUID, revisionUUID, apiRevisionDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForDeployAPI(apiUUID, revisionUUID, apiType); //apiRevisionDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // if (StringUtils.isNotEmpty(apiRevisionDeploymentDTOResponseList.toString())) { // response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // } return response; } /** * This method is used to deploy API Revision to Gateways. * * @param apiRevisionDeployRequestList API Revision deploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deployAPIRevision(String apiUUID, String revisionUUID, APIRevisionDeployUndeployRequest apiRevisionDeployRequest, String apiType) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOResponseList = new ArrayList<>(); APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionDeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionDeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionDeployRequest.isDisplayOnDevportal()); apiRevisionDeploymentDTOList.add(apiRevisionDeploymentDTO); try { ApiResponse<List<APIRevisionDeploymentDTO>> httpInfo = apiRevisionsApi.deployAPIRevisionWithHttpInfo(apiUUID, revisionUUID, apiRevisionDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForDeployAPI(apiUUID,revisionUUID, apiType); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); return response; } private void waitForDeployAPI(String apiUUID, String revisionUUID, String apiType) throws ApiException, APIManagerIntegrationTestException { if (Boolean.parseBoolean(disableVerification)){ return; } String context, version, provider, name, apiPolicy; if ("APIProduct".equals(apiType)) { APIProductDTO apiProduct = getApiProduct(revisionUUID); context = apiProduct.getContext(); version = "1.0.0"; provider = apiProduct.getProvider(); name = apiProduct.getName(); apiPolicy = apiProduct.getApiThrottlingPolicy(); } else { APIDTO api = getAPIByID(revisionUUID); context = api.getContext(); version = api.getVersion(); provider = api.getProvider(); name = api.getName(); apiPolicy = api.getApiThrottlingPolicy(); } APIInfoDTO apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo != null) { if (!"APIProduct".equals(apiType)) { if (context.startsWith("/{version}")) { Assert.assertEquals(apiInfo.getContext(), context.replace("{version}", version)); } else { Assert.assertEquals(apiInfo.getContext(), context.concat("/").concat(version)); } } else { Assert.assertEquals(apiInfo.getContext(), context); } Assert.assertEquals(apiInfo.getName(), name); Assert.assertEquals(apiInfo.getProvider(), provider); if (!StringUtils.equals(apiPolicy, apiInfo.getPolicy())) { int retries = 0; while (retries <= 5) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (!StringUtils.equals(apiPolicy, apiInfo.getPolicy())) { retries++; } else { break; } } } return; } int retries = 0; while (retries <= 20) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo != null) { if (!"APIProduct".equals(apiType)) { if (context.startsWith("/{version}")) { Assert.assertEquals(apiInfo.getContext(), context.replace("{version}", version)); } else { Assert.assertEquals(apiInfo.getContext(), context.concat("/").concat(version)); } } else { Assert.assertEquals(apiInfo.getContext(), context); } Assert.assertEquals(apiInfo.getName(), name); Assert.assertEquals(apiInfo.getProvider(), provider); break; } retries++; } } /** * This method is used to undeploy API Revision to Gateways. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @param apiRevisionUndeployRequestList API Revision undeploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when undeploying the API Revision. */ public HttpResponse undeployAPIRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionUndeployRequestList) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionUndeployRequest : apiRevisionUndeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionUndeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionUndeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionUndeployRequest.isDisplayOnDevportal()); apiRevisionUnDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<Void> httpInfo = apiRevisionsApi.undeployAPIRevisionWithHttpInfo(apiUUID, revisionUUID, null, false, apiRevisionUnDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForUnDeployAPI(apiUUID); //apiRevisionUnDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionUnDeploymentDTOResponseList), 201); return response; } private void waitForUnDeployAPI(String apiUUID) throws APIManagerIntegrationTestException { if (Boolean.parseBoolean(disableVerification)) { return; } APIInfoDTO apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo == null) { return; } int retries = 0; while (retries <= 20) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo == null) { break; } retries++; } } /** * This method is used to restore an API Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse restoreAPIRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIDTO apidto = null; try { ApiResponse<APIDTO> httpInfo = apiRevisionsApi.restoreAPIRevisionWithHttpInfo(apiUUID, revisionUUID); Assert.assertEquals(201, httpInfo.getStatusCode()); apidto = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apidto.toString())) { response = new HttpResponse(gson.toJson(apidto), 201); } return response; } /** * This method is used to delete an API Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deleteAPIRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIRevisionListDTO apiRevisionListDTO = null; try { ApiResponse<APIRevisionListDTO> httpInfo = apiRevisionsApi.deleteAPIRevisionWithHttpInfo(apiUUID, revisionUUID); Assert.assertEquals(200, httpInfo.getStatusCode()); apiRevisionListDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apiRevisionListDTO.toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } public MediationListDTO retrieveMediationPolicies() throws ApiException { return globalMediationPoliciesApi.getAllGlobalMediationPolicies(100, 0, null, null); } /** * This method is used to create an API Product Revision. * * @param apiRevisionRequest API Revision create object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse addAPIProductRevision(APIRevisionRequest apiRevisionRequest) throws ApiException { APIRevisionDTO apiRevisionDTO = new APIRevisionDTO(); apiRevisionDTO.setDescription(apiRevisionRequest.getDescription()); Gson gson = new Gson(); try { ApiResponse<APIRevisionDTO> httpInfo = apiProductRevisionsApi. createAPIProductRevisionWithHttpInfo(apiRevisionRequest.getApiUUID(), apiRevisionDTO); Assert.assertEquals(201, httpInfo.getStatusCode()); apiRevisionDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (apiRevisionDTO != null && StringUtils.isNotEmpty(apiRevisionDTO.getId())) { response = new HttpResponse(gson.toJson(apiRevisionDTO), 201); } return response; } /** * Method to get API Product Revisions per API * * @param apiUUID - API uuid * @param query - Search query * @return http response object * @throws ApiException - Throws if api information cannot be retrieved. */ public HttpResponse getAPIProductRevisions(String apiUUID, String query) throws ApiException { APIRevisionListDTO apiRevisionListDTO = null; HttpResponse response = null; Gson gson = new Gson(); try { apiRevisionListDTO = apiProductRevisionsApi.getAPIProductRevisions(apiUUID, query); } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(apiRevisionListDTO.getList().toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } /** * This method is used to deploy API Product Revision to Gateways. * * @param apiRevisionDeployRequestList API Revision deploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deployAPIProductRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionDeployRequestList, String apiType) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionDeployRequest : apiRevisionDeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionDeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionDeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionDeployRequest.isDisplayOnDevportal()); apiRevisionDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<Void> httpInfo = apiProductRevisionsApi.deployAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID, apiRevisionDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForDeployAPI(apiUUID, revisionUUID, apiType); //apiRevisionDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // if (StringUtils.isNotEmpty(apiRevisionDeploymentDTOResponseList.toString())) { // response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // } return response; } /** * This method is used to undeploy API Product Revision to Gateways. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @param apiRevisionUndeployRequestList API Revision undeploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when undeploying the API Revision. */ public HttpResponse undeployAPIProductRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionUndeployRequestList) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionUndeployRequest : apiRevisionUndeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionUndeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionUndeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionUndeployRequest.isDisplayOnDevportal()); apiRevisionUnDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<Void> httpInfo = apiProductRevisionsApi.undeployAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID, null, false, apiRevisionUnDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForUnDeployAPI(apiUUID); //apiRevisionUnDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionUnDeploymentDTOResponseList), 201); // if (StringUtils.isNotEmpty(apiRevisionUnDeploymentDTOResponseList.toString())) { // response = new HttpResponse(gson.toJson(apiRevisionUnDeploymentDTOResponseList), 201); // } return response; } /** * This method is used to restore an API Product Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse restoreAPIProductRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIProductDTO apiProductDTO = null; try { ApiResponse<APIProductDTO> httpInfo = apiProductRevisionsApi.restoreAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID); Assert.assertEquals(201, httpInfo.getStatusCode()); apiProductDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apiProductDTO.toString())) { response = new HttpResponse(gson.toJson(apiProductDTO), 201); } return response; } /** * This method is used to delete an API product Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deleteAPIProductRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIRevisionListDTO apiRevisionListDTO = null; try { ApiResponse<APIRevisionListDTO> httpInfo = apiProductRevisionsApi.deleteAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID); Assert.assertEquals(200, httpInfo.getStatusCode()); apiRevisionListDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apiRevisionListDTO.toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } public ApiResponse<APIKeyDTO> generateInternalApiKey(String apiId) throws ApiException { return apIsApi.generateInternalAPIKeyWithHttpInfo(apiId); } /** * Add comment to given API * * @param apiId - api Id * @param comment - comment to add * @param category - category of the comment * @param replyTo - comment id of the root comment to add replies * @return - http response of add comment * @throws ApiException - throws if add comment fails */ public HttpResponse addComment(String apiId, String comment, String category, String replyTo) throws ApiException { PostRequestBodyDTO postRequestBodyDTO = new PostRequestBodyDTO(); postRequestBodyDTO.setContent(comment); postRequestBodyDTO.setCategory(category); Gson gson = new Gson(); CommentDTO commentDTO = commentsApi.addCommentToAPI(apiId, postRequestBodyDTO, replyTo); HttpResponse response = null; if (commentDTO != null) { response = new HttpResponse(gson.toJson(commentDTO), 200); } return response; } /** * Get Comment from given API * * @param commentId - comment Id * @param apiId - api Id * @param tenantDomain - tenant domain * @param limit - for pagination * @param offset - for pagination * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse getComment(String commentId, String apiId, String tenantDomain, boolean includeCommentorInfo, Integer limit, Integer offset) throws ApiException { CommentDTO commentDTO; HttpResponse response = null; Gson gson = new Gson(); try { commentDTO = commentsApi.getCommentOfAPI(commentId, apiId, tenantDomain, null, includeCommentorInfo, limit, offset); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(commentDTO.getId())) { response = new HttpResponse(gson.toJson(commentDTO), 200); } return response; } /** * Get all the comments from given API * * @param apiId - api Id * @param tenantDomain - tenant domain * @param limit - for pagination * @param offset - for pagination * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse getComments(String apiId, String tenantDomain, boolean includeCommentorInfo, Integer limit, Integer offset) throws ApiException { CommentListDTO commentListDTO; HttpResponse response = null; Gson gson = new Gson(); try { commentListDTO = commentsApi.getAllCommentsOfAPI(apiId, tenantDomain, limit, offset, includeCommentorInfo); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (commentListDTO.getCount() > 0) { response = new HttpResponse(gson.toJson(commentListDTO), 200); } return response; } /** * Get replies of a comment from given API * * @param commentId - comment Id * @param apiId - api Id * @param tenantDomain - tenant domain * @param limit - for pagination * @param offset - for pagination * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse getReplies(String commentId, String apiId, String tenantDomain, boolean includeCommentorInfo, Integer limit, Integer offset) throws ApiException { CommentListDTO commentListDTO; HttpResponse response = null; Gson gson = new Gson(); try { commentListDTO = commentsApi.getRepliesOfComment(commentId, apiId, tenantDomain, limit, offset, null, includeCommentorInfo); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (commentListDTO.getCount() > 0) { response = new HttpResponse(gson.toJson(commentListDTO), 200); } return response; } /** * Get Comment from given API * * @param commentId - comment Id * @param apiId - api Id * @param comment - comment to add * @param category - category of the comment * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse editComment(String commentId, String apiId, String comment, String category) throws ApiException { HttpResponse response = null; Gson gson = new Gson(); try { PatchRequestBodyDTO patchRequestBodyDTO = new PatchRequestBodyDTO(); patchRequestBodyDTO.setCategory(category); patchRequestBodyDTO.setContent(comment); CommentDTO editedCommentDTO = commentsApi.editCommentOfAPI(commentId, apiId, patchRequestBodyDTO); if (editedCommentDTO != null) { response = new HttpResponse(gson.toJson(editedCommentDTO), 200); } else { response = new HttpResponse(null, 200); } } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } return response; } /** * Remove comment in given API * * @param commentId - comment Id * @param apiId - api Id * @throws ApiException - throws if remove comment fails */ public HttpResponse removeComment(String commentId, String apiId) throws ApiException { HttpResponse response; try { commentsApi.deleteComment(commentId, apiId, null); response = new HttpResponse("Successfully deleted the comment", 200); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { response = new HttpResponse("Failed to delete the comment", e.getCode()); } return response; } public ApiResponse<APIProductDTO> updateAPIProduct(APIProductDTO apiProductDTO) throws ApiException { return apiProductsApi.updateAPIProductWithHttpInfo(apiProductDTO.getId(), apiProductDTO, null); } public CertificatesDTO getEndpointCertificiates(String endpoint, String alias) throws ApiException { return endpointCertificatesApi.getEndpointCertificates(Integer.MAX_VALUE, 0, alias, endpoint); } public org.wso2.am.integration.clients.publisher.api.v1.dto.CertificateInfoDTO getendpointCertificateContent(String alias) throws ApiException { return endpointCertificatesApi.getEndpointCertificateByAlias(alias); } public ApiResponse<Void> deleteEndpointCertificate(String alias) throws ApiException { return endpointCertificatesApi.deleteEndpointCertificateByAliasWithHttpInfo(alias); } private void setActivityID() { apiPublisherClient.addDefaultHeader("activityID", System.getProperty(testNameProperty)); } }
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/impl/RestAPIPublisherImpl.java
/* * Copyright (c) 2019, WSO2 Inc. (http://wso2.com) 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 org.wso2.am.integration.test.impl; import com.google.gson.Gson; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.HttpStatus; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import org.testng.Assert; import org.wso2.am.integration.clients.gateway.api.v2.dto.APIInfoDTO; import org.wso2.am.integration.clients.publisher.api.ApiClient; import org.wso2.am.integration.clients.publisher.api.ApiException; import org.wso2.am.integration.clients.publisher.api.ApiResponse; import org.wso2.am.integration.clients.publisher.api.v1.ApIsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiAuditApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiDocumentsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiLifecycleApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiProductRevisionsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiProductsApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiResourcePoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.ApiRevisionsApi; import org.wso2.am.integration.clients.publisher.api.v1.ClientCertificatesApi; import org.wso2.am.integration.clients.publisher.api.v1.CommentsApi; import org.wso2.am.integration.clients.publisher.api.v1.EndpointCertificatesApi; import org.wso2.am.integration.clients.publisher.api.v1.GlobalMediationPoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.GraphQlPoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.GraphQlSchemaApi; import org.wso2.am.integration.clients.publisher.api.v1.GraphQlSchemaIndividualApi; import org.wso2.am.integration.clients.publisher.api.v1.RolesApi; import org.wso2.am.integration.clients.publisher.api.v1.ScopesApi; import org.wso2.am.integration.clients.publisher.api.v1.SubscriptionsApi; import org.wso2.am.integration.clients.publisher.api.v1.ThrottlingPoliciesApi; import org.wso2.am.integration.clients.publisher.api.v1.UnifiedSearchApi; import org.wso2.am.integration.clients.publisher.api.v1.ValidationApi; import org.wso2.am.integration.clients.publisher.api.v1.dto.*; import org.wso2.am.integration.test.ClientAuthenticator; import org.wso2.am.integration.test.Constants; import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException; import org.wso2.am.integration.test.utils.bean.APICreationRequestBean; import org.wso2.am.integration.test.utils.bean.APIRequest; import org.wso2.am.integration.test.utils.bean.APIResourceBean; import org.wso2.am.integration.test.utils.bean.APIRevisionDeployUndeployRequest; import org.wso2.am.integration.test.utils.bean.APIRevisionRequest; import org.wso2.carbon.automation.test.utils.http.client.HttpResponse; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Base64; import java.util.List; /** * This util class performs the actions related to APIDTOobjects. */ public class RestAPIPublisherImpl { public static final String appName = "Integration_Test_App_Publisher"; public static final String callBackURL = "test.com"; public static final String tokenScope = "Production"; public static final String appOwner = "admin"; public static final String grantType = "password"; public static final String username = "admin"; public static final String password = "admin"; public static final String testNameProperty = "testName"; public ApIsApi apIsApi = new ApIsApi(); public ApiDocumentsApi apiDocumentsApi = new ApiDocumentsApi(); public ApiRevisionsApi apiRevisionsApi = new ApiRevisionsApi(); public ApiResourcePoliciesApi apiResourcePoliciesApi = new ApiResourcePoliciesApi(); public ApiProductRevisionsApi apiProductRevisionsApi = new ApiProductRevisionsApi(); public ThrottlingPoliciesApi throttlingPoliciesApi = new ThrottlingPoliciesApi(); public ClientCertificatesApi clientCertificatesApi = new ClientCertificatesApi(); public EndpointCertificatesApi endpointCertificatesApi = new EndpointCertificatesApi(); public GraphQlSchemaApi graphQlSchemaApi = new GraphQlSchemaApi(); public GraphQlSchemaIndividualApi graphQlSchemaIndividualApi = new GraphQlSchemaIndividualApi(); public ApiLifecycleApi apiLifecycleApi = new ApiLifecycleApi(); public CommentsApi commentsApi = new CommentsApi(); public RolesApi rolesApi = new RolesApi(); public ValidationApi validationApi = new ValidationApi(); public SubscriptionsApi subscriptionsApi = new SubscriptionsApi(); public ApiAuditApi apiAuditApi = new ApiAuditApi(); public GraphQlPoliciesApi graphQlPoliciesApi = new GraphQlPoliciesApi(); public UnifiedSearchApi unifiedSearchApi = new UnifiedSearchApi(); public GlobalMediationPoliciesApi globalMediationPoliciesApi = new GlobalMediationPoliciesApi(); public ScopesApi sharedScopesApi = new ScopesApi(); public ApiClient apiPublisherClient = new ApiClient(); public String tenantDomain; private ApiProductsApi apiProductsApi = new ApiProductsApi(); private RestAPIGatewayImpl restAPIGateway; private String disableVerification = System.getProperty("disableVerification"); @Deprecated public RestAPIPublisherImpl() { this(username, password, "", "https://localhost:9943"); } public RestAPIPublisherImpl(String username, String password, String tenantDomain, String publisherURL) { // token/DCR of Publisher node itself will be used String tokenURL = publisherURL + "oauth2/token"; String dcrURL = publisherURL + "client-registration/v0.17/register"; String accessToken = ClientAuthenticator .getAccessToken("openid apim:api_view apim:api_create apim:api_delete apim:api_publish " + "apim:subscription_view apim:subscription_block apim:external_services_discover " + "apim:threat_protection_policy_create apim:threat_protection_policy_manage " + "apim:document_create apim:document_manage apim:mediation_policy_view " + "apim:mediation_policy_create apim:mediation_policy_manage " + "apim:client_certificates_view apim:client_certificates_add " + "apim:client_certificates_update apim:ep_certificates_view " + "apim:ep_certificates_add apim:ep_certificates_update apim:publisher_settings " + "apim:pub_alert_manage apim:shared_scope_manage apim:api_generate_key apim:comment_view " + "apim:comment_write", appName, callBackURL, tokenScope, appOwner, grantType, dcrURL, username, password, tenantDomain, tokenURL); apiPublisherClient.addDefaultHeader("Authorization", "Bearer " + accessToken); apiPublisherClient.setBasePath(publisherURL + "api/am/publisher/v2"); apiPublisherClient.setDebugging(true); apiPublisherClient.setReadTimeout(600000); apiPublisherClient.setConnectTimeout(600000); apiPublisherClient.setWriteTimeout(600000); apIsApi.setApiClient(apiPublisherClient); apiProductsApi.setApiClient(apiPublisherClient); apiRevisionsApi.setApiClient(apiPublisherClient); apiResourcePoliciesApi.setApiClient(apiPublisherClient); apiProductRevisionsApi.setApiClient(apiPublisherClient); graphQlSchemaApi.setApiClient(apiPublisherClient); commentsApi.setApiClient(apiPublisherClient); graphQlSchemaIndividualApi.setApiClient(apiPublisherClient); apiDocumentsApi.setApiClient(apiPublisherClient); throttlingPoliciesApi.setApiClient(apiPublisherClient); apiLifecycleApi.setApiClient(apiPublisherClient); rolesApi.setApiClient(apiPublisherClient); validationApi.setApiClient(apiPublisherClient); clientCertificatesApi.setApiClient(apiPublisherClient); subscriptionsApi.setApiClient(apiPublisherClient); graphQlPoliciesApi.setApiClient(apiPublisherClient); apiAuditApi.setApiClient(apiPublisherClient); unifiedSearchApi.setApiClient(apiPublisherClient); sharedScopesApi.setApiClient(apiPublisherClient); globalMediationPoliciesApi.setApiClient(apiPublisherClient); endpointCertificatesApi.setApiClient(apiPublisherClient); this.tenantDomain = tenantDomain; this.restAPIGateway = new RestAPIGatewayImpl(this.username, this.password, tenantDomain); } /** * \ * This method is used to create an API. * * @param apiRequest * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API. */ public HttpResponse addAPI(APIRequest apiRequest) throws ApiException { String osVersion = "v3"; setActivityID(); APIDTO apidto = this.addAPI(apiRequest, osVersion); HttpResponse response = null; if (apidto != null && StringUtils.isNotEmpty(apidto.getId())) { response = new HttpResponse(apidto.getId(), 201); } return response; } /** * \ * This method is used to create an API. * * @param apiRequest * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API. */ public APIDTO addAPI(APIRequest apiRequest, String osVersion) throws ApiException { APIDTO body = new APIDTO(); body.setName(apiRequest.getName()); body.setContext(apiRequest.getContext()); body.setVersion(apiRequest.getVersion()); if (apiRequest.getVisibility() != null) { body.setVisibility(APIDTO.VisibilityEnum.valueOf(apiRequest.getVisibility().toUpperCase())); if (APIDTO.VisibilityEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getVisibility()) && StringUtils.isNotEmpty(apiRequest.getRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getRoles().split(" , "))); body.setVisibleRoles(roleList); } } else { body.setVisibility(APIDTO.VisibilityEnum.PUBLIC); } if (apiRequest.getAccessControl() != null) { body.setAccessControl(APIDTO.AccessControlEnum.valueOf(apiRequest.getAccessControl().toUpperCase())); if (APIDTO.AccessControlEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getAccessControl()) && StringUtils.isNotEmpty(apiRequest.getAccessControlRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getAccessControlRoles().split(" , "))); body.setAccessControlRoles(roleList); } } else { body.setAccessControl(APIDTO.AccessControlEnum.NONE); } body.setDescription(apiRequest.getDescription()); body.setProvider(apiRequest.getProvider()); ArrayList<String> transports = new ArrayList<>(); if (Constants.PROTOCOL_HTTP.equals(apiRequest.getHttp_checked())) { transports.add(Constants.PROTOCOL_HTTP); } if (Constants.PROTOCOL_HTTPS.equals(apiRequest.getHttps_checked())) { transports.add(Constants.PROTOCOL_HTTPS); } body.setTransport(transports); body.isDefaultVersion(false); body.setCacheTimeout(100); if (apiRequest.getOperationsDTOS() != null) { body.setOperations(apiRequest.getOperationsDTOS()); } else { List<APIOperationsDTO> operations = new ArrayList<>(); APIOperationsDTO apiOperationsDTO = new APIOperationsDTO(); if (isAsyncApi(apiRequest)) { apiOperationsDTO.setVerb("SUBSCRIBE"); } else { apiOperationsDTO.setVerb("GET"); } if ("WEBSUB".equalsIgnoreCase(apiRequest.getType())) { apiOperationsDTO.setTarget("_default"); } else { apiOperationsDTO.setTarget("/*"); } apiOperationsDTO.setAuthType("Application & Application User"); apiOperationsDTO.setThrottlingPolicy("Unlimited"); operations.add(apiOperationsDTO); body.setOperations(operations); } body.setMediationPolicies(apiRequest.getMediationPolicies()); body.setBusinessInformation(new APIBusinessInformationDTO()); body.setCorsConfiguration(new APICorsConfigurationDTO()); body.setTags(Arrays.asList(apiRequest.getTags().split(","))); body.setEndpointConfig(apiRequest.getEndpointConfig()); body.setSecurityScheme(apiRequest.getSecurityScheme()); body.setType(APIDTO.TypeEnum.fromValue(apiRequest.getType())); if (StringUtils.isNotBlank(apiRequest.getApiTier())) { body.setApiThrottlingPolicy(apiRequest.getApiTier()); } List<String> tierList = new ArrayList<>(); tierList.add(Constants.TIERS_UNLIMITED); body.setPolicies(Arrays.asList(apiRequest.getTiersCollection().split(","))); body.isDefaultVersion(Boolean.valueOf(apiRequest.getDefault_version_checked())); APIDTO apidto; try { ApiResponse<APIDTO> httpInfo = apIsApi.createAPIWithHttpInfo(body, osVersion); Assert.assertEquals(201, httpInfo.getStatusCode()); apidto = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } return apidto; } public APIDTO addAPI(APIDTO apidto, String osVersion) throws ApiException { ApiResponse<APIDTO> httpInfo = apIsApi.createAPIWithHttpInfo(apidto, osVersion); Assert.assertEquals(201, httpInfo.getStatusCode()); return httpInfo.getData(); } private boolean isAsyncApi(APIRequest apiRequest) { String type = apiRequest.getType(); return "SSE".equalsIgnoreCase(type) || "WS".equalsIgnoreCase(type) || "WEBSUB".equalsIgnoreCase(type); } /** * This method is used to create a new API of the existing API. * * @param newVersion new API version * @param apiId old API ID * @param defaultVersion is this the * @return apiID of the newly created api version. * @throws ApiException Throws if an error occurs when creating the new API version. */ public String createNewAPIVersion(String newVersion, String apiId, boolean defaultVersion) throws ApiException { String apiLocation = apIsApi.createNewAPIVersionWithHttpInfo(newVersion, apiId, defaultVersion, null).getHeaders() .get("Location").get(0); String[] splitValues = apiLocation.split("/"); return splitValues[splitValues.length - 1]; } /** * This method is used to get the JSON content. * * @return API definition. * @throws IOException throws if an error occurred when creating the API. */ private String getJsonContent(String fileName) throws IOException { if (StringUtils.isNotEmpty(fileName)) { return IOUtils.toString(RestAPIPublisherImpl.class.getClassLoader().getResourceAsStream(fileName), StandardCharsets.UTF_8.name()); } return null; } /** * This method is used to publish the created API. * * @param action API id that need to published. * @param apiId API id that need to published. * return ApiResponse<WorkflowResponseDTO> change response. * @throws ApiException throws if an error occurred when publishing the API. */ public HttpResponse changeAPILifeCycleStatus(String apiId, String action, String lifecycleChecklist) throws ApiException { setActivityID(); WorkflowResponseDTO workflowResponseDTO = this.apiLifecycleApi .changeAPILifecycle(action, apiId, lifecycleChecklist, null); HttpResponse response = null; if (StringUtils.isNotEmpty(workflowResponseDTO.getLifecycleState().getState())) { response = new HttpResponse(workflowResponseDTO.getLifecycleState().getState(), 200); } return response; } public WorkflowResponseDTO changeAPILifeCycleStatus(String apiId, String action) throws ApiException { ApiResponse<WorkflowResponseDTO> workflowResponseDTOApiResponse = this.apiLifecycleApi.changeAPILifecycleWithHttpInfo(action, apiId, null, null); Assert.assertEquals(HttpStatus.SC_OK, workflowResponseDTOApiResponse.getStatusCode()); return workflowResponseDTOApiResponse.getData(); } /** * This method is used to deprecate the created API. * * @param apiId API id that need to published. * @throws ApiException throws if an error occurred when publishing the API. */ public void deprecateAPI(String apiId) throws ApiException { apiLifecycleApi.changeAPILifecycle(Constants.DEPRECATE, apiId, null, null); } /** * This method is used to deploy the api as a prototype. * * @param apiId API id that need to be prototyped. * @throws ApiException throws if an error occurred when publishing the API. */ public void deployPrototypeAPI(String apiId) throws ApiException { apiLifecycleApi.changeAPILifecycle(Constants.DEPLOY_AS_PROTOTYPE, apiId, null, null); } /** * This method is used to block the created API. * * @param apiId API id that need to published. * @throws ApiException throws if an error occurred when publishing the API. */ public void blockAPI(String apiId) throws ApiException { apiLifecycleApi.changeAPILifecycle(Constants.BLOCK, apiId, null, null); } public HttpResponse getLifecycleStatus(String apiId) throws ApiException { LifecycleStateDTO lifecycleStateDTO = this.apiLifecycleApi.getAPILifecycleState(apiId, null); HttpResponse response = null; if (StringUtils.isNotEmpty(lifecycleStateDTO.getState())) { response = new HttpResponse(lifecycleStateDTO.getState(), 200); } return response; } public LifecycleStateDTO getLifecycleStatusDTO(String apiId) throws ApiException { ApiResponse<LifecycleStateDTO> apiResponse = this.apiLifecycleApi.getAPILifecycleStateWithHttpInfo(apiId, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public LifecycleHistoryDTO getLifecycleHistory(String apiId) throws ApiException { ApiResponse<LifecycleHistoryDTO> apiResponse = this.apiLifecycleApi.getAPILifecycleHistoryWithHttpInfo(apiId, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } /** * copy API from existing API * * @param newVersion - new version of the API * @param apiId - existing API Id * @param isDefault - make the default version * @return - http response object * @throws APIManagerIntegrationTestException - Throws if error occurred at API copy operation */ public HttpResponse copyAPI(String newVersion, String apiId, Boolean isDefault) throws ApiException { APIDTO apiDto = apIsApi.createNewAPIVersion(newVersion, apiId, isDefault, null); HttpResponse response = null; if (StringUtils.isNotEmpty(apiDto.getId())) { response = new HttpResponse(apiDto.getId(), 200); } return response; } /** * @param newVersion * @param apiId * @param isDefault * @return * @throws ApiException */ public APIDTO copyAPIWithReturnDTO(String newVersion, String apiId, Boolean isDefault) throws ApiException { ApiResponse<APIDTO> response = apIsApi.createNewAPIVersionWithHttpInfo(newVersion, apiId, isDefault, null); Assert.assertEquals(HttpStatus.SC_CREATED, response.getStatusCode()); return response.getData(); } /** * Facilitate update API * * @param apiRequest - constructed API request object * @return http response object * @throws APIManagerIntegrationTestException - throws if update API fails */ public HttpResponse updateAPI(APIRequest apiRequest, String apiId) throws ApiException { APIDTO body = new APIDTO(); body.setName(apiRequest.getName()); body.setContext(apiRequest.getContext()); body.setVersion(apiRequest.getVersion()); if (apiRequest.getVisibility() != null) { body.setVisibility(APIDTO.VisibilityEnum.valueOf(apiRequest.getVisibility().toUpperCase())); if (APIDTO.VisibilityEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getVisibility()) && StringUtils.isNotEmpty(apiRequest.getRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getRoles().split(" , "))); body.setVisibleRoles(roleList); } } else { body.setVisibility(APIDTO.VisibilityEnum.PUBLIC); } if (apiRequest.getAccessControl() != null) { body.setAccessControl(APIDTO.AccessControlEnum.valueOf(apiRequest.getAccessControl().toUpperCase())); if (APIDTO.AccessControlEnum.RESTRICTED.getValue().equalsIgnoreCase(apiRequest.getAccessControl()) && StringUtils.isNotEmpty(apiRequest.getAccessControlRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiRequest.getAccessControlRoles().split(" , "))); body.setAccessControlRoles(roleList); } } else { body.setAccessControl(APIDTO.AccessControlEnum.NONE); } body.setDescription(apiRequest.getDescription()); body.setProvider(apiRequest.getProvider()); ArrayList<String> transports = new ArrayList<>(); if (Constants.PROTOCOL_HTTP.equals(apiRequest.getHttp_checked())) { transports.add(Constants.PROTOCOL_HTTP); } if (Constants.PROTOCOL_HTTPS.equals(apiRequest.getHttps_checked())) { transports.add(Constants.PROTOCOL_HTTPS); } body.setTransport(transports); body.isDefaultVersion(false); body.setCacheTimeout(100); body.setMediationPolicies(apiRequest.getMediationPolicies()); if (apiRequest.getOperationsDTOS() != null) { body.setOperations(apiRequest.getOperationsDTOS()); } else { List<APIOperationsDTO> operations = new ArrayList<>(); APIOperationsDTO apiOperationsDTO = new APIOperationsDTO(); apiOperationsDTO.setVerb("GET"); apiOperationsDTO.setTarget("/*"); apiOperationsDTO.setAuthType("Application & Application User"); apiOperationsDTO.setThrottlingPolicy("Unlimited"); operations.add(apiOperationsDTO); body.setOperations(operations); } body.setBusinessInformation(new APIBusinessInformationDTO()); body.setCorsConfiguration(new APICorsConfigurationDTO()); body.setTags(Arrays.asList(apiRequest.getTags().split(","))); body.setEndpointConfig(apiRequest.getEndpointConfig()); if (StringUtils.isNotBlank(apiRequest.getApiTier())) { body.setApiThrottlingPolicy(apiRequest.getApiTier()); } List<String> tierList = new ArrayList<>(); tierList.add(Constants.TIERS_UNLIMITED); body.setPolicies(Arrays.asList(apiRequest.getTiersCollection().split(","))); body.setCategories(apiRequest.getApiCategories()); APIDTO apidto; try { apidto = apIsApi.updateAPI(apiId, body, null); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apidto.getId())) { response = new HttpResponse(apidto.getId(), 200); } return response; } public APIDTO updateAPI(APIDTO apidto, String apiId) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.updateAPIWithHttpInfo(apiId, apidto, null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } /** * Method to get API information * * @param apiId - API id * @return http response object * @throws ApiException - Throws if api information cannot be retrieved. */ public HttpResponse getAPI(String apiId) throws ApiException { setActivityID(); APIDTO apidto = null; HttpResponse response = null; Gson gson = new Gson(); try { apidto = apIsApi.getAPI(apiId, null, null); } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(apidto.getId())) { response = new HttpResponse(gson.toJson(apidto), 200); } return response; } /** * delete API * * @param apiId - API id * @return http response object * @throws ApiException - Throws if API delete fails */ public HttpResponse deleteAPI(String apiId) throws ApiException { ApiResponse<Void> deleteResponse = apIsApi.deleteAPIWithHttpInfo(apiId, null); HttpResponse response = null; if (deleteResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully deleted the API", 200); } return response; } public HttpResponse generateMockScript(String apiId) throws ApiException { ApiResponse<String> mockResponse = apIsApi.generateMockScriptsWithHttpInfo(apiId, null); HttpResponse response = null; if (mockResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully generated MockScript", 200); } return response; } public HttpResponse getGenerateMockScript(String apiId) throws ApiException { ApiResponse<MockResponsePayloadListDTO> mockResponse = apIsApi.getGeneratedMockScriptsOfAPIWithHttpInfo(apiId, null); HttpResponse response = null; if (mockResponse.getStatusCode() == 200) { response = new HttpResponse(mockResponse.getData().toString(), 200); } return response; } /** * Remove document * * @param apiId - API id * @param docId - document id * @return http response object * @throws ApiException - Throws if remove API document fails */ public HttpResponse removeDocumentation(String apiId, String docId) throws ApiException { ApiResponse<Void> deleteResponse = apiDocumentsApi.deleteAPIDocumentWithHttpInfo(apiId, docId, null); HttpResponse response = null; if (deleteResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully removed the documentation", 200); } return response; } /** * revoke access token * * @param accessToken - access token already received * @param consumerKey - consumer key returned * @param authUser - user name * @return http response object * @throws APIManagerIntegrationTestException - throws if access token revoke fails */ public HttpResponse revokeAccessToken(String accessToken, String consumerKey, String authUser) throws APIManagerIntegrationTestException { return null; } /** * update permissions to API access * * @param tierName - name of api throttling tier * @param permissionType - permission type * @param roles - roles of permission * @return http response object * @throws APIManagerIntegrationTestException - throws if permission update fails */ public HttpResponse updatePermissions(String tierName, String permissionType, String roles) throws APIManagerIntegrationTestException { return null; } /** * Update resources of API * * @param apiId - API Id * @return http response object * @throws APIManagerIntegrationTestException - throws if API resource update fails */ public HttpResponse updateResourceOfAPI(String apiId, String api) throws APIManagerIntegrationTestException { return null; } /** * Check whether the Endpoint is valid * * @param endpointUrl url of the endpoint * @param apiId id of the api which the endpoint to be validated * @return HttpResponse - Response of the getAPI request * @throws ApiException - Check for valid endpoint fails. */ public HttpResponse checkValidEndpoint(String endpointUrl, String apiId) throws ApiException { ApiEndpointValidationResponseDTO validationResponseDTO = validationApi.validateEndpoint(endpointUrl, apiId); HttpResponse response = null; if (validationResponseDTO.getStatusCode() == 200) { response = new HttpResponse(validationResponseDTO.getStatusMessage(), 200); } return response; } /** * Change the API Lifecycle status to Publish with the option of Re-subscription is required or not * * @param apiId - API ID * @param isRequireReSubscription - true if Re-subscription is required else false. * @return HttpResponse - Response of the API publish event * @throws APIManagerIntegrationTestException - Exception Throws in checkAuthentication() and when do the REST * service calls to do the lifecycle change. */ public HttpResponse changeAPILifeCycleStatusToPublish(String apiId, boolean isRequireReSubscription) throws ApiException { ApiResponse<WorkflowResponseDTO> responseDTOApiResponse = this.apiLifecycleApi.changeAPILifecycleWithHttpInfo( Constants.PUBLISHED, apiId, "Re-Subscription:" + isRequireReSubscription, null); HttpResponse response = null; if (responseDTOApiResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully changed the lifecycle of the API", 200); } return response; } /** * Retrieve the Tier Permission Page * * @return HttpResponse - Response that contains the Tier Permission Page * @throws APIManagerIntegrationTestException - Exception throws from checkAuthentication() method and * HTTPSClientUtils.doGet() method call */ public HttpResponse getTierPermissionsPage() throws APIManagerIntegrationTestException { return null; } /** * Adding a documentation * * @param apiId - Id of the API. * @param body - document Body. * @return HttpResponse - Response with Document adding result. * @throws ApiException - Exception throws if error occurred when adding document. */ public HttpResponse addDocument(String apiId, DocumentDTO body) throws ApiException { DocumentDTO doc = apiDocumentsApi.addAPIDocument(apiId, body, null); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse(doc.getDocumentId(), 200); } return response; } /** * Adding a content to the document * * @param apiId - Id of the API. * @param docId - document Id. * @param docContent - document content * @return HttpResponse - Response with Document adding result. * @throws ApiException - Exception throws if error occurred when adding document. */ public HttpResponse addContentDocument(String apiId, String docId, String docContent) throws ApiException { DocumentDTO doc = apiDocumentsApi.addAPIDocumentContent(apiId, docId, null, null, docContent); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse("Successfully created the documentation", 200); } return response; } /** * Updating the document content using file * * @param apiId - Id of the API. * @param docId - document Id. * @param docContent - file content * @return HttpResponse - Response with Document adding result. * @throws ApiException - Exception throws if error occurred when adding document. */ public HttpResponse updateContentDocument(String apiId, String docId, File docContent) throws ApiException { DocumentDTO doc = apiDocumentsApi.addAPIDocumentContent(apiId, docId, null, docContent, null); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse("Successfully updated the documentation", 200); } return response; } /** * Update API document. * * @param apiId api Id * @param docId document Id * @param documentDTO documentation object. * @return * @throws ApiException Exception throws if error occurred when updating document. */ public HttpResponse updateDocument(String apiId, String docId, DocumentDTO documentDTO) throws ApiException { DocumentDTO doc = apiDocumentsApi.updateAPIDocument(apiId, docId, documentDTO, null); HttpResponse response = null; if (StringUtils.isNotEmpty(doc.getDocumentId())) { response = new HttpResponse("Successfully created the documentation", 200); } return response; } /** * This method is used to get documents * Get Documents for the given limit and offset values * * @param apiId apiId * @return Documents for the given limit and offset values */ public DocumentListDTO getDocuments(String apiId) throws ApiException { ApiResponse<DocumentListDTO> apiResponse = apiDocumentsApi.getAPIDocumentsWithHttpInfo(apiId, null, null, null); Assert.assertEquals(HttpStatus.SC_OK, apiResponse.getStatusCode()); return apiResponse.getData(); } /** * This method is used to get the content of API documents * * @param apiId UUID of the API * @param documentId UUID of the API document * @return * @throws ApiException */ public HttpResponse getDocumentContent(String apiId, String documentId) throws ApiException { ApiResponse<String> apiResponse = apiDocumentsApi.getAPIDocumentContentByDocumentIdWithHttpInfo(apiId, documentId, null); HttpResponse response = null; if (apiResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully retrieved the Document content", 200); } return response; } /** * delete Document * * @param apiId - API id * @param documentId - API id * @return http response object * @throws ApiException - Throws if API delete fails */ public HttpResponse deleteDocument(String apiId, String documentId) throws ApiException { ApiResponse<Void> deleteResponse = apiDocumentsApi.deleteAPIDocumentWithHttpInfo(apiId, documentId, null); HttpResponse response = null; if (deleteResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully deleted the Document", 200); } return response; } /*** * Add a shared scope * * @param scopeDTO * @return ScopeDTO - Returns the added shared scope * @throws ApiException */ public ScopeDTO addSharedScope(ScopeDTO scopeDTO) throws ApiException { ApiResponse<ScopeDTO> httpInfo = sharedScopesApi.addSharedScopeWithHttpInfo(scopeDTO); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_CREATED); return httpInfo.getData(); } /*** * Remove a shared scope * * @param id id of the scope to delete * @throws ApiException */ public void removeSharedScope(String id) throws ApiException { ApiResponse<Void> httpInfo = sharedScopesApi.deleteSharedScopeWithHttpInfo(id); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); } /*** * Update a shared scopes * * @param uuid * @param scopeDTO * @return ScopeDTO - Returns the updated shared scope * @throws ApiException */ public ScopeDTO updateSharedScope(String uuid, ScopeDTO scopeDTO) throws ApiException { ApiResponse<ScopeDTO> httpInfo = sharedScopesApi.updateSharedScopeWithHttpInfo(uuid, scopeDTO); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); return httpInfo.getData(); } /*** * Get a shared scope * * @param uuid * @return ScopeDTO - Returns the updated shared scope * @throws ApiException */ public ScopeDTO getSharedScopeById(String uuid) throws ApiException { ApiResponse<ScopeDTO> httpInfo = sharedScopesApi.getSharedScopeWithHttpInfo(uuid); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); return httpInfo.getData(); } /*** * Delete a shared scope * * @param uuid * @throws ApiException */ public void deleteSharedScope(String uuid) throws ApiException { ApiResponse<Void> httpInfo = sharedScopesApi.deleteSharedScopeWithHttpInfo(uuid); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); } /*** * Get all shared scopes * * @return ScopeListDTO - Returns all the shared scopes * @throws ApiException */ public ScopeListDTO getAllSharedScopes() throws ApiException { ApiResponse<ScopeListDTO> httpInfo = sharedScopesApi.getSharedScopesWithHttpInfo(null, null); Assert.assertEquals(httpInfo.getStatusCode(), HttpStatus.SC_OK); return httpInfo.getData(); } /** * Retrieve the All APIs available for the user in Publisher. * * @return HttpResponse - Response that contains all available APIs for the user * @throws APIManagerIntegrationTestException - Exception throws from checkAuthentication() method and * HTTPSClientUtils.doGet() method call */ public APIListDTO getAllAPIs() throws APIManagerIntegrationTestException, ApiException { APIListDTO apis = apIsApi.getAllAPIs(null, null, null, null, null, null, null); if (apis.getCount() > 0) { return apis; } return null; } /** * Retrieve the APIs according to the search query in Publisher. * * @param query - The query on which the APIs needs to be filtered * @return SearchResultListDTO - The search results of the query * @throws ApiException */ public SearchResultListDTO searchAPIs(String query) throws ApiException { ApiResponse<SearchResultListDTO> searchResponse = unifiedSearchApi.searchWithHttpInfo(null, null, query, null); Assert.assertEquals(HttpStatus.SC_OK, searchResponse.getStatusCode()); return searchResponse.getData(); } /** * This method is used to upload endpoint certificates * Get APIs for the given limit and offset values * * @param offset starting position * @param limit maximum number of APIs to return * @return APIs for the given limit and offset values */ public APIListDTO getAPIs(int offset, int limit) throws ApiException { setActivityID(); ApiResponse<APIListDTO> apiResponse = apIsApi.getAllAPIsWithHttpInfo(limit, offset, this.tenantDomain, null, null, false, null); Assert.assertEquals(HttpStatus.SC_OK, apiResponse.getStatusCode()); return apiResponse.getData(); } /** * This method is used to upload certificates * * @param certificate certificate * @param alias alis * @param endpoint endpoint. * @return * @throws ApiException if an error occurred while uploading the certificate. */ public ApiResponse<CertMetadataDTO> uploadEndpointCertificate(File certificate, String alias, String endpoint) throws ApiException { ApiResponse<CertMetadataDTO> certificateDTO = endpointCertificatesApi.addEndpointCertificateWithHttpInfo(certificate, alias, endpoint); return certificateDTO; } /** * This method is used to get all throttling tiers. * * @param - API or resource * @return - Response that contains all the available tiers * @throws ApiException */ public ThrottlingPolicyListDTO getTiers(String policyLevel) throws ApiException { ThrottlingPolicyListDTO policies = throttlingPoliciesApi.getAllThrottlingPolicies(policyLevel, null, null, null); if (policies.getCount() > 0) { return policies; } return null; } public SubscriptionPolicyListDTO getSubscriptionPolicies(String tierQuotaTypes) throws ApiException { SubscriptionPolicyListDTO subscriptionPolicyList = throttlingPoliciesApi.getSubscriptionThrottlingPolicies(null, null, null); if (subscriptionPolicyList.getCount() > 0) { return subscriptionPolicyList; } return null; } /** * This method is used to validate roles. * * @param roleId role Id * @return HttpResponse * @throws APIManagerIntegrationTestException */ public ApiResponse<Void> validateRoles(String roleId) throws ApiException { String encodedRoleName = Base64.getUrlEncoder().encodeToString(roleId.getBytes()); return rolesApi.validateSystemRoleWithHttpInfo(encodedRoleName); } public String getSwaggerByID(String apiId) throws ApiException { ApiResponse<String> response = apIsApi.getAPISwaggerWithHttpInfo(apiId, null); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public String updateSwagger(String apiId, String definition) throws ApiException { ApiResponse<String> apiResponse = apIsApi.updateAPISwaggerWithHttpInfo(apiId, null, definition, null, null); Assert.assertEquals(HttpStatus.SC_OK, apiResponse.getStatusCode()); return apiResponse.getData(); } public OpenAPIDefinitionValidationResponseDTO validateOASDefinition(File oasDefinition) throws ApiException { ApiResponse<OpenAPIDefinitionValidationResponseDTO> response = validationApi.validateOpenAPIDefinitionWithHttpInfo(null, null, oasDefinition, null); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO getAPIByID(String apiId, String tenantDomain) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.getAPIWithHttpInfo(apiId, tenantDomain, null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public APIDTO getAPIByID(String apiId) throws ApiException { return apIsApi.getAPI(apiId, tenantDomain, null); } public APIDTO importOASDefinition(File file, String properties) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importOpenAPIDefinitionWithHttpInfo(file, null, properties, null); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public GraphQLValidationResponseDTO validateGraphqlSchemaDefinition(File schemaDefinition) throws ApiException { ApiResponse<GraphQLValidationResponseDTO> response = validationApi.validateGraphQLSchemaWithHttpInfo(schemaDefinition); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO importGraphqlSchemaDefinition(File file, String properties) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importGraphQLSchemaWithHttpInfo(null, "GRAPHQL", file, properties); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public GraphQLSchemaDTO getGraphqlSchemaDefinition(String apiId) throws ApiException { ApiResponse<GraphQLSchemaDTO> schemaDefinitionDTO = graphQlSchemaIndividualApi. getAPIGraphQLSchemaWithHttpInfo(apiId, "application/json", null); Assert.assertEquals(HttpStatus.SC_OK, schemaDefinitionDTO.getStatusCode()); return schemaDefinitionDTO.getData(); } public void updateGraphqlSchemaDefinition(String apiId, String schemaDefinition) throws ApiException { ApiResponse<Void> schemaDefinitionDTO = graphQlSchemaApi.updateAPIGraphQLSchemaWithHttpInfo (apiId, schemaDefinition, null); Assert.assertEquals(HttpStatus.SC_OK, schemaDefinitionDTO.getStatusCode()); } public WSDLValidationResponseDTO validateWsdlDefinition(String url, File wsdlDefinition) throws ApiException { ApiResponse<WSDLValidationResponseDTO> response = validationApi .validateWSDLDefinitionWithHttpInfo(url, wsdlDefinition); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO importWSDLSchemaDefinition(File file, String url, String properties, String type) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importWSDLDefinitionWithHttpInfo(file, url, properties, type); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public ApiResponse<Void> getWSDLSchemaDefinitionOfAPI(String apiId) throws ApiException { ApiResponse<Void> apiDtoApiResponse = apIsApi.getWSDLOfAPIWithHttpInfo(apiId,null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse; } public ResourcePolicyListDTO getApiResourcePolicies(String apiId, String sequenceType, String resourcePath, String verb) throws ApiException { ApiResponse<ResourcePolicyListDTO> policyListDTOApiResponse = apiResourcePoliciesApi .getAPIResourcePoliciesWithHttpInfo(apiId, sequenceType, resourcePath, verb, null); Assert.assertEquals(policyListDTOApiResponse.getStatusCode(), HttpStatus.SC_OK); return policyListDTOApiResponse.getData(); } public ResourcePolicyInfoDTO updateApiResourcePolicies(String apiId, String resourcePolicyId, String resourcePath, ResourcePolicyInfoDTO resourcePolicyInfoDTO, String verb) throws ApiException { ApiResponse<ResourcePolicyInfoDTO> response = apiResourcePoliciesApi .updateAPIResourcePoliciesByPolicyIdWithHttpInfo(apiId, resourcePolicyId, resourcePolicyInfoDTO, null); Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_OK); return response.getData(); } public AsyncAPISpecificationValidationResponseDTO validateAsyncAPISchemaDefinition(String url, File file) throws ApiException { ApiResponse<AsyncAPISpecificationValidationResponseDTO> response = validationApi .validateAsyncAPISpecificationWithHttpInfo(false, url, file); Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode()); return response.getData(); } public APIDTO importAsyncAPISchemaDefinition(File file, String url, String properties) throws ApiException { ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importAsyncAPISpecificationWithHttpInfo(file, url, properties); Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse.getData(); } public ApiResponse<Void> getAsyncAPIDefinitionOfAPI(String apiId) throws ApiException { ApiResponse<Void> apiDtoApiResponse = apIsApi.getWSDLOfAPIWithHttpInfo(apiId,null); Assert.assertEquals(HttpStatus.SC_OK, apiDtoApiResponse.getStatusCode()); return apiDtoApiResponse; } public APIDTO addAPI(APICreationRequestBean apiCreationRequestBean) throws ApiException { APIDTO body = new APIDTO(); body.setName(apiCreationRequestBean.getName()); body.setContext(apiCreationRequestBean.getContext()); body.setVersion(apiCreationRequestBean.getVersion()); if (apiCreationRequestBean.getVisibility() != null) { body.setVisibility(APIDTO.VisibilityEnum.valueOf(apiCreationRequestBean.getVisibility().toUpperCase())); if (APIDTO.VisibilityEnum.RESTRICTED.getValue().equalsIgnoreCase(apiCreationRequestBean.getVisibility()) && StringUtils.isNotEmpty(apiCreationRequestBean.getRoles())) { List<String> roleList = new ArrayList<>( Arrays.asList(apiCreationRequestBean.getRoles().split(" , "))); body.setVisibleRoles(roleList); } } else { body.setVisibility(APIDTO.VisibilityEnum.PUBLIC); } body.setDescription(apiCreationRequestBean.getDescription()); body.setProvider(apiCreationRequestBean.getProvider()); body.setTransport(new ArrayList<String>() {{ add(Constants.PROTOCOL_HTTP); add(Constants.PROTOCOL_HTTPS); }}); body.isDefaultVersion(false); body.setCacheTimeout(100); List<APIOperationsDTO> operations = new ArrayList<>(); for (APIResourceBean resourceBean : apiCreationRequestBean.getResourceBeanList()) { APIOperationsDTO dto = new APIOperationsDTO(); dto.setTarget(resourceBean.getUriTemplate()); dto.setAuthType(resourceBean.getResourceMethodAuthType()); dto.setVerb(resourceBean.getResourceMethod()); dto.setThrottlingPolicy(resourceBean.getResourceMethodThrottlingTier()); operations.add(dto); } body.setOperations(operations); body.setBusinessInformation(new APIBusinessInformationDTO()); body.setCorsConfiguration(new APICorsConfigurationDTO()); body.setTags(Arrays.asList(apiCreationRequestBean.getTags().split(","))); if (apiCreationRequestBean.getSetEndpointSecurityDirectlyToEndpoint()) { try { body.setEndpointConfig(new JSONParser().parse(apiCreationRequestBean.getEndpoint().toString())); } catch (ParseException e) { throw new ApiException(e); } } else { JSONObject jsonObject = new JSONObject(); jsonObject.put("endpoint_type", "http"); JSONObject sandUrl = new JSONObject(); sandUrl.put("url", apiCreationRequestBean.getEndpointUrl().toString()); jsonObject.put("sandbox_endpoints", sandUrl); jsonObject.put("production_endpoints", sandUrl); if ("basic".equalsIgnoreCase(apiCreationRequestBean.getEndpointType())) { JSONObject endpointSecurityGlobal = new JSONObject(); endpointSecurityGlobal.put("enabled", true); endpointSecurityGlobal.put("type", "basic"); endpointSecurityGlobal.put("username", apiCreationRequestBean.getEpUsername()); endpointSecurityGlobal.put("password", apiCreationRequestBean.getEpPassword()); JSONObject endpointSecurity = new JSONObject(); endpointSecurity.put("production", endpointSecurityGlobal); endpointSecurity.put("sandbox", endpointSecurityGlobal); jsonObject.put("endpoint_security", endpointSecurity); } body.setEndpointConfig(jsonObject); } List<String> tierList = new ArrayList<>(); tierList.add(Constants.TIERS_UNLIMITED); if (apiCreationRequestBean.getSubPolicyCollection() != null) { String[] tiers = apiCreationRequestBean.getSubPolicyCollection().split(","); for (String tier : tiers) { tierList.add(tier); } } body.setPolicies(tierList); ApiResponse<APIDTO> httpInfo = apIsApi.createAPIWithHttpInfo(body, "v3"); Assert.assertEquals(201, httpInfo.getStatusCode()); return httpInfo.getData(); } /** * This method is used to upload certificates * * @param certificate certificate * @param alias alis * @return * @throws ApiException if an error occurred while uploading the certificate. */ public HttpResponse uploadCertificate(File certificate, String alias, String apiId, String tier) throws ApiException { ClientCertMetadataDTO certificateDTO = clientCertificatesApi.addAPIClientCertificate(apiId, certificate, alias, tier); HttpResponse response = null; if (StringUtils.isNotEmpty(certificateDTO.getAlias())) { response = new HttpResponse("Successfully uploaded the certificate", 200); } return response; } /** * Update an API * * @param apidto * @return * @throws ApiException */ public APIDTO updateAPI(APIDTO apidto) throws ApiException { ApiResponse<APIDTO> response = apIsApi.updateAPIWithHttpInfo(apidto.getId(), apidto, null); Assert.assertEquals(response.getStatusCode(), HttpStatus.SC_OK); return response.getData(); } /** * Get subscription of an API * * @param apiID * @return * @throws ApiException */ public SubscriptionListDTO getSubscriptionByAPIID(String apiID) throws ApiException { ApiResponse<SubscriptionListDTO> apiResponse = subscriptionsApi.getSubscriptionsWithHttpInfo(apiID, 10, 0, null, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public APIProductListDTO getAllApiProducts() throws ApiException { ApiResponse<APIProductListDTO> apiResponse = apiProductsApi.getAllAPIProductsWithHttpInfo(null, null, null, null, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public APIProductDTO getApiProduct(String apiProductId) throws ApiException { ApiResponse<APIProductDTO> apiResponse = apiProductsApi.getAPIProductWithHttpInfo(apiProductId, null, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); return apiResponse.getData(); } public APIProductDTO addApiProduct(APIProductDTO apiProductDTO) throws ApiException { ApiResponse<APIProductDTO> apiResponse = apiProductsApi.createAPIProductWithHttpInfo(apiProductDTO); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_CREATED); return apiResponse.getData(); } public void deleteApiProduct(String apiProductId) throws ApiException { ApiResponse<Void> apiResponse = apiProductsApi.deleteAPIProductWithHttpInfo(apiProductId, null); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); } /** * Method to retrieve the Audit Report of an API * * @param apiId apiId of the API * @return HttpResponse response * @throws ApiException */ public HttpResponse getAuditApi(String apiId) throws ApiException { HttpResponse response = null; ApiResponse<AuditReportDTO> auditReportResponse = apiAuditApi .getAuditReportOfAPIWithHttpInfo(apiId, "application/json"); if (auditReportResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully audited the report", 200); } return response; } /** * Method to retrieve the GraphQL Schema Type List * * @param apiId apiId of the API * @return HttpResponse response * @throws ApiException */ public HttpResponse getGraphQLSchemaTypeListResponse(String apiId) throws ApiException { HttpResponse response = null; ApiResponse<GraphQLSchemaTypeListDTO> graphQLSchemaTypeListDTOApiResponse = graphQlPoliciesApi .getGraphQLPolicyComplexityTypesOfAPIWithHttpInfo(apiId); if (graphQLSchemaTypeListDTOApiResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully get the GraphQL Schema Type List", 200); } return response; } /** * Method to retrieve the GraphQL Schema Type List * * @param apiId apiId of the API * @return GraphQLSchemaTypeListDTO GraphQLSchemaTypeList object * @throws ApiException */ public GraphQLSchemaTypeListDTO getGraphQLSchemaTypeList(String apiId) throws ApiException { ApiResponse<GraphQLSchemaTypeListDTO> graphQLSchemaTypeListDTOApiResponse = graphQlPoliciesApi .getGraphQLPolicyComplexityTypesOfAPIWithHttpInfo(apiId); Assert.assertEquals(graphQLSchemaTypeListDTOApiResponse.getStatusCode(), HttpStatus.SC_OK); return graphQLSchemaTypeListDTOApiResponse.getData(); } /** * Method to add GraphQL Complexity Info of an API * * @param apiID * @param graphQLQueryComplexityInfoDTO GraphQL Complexity Object * @return * @throws ApiException */ public void addGraphQLComplexityDetails(GraphQLQueryComplexityInfoDTO graphQLQueryComplexityInfoDTO, String apiID) throws ApiException { ApiResponse<Void> apiResponse = graphQlPoliciesApi.updateGraphQLPolicyComplexityOfAPIWithHttpInfo(apiID, graphQLQueryComplexityInfoDTO); Assert.assertEquals(apiResponse.getStatusCode(), HttpStatus.SC_OK); } /** * Method to retrieve the GraphQL Complexity Details * * @param apiId apiId of the API * @return HttpResponse response * @throws ApiException */ public HttpResponse getGraphQLComplexityResponse(String apiId) throws ApiException { HttpResponse response = null; ApiResponse<GraphQLQueryComplexityInfoDTO> complexityResponse = graphQlPoliciesApi .getGraphQLPolicyComplexityOfAPIWithHttpInfo(apiId); if (complexityResponse.getStatusCode() == 200) { response = new HttpResponse("Successfully get the GraphQL Complexity Details", 200); } return response; } /** * This method is used to create an API Revision. * * @param apiRevisionRequest API Revision create object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse addAPIRevision(APIRevisionRequest apiRevisionRequest) throws ApiException { setActivityID(); APIRevisionDTO apiRevisionDTO = new APIRevisionDTO(); apiRevisionDTO.setDescription(apiRevisionRequest.getDescription()); Gson gson = new Gson(); try { ApiResponse<APIRevisionDTO> httpInfo = apiRevisionsApi. createAPIRevisionWithHttpInfo(apiRevisionRequest.getApiUUID(), apiRevisionDTO); Assert.assertEquals(201, httpInfo.getStatusCode()); apiRevisionDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; if (apiRevisionDTO != null && StringUtils.isNotEmpty(apiRevisionDTO.getId())) { response = new HttpResponse(gson.toJson(apiRevisionDTO), 201); } return response; } /** * This method is used to create an API Revision. * * @param apiId API Revision create object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public APIRevisionDTO addAPIRevision(String apiId) throws ApiException { APIRevisionDTO apiRevisionDTO = new APIRevisionDTO(); Gson gson = new Gson(); try { ApiResponse<APIRevisionDTO> httpInfo = apiRevisionsApi. createAPIRevisionWithHttpInfo(apiId, apiRevisionDTO); Assert.assertEquals(201, httpInfo.getStatusCode()); return httpInfo.getData(); } catch (ApiException e) { throw new ApiException(e); } } /** * Method to get API Revisions per API * * @param apiUUID - API uuid * @param query - Search query * @return http response object * @throws ApiException - Throws if api information cannot be retrieved. */ public HttpResponse getAPIRevisions(String apiUUID, String query) throws ApiException { APIRevisionListDTO apiRevisionListDTO = null; HttpResponse response = null; Gson gson = new Gson(); try { apiRevisionListDTO = apiRevisionsApi.getAPIRevisions(apiUUID, query); } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(apiRevisionListDTO.getList().toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } /** * This method is used to deploy API Revision to Gateways. * * @param apiRevisionDeployRequestList API Revision deploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deployAPIRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionDeployRequestList, String apiType) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionDeployRequest : apiRevisionDeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionDeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionDeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionDeployRequest.isDisplayOnDevportal()); apiRevisionDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<List<APIRevisionDeploymentDTO>> httpInfo = apiRevisionsApi.deployAPIRevisionWithHttpInfo(apiUUID, revisionUUID, apiRevisionDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForDeployAPI(apiUUID, revisionUUID, apiType); //apiRevisionDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // if (StringUtils.isNotEmpty(apiRevisionDeploymentDTOResponseList.toString())) { // response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // } return response; } /** * This method is used to deploy API Revision to Gateways. * * @param apiRevisionDeployRequestList API Revision deploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deployAPIRevision(String apiUUID, String revisionUUID, APIRevisionDeployUndeployRequest apiRevisionDeployRequest, String apiType) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOResponseList = new ArrayList<>(); APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionDeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionDeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionDeployRequest.isDisplayOnDevportal()); apiRevisionDeploymentDTOList.add(apiRevisionDeploymentDTO); try { ApiResponse<List<APIRevisionDeploymentDTO>> httpInfo = apiRevisionsApi.deployAPIRevisionWithHttpInfo(apiUUID, revisionUUID, apiRevisionDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForDeployAPI(apiUUID,revisionUUID, apiType); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); return response; } private void waitForDeployAPI(String apiUUID, String revisionUUID, String apiType) throws ApiException, APIManagerIntegrationTestException { if (Boolean.parseBoolean(disableVerification)){ return; } String context, version, provider, name, apiPolicy; if ("APIProduct".equals(apiType)) { APIProductDTO apiProduct = getApiProduct(revisionUUID); context = apiProduct.getContext(); version = "1.0.0"; provider = apiProduct.getProvider(); name = apiProduct.getName(); apiPolicy = apiProduct.getApiThrottlingPolicy(); } else { APIDTO api = getAPIByID(revisionUUID); context = api.getContext(); version = api.getVersion(); provider = api.getProvider(); name = api.getName(); apiPolicy = api.getApiThrottlingPolicy(); } APIInfoDTO apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo != null) { if (!"APIProduct".equals(apiType)) { if (context.startsWith("/{version}")) { Assert.assertEquals(apiInfo.getContext(), context.replace("{version}", version)); } else { Assert.assertEquals(apiInfo.getContext(), context.concat("/").concat(version)); } } else { Assert.assertEquals(apiInfo.getContext(), context); } Assert.assertEquals(apiInfo.getName(), name); Assert.assertEquals(apiInfo.getProvider(), provider); if (!StringUtils.equals(apiPolicy, apiInfo.getPolicy())) { int retries = 0; while (retries <= 5) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (!StringUtils.equals(apiPolicy, apiInfo.getPolicy())) { retries++; } else { break; } } } return; } int retries = 0; while (retries <= 20) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo != null) { if (!"APIProduct".equals(apiType)) { if (context.startsWith("/{version}")) { Assert.assertEquals(apiInfo.getContext(), context.replace("{version}", version)); } else { Assert.assertEquals(apiInfo.getContext(), context.concat("/").concat(version)); } } else { Assert.assertEquals(apiInfo.getContext(), context); } Assert.assertEquals(apiInfo.getName(), name); Assert.assertEquals(apiInfo.getProvider(), provider); break; } retries++; } } /** * This method is used to undeploy API Revision to Gateways. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @param apiRevisionUndeployRequestList API Revision undeploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when undeploying the API Revision. */ public HttpResponse undeployAPIRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionUndeployRequestList) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionUndeployRequest : apiRevisionUndeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionUndeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionUndeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionUndeployRequest.isDisplayOnDevportal()); apiRevisionUnDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<Void> httpInfo = apiRevisionsApi.undeployAPIRevisionWithHttpInfo(apiUUID, revisionUUID, null, false, apiRevisionUnDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForUnDeployAPI(apiUUID); //apiRevisionUnDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionUnDeploymentDTOResponseList), 201); return response; } private void waitForUnDeployAPI(String apiUUID) throws APIManagerIntegrationTestException { if (Boolean.parseBoolean(disableVerification)) { return; } APIInfoDTO apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo == null) { return; } int retries = 0; while (retries <= 20) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } apiInfo = restAPIGateway.getAPIInfo(apiUUID); if (apiInfo == null) { break; } retries++; } } /** * This method is used to restore an API Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse restoreAPIRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIDTO apidto = null; try { ApiResponse<APIDTO> httpInfo = apiRevisionsApi.restoreAPIRevisionWithHttpInfo(apiUUID, revisionUUID); Assert.assertEquals(201, httpInfo.getStatusCode()); apidto = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apidto.toString())) { response = new HttpResponse(gson.toJson(apidto), 201); } return response; } /** * This method is used to delete an API Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deleteAPIRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIRevisionListDTO apiRevisionListDTO = null; try { ApiResponse<APIRevisionListDTO> httpInfo = apiRevisionsApi.deleteAPIRevisionWithHttpInfo(apiUUID, revisionUUID); Assert.assertEquals(200, httpInfo.getStatusCode()); apiRevisionListDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } else if (e.getCode() != 0) { return new HttpResponse(null, e.getCode()); } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apiRevisionListDTO.toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } public MediationListDTO retrieveMediationPolicies() throws ApiException { return globalMediationPoliciesApi.getAllGlobalMediationPolicies(100, 0, null, null); } /** * This method is used to create an API Product Revision. * * @param apiRevisionRequest API Revision create object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse addAPIProductRevision(APIRevisionRequest apiRevisionRequest) throws ApiException { APIRevisionDTO apiRevisionDTO = new APIRevisionDTO(); apiRevisionDTO.setDescription(apiRevisionRequest.getDescription()); Gson gson = new Gson(); try { ApiResponse<APIRevisionDTO> httpInfo = apiProductRevisionsApi. createAPIProductRevisionWithHttpInfo(apiRevisionRequest.getApiUUID(), apiRevisionDTO); Assert.assertEquals(201, httpInfo.getStatusCode()); apiRevisionDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (apiRevisionDTO != null && StringUtils.isNotEmpty(apiRevisionDTO.getId())) { response = new HttpResponse(gson.toJson(apiRevisionDTO), 201); } return response; } /** * Method to get API Product Revisions per API * * @param apiUUID - API uuid * @param query - Search query * @return http response object * @throws ApiException - Throws if api information cannot be retrieved. */ public HttpResponse getAPIProductRevisions(String apiUUID, String query) throws ApiException { APIRevisionListDTO apiRevisionListDTO = null; HttpResponse response = null; Gson gson = new Gson(); try { apiRevisionListDTO = apiProductRevisionsApi.getAPIProductRevisions(apiUUID, query); } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(apiRevisionListDTO.getList().toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } /** * This method is used to deploy API Product Revision to Gateways. * * @param apiRevisionDeployRequestList API Revision deploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deployAPIProductRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionDeployRequestList, String apiType) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionDeployRequest : apiRevisionDeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionDeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionDeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionDeployRequest.isDisplayOnDevportal()); apiRevisionDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<Void> httpInfo = apiProductRevisionsApi.deployAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID, apiRevisionDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForDeployAPI(apiUUID, revisionUUID, apiType); //apiRevisionDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // if (StringUtils.isNotEmpty(apiRevisionDeploymentDTOResponseList.toString())) { // response = new HttpResponse(gson.toJson(apiRevisionDeploymentDTOResponseList), 201); // } return response; } /** * This method is used to undeploy API Product Revision to Gateways. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @param apiRevisionUndeployRequestList API Revision undeploy object body * @return HttpResponse * @throws ApiException throws of an error occurred when undeploying the API Revision. */ public HttpResponse undeployAPIProductRevision(String apiUUID, String revisionUUID, List<APIRevisionDeployUndeployRequest> apiRevisionUndeployRequestList) throws ApiException, APIManagerIntegrationTestException { Gson gson = new Gson(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOList = new ArrayList<>(); List<APIRevisionDeploymentDTO> apiRevisionUnDeploymentDTOResponseList = new ArrayList<>(); for (APIRevisionDeployUndeployRequest apiRevisionUndeployRequest : apiRevisionUndeployRequestList) { APIRevisionDeploymentDTO apiRevisionDeploymentDTO = new APIRevisionDeploymentDTO(); apiRevisionDeploymentDTO.setName(apiRevisionUndeployRequest.getName()); apiRevisionDeploymentDTO.setVhost(apiRevisionUndeployRequest.getVhost()); apiRevisionDeploymentDTO.setDisplayOnDevportal(apiRevisionUndeployRequest.isDisplayOnDevportal()); apiRevisionUnDeploymentDTOList.add(apiRevisionDeploymentDTO); } try { ApiResponse<Void> httpInfo = apiProductRevisionsApi.undeployAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID, null, false, apiRevisionUnDeploymentDTOList); Assert.assertEquals(201, httpInfo.getStatusCode()); waitForUnDeployAPI(apiUUID); //apiRevisionUnDeploymentDTOResponseList = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; response = new HttpResponse(gson.toJson(apiRevisionUnDeploymentDTOResponseList), 201); // if (StringUtils.isNotEmpty(apiRevisionUnDeploymentDTOResponseList.toString())) { // response = new HttpResponse(gson.toJson(apiRevisionUnDeploymentDTOResponseList), 201); // } return response; } /** * This method is used to restore an API Product Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse restoreAPIProductRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIProductDTO apiProductDTO = null; try { ApiResponse<APIProductDTO> httpInfo = apiProductRevisionsApi.restoreAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID); Assert.assertEquals(201, httpInfo.getStatusCode()); apiProductDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apiProductDTO.toString())) { response = new HttpResponse(gson.toJson(apiProductDTO), 201); } return response; } /** * This method is used to delete an API product Revision. * * @param apiUUID API UUID * @param revisionUUID API Revision UUID * @return HttpResponse * @throws ApiException throws of an error occurred when creating the API Revision. */ public HttpResponse deleteAPIProductRevision(String apiUUID, String revisionUUID) throws ApiException { Gson gson = new Gson(); APIRevisionListDTO apiRevisionListDTO = null; try { ApiResponse<APIRevisionListDTO> httpInfo = apiProductRevisionsApi.deleteAPIProductRevisionWithHttpInfo( apiUUID, revisionUUID); Assert.assertEquals(200, httpInfo.getStatusCode()); apiRevisionListDTO = httpInfo.getData(); } catch (ApiException e) { if (e.getResponseBody().contains("already exists")) { return null; } throw new ApiException(e); } HttpResponse response = null; if (StringUtils.isNotEmpty(apiRevisionListDTO.toString())) { response = new HttpResponse(gson.toJson(apiRevisionListDTO), 200); } return response; } public ApiResponse<APIKeyDTO> generateInternalApiKey(String apiId) throws ApiException { return apIsApi.generateInternalAPIKeyWithHttpInfo(apiId); } /** * Add comment to given API * * @param apiId - api Id * @param comment - comment to add * @param category - category of the comment * @param replyTo - comment id of the root comment to add replies * @return - http response of add comment * @throws ApiException - throws if add comment fails */ public HttpResponse addComment(String apiId, String comment, String category, String replyTo) throws ApiException { PostRequestBodyDTO postRequestBodyDTO = new PostRequestBodyDTO(); postRequestBodyDTO.setContent(comment); postRequestBodyDTO.setCategory(category); Gson gson = new Gson(); CommentDTO commentDTO = commentsApi.addCommentToAPI(apiId, postRequestBodyDTO, replyTo); HttpResponse response = null; if (commentDTO != null) { response = new HttpResponse(gson.toJson(commentDTO), 200); } return response; } /** * Get Comment from given API * * @param commentId - comment Id * @param apiId - api Id * @param tenantDomain - tenant domain * @param limit - for pagination * @param offset - for pagination * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse getComment(String commentId, String apiId, String tenantDomain, boolean includeCommentorInfo, Integer limit, Integer offset) throws ApiException { CommentDTO commentDTO; HttpResponse response = null; Gson gson = new Gson(); try { commentDTO = commentsApi.getCommentOfAPI(commentId, apiId, tenantDomain, null, includeCommentorInfo, limit, offset); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (StringUtils.isNotEmpty(commentDTO.getId())) { response = new HttpResponse(gson.toJson(commentDTO), 200); } return response; } /** * Get all the comments from given API * * @param apiId - api Id * @param tenantDomain - tenant domain * @param limit - for pagination * @param offset - for pagination * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse getComments(String apiId, String tenantDomain, boolean includeCommentorInfo, Integer limit, Integer offset) throws ApiException { CommentListDTO commentListDTO; HttpResponse response = null; Gson gson = new Gson(); try { commentListDTO = commentsApi.getAllCommentsOfAPI(apiId, tenantDomain, limit, offset, includeCommentorInfo); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (commentListDTO.getCount() > 0) { response = new HttpResponse(gson.toJson(commentListDTO), 200); } return response; } /** * Get replies of a comment from given API * * @param commentId - comment Id * @param apiId - api Id * @param tenantDomain - tenant domain * @param limit - for pagination * @param offset - for pagination * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse getReplies(String commentId, String apiId, String tenantDomain, boolean includeCommentorInfo, Integer limit, Integer offset) throws ApiException { CommentListDTO commentListDTO; HttpResponse response = null; Gson gson = new Gson(); try { commentListDTO = commentsApi.getRepliesOfComment(commentId, apiId, tenantDomain, limit, offset, null, includeCommentorInfo); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } if (commentListDTO.getCount() > 0) { response = new HttpResponse(gson.toJson(commentListDTO), 200); } return response; } /** * Get Comment from given API * * @param commentId - comment Id * @param apiId - api Id * @param comment - comment to add * @param category - category of the comment * @return - http response get comment * @throws ApiException - throws if get comment fails */ public HttpResponse editComment(String commentId, String apiId, String comment, String category) throws ApiException { HttpResponse response = null; Gson gson = new Gson(); try { PatchRequestBodyDTO patchRequestBodyDTO = new PatchRequestBodyDTO(); patchRequestBodyDTO.setCategory(category); patchRequestBodyDTO.setContent(comment); CommentDTO editedCommentDTO = commentsApi.editCommentOfAPI(commentId, apiId, patchRequestBodyDTO); if (editedCommentDTO != null) { response = new HttpResponse(gson.toJson(editedCommentDTO), 200); } else { response = new HttpResponse(null, 200); } } catch (ApiException e) { return new HttpResponse(gson.toJson(e.getResponseBody()), e.getCode()); } return response; } /** * Remove comment in given API * * @param commentId - comment Id * @param apiId - api Id * @throws ApiException - throws if remove comment fails */ public HttpResponse removeComment(String commentId, String apiId) throws ApiException { HttpResponse response; try { commentsApi.deleteComment(commentId, apiId, null); response = new HttpResponse("Successfully deleted the comment", 200); } catch (org.wso2.am.integration.clients.publisher.api.ApiException e) { response = new HttpResponse("Failed to delete the comment", e.getCode()); } return response; } public ApiResponse<APIProductDTO> updateAPIProduct(APIProductDTO apiProductDTO) throws ApiException { return apiProductsApi.updateAPIProductWithHttpInfo(apiProductDTO.getId(), apiProductDTO, null); } public CertificatesDTO getEndpointCertificiates(String endpoint, String alias) throws ApiException { return endpointCertificatesApi.getEndpointCertificates(Integer.MAX_VALUE, 0, alias, endpoint); } public org.wso2.am.integration.clients.publisher.api.v1.dto.CertificateInfoDTO getendpointCertificateContent(String alias) throws ApiException { return endpointCertificatesApi.getEndpointCertificateByAlias(alias); } public ApiResponse<Void> deleteEndpointCertificate(String alias) throws ApiException { return endpointCertificatesApi.deleteEndpointCertificateByAliasWithHttpInfo(alias); } private void setActivityID() { apiPublisherClient.addDefaultHeader("activityID", System.getProperty(testNameProperty)); } }
Remove wildcard imports
modules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/impl/RestAPIPublisherImpl.java
Remove wildcard imports
<ide><path>odules/integration/tests-common/integration-test-utils/src/main/java/org/wso2/am/integration/test/impl/RestAPIPublisherImpl.java <ide> import org.wso2.am.integration.clients.publisher.api.v1.ThrottlingPoliciesApi; <ide> import org.wso2.am.integration.clients.publisher.api.v1.UnifiedSearchApi; <ide> import org.wso2.am.integration.clients.publisher.api.v1.ValidationApi; <del>import org.wso2.am.integration.clients.publisher.api.v1.dto.*; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIBusinessInformationDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APICorsConfigurationDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIKeyDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIOperationsDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIProductDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIProductListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIRevisionDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIRevisionDeploymentDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.APIRevisionListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ApiEndpointValidationResponseDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.AsyncAPISpecificationValidationResponseDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.AuditReportDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.CertMetadataDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.CertificatesDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ClientCertMetadataDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.CommentDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.CommentListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.DocumentDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.DocumentListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLQueryComplexityInfoDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLSchemaDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLSchemaTypeListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.GraphQLValidationResponseDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.LifecycleHistoryDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.LifecycleStateDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.MediationListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.MockResponsePayloadListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.OpenAPIDefinitionValidationResponseDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.PatchRequestBodyDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.PostRequestBodyDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ResourcePolicyInfoDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ResourcePolicyListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ScopeDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ScopeListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.SearchResultListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.SubscriptionListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.SubscriptionPolicyListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.ThrottlingPolicyListDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.WSDLValidationResponseDTO; <add>import org.wso2.am.integration.clients.publisher.api.v1.dto.WorkflowResponseDTO; <ide> import org.wso2.am.integration.test.ClientAuthenticator; <ide> import org.wso2.am.integration.test.Constants; <ide> import org.wso2.am.integration.test.utils.APIManagerIntegrationTestException;
Java
apache-2.0
0f8a21ab9457c422fe971d482282c25c83fa14e3
0
Uni-Sol/batik,Uni-Sol/batik,apache/batik,apache/batik,Uni-Sol/batik,apache/batik,Uni-Sol/batik,Uni-Sol/batik,apache/batik
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.bridge; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.batik.css.AbstractViewCSS; import org.apache.batik.css.CSSOMReadOnlyStyleDeclaration; import org.apache.batik.css.CSSOMReadOnlyValue; import org.apache.batik.dom.svg.SVGOMDocument; import org.apache.batik.dom.svg.XMLBaseSupport; import org.apache.batik.dom.util.XLinkSupport; import org.apache.batik.util.ParsedURL; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.svg.SVGDocument; /** * This class is used to resolve the URI that can be found in a SVG document. * * @author <a href="mailto:[email protected]">Stephane Hillion</a> * @version $Id$ */ public class URIResolver { /** * The reference document. */ protected SVGOMDocument document; /** * The document URI. */ protected String documentURI; /** * The document loader. */ protected DocumentLoader documentLoader; /** * Creates a new URI resolver object. * @param doc The reference document. * @param dl The document loader. */ public URIResolver(SVGDocument doc, DocumentLoader dl) { document = (SVGOMDocument)doc; documentLoader = dl; } /** * Imports the Element referenced by the given URI on Element * <tt>ref</tt>. * @param uri The element URI. * @param ref The Element in the DOM tree to evaluate <tt>uri</tt> * from. * @return The referenced element or null if element can't be found. */ public Element getElement(String uri, Element ref) throws MalformedURLException, IOException { Node n = getNode(uri, ref); if (n == null) { return null; } else if (n.getNodeType() == n.DOCUMENT_NODE) { throw new IllegalArgumentException(); } else { return (Element)n; } } /** * Imports the Node referenced by the given URI on Element * <tt>ref</tt>. * @param uri The element URI. * @param ref The Element in the DOM tree to evaluate <tt>uri</tt> * from. * @return The referenced Node/Document or null if element can't be found. */ public Node getNode(String uri, Element ref) throws MalformedURLException, IOException { String baseURI = XMLBaseSupport.getXMLBase(ref); if ((baseURI == null) && (uri.startsWith("#"))) return document.getElementById(uri.substring(1)); ParsedURL purl = new ParsedURL(baseURI, uri); // System.out.println("PURL: " + purl); if (documentURI == null) documentURI = document.getURL(); String frag = purl.getRef(); if ((frag != null) && (documentURI != null)) { ParsedURL pDocURL = new ParsedURL(documentURI); // System.out.println("Purl: " + // purl.getPath() + " - " + // purl.getPort() + " - " + // purl.getHost() + " - " + // purl.getProtocol() + "\n" + // "doc: " + // pDocURL.getPath() + " - " + // pDocURL.getPort() + " - " + // pDocURL.getHost() + " - " + // pDocURL.getProtocol()); // Check if the rest of the URL matches... // if so then return the referenced element. // if ((pDocURL.getPath() == purl.getPath()) && // (pDocURL.getPort() == purl.getPort()) && // (pDocURL.getHost() == purl.getHost()) && // (pDocURL.getProtocol() == purl.getProtocol())) // return document.getElementById(frag); if ((pDocURL.getPort() == purl.getPort()) && ((pDocURL.getPath() == purl.getPath()) || ((pDocURL.getPath()!=null) && pDocURL.getPath().equals(purl.getPath()))) && ((pDocURL.getHost() == purl.getHost()) || ((pDocURL.getHost()!=null) && pDocURL.getHost().equals(purl.getHost()))) && ((pDocURL.getProtocol() == purl.getProtocol()) || ((pDocURL.getProtocol()!=null) && pDocURL.getProtocol().equals(purl.getProtocol())))) return document.getElementById(frag); } // uri is not a reference into this document, so load the // document it does reference. Document doc = documentLoader.loadDocument(purl.toString()); if (frag != null) return doc.getElementById(frag); return doc; } }
sources/org/apache/batik/bridge/URIResolver.java
/***************************************************************************** * Copyright (C) The Apache Software Foundation. All rights reserved. * * ------------------------------------------------------------------------- * * This software is published under the terms of the Apache Software License * * version 1.1, a copy of which has been included with this distribution in * * the LICENSE file. * *****************************************************************************/ package org.apache.batik.bridge; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import org.apache.batik.css.AbstractViewCSS; import org.apache.batik.css.CSSOMReadOnlyStyleDeclaration; import org.apache.batik.css.CSSOMReadOnlyValue; import org.apache.batik.dom.svg.SVGOMDocument; import org.apache.batik.dom.svg.XMLBaseSupport; import org.apache.batik.dom.util.XLinkSupport; import org.apache.batik.util.ParsedURL; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.svg.SVGDocument; /** * This class is used to resolve the URI that can be found in a SVG document. * * @author <a href="mailto:[email protected]">Stephane Hillion</a> * @version $Id$ */ public class URIResolver { /** * The reference document. */ protected SVGOMDocument document; /** * The document URI. */ protected String documentURI; /** * The document loader. */ protected DocumentLoader documentLoader; /** * Creates a new URI resolver object. * @param doc The reference document. * @param dl The document loader. */ public URIResolver(SVGDocument doc, DocumentLoader dl) { document = (SVGOMDocument)doc; documentLoader = dl; } /** * Imports the element referenced by the given URI. * @param uri The element URI. */ public Element getElement(String uri, Element ref) throws MalformedURLException, IOException { Node n = getNode(uri, ref); if (n == null) { return null; } else if (n.getNodeType() == n.DOCUMENT_NODE) { throw new IllegalArgumentException(); } else { return (Element)n; } } /** * Returns the node referenced by the given URI on element ref. * @return The document or the element */ public Node getNode(String uri, Element ref) throws MalformedURLException, IOException { String baseURI = XMLBaseSupport.getXMLBase(ref); if ((baseURI == null) && (uri.startsWith("#"))) return document.getElementById(uri.substring(1)); ParsedURL purl = new ParsedURL(baseURI, uri); // System.out.println("PURL: " + purl); if (documentURI == null) documentURI = document.getURL(); String frag = purl.getRef(); if ((frag != null) && (documentURI != null)) { ParsedURL pDocURL = new ParsedURL(documentURI); // System.out.println("Purl: " + // purl.getPath() + " - " + // purl.getPort() + " - " + // purl.getHost() + " - " + // purl.getProtocol() + "\n" + // "doc: " + // pDocURL.getPath() + " - " + // pDocURL.getPort() + " - " + // pDocURL.getHost() + " - " + // pDocURL.getProtocol()); // Check if the rest of the URL matches... // if so then return the referenced element. // if ((pDocURL.getPath() == purl.getPath()) && // (pDocURL.getPort() == purl.getPort()) && // (pDocURL.getHost() == purl.getHost()) && // (pDocURL.getProtocol() == purl.getProtocol())) // return document.getElementById(frag); if ((pDocURL.getPort() == purl.getPort()) && ((pDocURL.getPath() == purl.getPath()) || ((pDocURL.getPath()!=null) && pDocURL.getPath().equals(purl.getPath()))) && ((pDocURL.getHost() == purl.getHost()) || ((pDocURL.getHost()!=null) && pDocURL.getHost().equals(purl.getHost()))) && ((pDocURL.getProtocol() == purl.getProtocol()) || ((pDocURL.getProtocol()!=null) && pDocURL.getProtocol().equals(purl.getProtocol())))) return document.getElementById(frag); } // uri is not a reference into this document, so load the // document it does reference. Document doc = documentLoader.loadDocument(purl.toString()); if (frag != null) return doc.getElementById(frag); return doc; } }
1) Synced JavaDocs with Implementation. git-svn-id: e944db0f7b5c8f0ae3e1ad43ca99b026751ef0c2@200271 13f79535-47bb-0310-9956-ffa450edef68
sources/org/apache/batik/bridge/URIResolver.java
1) Synced JavaDocs with Implementation.
<ide><path>ources/org/apache/batik/bridge/URIResolver.java <ide> } <ide> <ide> /** <del> * Imports the element referenced by the given URI. <add> * Imports the Element referenced by the given URI on Element <add> * <tt>ref</tt>. <ide> * @param uri The element URI. <add> * @param ref The Element in the DOM tree to evaluate <tt>uri</tt> <add> * from. <add> * @return The referenced element or null if element can't be found. <ide> */ <ide> public Element getElement(String uri, Element ref) <ide> throws MalformedURLException, IOException { <ide> } <ide> <ide> /** <del> * Returns the node referenced by the given URI on element ref. <del> * @return The document or the element <add> * Imports the Node referenced by the given URI on Element <add> * <tt>ref</tt>. <add> * @param uri The element URI. <add> * @param ref The Element in the DOM tree to evaluate <tt>uri</tt> <add> * from. <add> * @return The referenced Node/Document or null if element can't be found. <ide> */ <ide> public Node getNode(String uri, Element ref) <ide> throws MalformedURLException, IOException {
Java
apache-2.0
04af1b6a293d90c216a8af0e2a36c8864a228156
0
tbeadle/selenium,doungni/selenium,petruc/selenium,rovner/selenium,dcjohnson1989/selenium,livioc/selenium,jsarenik/jajomojo-selenium,lrowe/selenium,petruc/selenium,blackboarddd/selenium,manuelpirez/selenium,misttechnologies/selenium,bayandin/selenium,actmd/selenium,dandv/selenium,Sravyaksr/selenium,amikey/selenium,mach6/selenium,carsonmcdonald/selenium,zenefits/selenium,wambat/selenium,chrsmithdemos/selenium,twalpole/selenium,BlackSmith/selenium,jsakamoto/selenium,compstak/selenium,gurayinan/selenium,Sravyaksr/selenium,carsonmcdonald/selenium,freynaud/selenium,BlackSmith/selenium,valfirst/selenium,arunsingh/selenium,GorK-ChO/selenium,gregerrag/selenium,lrowe/selenium,lummyare/lummyare-lummy,bmannix/selenium,jknguyen/josephknguyen-selenium,Dude-X/selenium,minhthuanit/selenium,lilredindy/selenium,stupidnetizen/selenium,titusfortner/selenium,denis-vilyuzhanin/selenium-fastview,jabbrwcky/selenium,rrussell39/selenium,krosenvold/selenium,eric-stanley/selenium,temyers/selenium,manuelpirez/selenium,chrisblock/selenium,lukeis/selenium,dandv/selenium,BlackSmith/selenium,uchida/selenium,gotcha/selenium,mojwang/selenium,skurochkin/selenium,gorlemik/selenium,dcjohnson1989/selenium,quoideneuf/selenium,sebady/selenium,lrowe/selenium,knorrium/selenium,s2oBCN/selenium,eric-stanley/selenium,onedox/selenium,MeetMe/selenium,manuelpirez/selenium,dkentw/selenium,yukaReal/selenium,vinay-qa/vinayit-android-server-apk,SouWilliams/selenium,carsonmcdonald/selenium,kalyanjvn1/selenium,mestihudson/selenium,yukaReal/selenium,i17c/selenium,sag-enorman/selenium,Tom-Trumper/selenium,thanhpete/selenium,zenefits/selenium,pulkitsinghal/selenium,gemini-testing/selenium,skurochkin/selenium,markodolancic/selenium,RamaraoDonta/ramarao-clone,joshmgrant/selenium,stupidnetizen/selenium,Sravyaksr/selenium,doungni/selenium,arunsingh/selenium,TheBlackTuxCorp/selenium,temyers/selenium,TikhomirovSergey/selenium,sebady/selenium,oddui/selenium,SevInf/IEDriver,s2oBCN/selenium,dibagga/selenium,lmtierney/selenium,xmhubj/selenium,soundcloud/selenium,s2oBCN/selenium,gabrielsimas/selenium,kalyanjvn1/selenium,TikhomirovSergey/selenium,anshumanchatterji/selenium,xmhubj/selenium,o-schneider/selenium,tbeadle/selenium,s2oBCN/selenium,lrowe/selenium,jsakamoto/selenium,livioc/selenium,bartolkaruza/selenium,gabrielsimas/selenium,gemini-testing/selenium,sri85/selenium,mach6/selenium,lukeis/selenium,dandv/selenium,JosephCastro/selenium,sevaseva/selenium,dkentw/selenium,slongwang/selenium,pulkitsinghal/selenium,lrowe/selenium,quoideneuf/selenium,telefonicaid/selenium,mestihudson/selenium,doungni/selenium,tbeadle/selenium,lukeis/selenium,amar-sharma/selenium,doungni/selenium,dkentw/selenium,5hawnknight/selenium,bayandin/selenium,oddui/selenium,RamaraoDonta/ramarao-clone,joshuaduffy/selenium,misttechnologies/selenium,xmhubj/selenium,misttechnologies/selenium,Appdynamics/selenium,dcjohnson1989/selenium,petruc/selenium,gorlemik/selenium,asolntsev/selenium,jsarenik/jajomojo-selenium,gregerrag/selenium,sri85/selenium,sri85/selenium,rovner/selenium,carlosroh/selenium,alb-i986/selenium,kalyanjvn1/selenium,p0deje/selenium,customcommander/selenium,bayandin/selenium,asolntsev/selenium,juangj/selenium,Jarob22/selenium,dimacus/selenium,denis-vilyuzhanin/selenium-fastview,compstak/selenium,SevInf/IEDriver,arunsingh/selenium,vveliev/selenium,gemini-testing/selenium,carlosroh/selenium,gregerrag/selenium,AutomatedTester/selenium,SouWilliams/selenium,i17c/selenium,gotcha/selenium,joshmgrant/selenium,rplevka/selenium,wambat/selenium,pulkitsinghal/selenium,sevaseva/selenium,joshbruning/selenium,asashour/selenium,alexec/selenium,dibagga/selenium,sankha93/selenium,Ardesco/selenium,o-schneider/selenium,MeetMe/selenium,amikey/selenium,davehunt/selenium,lummyare/lummyare-test,temyers/selenium,rovner/selenium,jabbrwcky/selenium,Sravyaksr/selenium,vveliev/selenium,onedox/selenium,Ardesco/selenium,rovner/selenium,carsonmcdonald/selenium,juangj/selenium,jknguyen/josephknguyen-selenium,manuelpirez/selenium,bartolkaruza/selenium,5hawnknight/selenium,titusfortner/selenium,carlosroh/selenium,markodolancic/selenium,gemini-testing/selenium,arunsingh/selenium,rrussell39/selenium,RamaraoDonta/ramarao-clone,jerome-jacob/selenium,p0deje/selenium,lummyare/lummyare-lummy,Tom-Trumper/selenium,mestihudson/selenium,5hawnknight/selenium,blackboarddd/selenium,sri85/selenium,chrsmithdemos/selenium,jabbrwcky/selenium,compstak/selenium,pulkitsinghal/selenium,dimacus/selenium,jknguyen/josephknguyen-selenium,SevInf/IEDriver,freynaud/selenium,chrisblock/selenium,Herst/selenium,krosenvold/selenium,Jarob22/selenium,stupidnetizen/selenium,vveliev/selenium,quoideneuf/selenium,SevInf/IEDriver,lilredindy/selenium,misttechnologies/selenium,SeleniumHQ/selenium,joshmgrant/selenium,jerome-jacob/selenium,MCGallaspy/selenium,joshuaduffy/selenium,aluedeke/chromedriver,rplevka/selenium,lummyare/lummyare-lummy,alb-i986/selenium,krosenvold/selenium,pulkitsinghal/selenium,skurochkin/selenium,titusfortner/selenium,tkurnosova/selenium,TheBlackTuxCorp/selenium,compstak/selenium,SevInf/IEDriver,o-schneider/selenium,eric-stanley/selenium,lilredindy/selenium,minhthuanit/selenium,juangj/selenium,Herst/selenium,AutomatedTester/selenium,amar-sharma/selenium,titusfortner/selenium,aluedeke/chromedriver,alexec/selenium,Tom-Trumper/selenium,tarlabs/selenium,krosenvold/selenium,mojwang/selenium,skurochkin/selenium,joshbruning/selenium,minhthuanit/selenium,krmahadevan/selenium,kalyanjvn1/selenium,krmahadevan/selenium,tkurnosova/selenium,mach6/selenium,Dude-X/selenium,dcjohnson1989/selenium,telefonicaid/selenium,eric-stanley/selenium,sri85/selenium,HtmlUnit/selenium,Herst/selenium,temyers/selenium,houchj/selenium,clavery/selenium,vinay-qa/vinayit-android-server-apk,sag-enorman/selenium,actmd/selenium,krmahadevan/selenium,arunsingh/selenium,lummyare/lummyare-test,anshumanchatterji/selenium,SeleniumHQ/selenium,lmtierney/selenium,gurayinan/selenium,quoideneuf/selenium,skurochkin/selenium,clavery/selenium,bartolkaruza/selenium,tarlabs/selenium,kalyanjvn1/selenium,lilredindy/selenium,sevaseva/selenium,alb-i986/selenium,meksh/selenium,pulkitsinghal/selenium,Sravyaksr/selenium,manuelpirez/selenium,sankha93/selenium,juangj/selenium,HtmlUnit/selenium,rovner/selenium,livioc/selenium,wambat/selenium,bayandin/selenium,gorlemik/selenium,blueyed/selenium,blueyed/selenium,lrowe/selenium,valfirst/selenium,Tom-Trumper/selenium,dimacus/selenium,TheBlackTuxCorp/selenium,asolntsev/selenium,BlackSmith/selenium,SeleniumHQ/selenium,gabrielsimas/selenium,davehunt/selenium,valfirst/selenium,dbo/selenium,krmahadevan/selenium,isaksky/selenium,houchj/selenium,clavery/selenium,temyers/selenium,thanhpete/selenium,valfirst/selenium,Herst/selenium,mojwang/selenium,carlosroh/selenium,gabrielsimas/selenium,joshuaduffy/selenium,telefonicaid/selenium,anshumanchatterji/selenium,mestihudson/selenium,chrisblock/selenium,dbo/selenium,TikhomirovSergey/selenium,jabbrwcky/selenium,lukeis/selenium,alb-i986/selenium,quoideneuf/selenium,blackboarddd/selenium,i17c/selenium,blackboarddd/selenium,sag-enorman/selenium,Dude-X/selenium,mojwang/selenium,mojwang/selenium,joshbruning/selenium,bartolkaruza/selenium,blackboarddd/selenium,carlosroh/selenium,dibagga/selenium,gorlemik/selenium,meksh/selenium,titusfortner/selenium,misttechnologies/selenium,livioc/selenium,sebady/selenium,JosephCastro/selenium,bmannix/selenium,clavery/selenium,AutomatedTester/selenium,soundcloud/selenium,sebady/selenium,jabbrwcky/selenium,lummyare/lummyare-lummy,aluedeke/chromedriver,rplevka/selenium,asashour/selenium,xsyntrex/selenium,SeleniumHQ/selenium,Tom-Trumper/selenium,DrMarcII/selenium,minhthuanit/selenium,actmd/selenium,isaksky/selenium,onedox/selenium,tbeadle/selenium,valfirst/selenium,actmd/selenium,gurayinan/selenium,aluedeke/chromedriver,gabrielsimas/selenium,gotcha/selenium,alexec/selenium,DrMarcII/selenium,davehunt/selenium,eric-stanley/selenium,5hawnknight/selenium,oddui/selenium,MCGallaspy/selenium,dkentw/selenium,tkurnosova/selenium,jerome-jacob/selenium,s2oBCN/selenium,jsarenik/jajomojo-selenium,thanhpete/selenium,houchj/selenium,lrowe/selenium,bmannix/selenium,pulkitsinghal/selenium,stupidnetizen/selenium,GorK-ChO/selenium,sevaseva/selenium,freynaud/selenium,stupidnetizen/selenium,alb-i986/selenium,rplevka/selenium,gemini-testing/selenium,anshumanchatterji/selenium,asolntsev/selenium,gemini-testing/selenium,clavery/selenium,sri85/selenium,dbo/selenium,jerome-jacob/selenium,gabrielsimas/selenium,sevaseva/selenium,Ardesco/selenium,lmtierney/selenium,i17c/selenium,chrsmithdemos/selenium,i17c/selenium,BlackSmith/selenium,mestihudson/selenium,mestihudson/selenium,oddui/selenium,bmannix/selenium,Herst/selenium,dandv/selenium,bayandin/selenium,sankha93/selenium,Herst/selenium,TikhomirovSergey/selenium,AutomatedTester/selenium,rrussell39/selenium,vinay-qa/vinayit-android-server-apk,Appdynamics/selenium,asolntsev/selenium,tkurnosova/selenium,denis-vilyuzhanin/selenium-fastview,p0deje/selenium,meksh/selenium,soundcloud/selenium,bmannix/selenium,rplevka/selenium,soundcloud/selenium,o-schneider/selenium,mestihudson/selenium,joshmgrant/selenium,markodolancic/selenium,markodolancic/selenium,MeetMe/selenium,twalpole/selenium,bayandin/selenium,gorlemik/selenium,blueyed/selenium,mach6/selenium,markodolancic/selenium,lummyare/lummyare-test,krmahadevan/selenium,thanhpete/selenium,xsyntrex/selenium,knorrium/selenium,HtmlUnit/selenium,s2oBCN/selenium,misttechnologies/selenium,lrowe/selenium,chrisblock/selenium,joshuaduffy/selenium,zenefits/selenium,telefonicaid/selenium,mach6/selenium,Ardesco/selenium,knorrium/selenium,TheBlackTuxCorp/selenium,juangj/selenium,petruc/selenium,jabbrwcky/selenium,gorlemik/selenium,lukeis/selenium,asashour/selenium,MCGallaspy/selenium,SeleniumHQ/selenium,amikey/selenium,alb-i986/selenium,tkurnosova/selenium,mojwang/selenium,freynaud/selenium,sag-enorman/selenium,mach6/selenium,actmd/selenium,vveliev/selenium,krosenvold/selenium,dkentw/selenium,minhthuanit/selenium,tarlabs/selenium,Tom-Trumper/selenium,thanhpete/selenium,jsakamoto/selenium,jsarenik/jajomojo-selenium,wambat/selenium,krosenvold/selenium,HtmlUnit/selenium,JosephCastro/selenium,joshuaduffy/selenium,bartolkaruza/selenium,SouWilliams/selenium,aluedeke/chromedriver,gabrielsimas/selenium,lilredindy/selenium,xsyntrex/selenium,twalpole/selenium,titusfortner/selenium,kalyanjvn1/selenium,Ardesco/selenium,Dude-X/selenium,vveliev/selenium,quoideneuf/selenium,actmd/selenium,krmahadevan/selenium,dandv/selenium,asashour/selenium,dbo/selenium,chrisblock/selenium,lummyare/lummyare-lummy,dibagga/selenium,joshbruning/selenium,xsyntrex/selenium,s2oBCN/selenium,Herst/selenium,thanhpete/selenium,amar-sharma/selenium,minhthuanit/selenium,DrMarcII/selenium,markodolancic/selenium,Sravyaksr/selenium,rrussell39/selenium,orange-tv-blagnac/selenium,livioc/selenium,vinay-qa/vinayit-android-server-apk,lilredindy/selenium,yukaReal/selenium,knorrium/selenium,BlackSmith/selenium,DrMarcII/selenium,sebady/selenium,customcommander/selenium,lilredindy/selenium,SeleniumHQ/selenium,rovner/selenium,sebady/selenium,juangj/selenium,lilredindy/selenium,krmahadevan/selenium,i17c/selenium,houchj/selenium,asolntsev/selenium,dimacus/selenium,chrsmithdemos/selenium,tarlabs/selenium,alexec/selenium,dibagga/selenium,lukeis/selenium,rplevka/selenium,JosephCastro/selenium,eric-stanley/selenium,amikey/selenium,jsarenik/jajomojo-selenium,uchida/selenium,doungni/selenium,bartolkaruza/selenium,TheBlackTuxCorp/selenium,houchj/selenium,twalpole/selenium,jknguyen/josephknguyen-selenium,tkurnosova/selenium,slongwang/selenium,Appdynamics/selenium,customcommander/selenium,zenefits/selenium,sankha93/selenium,blueyed/selenium,clavery/selenium,bayandin/selenium,mestihudson/selenium,HtmlUnit/selenium,lmtierney/selenium,dcjohnson1989/selenium,SevInf/IEDriver,blueyed/selenium,sevaseva/selenium,mestihudson/selenium,tarlabs/selenium,aluedeke/chromedriver,onedox/selenium,5hawnknight/selenium,krmahadevan/selenium,krosenvold/selenium,SouWilliams/selenium,valfirst/selenium,asolntsev/selenium,SouWilliams/selenium,rrussell39/selenium,bartolkaruza/selenium,dkentw/selenium,customcommander/selenium,Jarob22/selenium,DrMarcII/selenium,gregerrag/selenium,soundcloud/selenium,5hawnknight/selenium,Jarob22/selenium,SevInf/IEDriver,meksh/selenium,RamaraoDonta/ramarao-clone,sag-enorman/selenium,stupidnetizen/selenium,jsakamoto/selenium,RamaraoDonta/ramarao-clone,zenefits/selenium,i17c/selenium,sevaseva/selenium,orange-tv-blagnac/selenium,AutomatedTester/selenium,jknguyen/josephknguyen-selenium,manuelpirez/selenium,gurayinan/selenium,Herst/selenium,gemini-testing/selenium,isaksky/selenium,slongwang/selenium,dkentw/selenium,wambat/selenium,tkurnosova/selenium,compstak/selenium,carlosroh/selenium,freynaud/selenium,chrsmithdemos/selenium,isaksky/selenium,dkentw/selenium,compstak/selenium,alb-i986/selenium,freynaud/selenium,MeetMe/selenium,dbo/selenium,dibagga/selenium,zenefits/selenium,mach6/selenium,chrisblock/selenium,dibagga/selenium,DrMarcII/selenium,JosephCastro/selenium,gabrielsimas/selenium,amar-sharma/selenium,MCGallaspy/selenium,GorK-ChO/selenium,livioc/selenium,petruc/selenium,JosephCastro/selenium,customcommander/selenium,bmannix/selenium,SouWilliams/selenium,gotcha/selenium,alexec/selenium,onedox/selenium,i17c/selenium,soundcloud/selenium,quoideneuf/selenium,uchida/selenium,temyers/selenium,meksh/selenium,alb-i986/selenium,Dude-X/selenium,jsakamoto/selenium,telefonicaid/selenium,sri85/selenium,sankha93/selenium,blackboarddd/selenium,kalyanjvn1/selenium,TheBlackTuxCorp/selenium,Jarob22/selenium,lummyare/lummyare-lummy,GorK-ChO/selenium,meksh/selenium,jabbrwcky/selenium,rplevka/selenium,doungni/selenium,lmtierney/selenium,thanhpete/selenium,dimacus/selenium,anshumanchatterji/selenium,jerome-jacob/selenium,asashour/selenium,alexec/selenium,valfirst/selenium,5hawnknight/selenium,p0deje/selenium,tbeadle/selenium,gotcha/selenium,houchj/selenium,lummyare/lummyare-test,mojwang/selenium,yukaReal/selenium,uchida/selenium,petruc/selenium,meksh/selenium,tarlabs/selenium,xmhubj/selenium,clavery/selenium,DrMarcII/selenium,denis-vilyuzhanin/selenium-fastview,customcommander/selenium,Ardesco/selenium,gotcha/selenium,twalpole/selenium,gregerrag/selenium,jerome-jacob/selenium,customcommander/selenium,rovner/selenium,valfirst/selenium,manuelpirez/selenium,freynaud/selenium,amikey/selenium,jsakamoto/selenium,MCGallaspy/selenium,oddui/selenium,titusfortner/selenium,xsyntrex/selenium,doungni/selenium,orange-tv-blagnac/selenium,temyers/selenium,markodolancic/selenium,blueyed/selenium,asashour/selenium,MeetMe/selenium,JosephCastro/selenium,xmhubj/selenium,amar-sharma/selenium,TikhomirovSergey/selenium,temyers/selenium,onedox/selenium,DrMarcII/selenium,arunsingh/selenium,RamaraoDonta/ramarao-clone,tbeadle/selenium,AutomatedTester/selenium,sag-enorman/selenium,sag-enorman/selenium,amar-sharma/selenium,Dude-X/selenium,xsyntrex/selenium,eric-stanley/selenium,vveliev/selenium,Tom-Trumper/selenium,quoideneuf/selenium,soundcloud/selenium,gregerrag/selenium,TikhomirovSergey/selenium,orange-tv-blagnac/selenium,mach6/selenium,knorrium/selenium,mach6/selenium,bmannix/selenium,jabbrwcky/selenium,orange-tv-blagnac/selenium,orange-tv-blagnac/selenium,jerome-jacob/selenium,MeetMe/selenium,arunsingh/selenium,yukaReal/selenium,chrsmithdemos/selenium,minhthuanit/selenium,xmhubj/selenium,skurochkin/selenium,tarlabs/selenium,twalpole/selenium,gemini-testing/selenium,Appdynamics/selenium,clavery/selenium,sankha93/selenium,xsyntrex/selenium,tbeadle/selenium,juangj/selenium,lummyare/lummyare-test,dcjohnson1989/selenium,meksh/selenium,Appdynamics/selenium,uchida/selenium,tkurnosova/selenium,carlosroh/selenium,oddui/selenium,dbo/selenium,gurayinan/selenium,davehunt/selenium,SevInf/IEDriver,carsonmcdonald/selenium,gurayinan/selenium,dibagga/selenium,dbo/selenium,Jarob22/selenium,JosephCastro/selenium,oddui/selenium,rrussell39/selenium,lummyare/lummyare-test,joshmgrant/selenium,Ardesco/selenium,sri85/selenium,uchida/selenium,eric-stanley/selenium,Dude-X/selenium,freynaud/selenium,titusfortner/selenium,tbeadle/selenium,dandv/selenium,bayandin/selenium,yukaReal/selenium,juangj/selenium,temyers/selenium,chrisblock/selenium,joshmgrant/selenium,lummyare/lummyare-lummy,sag-enorman/selenium,chrsmithdemos/selenium,stupidnetizen/selenium,joshmgrant/selenium,tbeadle/selenium,joshuaduffy/selenium,lmtierney/selenium,orange-tv-blagnac/selenium,soundcloud/selenium,lilredindy/selenium,dimacus/selenium,krmahadevan/selenium,Dude-X/selenium,slongwang/selenium,xmhubj/selenium,sri85/selenium,MeetMe/selenium,MeetMe/selenium,s2oBCN/selenium,gotcha/selenium,slongwang/selenium,rrussell39/selenium,Sravyaksr/selenium,i17c/selenium,isaksky/selenium,manuelpirez/selenium,oddui/selenium,JosephCastro/selenium,Sravyaksr/selenium,houchj/selenium,actmd/selenium,jsarenik/jajomojo-selenium,joshmgrant/selenium,twalpole/selenium,GorK-ChO/selenium,joshuaduffy/selenium,denis-vilyuzhanin/selenium-fastview,SeleniumHQ/selenium,xmhubj/selenium,carlosroh/selenium,zenefits/selenium,onedox/selenium,p0deje/selenium,joshbruning/selenium,titusfortner/selenium,gregerrag/selenium,joshbruning/selenium,gurayinan/selenium,jknguyen/josephknguyen-selenium,knorrium/selenium,knorrium/selenium,stupidnetizen/selenium,jsakamoto/selenium,gregerrag/selenium,misttechnologies/selenium,sankha93/selenium,slongwang/selenium,orange-tv-blagnac/selenium,misttechnologies/selenium,krosenvold/selenium,skurochkin/selenium,tkurnosova/selenium,jsarenik/jajomojo-selenium,aluedeke/chromedriver,quoideneuf/selenium,amikey/selenium,BlackSmith/selenium,Appdynamics/selenium,kalyanjvn1/selenium,denis-vilyuzhanin/selenium-fastview,yukaReal/selenium,amar-sharma/selenium,sag-enorman/selenium,asolntsev/selenium,petruc/selenium,clavery/selenium,SevInf/IEDriver,dandv/selenium,denis-vilyuzhanin/selenium-fastview,SeleniumHQ/selenium,dcjohnson1989/selenium,s2oBCN/selenium,oddui/selenium,carsonmcdonald/selenium,dimacus/selenium,Tom-Trumper/selenium,MCGallaspy/selenium,SouWilliams/selenium,soundcloud/selenium,joshuaduffy/selenium,markodolancic/selenium,gregerrag/selenium,dimacus/selenium,Dude-X/selenium,valfirst/selenium,Herst/selenium,knorrium/selenium,chrsmithdemos/selenium,RamaraoDonta/ramarao-clone,twalpole/selenium,slongwang/selenium,blueyed/selenium,Jarob22/selenium,lukeis/selenium,bmannix/selenium,minhthuanit/selenium,vinay-qa/vinayit-android-server-apk,uchida/selenium,Jarob22/selenium,dibagga/selenium,houchj/selenium,gorlemik/selenium,anshumanchatterji/selenium,aluedeke/chromedriver,amar-sharma/selenium,wambat/selenium,markodolancic/selenium,gemini-testing/selenium,misttechnologies/selenium,davehunt/selenium,lukeis/selenium,telefonicaid/selenium,minhthuanit/selenium,onedox/selenium,dbo/selenium,Tom-Trumper/selenium,GorK-ChO/selenium,dimacus/selenium,stupidnetizen/selenium,SeleniumHQ/selenium,lummyare/lummyare-test,Jarob22/selenium,joshmgrant/selenium,davehunt/selenium,o-schneider/selenium,asolntsev/selenium,gotcha/selenium,carsonmcdonald/selenium,gabrielsimas/selenium,rplevka/selenium,petruc/selenium,kalyanjvn1/selenium,zenefits/selenium,gorlemik/selenium,MeetMe/selenium,mojwang/selenium,thanhpete/selenium,gurayinan/selenium,pulkitsinghal/selenium,freynaud/selenium,lukeis/selenium,SouWilliams/selenium,TikhomirovSergey/selenium,denis-vilyuzhanin/selenium-fastview,eric-stanley/selenium,blackboarddd/selenium,jerome-jacob/selenium,gotcha/selenium,rovner/selenium,titusfortner/selenium,blackboarddd/selenium,manuelpirez/selenium,lrowe/selenium,SeleniumHQ/selenium,bayandin/selenium,isaksky/selenium,amikey/selenium,meksh/selenium,wambat/selenium,vveliev/selenium,dbo/selenium,twalpole/selenium,bartolkaruza/selenium,DrMarcII/selenium,thanhpete/selenium,valfirst/selenium,vinay-qa/vinayit-android-server-apk,TheBlackTuxCorp/selenium,anshumanchatterji/selenium,dandv/selenium,bartolkaruza/selenium,MCGallaspy/selenium,GorK-ChO/selenium,AutomatedTester/selenium,jsakamoto/selenium,onedox/selenium,TheBlackTuxCorp/selenium,o-schneider/selenium,arunsingh/selenium,arunsingh/selenium,joshbruning/selenium,skurochkin/selenium,TikhomirovSergey/selenium,actmd/selenium,slongwang/selenium,davehunt/selenium,HtmlUnit/selenium,5hawnknight/selenium,telefonicaid/selenium,lummyare/lummyare-lummy,compstak/selenium,orange-tv-blagnac/selenium,wambat/selenium,p0deje/selenium,vinay-qa/vinayit-android-server-apk,titusfortner/selenium,lmtierney/selenium,rrussell39/selenium,lummyare/lummyare-test,sebady/selenium,TheBlackTuxCorp/selenium,yukaReal/selenium,krosenvold/selenium,joshbruning/selenium,telefonicaid/selenium,asashour/selenium,lummyare/lummyare-test,RamaraoDonta/ramarao-clone,p0deje/selenium,davehunt/selenium,anshumanchatterji/selenium,compstak/selenium,HtmlUnit/selenium,davehunt/selenium,alexec/selenium,sevaseva/selenium,Ardesco/selenium,RamaraoDonta/ramarao-clone,blackboarddd/selenium,asashour/selenium,o-schneider/selenium,jsakamoto/selenium,actmd/selenium,sankha93/selenium,jknguyen/josephknguyen-selenium,yukaReal/selenium,doungni/selenium,lmtierney/selenium,xsyntrex/selenium,blueyed/selenium,aluedeke/chromedriver,amikey/selenium,carsonmcdonald/selenium,vinay-qa/vinayit-android-server-apk,AutomatedTester/selenium,sebady/selenium,doungni/selenium,customcommander/selenium,vveliev/selenium,xsyntrex/selenium,dcjohnson1989/selenium,jerome-jacob/selenium,p0deje/selenium,BlackSmith/selenium,sebady/selenium,GorK-ChO/selenium,sevaseva/selenium,customcommander/selenium,tarlabs/selenium,isaksky/selenium,BlackSmith/selenium,uchida/selenium,Appdynamics/selenium,denis-vilyuzhanin/selenium-fastview,zenefits/selenium,jknguyen/josephknguyen-selenium,lummyare/lummyare-lummy,SouWilliams/selenium,bmannix/selenium,knorrium/selenium,compstak/selenium,asashour/selenium,houchj/selenium,Appdynamics/selenium,gorlemik/selenium,livioc/selenium,amikey/selenium,dkentw/selenium,vinay-qa/vinayit-android-server-apk,jsarenik/jajomojo-selenium,uchida/selenium,alexec/selenium,SeleniumHQ/selenium,Ardesco/selenium,alexec/selenium,Appdynamics/selenium,joshmgrant/selenium,joshbruning/selenium,AutomatedTester/selenium,o-schneider/selenium,HtmlUnit/selenium,livioc/selenium,TikhomirovSergey/selenium,lmtierney/selenium,p0deje/selenium,dcjohnson1989/selenium,wambat/selenium,chrisblock/selenium,isaksky/selenium,o-schneider/selenium,HtmlUnit/selenium,rovner/selenium,livioc/selenium,chrisblock/selenium,mojwang/selenium,MCGallaspy/selenium,pulkitsinghal/selenium,jsarenik/jajomojo-selenium,joshuaduffy/selenium,GorK-ChO/selenium,MCGallaspy/selenium,HtmlUnit/selenium,carlosroh/selenium,sankha93/selenium,xmhubj/selenium,skurochkin/selenium,5hawnknight/selenium,carsonmcdonald/selenium,anshumanchatterji/selenium,valfirst/selenium,joshmgrant/selenium,rrussell39/selenium,telefonicaid/selenium,petruc/selenium,gurayinan/selenium,vveliev/selenium,isaksky/selenium,rplevka/selenium,jabbrwcky/selenium,tarlabs/selenium,alb-i986/selenium,blueyed/selenium,dandv/selenium,slongwang/selenium,juangj/selenium,jknguyen/josephknguyen-selenium,chrsmithdemos/selenium,Sravyaksr/selenium,amar-sharma/selenium
/* Copyright 2011 WebDriver committers Copyright 2011 Software Freedom Conservancy. 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.openqa.selenium.support.ui; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.NoSuchFrameException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Canned {@link ExpectedCondition}s which are generally useful within webdriver * tests. */ public class ExpectedConditions { private final static Logger log = Logger.getLogger(ExpectedConditions.class.getName()); private ExpectedConditions() { // Utility class } /** * An expectation for checking the title of a page. * * @param title the expected title, which must be an exact match * @return true when the title matches, false otherwise */ public static ExpectedCondition<Boolean> titleIs(final String title) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return title.equals(driver.getTitle()); } }; } /** * An expectation for checking that the title contains a case-sensitive * substring * * @param title the fragment of title expected * @return true when the title matches, false otherwise */ public static ExpectedCondition<Boolean> titleContains(final String title) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { String currentTitle = driver.getTitle(); return currentTitle == null ? false : currentTitle.contains(title); } }; } /** * An expectation for checking that an element is present on the DOM of a * page. This does not necessarily mean that the element is visible. * * @param locator used to find the element * @return the WebElement once it is located */ public static ExpectedCondition<WebElement> presenceOfElementLocated( final By locator) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { return findElement(locator, driver); } }; } /** * An expectation for checking that an element is present on the DOM of a page * and visible. Visibility means that the element is not only displayed but * also has a height and width that is greater than 0. * * @param locator used to find the element * @return the WebElement once it is located and visible */ public static ExpectedCondition<WebElement> visibilityOfElementLocated( final By locator) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { try { return elementIfVisible(findElement(locator, driver)); } catch (StaleElementReferenceException e) { return null; } } }; } /** * An expectation for checking that an element, known to be present on the DOM * of a page, is visible. Visibility means that the element is not only * displayed but also has a height and width that is greater than 0. * * @param element the WebElement * @return the (same) WebElement once it is visible */ public static ExpectedCondition<WebElement> visibilityOf( final WebElement element) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { return elementIfVisible(element); } }; } /** * @return the given element if it is visible and has non-zero size, otherwise * null. */ private static WebElement elementIfVisible(WebElement element) { try { return element.isDisplayed() ? element : null; } catch (StaleElementReferenceException e) { // Returns null because a stale element reference implies that element // is no longer visible. return null; } } /** * An expectation for checking that there is at least one element present on a * web page. * * @param locator used to find the element * @return the list of WebElements once they are located */ public static ExpectedCondition<List<WebElement>> presenceOfAllElementsLocatedBy( final By locator) { return new ExpectedCondition<List<WebElement>>() { public List<WebElement> apply(WebDriver driver) { return findElements(locator, driver); } }; } /** * An expectation for checking if the given text is present in the specified * element. */ public static ExpectedCondition<Boolean> textToBePresentInElement( final By locator, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementText = findElement(locator, from).getText(); return elementText.contains(text); } catch (StaleElementReferenceException e) { return null; } } }; } /** * An expectation for checking if the given text is present in the specified * elements value attribute. */ public static ExpectedCondition<Boolean> textToBePresentInElementValue( final By locator, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementText = findElement(locator, from).getAttribute("value"); if (elementText != null) { return elementText.contains(text); } else { return false; } } catch (StaleElementReferenceException e) { return null; } } }; } /** * An expectation for checking whether the given frame is available to switch * to. <p> If the frame is available it switches the given driver to the * specified frame. */ public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt( final String frameLocator) { return new ExpectedCondition<WebDriver>() { public WebDriver apply(WebDriver from) { try { return from.switchTo().frame(frameLocator); } catch (NoSuchFrameException e) { return null; } } }; } /** * An Expectation for checking that an element is either invisible or not * present on the DOM. * * @param locator used to find the element */ public static ExpectedCondition<Boolean> invisibilityOfElementLocated( final By locator) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { return !(findElement(locator, driver).isDisplayed()); } catch (NoSuchElementException e) { // Returns true because the element is not present in DOM. The // try block checks if the element is present but is invisible. return true; } catch (StaleElementReferenceException e) { // Returns true because stale element reference implies that element // is no longer visible. return true; } } }; } /** * An Expectation for checking an element is visible and enabled such that you * can click it. */ public static ExpectedCondition<WebElement> elementToBeClickable( final By locator) { return new ExpectedCondition<WebElement>() { public ExpectedCondition<WebElement> visibilityOfElementLocated = ExpectedConditions.visibilityOfElementLocated(locator); public WebElement apply(WebDriver driver) { WebElement element = visibilityOfElementLocated.apply(driver); try { if (element != null && element.isEnabled()) { return element; } else { return null; } } catch (StaleElementReferenceException e) { return null; } } }; } /** * Wait until an element is no longer attached to the DOM. * * @param element The element to wait for. * @return false is the element is still attached to the DOM, true * otherwise. */ public static ExpectedCondition<Boolean> stalenessOf( final WebElement element) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver ignored) { try { // Calling any method forces a staleness check element.isEnabled(); return false; } catch (StaleElementReferenceException expected) { return true; } } }; } /** * An expectation for checking if the given element is selected. */ public static ExpectedCondition<Boolean> elementToBeSelected(final WebElement element) { return elementSelectionStateToBe(element, true); } /** * An expectation for checking if the given element is selected. */ public static ExpectedCondition<Boolean> elementSelectionStateToBe(final WebElement element, final boolean selected) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { return element.isSelected() == selected; } catch (StaleElementReferenceException e) { return false; } } }; } /** * Looks up an element. Logs and re-throws WebDriverException if thrown. <p/> * Method exists to gather data for http://code.google.com/p/selenium/issues/detail?id=1800 */ private static WebElement findElement(By by, WebDriver driver) { try { return driver.findElement(by); } catch (NoSuchElementException e) { throw e; } catch (WebDriverException e) { log.log(Level.WARNING, String.format("WebDriverException thrown by findElement(%s)", by), e); throw e; } } /** * @see #findElement(By, WebDriver) */ private static List<WebElement> findElements(By by, WebDriver driver) { try { return driver.findElements(by); } catch (WebDriverException e) { log.log(Level.WARNING, String.format("WebDriverException thrown by findElement(%s)", by), e); throw e; } } }
java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java
/* Copyright 2011 WebDriver committers Copyright 2011 Software Freedom Conservancy. 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.openqa.selenium.support.ui; import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.NoSuchFrameException; import org.openqa.selenium.StaleElementReferenceException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.WebElement; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Canned {@link ExpectedCondition}s which are generally useful within webdriver * tests. */ public class ExpectedConditions { private final static Logger log = Logger.getLogger(ExpectedConditions.class.getName()); private ExpectedConditions() { // Utility class } /** * An expectation for checking the title of a page. * * @param title the expected title, which must be an exact match * @return true when the title matches, false otherwise */ public static ExpectedCondition<Boolean> titleIs(final String title) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { return title.equals(driver.getTitle()); } }; } /** * An expectation for checking that the title contains a case-sensitive * substring * * @param title the fragment of title expected * @return true when the title matches, false otherwise */ public static ExpectedCondition<Boolean> titleContains(final String title) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { String currentTitle = driver.getTitle(); return currentTitle == null ? false : currentTitle.contains(title); } }; } /** * An expectation for checking that an element is present on the DOM of a * page. This does not necessarily mean that the element is visible. * * @param locator used to find the element * @return the WebElement once it is located */ public static ExpectedCondition<WebElement> presenceOfElementLocated( final By locator) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { return findElement(locator, driver); } }; } /** * An expectation for checking that an element is present on the DOM of a page * and visible. Visibility means that the element is not only displayed but * also has a height and width that is greater than 0. * * @param locator used to find the element * @return the WebElement once it is located and visible */ public static ExpectedCondition<WebElement> visibilityOfElementLocated( final By locator) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { try { return elementIfVisible(findElement(locator, driver)); } catch (StaleElementReferenceException e) { return null; } } }; } /** * An expectation for checking that an element, known to be present on the DOM * of a page, is visible. Visibility means that the element is not only * displayed but also has a height and width that is greater than 0. * * @param element the WebElement * @return the (same) WebElement once it is visible */ public static ExpectedCondition<WebElement> visibilityOf( final WebElement element) { return new ExpectedCondition<WebElement>() { public WebElement apply(WebDriver driver) { return elementIfVisible(element); } }; } /** * @return the given element if it is visible and has non-zero size, otherwise * null. */ private static WebElement elementIfVisible(WebElement element) { return element.isDisplayed() ? element : null; } /** * An expectation for checking that there is at least one element present on a * web page. * * @param locator used to find the element * @return the list of WebElements once they are located */ public static ExpectedCondition<List<WebElement>> presenceOfAllElementsLocatedBy( final By locator) { return new ExpectedCondition<List<WebElement>>() { public List<WebElement> apply(WebDriver driver) { return findElements(locator, driver); } }; } /** * An expectation for checking if the given text is present in the specified * element. */ public static ExpectedCondition<Boolean> textToBePresentInElement( final By locator, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementText = findElement(locator, from).getText(); return elementText.contains(text); } catch (StaleElementReferenceException e) { return null; } } }; } /** * An expectation for checking if the given text is present in the specified * elements value attribute. */ public static ExpectedCondition<Boolean> textToBePresentInElementValue( final By locator, final String text) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver from) { try { String elementText = findElement(locator, from).getAttribute("value"); if (elementText != null) { return elementText.contains(text); } else { return false; } } catch (StaleElementReferenceException e) { return null; } } }; } /** * An expectation for checking whether the given frame is available to switch * to. <p> If the frame is available it switches the given driver to the * specified frame. */ public static ExpectedCondition<WebDriver> frameToBeAvailableAndSwitchToIt( final String frameLocator) { return new ExpectedCondition<WebDriver>() { public WebDriver apply(WebDriver from) { try { return from.switchTo().frame(frameLocator); } catch (NoSuchFrameException e) { return null; } } }; } /** * An Expectation for checking that an element is either invisible or not * present on the DOM. * * @param locator used to find the element */ public static ExpectedCondition<Boolean> invisibilityOfElementLocated( final By locator) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { try { return !(findElement(locator, driver).isDisplayed()); } catch (NoSuchElementException e) { // Returns true because the element is not present in DOM. The // try block checks if the element is present but is invisible. return true; } catch (StaleElementReferenceException e) { // Returns true because stale element reference implies that element // is no longer visible. return true; } } }; } /** * An Expectation for checking an element is visible and enabled such that you * can click it. */ public static ExpectedCondition<WebElement> elementToBeClickable( final By locator) { return new ExpectedCondition<WebElement>() { public ExpectedCondition<WebElement> visibilityOfElementLocated = ExpectedConditions.visibilityOfElementLocated(locator); public WebElement apply(WebDriver driver) { WebElement element = visibilityOfElementLocated.apply(driver); if (element != null && element.isEnabled()) { return element; } else { return null; } } }; } /** * Wait until an element is no longer attached to the DOM. * * @param element The element to wait for. * @return false is the element is still attached to the DOM, true * otherwise. */ public static ExpectedCondition<Boolean> stalenessOf( final WebElement element) { return new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver ignored) { try { // Calling any method forces a staleness check element.isEnabled(); return false; } catch (StaleElementReferenceException expected) { return true; } } }; } /** * Looks up an element. Logs and re-throws WebDriverException if thrown. <p/> * Method exists to gather data for http://code.google.com/p/selenium/issues/detail?id=1800 */ private static WebElement findElement(By by, WebDriver driver) { try { return driver.findElement(by); } catch (NoSuchElementException e) { throw e; } catch (WebDriverException e) { log.log(Level.WARNING, String.format("WebDriverException thrown by findElement(%s)", by), e); throw e; } } /** * @see #findElement(By, WebDriver) */ private static List<WebElement> findElements(By by, WebDriver driver) { try { return driver.findElements(by); } catch (WebDriverException e) { log.log(Level.WARNING, String.format("WebDriverException thrown by findElement(%s)", by), e); throw e; } } }
EranMes: Fixing some ExpectedConditions not catching StaleElementReferenceException and adding expected conditions for selection state. r14940
java/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java
EranMes: Fixing some ExpectedConditions not catching StaleElementReferenceException and adding expected conditions for selection state.
<ide><path>ava/client/src/org/openqa/selenium/support/ui/ExpectedConditions.java <ide> * null. <ide> */ <ide> private static WebElement elementIfVisible(WebElement element) { <del> return element.isDisplayed() ? element : null; <add> try { <add> return element.isDisplayed() ? element : null; <add> } catch (StaleElementReferenceException e) { <add> // Returns null because a stale element reference implies that element <add> // is no longer visible. <add> return null; <add> } <ide> } <ide> <ide> /** <ide> <ide> public WebElement apply(WebDriver driver) { <ide> WebElement element = visibilityOfElementLocated.apply(driver); <del> if (element != null && element.isEnabled()) { <del> return element; <del> } else { <add> try { <add> if (element != null && element.isEnabled()) { <add> return element; <add> } else { <add> return null; <add> } <add> } catch (StaleElementReferenceException e) { <ide> return null; <ide> } <ide> } <ide> }; <ide> } <ide> <add> /** <add> * An expectation for checking if the given element is selected. <add> */ <add> public static ExpectedCondition<Boolean> elementToBeSelected(final WebElement element) { <add> return elementSelectionStateToBe(element, true); <add> } <add> <add> /** <add> * An expectation for checking if the given element is selected. <add> */ <add> public static ExpectedCondition<Boolean> elementSelectionStateToBe(final WebElement element, <add> final boolean selected) { <add> return new ExpectedCondition<Boolean>() { <add> public Boolean apply(WebDriver from) { <add> try { <add> return element.isSelected() == selected; <add> } catch (StaleElementReferenceException e) { <add> return false; <add> } <add> } <add> }; <add> } <ide> <ide> /** <ide> * Looks up an element. Logs and re-throws WebDriverException if thrown. <p/>
Java
agpl-3.0
a7ebb690d5275a45e62c2020a317971cce4402b0
0
Skelril/Aurora
/* * Copyright (c) 2014 Wyatt Childers. * * All Rights Reserved */ package com.skelril.aurora.economic.store; import com.sk89q.commandbook.CommandBook; import com.sk89q.commandbook.commands.PaginatedResult; import com.sk89q.commandbook.session.SessionComponent; import com.sk89q.commandbook.util.entity.player.PlayerUtil; import com.sk89q.minecraft.util.commands.*; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.skelril.aurora.admin.AdminComponent; import com.skelril.aurora.economic.store.mysql.MySQLItemStoreDatabase; import com.skelril.aurora.economic.store.mysql.MySQLMarketTransactionDatabase; import com.skelril.aurora.exceptions.UnknownPluginException; import com.skelril.aurora.util.ChatUtil; import com.skelril.aurora.util.EnvironmentUtil; import com.skelril.aurora.util.item.ItemType; import com.skelril.aurora.util.item.ItemUtil; import com.skelril.aurora.util.item.custom.CustomItemCenter; import com.skelril.aurora.util.item.custom.CustomItems; import com.zachsthings.libcomponents.ComponentInformation; import com.zachsthings.libcomponents.Depend; import com.zachsthings.libcomponents.InjectComponent; import com.zachsthings.libcomponents.bukkit.BukkitComponent; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import java.util.*; import java.util.logging.Logger; @ComponentInformation(friendlyName = "Admin Store", desc = "Admin Store system.") @Depend(plugins = {"WorldGuard"}, components = {AdminComponent.class, SessionComponent.class}) public class AdminStoreComponent extends BukkitComponent { private final CommandBook inst = CommandBook.inst(); private final Logger log = CommandBook.logger(); private final Server server = CommandBook.server(); @InjectComponent private AdminComponent adminComponent; @InjectComponent private SessionComponent sessions; private static ItemStoreDatabase itemDatabase; private static MarketTransactionDatabase transactionDatabase; private ProtectedRegion region = null; private Economy econ; @Override public void enable() { itemDatabase = new MySQLItemStoreDatabase(); itemDatabase.load(); transactionDatabase = new MySQLMarketTransactionDatabase(); transactionDatabase.load(); // Setup external systems setupEconomy(); // Register commands registerCommands(Commands.class); // Get the region server.getScheduler().runTaskLater(inst, () -> { try { region = getWorldGuard().getGlobalRegionManager().get(Bukkit.getWorld("City")).getRegion("vineam-district-bank"); } catch (UnknownPluginException e) { e.printStackTrace(); } }, 1); } @Override public void reload() { itemDatabase.load(); } private final String NOT_AVAILIBLE = "No item by that name is currently available!"; public class Commands { @Command(aliases = {"market", "mk", "ge"}, desc = "Admin Store commands") @NestedCommand({StoreCommands.class}) public void storeCommands(CommandContext args, CommandSender sender) throws CommandException { } } public class StoreCommands { @Command(aliases = {"buy", "b"}, usage = "[-a amount] <item name>", desc = "Buy an item", flags = "a:", min = 1) public void buyCmd(CommandContext args, CommandSender sender) throws CommandException { String playerName = checkPlayer(sender); Player player = (Player) sender; String itemName = args.getJoinedStrings(0).toLowerCase(); if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException(NOT_AVAILIBLE); } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null || !itemPricePair.isBuyable()) { throw new CommandException(NOT_AVAILIBLE); } itemName = itemPricePair.getName(); int amt = 1; if (args.hasFlag('a')) { amt = Math.max(1, args.getFlagInteger('a')); } double price = itemPricePair.getPrice() * amt; double rebate = 0; double lottery = price * .03; if (inst.hasPermission(sender, "aurora.market.rebate.onepointseven")) { rebate = price * .017; } if (!econ.has(playerName, price)) { throw new CommandException("You do not have enough money to purchase that item(s)."); } // Get the items and add them to the inventory ItemStack[] itemStacks = getItem(itemPricePair.getName(), amt); for (ItemStack itemStack : itemStacks) { if (player.getInventory().firstEmpty() == -1) { player.getWorld().dropItem(player.getLocation(), itemStack); continue; } player.getInventory().addItem(itemStack); } // Deposit into the lottery account econ.bankDeposit("Lottery", lottery); // Charge the money and send the sender some feedback econ.withdrawPlayer(playerName, price - rebate); transactionDatabase.logTransaction(playerName, itemName, amt); transactionDatabase.save(); String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(price), ""); ChatUtil.sendNotice(sender, "Item(s) purchased for " + priceString + "!"); if (rebate >= 0.01) { String rebateString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(rebate), ""); ChatUtil.sendNotice(sender, "You get " + rebateString + " back."); } // Market Command Help StoreSession sess = sessions.getSession(StoreSession.class, player); if (amt == 1 && sess.recentPurch() && sess.getLastPurch().equals(itemName)) { ChatUtil.sendNotice(sender, "Did you know you can specify the amount of items to buy?"); ChatUtil.sendNotice(sender, "/market buy -a <amount> " + itemName); } sess.setLastPurch(itemName); } @Command(aliases = {"sell", "s"}, usage = "", desc = "Sell an item", flags = "hau", min = 0, max = 0) public void sellCmd(CommandContext args, CommandSender sender) throws CommandException { String playerName = checkPlayer(sender); final Player player = (Player) sender; ItemStack[] itemStacks = player.getInventory().getContents(); HashMap<String, Integer> transactions = new HashMap<>(); double payment = 0; ItemStack filter = null; boolean singleItem = false; int min, max; if (args.hasFlag('a')) { min = 0; max = itemStacks.length; } else if (args.hasFlag('h')) { min = 0; max = 9; } else { min = player.getInventory().getHeldItemSlot(); max = min + 1; singleItem = true; } if (!singleItem && !args.hasFlag('u')) { filter = player.getItemInHand().clone(); if (!ItemType.usesDamageValue(filter.getTypeId())) { filter.setDurability((short) 0); } } for (int i = min; i < max; i++) { ItemStack stack = itemStacks[i]; if (stack == null || stack.getTypeId() == 0) { if (singleItem) { throw new CommandException("That's not a valid item!"); } else { continue; } } if (filter != null) { ItemStack testStack = stack.clone(); if (!ItemType.usesDamageValue(testStack.getTypeId())) { testStack.setDurability((short) 0); } if (!filter.isSimilar(testStack)) continue; } ItemMeta stackMeta = stack.getItemMeta(); String itemName = stack.getTypeId() + ":" + stack.getDurability(); if (stackMeta.hasDisplayName()) { itemName = stackMeta.getDisplayName(); if (!ItemUtil.isAuthenticCustomItem(itemName)) { if (singleItem) { throw new CommandException("You cannot sell items that have been renamed here!"); } else { continue; } } itemName = ChatColor.stripColor(itemName); } double percentageSale = 1; if (stack.getDurability() != 0 && !ItemType.usesDamageValue(stack.getTypeId())) { if (stack.getAmount() > 1) { if (singleItem) { throw new CommandException(NOT_AVAILIBLE); } else { continue; } } percentageSale = 1 - ((double) stack.getDurability() / (double) stack.getType().getMaxDurability()); } if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { if (singleItem) { throw new CommandException(NOT_AVAILIBLE); } else { continue; } } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null || !itemPricePair.isSellable()) { if (singleItem) { throw new CommandException(NOT_AVAILIBLE); } else { continue; } } int amt = stack.getAmount(); payment += itemPricePair.getSellPrice() * amt * percentageSale; // Multiply the amount by -1 since this is selling amt *= -1; if (transactions.containsKey(itemName)) { amt += transactions.get(itemName); } transactions.put(itemName, amt); itemStacks[i] = null; } if (transactions.isEmpty()) { throw new CommandException("No sellable items found" + (filter != null ? " that matched the filter" : "") + "!"); } for (Map.Entry<String, Integer> entry : transactions.entrySet()) { transactionDatabase.logTransaction(playerName, entry.getKey(), entry.getValue()); } transactionDatabase.save(); econ.depositPlayer(playerName, payment); player.getInventory().setContents(itemStacks); String paymentString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(payment), ""); ChatUtil.sendNotice(player, "Item(s) sold for: " + paymentString + "!"); // Market Command Help StoreSession sess = sessions.getSession(StoreSession.class, player); if (singleItem && sess.recentSale() && !sess.recentNotice()) { ChatUtil.sendNotice(sender, "Did you know you can sell more than one stack at a time?"); ChatUtil.sendNotice(sender, "To sell all of what you're holding:"); ChatUtil.sendNotice(sender, "/market sell -a"); ChatUtil.sendNotice(sender, "To sell everything in your inventory:"); ChatUtil.sendNotice(sender, "/market sell -au"); sess.updateNotice(); } sess.updateSale(); } @Command(aliases = {"enchant"}, usage = "<enchantment> <level>", desc = "Enchant an item", flags = "fy", min = 2, max = 2) public void enchantCmd(CommandContext args, CommandSender sender) throws CommandException { Player player = PlayerUtil.checkPlayer(sender); boolean isAdmin = adminComponent.isAdmin(player); if (!isAdmin) checkInArea(player); Enchantment enchantment = Enchantment.getByName(args.getString(0).toUpperCase()); int level = args.getInteger(1); if (enchantment == null) { throw new CommandException("That enchantment could not be found!"); } int min = enchantment.getStartLevel(); int max = enchantment.getMaxLevel(); if (level < min || level > max) { throw new CommandException("Enchantment level must be between " + min + " and " + max + '!'); } ItemStack targetItem = player.getItemInHand(); if (targetItem == null || targetItem.getTypeId() == BlockID.AIR) { throw new CommandException("You're not holding an item!"); } if (!enchantment.canEnchantItem(targetItem)) { throw new CommandException("You cannot give this item that enchantment!"); } ItemMeta meta = targetItem.getItemMeta(); if (meta.hasEnchant(enchantment)) { if (!args.hasFlag('f')) { throw new CommandException("That enchantment is already present, use -f to override this!"); } else { meta.removeEnchant(enchantment); } } if (!meta.addEnchant(enchantment, level, false)) { throw new CommandException("That enchantment could not be applied!"); } double cost = Math.max(1000, AdminStoreComponent.priceCheck(targetItem, false) * .1) * level; if (!isAdmin) { if (cost < 0) { throw new CommandException("That item cannot be enchanted!"); } if (!econ.has(player.getName(), cost)) { throw new CommandException("You don't have enough money!"); } String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(cost), ""); if (args.hasFlag('y')) { ChatUtil.sendNotice(sender, "Item enchanted for " + priceString + "!"); econ.withdrawPlayer(player.getName(), cost); } else { ChatUtil.sendNotice(sender, "That will cost " + priceString + '.'); ChatUtil.sendNotice(sender, "To confirm, use:"); String command = "/market enchant -y"; for (Character aChar : args.getFlags()) { command += aChar; } command += ' ' + enchantment.getName() + ' ' + level; ChatUtil.sendNotice(sender, command); return; } } else { ChatUtil.sendNotice(sender, "Item enchanted!"); } targetItem.setItemMeta(meta); } @Command(aliases = {"list", "l"}, usage = "[-p page] [filter...]", desc = "Get a list of items and their prices", flags = "p:", min = 0 ) public void listCmd(CommandContext args, CommandSender sender) throws CommandException { String filterString = args.argsLength() > 0 ? args.getJoinedStrings(0) : null; List<ItemPricePair> itemPricePairCollection = itemDatabase.getItemList(filterString, inst.hasPermission(sender, "aurora.admin.adminstore.disabled")); Collections.sort(itemPricePairCollection); new PaginatedResult<ItemPricePair>(ChatColor.GOLD + "Item List") { @Override public String format(ItemPricePair pair) { ChatColor color = pair.isEnabled() ? ChatColor.BLUE : ChatColor.DARK_RED; String buy, sell; if (pair.isBuyable() || !pair.isEnabled()) { buy = ChatColor.WHITE + econ.format(pair.getPrice()) + ChatColor.YELLOW; } else { buy = ChatColor.GRAY + "unavailable" + ChatColor.YELLOW; } if (pair.isSellable() || !pair.isEnabled()) { sell = ChatColor.WHITE + econ.format(pair.getSellPrice()) + ChatColor.YELLOW; } else { sell = ChatColor.GRAY + "unavailable" + ChatColor.YELLOW; } String message = color + pair.getName().toUpperCase() + ChatColor.YELLOW + " (Quick Price: " + buy + " - " + sell + ")"; return message.replace(' ' + econ.currencyNamePlural(), ""); } }.display(sender, itemPricePairCollection, args.getFlagInteger('p', 1)); } @Command(aliases = {"lookup", "value", "info", "pc"}, usage = "[item name]", desc = "Value an item", flags = "", min = 0) public void valueCmd(CommandContext args, CommandSender sender) throws CommandException { String itemName; double percentageSale = 1; if (args.argsLength() > 0) { itemName = args.getJoinedStrings(0).toLowerCase(); } else { ItemStack stack = PlayerUtil.checkPlayer(sender).getInventory().getItemInHand(); if (stack == null || stack.getTypeId() == 0) { throw new CommandException("That's not a valid item!"); } itemName = stack.getTypeId() + ":" + stack.getDurability(); ItemMeta stackMeta = stack.getItemMeta(); if (stackMeta.hasDisplayName()) { itemName = stackMeta.getDisplayName(); if (!ItemUtil.isAuthenticCustomItem(itemName)) { throw new CommandException(NOT_AVAILIBLE); } itemName = ChatColor.stripColor(itemName); } if (stack.getDurability() != 0 && !ItemType.usesDamageValue(stack.getTypeId())) { if (stack.getAmount() > 1) { throw new CommandException(NOT_AVAILIBLE); } percentageSale = 1 - ((double) stack.getDurability() / (double) stack.getType().getMaxDurability()); } } if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException(NOT_AVAILIBLE); } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null) { throw new CommandException(NOT_AVAILIBLE); } if (!itemPricePair.isEnabled() && !inst.hasPermission(sender, "aurora.admin.adminstore.disabled")) { throw new CommandException(NOT_AVAILIBLE); } ChatColor color = itemPricePair.isEnabled() ? ChatColor.BLUE : ChatColor.DARK_RED; double paymentPrice = itemPricePair.getSellPrice() * percentageSale; String purchasePrice = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(itemPricePair.getPrice()), ""); String sellPrice = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(paymentPrice), ""); ChatUtil.sendNotice(sender, ChatColor.GOLD, "Price Information for: " + color + itemName.toUpperCase()); // Purchase Information if (itemPricePair.isBuyable() || !itemPricePair.isEnabled()) { ChatUtil.sendNotice(sender, "When you buy it you pay:"); ChatUtil.sendNotice(sender, " - " + purchasePrice + " each."); } else { ChatUtil.sendNotice(sender, ChatColor.GRAY, "This item cannot be purchased."); } // Sale Information if (itemPricePair.isSellable() || !itemPricePair.isEnabled()) { ChatUtil.sendNotice(sender, "When you sell it you get:"); ChatUtil.sendNotice(sender, " - " + sellPrice + " each."); if (percentageSale != 1.0) { sellPrice = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(itemPricePair.getSellPrice()), ""); ChatUtil.sendNotice(sender, " - " + sellPrice + " each when new."); } } else { ChatUtil.sendNotice(sender, ChatColor.GRAY, "This item cannot be sold."); } } @Command(aliases = {"admin"}, desc = "Administrative Commands") @NestedCommand({AdminStoreCommands.class}) public void AdministrativeCommands(CommandContext args, CommandSender sender) throws CommandException { } } public class AdminStoreCommands { @Command(aliases = {"log"}, usage = "[-i item] [-u user] [-p page]", desc = "Item database logs", flags = "i:u:p:s", min = 0, max = 0) @CommandPermissions("aurora.admin.adminstore.log") public void logCmd(CommandContext args, CommandSender sender) throws CommandException { String item = args.getFlag('i', null); if (item != null && !hasItemOfName(item)) { ItemType type = ItemType.lookup(item); if (type == null) { throw new CommandException("No item by that name was found."); } item = type.getName(); } String player = args.getFlag('u', null); List<ItemTransaction> transactions = transactionDatabase.getTransactions(item, player); new PaginatedResult<ItemTransaction>(ChatColor.GOLD + "Market Transactions") { @Override public String format(ItemTransaction trans) { String message = ChatColor.YELLOW + trans.getPlayer() + ' '; if (trans.getAmount() > 0) { message += ChatColor.RED + "bought"; } else { message += ChatColor.DARK_GREEN + "sold"; } message += " " + ChatColor.YELLOW + Math.abs(trans.getAmount()) + ChatColor.BLUE + " " + trans.getItem().toUpperCase(); return message; } }.display(sender, transactions, args.getFlagInteger('p', 1)); } @Command(aliases = {"scale"}, usage = "<amount>", desc = "Scale the item database", flags = "", min = 1, max = 1) @CommandPermissions("aurora.admin.adminstore.scale") public void scaleCmd(CommandContext args, CommandSender sender) throws CommandException { double factor = args.getDouble(0); if (factor == 0) { throw new CommandException("Cannot scale by 0."); } List<ItemPricePair> items = itemDatabase.getItemList(); for (ItemPricePair item : items) { itemDatabase.addItem(sender.getName(), item.getName(), item.getPrice() * factor, !item.isBuyable(), !item.isSellable()); } itemDatabase.save(); ChatUtil.sendNotice(sender, "Market Scaled by: " + factor + "."); } @Command(aliases = {"add"}, usage = "[-p price] <item name>", desc = "Add an item to the database", flags = "bsp:", min = 1) @CommandPermissions("aurora.admin.adminstore.add") public void addCmd(CommandContext args, CommandSender sender) throws CommandException { String itemName = args.getJoinedStrings(0); if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException("No item by that name was found."); } itemName = type.getName(); } boolean disableBuy = args.hasFlag('b'); boolean disableSell = args.hasFlag('s'); double price = Math.max(.01, args.getFlagDouble('p', .1)); // Database operations ItemPricePair oldItem = itemDatabase.getItem(itemName); itemName = itemName.replace('_', ' '); itemDatabase.addItem(sender.getName(), itemName, price, disableBuy, disableSell); itemDatabase.save(); // Notification String noticeString = oldItem == null ? " added with a price of " : " is now "; String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(price), " "); ChatUtil.sendNotice(sender, ChatColor.BLUE + itemName.toUpperCase() + ChatColor.YELLOW + noticeString + priceString + "!"); if (disableBuy) { ChatUtil.sendNotice(sender, " - It cannot be purchased."); } if (disableSell) { ChatUtil.sendNotice(sender, " - It cannot be sold."); } } @Command(aliases = {"remove"}, usage = "<item name>", desc = "Value an item", flags = "", min = 1) @CommandPermissions("aurora.admin.adminstore.remove") public void removeCmd(CommandContext args, CommandSender sender) throws CommandException { String itemName = args.getJoinedStrings(0); if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException(NOT_AVAILIBLE); } itemName = type.getName(); } if (itemDatabase.getItem(itemName) == null) { throw new CommandException(NOT_AVAILIBLE); } itemDatabase.removeItem(sender.getName(), itemName); itemDatabase.save(); ChatUtil.sendNotice(sender, ChatColor.BLUE + itemName.toUpperCase() + ChatColor.YELLOW + " has been removed from the database!"); } } private static Set<String> names = new HashSet<>(); static { for (CustomItems item : CustomItems.values()) { names.add(item.name()); } } private static boolean hasItemOfName(String name) { return names.contains(name.toUpperCase().replace(' ', '_')); } private static ItemStack[] getItem(String name, int amount) throws CommandException { name = name.toUpperCase().replace(" ", "_"); List<ItemStack> itemStacks = new ArrayList<>(); ItemStack stack; ItemType type = ItemType.lookup(name); if (type == null) { try { CustomItems item = CustomItems.valueOf(name); stack = CustomItemCenter.build(item); } catch (IllegalArgumentException ex) { throw new CommandException("Please report this error, " + name + " could not be found."); } } else { stack = new ItemStack(type.getID(), 1, (short) type.getData()); } for (int i = amount; i > 0;) { ItemStack cloned = stack.clone(); cloned.setAmount(Math.min(stack.getMaxStackSize(), i)); i -= cloned.getAmount(); itemStacks.add(cloned); } return itemStacks.toArray(new ItemStack[itemStacks.size()]); } private static Set<Integer> ignored = new HashSet<>(); static { ignored.add(BlockID.AIR); ignored.add(BlockID.WATER); ignored.add(BlockID.STATIONARY_WATER); ignored.add(BlockID.LAVA); ignored.add(BlockID.STATIONARY_LAVA); ignored.add(BlockID.GRASS); ignored.add(BlockID.DIRT); ignored.add(BlockID.GRAVEL); ignored.add(BlockID.SAND); ignored.add(BlockID.SANDSTONE); ignored.add(BlockID.SNOW); ignored.add(BlockID.SNOW_BLOCK); ignored.add(BlockID.STONE); ignored.add(BlockID.BEDROCK); } public static double priceCheck(int blockID, int data) { if (ignored.contains(blockID) || EnvironmentUtil.isValuableBlock(blockID)) return 0; ItemType type = ItemType.fromNumberic(blockID, data); if (type == null) return 0; ItemPricePair itemPricePair = itemDatabase.getItem(type.getName()); if (itemPricePair == null) return 0; return itemPricePair.getPrice(); } /** * Price checks an item stack * * @param stack the item stack to be price checked * @return -1 if invalid, otherwise returns the price scaled to item stack quantity */ public static double priceCheck(ItemStack stack) { return priceCheck(stack, true); } public static double priceCheck(ItemStack stack, boolean percentDamage) { String itemName; double percentageSale = 1; if (stack == null || stack.getTypeId() == 0) { return -1; } itemName = stack.getTypeId() + ":" + stack.getDurability(); ItemMeta stackMeta = stack.getItemMeta(); if (stackMeta.hasDisplayName()) { itemName = stackMeta.getDisplayName(); if (!ItemUtil.isAuthenticCustomItem(itemName)) { return -1; } itemName = ChatColor.stripColor(itemName); } if (percentDamage && stack.getDurability() != 0 && !ItemType.usesDamageValue(stack.getTypeId())) { if (stack.getAmount() > 1) { return -1; } percentageSale = 1 - ((double) stack.getDurability() / (double) stack.getType().getMaxDurability()); } if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { return -1; } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null) { return -1; } return itemPricePair.getPrice() * percentageSale * stack.getAmount(); } public String checkPlayer(CommandSender sender) throws CommandException { PlayerUtil.checkPlayer(sender); if (adminComponent.isAdmin((Player) sender)) { throw new CommandException("You cannot use this command while in admin mode."); } checkInArea((Player) sender); return sender.getName(); } public void checkInArea(Player player) throws CommandException { if (!isInArea(player.getLocation())) { throw new CommandException("You call out, but no one hears your offer."); } } public boolean isInArea(Location location) { Vector v = BukkitUtil.toVector(location); return location.getWorld().getName().equals("City") && region != null && region.contains(v); } private WorldGuardPlugin getWorldGuard() throws UnknownPluginException { Plugin plugin = server.getPluginManager().getPlugin("WorldGuard"); // WorldGuard may not be loaded if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { throw new UnknownPluginException("WorldGuard"); } return (WorldGuardPlugin) plugin; } private boolean setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = server.getServicesManager().getRegistration(net.milkbowl .vault.economy.Economy.class); if (economyProvider != null) { econ = economyProvider.getProvider(); } return (econ != null); } }
src/main/java/com/skelril/aurora/economic/store/AdminStoreComponent.java
/* * Copyright (c) 2014 Wyatt Childers. * * All Rights Reserved */ package com.skelril.aurora.economic.store; import com.sk89q.commandbook.CommandBook; import com.sk89q.commandbook.commands.PaginatedResult; import com.sk89q.commandbook.session.SessionComponent; import com.sk89q.commandbook.util.entity.player.PlayerUtil; import com.sk89q.minecraft.util.commands.*; import com.sk89q.worldedit.Vector; import com.sk89q.worldedit.blocks.BlockID; import com.sk89q.worldedit.bukkit.BukkitUtil; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.sk89q.worldguard.protection.regions.ProtectedRegion; import com.skelril.aurora.admin.AdminComponent; import com.skelril.aurora.economic.store.mysql.MySQLItemStoreDatabase; import com.skelril.aurora.economic.store.mysql.MySQLMarketTransactionDatabase; import com.skelril.aurora.exceptions.UnknownPluginException; import com.skelril.aurora.util.ChatUtil; import com.skelril.aurora.util.EnvironmentUtil; import com.skelril.aurora.util.item.ItemType; import com.skelril.aurora.util.item.ItemUtil; import com.skelril.aurora.util.item.custom.CustomItemCenter; import com.skelril.aurora.util.item.custom.CustomItems; import com.zachsthings.libcomponents.ComponentInformation; import com.zachsthings.libcomponents.Depend; import com.zachsthings.libcomponents.InjectComponent; import com.zachsthings.libcomponents.bukkit.BukkitComponent; import net.milkbowl.vault.economy.Economy; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.enchantments.Enchantment; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.RegisteredServiceProvider; import java.util.*; import java.util.logging.Logger; @ComponentInformation(friendlyName = "Admin Store", desc = "Admin Store system.") @Depend(plugins = {"WorldGuard"}, components = {AdminComponent.class, SessionComponent.class}) public class AdminStoreComponent extends BukkitComponent { private final CommandBook inst = CommandBook.inst(); private final Logger log = CommandBook.logger(); private final Server server = CommandBook.server(); @InjectComponent private AdminComponent adminComponent; @InjectComponent private SessionComponent sessions; private static ItemStoreDatabase itemDatabase; private static MarketTransactionDatabase transactionDatabase; private ProtectedRegion region = null; private Economy econ; @Override public void enable() { itemDatabase = new MySQLItemStoreDatabase(); itemDatabase.load(); transactionDatabase = new MySQLMarketTransactionDatabase(); transactionDatabase.load(); // Setup external systems setupEconomy(); // Register commands registerCommands(Commands.class); // Get the region server.getScheduler().runTaskLater(inst, () -> { try { region = getWorldGuard().getGlobalRegionManager().get(Bukkit.getWorld("City")).getRegion("vineam-district-bank"); } catch (UnknownPluginException e) { e.printStackTrace(); } }, 1); } @Override public void reload() { itemDatabase.load(); } private final String NOT_AVAILIBLE = "No item by that name is currently available!"; public class Commands { @Command(aliases = {"market", "mk", "ge"}, desc = "Admin Store commands") @NestedCommand({StoreCommands.class}) public void storeCommands(CommandContext args, CommandSender sender) throws CommandException { } } public class StoreCommands { @Command(aliases = {"buy", "b"}, usage = "[-a amount] <item name>", desc = "Buy an item", flags = "a:", min = 1) public void buyCmd(CommandContext args, CommandSender sender) throws CommandException { String playerName = checkPlayer(sender); Player player = (Player) sender; String itemName = args.getJoinedStrings(0).toLowerCase(); if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException(NOT_AVAILIBLE); } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null || !itemPricePair.isBuyable()) { throw new CommandException(NOT_AVAILIBLE); } itemName = itemPricePair.getName(); int amt = 1; if (args.hasFlag('a')) { amt = Math.max(1, args.getFlagInteger('a')); } double price = itemPricePair.getPrice() * amt; double rebate = 0; double lottery = price * .03; if (inst.hasPermission(sender, "aurora.market.rebate.onepointseven")) { rebate = price * .017; } if (!econ.has(playerName, price)) { throw new CommandException("You do not have enough money to purchase that item(s)."); } // Get the items and add them to the inventory ItemStack[] itemStacks = getItem(itemPricePair.getName(), amt); for (ItemStack itemStack : itemStacks) { if (player.getInventory().firstEmpty() == -1) { player.getWorld().dropItem(player.getLocation(), itemStack); continue; } player.getInventory().addItem(itemStack); } // Deposit into the lottery account econ.bankDeposit("Lottery", lottery); // Charge the money and send the sender some feedback econ.withdrawPlayer(playerName, price - rebate); transactionDatabase.logTransaction(playerName, itemName, amt); transactionDatabase.save(); String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(price), ""); ChatUtil.sendNotice(sender, "Item(s) purchased for " + priceString + "!"); if (rebate >= 0.01) { String rebateString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(rebate), ""); ChatUtil.sendNotice(sender, "You get " + rebateString + " back."); } // Market Command Help StoreSession sess = sessions.getSession(StoreSession.class, player); if (amt == 1 && sess.recentPurch() && sess.getLastPurch().equals(itemName)) { ChatUtil.sendNotice(sender, "Did you know you can specify the amount of items to buy?"); ChatUtil.sendNotice(sender, "/market buy -a <amount> " + itemName); } sess.setLastPurch(itemName); } @Command(aliases = {"sell", "s"}, usage = "", desc = "Sell an item", flags = "hau", min = 0, max = 0) public void sellCmd(CommandContext args, CommandSender sender) throws CommandException { String playerName = checkPlayer(sender); final Player player = (Player) sender; ItemStack[] itemStacks = player.getInventory().getContents(); HashMap<String, Integer> transactions = new HashMap<>(); double payment = 0; ItemStack filter = null; boolean singleItem = false; int min, max; if (args.hasFlag('a')) { min = 0; max = itemStacks.length; } else if (args.hasFlag('h')) { min = 0; max = 9; } else { min = player.getInventory().getHeldItemSlot(); max = min + 1; singleItem = true; } if (!singleItem && !args.hasFlag('u')) { filter = player.getItemInHand().clone(); if (!ItemType.usesDamageValue(filter.getTypeId())) { filter.setDurability((short) 0); } } for (int i = min; i < max; i++) { ItemStack stack = itemStacks[i]; if (stack == null || stack.getTypeId() == 0) { if (singleItem) { throw new CommandException("That's not a valid item!"); } else { continue; } } if (filter != null) { ItemStack testStack = stack.clone(); if (!ItemType.usesDamageValue(testStack.getTypeId())) { testStack.setDurability((short) 0); } if (!filter.isSimilar(testStack)) continue; } ItemMeta stackMeta = stack.getItemMeta(); String itemName = stack.getTypeId() + ":" + stack.getDurability(); if (stackMeta.hasDisplayName()) { itemName = stackMeta.getDisplayName(); if (!ItemUtil.isAuthenticCustomItem(itemName)) { if (singleItem) { throw new CommandException("You cannot sell items that have been renamed here!"); } else { continue; } } itemName = ChatColor.stripColor(itemName); } double percentageSale = 1; if (stack.getDurability() != 0 && !ItemType.usesDamageValue(stack.getTypeId())) { if (stack.getAmount() > 1) { if (singleItem) { throw new CommandException(NOT_AVAILIBLE); } else { continue; } } percentageSale = 1 - ((double) stack.getDurability() / (double) stack.getType().getMaxDurability()); } if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { if (singleItem) { throw new CommandException(NOT_AVAILIBLE); } else { continue; } } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null || !itemPricePair.isSellable()) { if (singleItem) { throw new CommandException(NOT_AVAILIBLE); } else { continue; } } int amt = stack.getAmount(); payment += itemPricePair.getSellPrice() * amt * percentageSale; // Multiply the amount by -1 since this is selling amt *= -1; if (transactions.containsKey(itemName)) { amt += transactions.get(itemName); } transactions.put(itemName, amt); itemStacks[i] = null; } if (transactions.isEmpty()) { throw new CommandException("No sellable items found" + (filter != null ? " that matched the filter" : "") + "!"); } for (Map.Entry<String, Integer> entry : transactions.entrySet()) { transactionDatabase.logTransaction(playerName, entry.getKey(), entry.getValue()); } transactionDatabase.save(); econ.depositPlayer(playerName, payment); player.getInventory().setContents(itemStacks); String paymentString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(payment), ""); ChatUtil.sendNotice(player, "Item(s) sold for: " + paymentString + "!"); // Market Command Help StoreSession sess = sessions.getSession(StoreSession.class, player); if (singleItem && sess.recentSale() && !sess.recentNotice()) { ChatUtil.sendNotice(sender, "Did you know you can sell more than one stack at a time?"); ChatUtil.sendNotice(sender, "To sell all of what you're holding:"); ChatUtil.sendNotice(sender, "/market sell -a"); ChatUtil.sendNotice(sender, "To sell everything in your inventory:"); ChatUtil.sendNotice(sender, "/market sell -au"); sess.updateNotice(); } sess.updateSale(); } @Command(aliases = {"enchant"}, usage = "<enchantment> <level>", desc = "Enchant an item", flags = "fy", min = 2, max = 2) public void enchantCmd(CommandContext args, CommandSender sender) throws CommandException { Player player = PlayerUtil.checkPlayer(sender); boolean isAdmin = adminComponent.isAdmin(player); if (!isAdmin) checkInArea(player); Enchantment enchantment = Enchantment.getByName(args.getString(0).toUpperCase()); int level = args.getInteger(1); if (enchantment == null) { throw new CommandException("That enchantment could not be found!"); } int min = enchantment.getStartLevel(); int max = enchantment.getMaxLevel(); if (level < min || level > max) { throw new CommandException("Enchantment level must be between " + min + " and " + max + '!'); } ItemStack targetItem = player.getItemInHand(); if (targetItem == null || targetItem.getTypeId() == BlockID.AIR) { throw new CommandException("You're not holding an item!"); } if (!enchantment.canEnchantItem(targetItem)) { throw new CommandException("You cannot give this item that enchantment!"); } ItemMeta meta = targetItem.getItemMeta(); if (meta.hasEnchant(enchantment)) { if (!args.hasFlag('f')) { throw new CommandException("That enchantment is already present, use -f to override this!"); } else { meta.removeEnchant(enchantment); } } if (!meta.addEnchant(enchantment, level, false)) { throw new CommandException("That enchantment could not be applied!"); } double cost = Math.max(1000, AdminStoreComponent.priceCheck(targetItem, false) * .1) * level; if (!isAdmin) { if (cost < 0) { throw new CommandException("That item cannot be enchanted!"); } if (!econ.has(player, cost)) { throw new CommandException("You don't have enough money!"); } String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(cost), ""); if (args.hasFlag('y')) { ChatUtil.sendNotice(sender, "Item enchanted for " + priceString + "!"); econ.withdrawPlayer(player, cost); } else { ChatUtil.sendNotice(sender, "That will cost " + priceString + '.'); ChatUtil.sendNotice(sender, "To confirm, use:"); String command = "/market enchant -y"; for (Character aChar : args.getFlags()) { command += aChar; } command += ' ' + enchantment.getName() + ' ' + level; ChatUtil.sendNotice(sender, command); return; } } else { ChatUtil.sendNotice(sender, "Item enchanted!"); } targetItem.setItemMeta(meta); } @Command(aliases = {"list", "l"}, usage = "[-p page] [filter...]", desc = "Get a list of items and their prices", flags = "p:", min = 0 ) public void listCmd(CommandContext args, CommandSender sender) throws CommandException { String filterString = args.argsLength() > 0 ? args.getJoinedStrings(0) : null; List<ItemPricePair> itemPricePairCollection = itemDatabase.getItemList(filterString, inst.hasPermission(sender, "aurora.admin.adminstore.disabled")); Collections.sort(itemPricePairCollection); new PaginatedResult<ItemPricePair>(ChatColor.GOLD + "Item List") { @Override public String format(ItemPricePair pair) { ChatColor color = pair.isEnabled() ? ChatColor.BLUE : ChatColor.DARK_RED; String buy, sell; if (pair.isBuyable() || !pair.isEnabled()) { buy = ChatColor.WHITE + econ.format(pair.getPrice()) + ChatColor.YELLOW; } else { buy = ChatColor.GRAY + "unavailable" + ChatColor.YELLOW; } if (pair.isSellable() || !pair.isEnabled()) { sell = ChatColor.WHITE + econ.format(pair.getSellPrice()) + ChatColor.YELLOW; } else { sell = ChatColor.GRAY + "unavailable" + ChatColor.YELLOW; } String message = color + pair.getName().toUpperCase() + ChatColor.YELLOW + " (Quick Price: " + buy + " - " + sell + ")"; return message.replace(' ' + econ.currencyNamePlural(), ""); } }.display(sender, itemPricePairCollection, args.getFlagInteger('p', 1)); } @Command(aliases = {"lookup", "value", "info", "pc"}, usage = "[item name]", desc = "Value an item", flags = "", min = 0) public void valueCmd(CommandContext args, CommandSender sender) throws CommandException { String itemName; double percentageSale = 1; if (args.argsLength() > 0) { itemName = args.getJoinedStrings(0).toLowerCase(); } else { ItemStack stack = PlayerUtil.checkPlayer(sender).getInventory().getItemInHand(); if (stack == null || stack.getTypeId() == 0) { throw new CommandException("That's not a valid item!"); } itemName = stack.getTypeId() + ":" + stack.getDurability(); ItemMeta stackMeta = stack.getItemMeta(); if (stackMeta.hasDisplayName()) { itemName = stackMeta.getDisplayName(); if (!ItemUtil.isAuthenticCustomItem(itemName)) { throw new CommandException(NOT_AVAILIBLE); } itemName = ChatColor.stripColor(itemName); } if (stack.getDurability() != 0 && !ItemType.usesDamageValue(stack.getTypeId())) { if (stack.getAmount() > 1) { throw new CommandException(NOT_AVAILIBLE); } percentageSale = 1 - ((double) stack.getDurability() / (double) stack.getType().getMaxDurability()); } } if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException(NOT_AVAILIBLE); } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null) { throw new CommandException(NOT_AVAILIBLE); } if (!itemPricePair.isEnabled() && !inst.hasPermission(sender, "aurora.admin.adminstore.disabled")) { throw new CommandException(NOT_AVAILIBLE); } ChatColor color = itemPricePair.isEnabled() ? ChatColor.BLUE : ChatColor.DARK_RED; double paymentPrice = itemPricePair.getSellPrice() * percentageSale; String purchasePrice = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(itemPricePair.getPrice()), ""); String sellPrice = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(paymentPrice), ""); ChatUtil.sendNotice(sender, ChatColor.GOLD, "Price Information for: " + color + itemName.toUpperCase()); // Purchase Information if (itemPricePair.isBuyable() || !itemPricePair.isEnabled()) { ChatUtil.sendNotice(sender, "When you buy it you pay:"); ChatUtil.sendNotice(sender, " - " + purchasePrice + " each."); } else { ChatUtil.sendNotice(sender, ChatColor.GRAY, "This item cannot be purchased."); } // Sale Information if (itemPricePair.isSellable() || !itemPricePair.isEnabled()) { ChatUtil.sendNotice(sender, "When you sell it you get:"); ChatUtil.sendNotice(sender, " - " + sellPrice + " each."); if (percentageSale != 1.0) { sellPrice = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(itemPricePair.getSellPrice()), ""); ChatUtil.sendNotice(sender, " - " + sellPrice + " each when new."); } } else { ChatUtil.sendNotice(sender, ChatColor.GRAY, "This item cannot be sold."); } } @Command(aliases = {"admin"}, desc = "Administrative Commands") @NestedCommand({AdminStoreCommands.class}) public void AdministrativeCommands(CommandContext args, CommandSender sender) throws CommandException { } } public class AdminStoreCommands { @Command(aliases = {"log"}, usage = "[-i item] [-u user] [-p page]", desc = "Item database logs", flags = "i:u:p:s", min = 0, max = 0) @CommandPermissions("aurora.admin.adminstore.log") public void logCmd(CommandContext args, CommandSender sender) throws CommandException { String item = args.getFlag('i', null); if (item != null && !hasItemOfName(item)) { ItemType type = ItemType.lookup(item); if (type == null) { throw new CommandException("No item by that name was found."); } item = type.getName(); } String player = args.getFlag('u', null); List<ItemTransaction> transactions = transactionDatabase.getTransactions(item, player); new PaginatedResult<ItemTransaction>(ChatColor.GOLD + "Market Transactions") { @Override public String format(ItemTransaction trans) { String message = ChatColor.YELLOW + trans.getPlayer() + ' '; if (trans.getAmount() > 0) { message += ChatColor.RED + "bought"; } else { message += ChatColor.DARK_GREEN + "sold"; } message += " " + ChatColor.YELLOW + Math.abs(trans.getAmount()) + ChatColor.BLUE + " " + trans.getItem().toUpperCase(); return message; } }.display(sender, transactions, args.getFlagInteger('p', 1)); } @Command(aliases = {"scale"}, usage = "<amount>", desc = "Scale the item database", flags = "", min = 1, max = 1) @CommandPermissions("aurora.admin.adminstore.scale") public void scaleCmd(CommandContext args, CommandSender sender) throws CommandException { double factor = args.getDouble(0); if (factor == 0) { throw new CommandException("Cannot scale by 0."); } List<ItemPricePair> items = itemDatabase.getItemList(); for (ItemPricePair item : items) { itemDatabase.addItem(sender.getName(), item.getName(), item.getPrice() * factor, !item.isBuyable(), !item.isSellable()); } itemDatabase.save(); ChatUtil.sendNotice(sender, "Market Scaled by: " + factor + "."); } @Command(aliases = {"add"}, usage = "[-p price] <item name>", desc = "Add an item to the database", flags = "bsp:", min = 1) @CommandPermissions("aurora.admin.adminstore.add") public void addCmd(CommandContext args, CommandSender sender) throws CommandException { String itemName = args.getJoinedStrings(0); if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException("No item by that name was found."); } itemName = type.getName(); } boolean disableBuy = args.hasFlag('b'); boolean disableSell = args.hasFlag('s'); double price = Math.max(.01, args.getFlagDouble('p', .1)); // Database operations ItemPricePair oldItem = itemDatabase.getItem(itemName); itemName = itemName.replace('_', ' '); itemDatabase.addItem(sender.getName(), itemName, price, disableBuy, disableSell); itemDatabase.save(); // Notification String noticeString = oldItem == null ? " added with a price of " : " is now "; String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(price), " "); ChatUtil.sendNotice(sender, ChatColor.BLUE + itemName.toUpperCase() + ChatColor.YELLOW + noticeString + priceString + "!"); if (disableBuy) { ChatUtil.sendNotice(sender, " - It cannot be purchased."); } if (disableSell) { ChatUtil.sendNotice(sender, " - It cannot be sold."); } } @Command(aliases = {"remove"}, usage = "<item name>", desc = "Value an item", flags = "", min = 1) @CommandPermissions("aurora.admin.adminstore.remove") public void removeCmd(CommandContext args, CommandSender sender) throws CommandException { String itemName = args.getJoinedStrings(0); if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { throw new CommandException(NOT_AVAILIBLE); } itemName = type.getName(); } if (itemDatabase.getItem(itemName) == null) { throw new CommandException(NOT_AVAILIBLE); } itemDatabase.removeItem(sender.getName(), itemName); itemDatabase.save(); ChatUtil.sendNotice(sender, ChatColor.BLUE + itemName.toUpperCase() + ChatColor.YELLOW + " has been removed from the database!"); } } private static Set<String> names = new HashSet<>(); static { for (CustomItems item : CustomItems.values()) { names.add(item.name()); } } private static boolean hasItemOfName(String name) { return names.contains(name.toUpperCase().replace(' ', '_')); } private static ItemStack[] getItem(String name, int amount) throws CommandException { name = name.toUpperCase().replace(" ", "_"); List<ItemStack> itemStacks = new ArrayList<>(); ItemStack stack; ItemType type = ItemType.lookup(name); if (type == null) { try { CustomItems item = CustomItems.valueOf(name); stack = CustomItemCenter.build(item); } catch (IllegalArgumentException ex) { throw new CommandException("Please report this error, " + name + " could not be found."); } } else { stack = new ItemStack(type.getID(), 1, (short) type.getData()); } for (int i = amount; i > 0;) { ItemStack cloned = stack.clone(); cloned.setAmount(Math.min(stack.getMaxStackSize(), i)); i -= cloned.getAmount(); itemStacks.add(cloned); } return itemStacks.toArray(new ItemStack[itemStacks.size()]); } private static Set<Integer> ignored = new HashSet<>(); static { ignored.add(BlockID.AIR); ignored.add(BlockID.WATER); ignored.add(BlockID.STATIONARY_WATER); ignored.add(BlockID.LAVA); ignored.add(BlockID.STATIONARY_LAVA); ignored.add(BlockID.GRASS); ignored.add(BlockID.DIRT); ignored.add(BlockID.GRAVEL); ignored.add(BlockID.SAND); ignored.add(BlockID.SANDSTONE); ignored.add(BlockID.SNOW); ignored.add(BlockID.SNOW_BLOCK); ignored.add(BlockID.STONE); ignored.add(BlockID.BEDROCK); } public static double priceCheck(int blockID, int data) { if (ignored.contains(blockID) || EnvironmentUtil.isValuableBlock(blockID)) return 0; ItemType type = ItemType.fromNumberic(blockID, data); if (type == null) return 0; ItemPricePair itemPricePair = itemDatabase.getItem(type.getName()); if (itemPricePair == null) return 0; return itemPricePair.getPrice(); } /** * Price checks an item stack * * @param stack the item stack to be price checked * @return -1 if invalid, otherwise returns the price scaled to item stack quantity */ public static double priceCheck(ItemStack stack) { return priceCheck(stack, true); } public static double priceCheck(ItemStack stack, boolean percentDamage) { String itemName; double percentageSale = 1; if (stack == null || stack.getTypeId() == 0) { return -1; } itemName = stack.getTypeId() + ":" + stack.getDurability(); ItemMeta stackMeta = stack.getItemMeta(); if (stackMeta.hasDisplayName()) { itemName = stackMeta.getDisplayName(); if (!ItemUtil.isAuthenticCustomItem(itemName)) { return -1; } itemName = ChatColor.stripColor(itemName); } if (percentDamage && stack.getDurability() != 0 && !ItemType.usesDamageValue(stack.getTypeId())) { if (stack.getAmount() > 1) { return -1; } percentageSale = 1 - ((double) stack.getDurability() / (double) stack.getType().getMaxDurability()); } if (!hasItemOfName(itemName)) { ItemType type = ItemType.lookup(itemName); if (type == null) { return -1; } itemName = type.getName(); } ItemPricePair itemPricePair = itemDatabase.getItem(itemName); if (itemPricePair == null) { return -1; } return itemPricePair.getPrice() * percentageSale * stack.getAmount(); } public String checkPlayer(CommandSender sender) throws CommandException { PlayerUtil.checkPlayer(sender); if (adminComponent.isAdmin((Player) sender)) { throw new CommandException("You cannot use this command while in admin mode."); } checkInArea((Player) sender); return sender.getName(); } public void checkInArea(Player player) throws CommandException { if (!isInArea(player.getLocation())) { throw new CommandException("You call out, but no one hears your offer."); } } public boolean isInArea(Location location) { Vector v = BukkitUtil.toVector(location); return location.getWorld().getName().equals("City") && region != null && region.contains(v); } private WorldGuardPlugin getWorldGuard() throws UnknownPluginException { Plugin plugin = server.getPluginManager().getPlugin("WorldGuard"); // WorldGuard may not be loaded if (plugin == null || !(plugin instanceof WorldGuardPlugin)) { throw new UnknownPluginException("WorldGuard"); } return (WorldGuardPlugin) plugin; } private boolean setupEconomy() { RegisteredServiceProvider<Economy> economyProvider = server.getServicesManager().getRegistration(net.milkbowl .vault.economy.Economy.class); if (economyProvider != null) { econ = economyProvider.getProvider(); } return (econ != null); } }
Fixed a compilation error
src/main/java/com/skelril/aurora/economic/store/AdminStoreComponent.java
Fixed a compilation error
<ide><path>rc/main/java/com/skelril/aurora/economic/store/AdminStoreComponent.java <ide> if (cost < 0) { <ide> throw new CommandException("That item cannot be enchanted!"); <ide> } <del> if (!econ.has(player, cost)) { <add> if (!econ.has(player.getName(), cost)) { <ide> throw new CommandException("You don't have enough money!"); <ide> } <ide> String priceString = ChatUtil.makeCountString(ChatColor.YELLOW, econ.format(cost), ""); <ide> if (args.hasFlag('y')) { <ide> ChatUtil.sendNotice(sender, "Item enchanted for " + priceString + "!"); <del> econ.withdrawPlayer(player, cost); <add> econ.withdrawPlayer(player.getName(), cost); <ide> } else { <ide> ChatUtil.sendNotice(sender, "That will cost " + priceString + '.'); <ide> ChatUtil.sendNotice(sender, "To confirm, use:");
Java
epl-1.0
61f7efd08902a21054255951381fbb65dbd90743
0
Beagle-PSE/Beagle,Beagle-PSE/Beagle,Beagle-PSE/Beagle
package de.uka.ipd.sdq.beagle.core; import de.uka.ipd.sdq.beagle.analysis.ResultAnalyser; import java.io.Serializable; /** * Interface for classes that wish to write their state to the Blackboard. The type of the * state object is defined by {@code WRITTEN_TYPE}. * * <p>To illustrate the usage of this interface, two examples follow. We look at a typical * use case: Two {@linkplain ResultAnalyser ResultAnalysers}, {@code MyAnalyser} and * {@code YourAnalyser}. Both want to store data on the {@linkplain Blackboard} to keep * track of whether there is something new to look at. * * <p>{@code YourAnalyser} simply wants to keep track of the {@linkplain SEFFLoop * SEFFLoops} he has already seen. He wants to use an {@code HashSet} to do so: * * <code> * * <pre> * public class YourAnalyser implements ResultAnalyser, BlackboardStorer&lt;HashSet&lt;SEFFLoop&gt;&lt; { * * public boolean canContribute(ReadOnlyBlackboardView blackboard) { * Set<SEFFLoop> alreadySeen = blackboard.readFor(YourAnalyser.class); * Set<SEFFLoop> allLoops = blackboard.getAllSEFFLoops(); * return allLoops.size() > 0 && (alreadySeen == null || !alreadySeen.containsAll(allLoops)); * } * * public boolean contribute(AnalyserBlackboardView blackboard) { * Set<SEFFLoop> alreadySeen = blackboard.readFor(YourAnalyser.class); * if (alreadySeen == null) { * alreadySeen = new HashSet<SEFFLoop>(); * blackboard.writeFor(YourAnalyser.class, alreadySeen); * } * Set<SEFFLoop> allLoops = blackboard.getAllSEFFLoops(); * Set<SEFFLoop> todo = allLoops.removeAll(alreadySeen); * * for (SEFFLoop loop : todo) { * // do the logic here * alreadySeen.add(loop); * } * } * } * </pre> * * </code> * * <p>{@code MyAnalyser} however, wants to use its own data structure: * * <code> * * <pre> * public MyAnalyserDataStructure implements Serializable { * // a whole bunch of getters and setters * } * </pre> * * </code> * * <code> * * <pre> * public class MyAnalyser implements ResultAnalyser, BlackboardStorer<MyAnalyserDataStructure> { * // everything here is like above: * public boolean canContribute(ReadOnlyBlackboardView blackboard) { * MyAnalyserDataStructure stored = blackboard.readFor(MyAnalyser.class); * // … * } * * public boolean contribute(AnalyserBlackboardView blackboard) { * MyAnalyserDataStructure stored = blackboard.readFor(MyAnalyser.class); * // … * MyAnalyserDataStructure newData = new MyAnalyserDataStructure(); * // … * blackboard.writeFor(MyAnalyser.class, newData); * // … * } * </pre> * * </code> * * @author Joshua Gleitze * @param <WRITTEN_TYPE> * The type of data the BlackboardStorer wants to write to the blackboard. * @see Blackboard */ public interface BlackboardStorer<WRITTEN_TYPE extends Serializable> { }
src/main/java/de/uka/ipd/sdq/beagle/core/BlackboardStorer.java
package de.uka.ipd.sdq.beagle.core; import java.io.Serializable; /** * Interface for classes that wish to write something to the Blackboard. * * @author Joshua Gleitze * @param <WRITTEN_TYPE> * The type of data the BlackboardStorer wants to write to the blackboard. */ public interface BlackboardStorer<WRITTEN_TYPE extends Serializable> { }
Extended documentation of Blackboard Storer
src/main/java/de/uka/ipd/sdq/beagle/core/BlackboardStorer.java
Extended documentation of Blackboard Storer
<ide><path>rc/main/java/de/uka/ipd/sdq/beagle/core/BlackboardStorer.java <ide> package de.uka.ipd.sdq.beagle.core; <add> <add>import de.uka.ipd.sdq.beagle.analysis.ResultAnalyser; <ide> <ide> import java.io.Serializable; <ide> <ide> /** <del> * Interface for classes that wish to write something to the Blackboard. <add> * Interface for classes that wish to write their state to the Blackboard. The type of the <add> * state object is defined by {@code WRITTEN_TYPE}. <add> * <add> * <p>To illustrate the usage of this interface, two examples follow. We look at a typical <add> * use case: Two {@linkplain ResultAnalyser ResultAnalysers}, {@code MyAnalyser} and <add> * {@code YourAnalyser}. Both want to store data on the {@linkplain Blackboard} to keep <add> * track of whether there is something new to look at. <add> * <add> * <p>{@code YourAnalyser} simply wants to keep track of the {@linkplain SEFFLoop <add> * SEFFLoops} he has already seen. He wants to use an {@code HashSet} to do so: <add> * <add> * <code> <add> * <add> * <pre> <add> * public class YourAnalyser implements ResultAnalyser, BlackboardStorer&lt;HashSet&lt;SEFFLoop&gt;&lt; { <add> * <add> * public boolean canContribute(ReadOnlyBlackboardView blackboard) { <add> * Set<SEFFLoop> alreadySeen = blackboard.readFor(YourAnalyser.class); <add> * Set<SEFFLoop> allLoops = blackboard.getAllSEFFLoops(); <add> * return allLoops.size() > 0 && (alreadySeen == null || !alreadySeen.containsAll(allLoops)); <add> * } <add> * <add> * public boolean contribute(AnalyserBlackboardView blackboard) { <add> * Set<SEFFLoop> alreadySeen = blackboard.readFor(YourAnalyser.class); <add> * if (alreadySeen == null) { <add> * alreadySeen = new HashSet<SEFFLoop>(); <add> * blackboard.writeFor(YourAnalyser.class, alreadySeen); <add> * } <add> * Set<SEFFLoop> allLoops = blackboard.getAllSEFFLoops(); <add> * Set<SEFFLoop> todo = allLoops.removeAll(alreadySeen); <add> * <add> * for (SEFFLoop loop : todo) { <add> * // do the logic here <add> * alreadySeen.add(loop); <add> * } <add> * } <add> * } <add> * </pre> <add> * <add> * </code> <add> * <add> * <p>{@code MyAnalyser} however, wants to use its own data structure: <add> * <add> * <code> <add> * <add> * <pre> <add> * public MyAnalyserDataStructure implements Serializable { <add> * // a whole bunch of getters and setters <add> * } <add> * </pre> <add> * <add> * </code> <add> * <add> * <code> <add> * <add> * <pre> <add> * public class MyAnalyser implements ResultAnalyser, BlackboardStorer<MyAnalyserDataStructure> { <add> * // everything here is like above: <add> * public boolean canContribute(ReadOnlyBlackboardView blackboard) { <add> * MyAnalyserDataStructure stored = blackboard.readFor(MyAnalyser.class); <add> * // … <add> * } <add> * <add> * public boolean contribute(AnalyserBlackboardView blackboard) { <add> * MyAnalyserDataStructure stored = blackboard.readFor(MyAnalyser.class); <add> * // … <add> * MyAnalyserDataStructure newData = new MyAnalyserDataStructure(); <add> * // … <add> * blackboard.writeFor(MyAnalyser.class, newData); <add> * // … <add> * } <add> * </pre> <add> * <add> * </code> <ide> * <ide> * @author Joshua Gleitze <ide> * @param <WRITTEN_TYPE> <ide> * The type of data the BlackboardStorer wants to write to the blackboard. <add> * @see Blackboard <ide> */ <ide> public interface BlackboardStorer<WRITTEN_TYPE extends Serializable> { <ide> }
JavaScript
mit
6cc4c0efba1b3cb1e6222a64b78307af0fb243b7
0
gtremper/vr-server
#!/usr/bin/env node var WebSocketServer = require('websocket').server; var http = require('http'); var _ = require('underscore') // // Configurations // var PORT = 5000 // // Create and start http server // var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); // We're only handling websockets, so return 404 when we receive http request response.writeHead(404); response.end(); }); server.listen(PORT, function() { console.log((new Date()) + ' Server is listening on port ' + PORT); }); // // Create websocket server // wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: true }); // Generates an incrementing ID whenever called var genID = function() { var counter = 0; return function() { return counter++; } }(); // connection ID to connection OpenConnections = {}; wsServer.on('connect', function(connection) { // Give this socket an ID and add it to our collection of open connections var socketID = genID(); OpenConnections[socketID] = connection; console.log('Player ' + socketID + ' connected'); connection.on('message', function(message) { // Can't handle binary data if (message.type !== 'utf8') { console.log('Can only handle utf8 data'); return; } console.log('Received Message: ' + message.utf8Data); // Forward message to all clients except this one _.each(OpenConnections, function(conn, id) { if (id != socketID) { var msg = { "player": socketID, "event": "update", "data": JSON.parse(message.utf8Data) }; conn.sendUTF(JSON.stringify(msg)); } }); }); connection.on('close', function(reasonCode, description) { console.log('Player ' + socketID + ' disconnected.'); // Remove from our collection of open connections delete OpenConnections[socketID] // Tell all other clients that a player left _.each(OpenConnections, function(conn, id) { var msg = { "player": socketID, "event": "disconnect" }; conn.sendUTF(JSON.stringify(msg)); }); }); });
index.js
#!/usr/bin/env node var WebSocketServer = require('websocket').server; var http = require('http'); var _ = require('underscore') // // Configurations // var PORT = 5000 // // Create and start http server // var server = http.createServer(function(request, response) { console.log((new Date()) + ' Received request for ' + request.url); // We're only handling websockets, so return 404 when we receive http request response.writeHead(404); response.end(); }); server.listen(PORT, function() { console.log((new Date()) + ' Server is listening on port ' + PORT); }); // // Create websocket server // wsServer = new WebSocketServer({ httpServer: server, // You should not use autoAcceptConnections for production // applications, as it defeats all standard cross-origin protection // facilities built into the protocol and the browser. You should // *always* verify the connection's origin and decide whether or not // to accept it. autoAcceptConnections: true }); // Generates an incrementing ID whenever called var genID = function() { var counter = 0; return function() { return counter++; } }(); // connection ID to connection OpenConnections = {}; wsServer.on('connect', function(connection) { // Give this socket an ID and add it to our collection of open connections var socketID = genID(); OpenConnections[socketID] = connection; console.log('Player ' + socketID + ' connected'); connection.on('message', function(message) { // Can't handle binary data if (message.type !== 'utf8') { console.log('Can only handle utf8 data'); return; } console.log('Received Message: ' + message.utf8Data); // Forward message to all clients except this one _.each(OpenConnections, function(conn, id) { if (id != socketID) { var msg = { "player": socketID, "event": "update", "data": message.utf8Data }; conn.sendUTF(JSON.stringify(msg)); } }); }); connection.on('close', function(reasonCode, description) { console.log('Player ' + socketID + ' disconnected.'); // Remove from our collection of open connections delete OpenConnections[socketID] // Tell all other clients that a player left _.each(OpenConnections, function(conn, id) { var msg = { "player": socketID, "event": "disconnect" }; conn.sendUTF(JSON.stringify(msg)); }); }); });
First deserialize message, then serialize wrapper
index.js
First deserialize message, then serialize wrapper
<ide><path>ndex.js <ide> var msg = { <ide> "player": socketID, <ide> "event": "update", <del> "data": message.utf8Data <add> "data": JSON.parse(message.utf8Data) <ide> }; <ide> conn.sendUTF(JSON.stringify(msg)); <ide> }
Java
agpl-3.0
ab903be19bf6d50e268c9932ab4fd265b82c72bf
0
more1/rstudio,piersharding/rstudio,sfloresm/rstudio,edrogers/rstudio,pssguy/rstudio,jrnold/rstudio,jar1karp/rstudio,suribes/rstudio,more1/rstudio,githubfun/rstudio,tbarrongh/rstudio,nvoron23/rstudio,nvoron23/rstudio,jzhu8803/rstudio,jar1karp/rstudio,thklaus/rstudio,more1/rstudio,jrnold/rstudio,maligulzar/Rstudio-instrumented,suribes/rstudio,maligulzar/Rstudio-instrumented,sfloresm/rstudio,nvoron23/rstudio,pssguy/rstudio,tbarrongh/rstudio,thklaus/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,JanMarvin/rstudio,JanMarvin/rstudio,nvoron23/rstudio,Sage-Bionetworks/rstudio,githubfun/rstudio,jrnold/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,githubfun/rstudio,nvoron23/rstudio,suribes/rstudio,vbelakov/rstudio,githubfun/rstudio,more1/rstudio,githubfun/rstudio,sfloresm/rstudio,tbarrongh/rstudio,edrogers/rstudio,tbarrongh/rstudio,more1/rstudio,maligulzar/Rstudio-instrumented,vbelakov/rstudio,pssguy/rstudio,JanMarvin/rstudio,vbelakov/rstudio,githubfun/rstudio,JanMarvin/rstudio,thklaus/rstudio,Sage-Bionetworks/rstudio,brsimioni/rstudio,jrnold/rstudio,vbelakov/rstudio,brsimioni/rstudio,pssguy/rstudio,jar1karp/rstudio,suribes/rstudio,more1/rstudio,vbelakov/rstudio,JanMarvin/rstudio,jar1karp/rstudio,Sage-Bionetworks/rstudio,brsimioni/rstudio,githubfun/rstudio,thklaus/rstudio,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,maligulzar/Rstudio-instrumented,jzhu8803/rstudio,jar1karp/rstudio,edrogers/rstudio,jzhu8803/rstudio,githubfun/rstudio,tbarrongh/rstudio,more1/rstudio,suribes/rstudio,vbelakov/rstudio,sfloresm/rstudio,jrnold/rstudio,JanMarvin/rstudio,brsimioni/rstudio,jar1karp/rstudio,jzhu8803/rstudio,jrnold/rstudio,thklaus/rstudio,JanMarvin/rstudio,maligulzar/Rstudio-instrumented,jrnold/rstudio,edrogers/rstudio,piersharding/rstudio,nvoron23/rstudio,sfloresm/rstudio,piersharding/rstudio,pssguy/rstudio,pssguy/rstudio,edrogers/rstudio,piersharding/rstudio,Sage-Bionetworks/rstudio,jzhu8803/rstudio,maligulzar/Rstudio-instrumented,brsimioni/rstudio,piersharding/rstudio,jzhu8803/rstudio,thklaus/rstudio,vbelakov/rstudio,jar1karp/rstudio,jrnold/rstudio,sfloresm/rstudio,piersharding/rstudio,jar1karp/rstudio,JanMarvin/rstudio,edrogers/rstudio,pssguy/rstudio,suribes/rstudio,tbarrongh/rstudio,piersharding/rstudio,jzhu8803/rstudio,Sage-Bionetworks/rstudio,brsimioni/rstudio,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,JanMarvin/rstudio,more1/rstudio,Sage-Bionetworks/rstudio,john-r-mcpherson/rstudio,suribes/rstudio,nvoron23/rstudio,edrogers/rstudio,john-r-mcpherson/rstudio,sfloresm/rstudio,tbarrongh/rstudio,maligulzar/Rstudio-instrumented,john-r-mcpherson/rstudio,vbelakov/rstudio,brsimioni/rstudio,brsimioni/rstudio,thklaus/rstudio,jzhu8803/rstudio,piersharding/rstudio,piersharding/rstudio,jar1karp/rstudio,Sage-Bionetworks/rstudio,pssguy/rstudio,tbarrongh/rstudio,edrogers/rstudio,thklaus/rstudio
/* * TextEditingTarget.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text; import com.google.gwt.core.client.*; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.*; import org.rstudio.core.client.Invalidation.Token; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.events.EnsureVisibleHandler; import org.rstudio.core.client.events.HasEnsureVisibleHandlers; import org.rstudio.core.client.files.FileSystemContext; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.regex.Match; import org.rstudio.core.client.regex.Pattern; import org.rstudio.core.client.widget.*; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.ChangeFontSizeEvent; import org.rstudio.studio.client.application.events.ChangeFontSizeHandler; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.*; import org.rstudio.studio.client.common.filetypes.FileType; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.ChangeTracker; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.WorkbenchServerOperations; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.ui.FontSizeManager; import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.events.*; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.ChooseEncodingDialog; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget.DocDisplay.AnchoredSelection; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.PublishPdfDialog; import org.rstudio.studio.client.workbench.views.source.events.SourceFileSavedEvent; import org.rstudio.studio.client.workbench.views.source.model.*; import java.util.ArrayList; import java.util.HashSet; public class TextEditingTarget implements EditingTarget { interface MyCommandBinder extends CommandBinder<Commands, TextEditingTarget> { } private static final MyCommandBinder commandBinder = GWT.create(MyCommandBinder.class); public interface Display extends HasEnsureVisibleHandlers { void adaptToFileType(TextFileType fileType); HasValue<Boolean> getSourceOnSave(); void ensureVisible(); void showWarningBar(String warning); void hideWarningBar(); void showFindReplace(); void onActivate(); void setFontSize(double size); StatusBar getStatusBar(); boolean isAttached(); } public interface DocDisplay extends HasValueChangeHandlers<Void>, Widgetable, HasFocusHandlers, HasKeyDownHandlers { public interface AnchoredSelection { String getValue(); void apply(); void detach(); } void setFileType(TextFileType fileType); String getCode(); void setCode(String code, boolean preserveCursorPosition); void insertCode(String code, boolean blockMode); void focus(); void print(); String getSelectionValue(); String getCurrentLine(); void replaceSelection(String code); boolean moveSelectionToNextLine(boolean skipBlankLines); ChangeTracker getChangeTracker(); String getCode(Position start, Position end); AnchoredSelection createAnchoredSelection(Position start, Position end); void fitSelectionToLines(boolean expand); int getSelectionOffset(boolean start); // Fix bug 964 void onActivate(); void setFontSize(double size); void onVisibilityChanged(boolean visible); void setHighlightSelectedLine(boolean on); void setShowLineNumbers(boolean on); void setUseSoftTabs(boolean on); void setUseWrapMode(boolean on); void setTabSize(int tabSize); void setShowPrintMargin(boolean on); void setPrintMarginColumn(int column); HandlerRegistration addCursorChangedHandler(CursorChangedHandler handler); Position getCursorPosition(); void setCursorPosition(Position position); void moveCursorNearTop(); FunctionStart getCurrentFunction(); JsArray<FunctionStart> getFunctionTree(); HandlerRegistration addUndoRedoHandler(UndoRedoHandler handler); JavaScriptObject getCleanStateToken(); boolean checkCleanStateToken(JavaScriptObject token); Position getSelectionStart(); Position getSelectionEnd(); int getLength(int row); } private class SaveProgressIndicator implements ProgressIndicator { public SaveProgressIndicator(FileSystemItem file, TextFileType fileType, Command executeOnSuccess) { file_ = file; newFileType_ = fileType; executeOnSuccess_ = executeOnSuccess; } public void onProgress(String message) { } public void onCompleted() { if (newFileType_ != null) fileType_ = newFileType_; if (file_ != null) { ignoreDeletes_ = false; commands_.reopenSourceDocWithEncoding().setEnabled(true); name_.setValue(file_.getName(), true); // Make sure tooltip gets updated, even if name hasn't changed name_.fireChangeEvent(); dirtyState_.markClean(); } if (newFileType_ != null) { // Make sure the icon gets updated, even if name hasn't changed name_.fireChangeEvent(); updateStatusBarLanguage(); view_.adaptToFileType(newFileType_); events_.fireEvent(new FileTypeChangedEvent()); if (!fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { view_.getSourceOnSave().setValue(false, true); } } if (executeOnSuccess_ != null) executeOnSuccess_.execute(); } public void onError(String message) { globalDisplay_.showErrorMessage( "Error Saving File", message); } private final FileSystemItem file_; private final TextFileType newFileType_; private final Command executeOnSuccess_; } @Inject public TextEditingTarget(Commands commands, SourceServerOperations server, WorkbenchServerOperations server2, EventBus events, GlobalDisplay globalDisplay, FileDialogs fileDialogs, FileTypeRegistry fileTypeRegistry, ConsoleDispatcher consoleDispatcher, WorkbenchContext workbenchContext, Provider<PublishPdf> pPublishPdf, Session session, FontSizeManager fontSizeManager, DocDisplay docDisplay, UIPrefs prefs) { commands_ = commands; server_ = server; server2_ = server2; events_ = events; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileTypeRegistry_ = fileTypeRegistry; consoleDispatcher_ = consoleDispatcher; workbenchContext_ = workbenchContext; session_ = session; fontSizeManager_ = fontSizeManager; pPublishPdf_ = pPublishPdf; docDisplay_ = docDisplay; dirtyState_ = new DirtyState(docDisplay_, false); prefs_ = prefs; docDisplay_.addKeyDownHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { NativeEvent ne = event.getNativeEvent(); int mod = KeyboardShortcut.getModifierValue(ne); if ((mod == KeyboardShortcut.META || mod == KeyboardShortcut.CTRL) && ne.getKeyCode() == 'F') { event.preventDefault(); event.stopPropagation(); commands_.findReplace().execute(); } else if (mod == KeyboardShortcut.ALT && ne.getKeyCode() == 189) // hyphen { event.preventDefault(); event.stopPropagation(); docDisplay_.insertCode(" <- ", false); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_UP && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToPreviousFunction(); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_DOWN && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToNextFunction(); } } }); } private void jumpToPreviousFunction() { Position cursor = docDisplay_.getCursorPosition(); JsArray<FunctionStart> functions = docDisplay_.getFunctionTree(); FunctionStart jumpTo = findPreviousFunction(functions, cursor); docDisplay_.setCursorPosition(jumpTo.getPreamble()); docDisplay_.moveCursorNearTop(); } private FunctionStart findPreviousFunction(JsArray<FunctionStart> funcs, Position pos) { FunctionStart result = null; for (int i = 0; i < funcs.length(); i++) { FunctionStart child = funcs.get(i); if (child.getPreamble().compareTo(pos) >= 0) break; result = child; } if (result == null) return result; FunctionStart descendant = findPreviousFunction(result.getChildren(), pos); if (descendant != null) result = descendant; return result; } private void jumpToNextFunction() { Position cursor = docDisplay_.getCursorPosition(); JsArray<FunctionStart> functions = docDisplay_.getFunctionTree(); FunctionStart jumpTo = findNextFunction(functions, cursor); docDisplay_.setCursorPosition(jumpTo.getPreamble()); docDisplay_.moveCursorNearTop(); } private FunctionStart findNextFunction(JsArray<FunctionStart> funcs, Position pos) { for (int i = 0; i < funcs.length(); i++) { FunctionStart child = funcs.get(i); if (child.getPreamble().compareTo(pos) <= 0) { FunctionStart descendant = findNextFunction(child.getChildren(), pos); if (descendant != null) return descendant; } else { return child; } } return null; } public void initialize(SourceDocument document, FileSystemContext fileContext, FileType type, Provider<String> defaultNameProvider) { id_ = document.getId(); fileContext_ = fileContext; fileType_ = (TextFileType) type; view_ = new TextEditingTargetWidget(commands_, docDisplay_, fileType_, events_); docUpdateSentinel_ = new DocUpdateSentinel( server_, docDisplay_, document, globalDisplay_.getProgressIndicator("Save File"), dirtyState_, events_); name_.setValue(getNameFromDocument(document, defaultNameProvider), true); docDisplay_.setCode(document.getContents(), false); registerPrefs(); // Initialize sourceOnSave, and keep it in sync view_.getSourceOnSave().setValue(document.sourceOnSave(), false); view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { docUpdateSentinel_.setSourceOnSave( event.getValue(), globalDisplay_.getProgressIndicator("Error Saving Setting")); } }); if (document.isDirty()) dirtyState_.markDirty(false); else dirtyState_.markClean(); docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>() { public void onValueChange(ValueChangeEvent<Void> event) { dirtyState_.markDirty(true); } }); docDisplay_.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { public boolean execute() { if (view_.isAttached()) checkForExternalEdit(); return false; } }, 500); } }); if (fileType_.canCompilePDF() && !session_.getSessionInfo().isTexInstalled()) { server_.isTexInstalled(new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean response) { if (!response) { String warning; if (Desktop.isDesktop()) warning = "No TeX installation detected. Please install " + "TeX before compiling."; else warning = "This server does not have TeX installed. You " + "may not be able to compile."; view_.showWarningBar(warning); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } releaseOnDismiss_.add(events_.addHandler( ChangeFontSizeEvent.TYPE, new ChangeFontSizeHandler() { public void onChangeFontSize(ChangeFontSizeEvent event) { view_.setFontSize(event.getFontSize()); } })); view_.setFontSize(fontSizeManager_.getSize()); final String rTypeId = FileTypeRegistry.R.getTypeId(); releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler( new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> evt) { if (fileType_.getTypeId().equals(rTypeId)) view_.adaptToFileType(fileType_); } } )); initStatusBar(); } private void initStatusBar() { statusBar_ = view_.getStatusBar(); docDisplay_.addCursorChangedHandler(new CursorChangedHandler() { public void onCursorChanged(CursorChangedEvent event) { updateStatusBarPosition(); } }); updateStatusBarPosition(); updateStatusBarLanguage(); statusBarFileTypes_ = new TextFileType[] { FileTypeRegistry.R, FileTypeRegistry.TEXT, FileTypeRegistry.SWEAVE, FileTypeRegistry.RD, FileTypeRegistry.TEX, }; for (TextFileType fileType : statusBarFileTypes_) { statusBar_.getLanguage().addOptionValue(fileType.getLabel()); } statusBar_.getLanguage().addSelectionHandler(new SelectionHandler<String>() { public void onSelection(SelectionEvent<String> event) { String item = event.getSelectedItem(); for (TextFileType fileType : statusBarFileTypes_) { if (fileType.getLabel().equals(item)) { docUpdateSentinel_.changeFileType( fileType.getTypeId(), new SaveProgressIndicator(null, fileType, null)); break; } } } }); statusBar_.getFunction().addMouseDownHandler(new MouseDownHandler() { public void onMouseDown(MouseDownEvent event) { // Unlike the other status bar elements, the function outliner // needs its menu built on demand JsArray<FunctionStart> tree = docDisplay_.getFunctionTree(); final StatusBarPopupMenu menu = new StatusBarPopupMenu(); MenuItem defaultItem = addFunctionsToMenu( menu, tree, "", docDisplay_.getCurrentFunction()); if (defaultItem != null) { menu.selectItem(defaultItem); Scheduler.get().scheduleFinally(new RepeatingCommand() { public boolean execute() { menu.ensureSelectedIsVisible(); return false; } }); } menu.showRelativeToUpward((UIObject) statusBar_.getFunction()); } }); } private MenuItem addFunctionsToMenu(StatusBarPopupMenu menu, final JsArray<FunctionStart> funcs, String indent, FunctionStart defaultFunction) { MenuItem defaultMenuItem = null; for (int i = 0; i < funcs.length(); i++) { final FunctionStart func = funcs.get(i); SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder(); labelBuilder.appendHtmlConstant(indent); labelBuilder.appendEscaped(func.getLabel()); final MenuItem menuItem = new MenuItem( labelBuilder.toSafeHtml(), new Command() { public void execute() { docDisplay_.setCursorPosition(func.getPreamble()); docDisplay_.moveCursorNearTop(); docDisplay_.focus(); } }); menu.addItem(menuItem); if (defaultFunction != null && defaultMenuItem == null && func.getLabel().equals(defaultFunction.getLabel()) && func.getPreamble().getRow() == defaultFunction.getPreamble().getRow() && func.getPreamble().getColumn() == defaultFunction.getPreamble().getColumn()) { defaultMenuItem = menuItem; } MenuItem childDefaultMenuItem = addFunctionsToMenu( menu, func.getChildren(), indent + "&nbsp;&nbsp;", defaultMenuItem == null ? defaultFunction : null); if (childDefaultMenuItem != null) defaultMenuItem = childDefaultMenuItem; } return defaultMenuItem; } private void updateStatusBarLanguage() { statusBar_.getLanguage().setValue(fileType_.getLabel()); boolean isR = fileType_ == FileTypeRegistry.R; statusBar_.setFunctionVisible(isR); if (isR) updateCurrentFunction(); } private void updateStatusBarPosition() { Position pos = docDisplay_.getCursorPosition(); statusBar_.getPosition().setValue((pos.getRow() + 1) + ":" + (pos.getColumn() + 1)); updateCurrentFunction(); } private void updateCurrentFunction() { Scheduler.get().scheduleDeferred( new ScheduledCommand() { public void execute() { FunctionStart function = docDisplay_.getCurrentFunction(); String label = function != null ? function.getLabel() : null; statusBar_.getFunction().setValue(label); } }); } private void registerPrefs() { releaseOnDismiss_.add(prefs_.highlightSelectedLine().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setHighlightSelectedLine(arg); }})); releaseOnDismiss_.add(prefs_.showLineNumbers().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setShowLineNumbers(arg); }})); releaseOnDismiss_.add(prefs_.useSpacesForTab().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setUseSoftTabs(arg); }})); releaseOnDismiss_.add(prefs_.numSpacesForTab().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay_.setTabSize(arg); }})); releaseOnDismiss_.add(prefs_.showMargin().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setShowPrintMargin(arg); }})); releaseOnDismiss_.add(prefs_.printMarginColumn().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay_.setPrintMarginColumn(arg); }})); } private String getNameFromDocument(SourceDocument document, Provider<String> defaultNameProvider) { if (document.getPath() != null) return FileSystemItem.getNameFromPath(document.getPath()); String name = document.getProperties().getString("tempName"); if (!StringUtil.isNullOrEmpty(name)) return name; String defaultName = defaultNameProvider.get(); docUpdateSentinel_.setProperty("tempName", defaultName, null); return defaultName; } public long getFileSizeLimit() { return 5 * 1024 * 1024; } public long getLargeFileSize() { return Desktop.isDesktop() ? 1024 * 1024 : 512 * 1024; } public void insertCode(String source, boolean blockMode) { docDisplay_.insertCode(source, blockMode); } public HashSet<AppCommand> getSupportedCommands() { return fileType_.getSupportedCommands(commands_); } public void focus() { docDisplay_.focus(); } public HandlerRegistration addEnsureVisibleHandler(EnsureVisibleHandler handler) { return view_.addEnsureVisibleHandler(handler); } public HandlerRegistration addCloseHandler(CloseHandler<java.lang.Void> handler) { return handlers_.addHandler(CloseEvent.getType(), handler); } public void fireEvent(GwtEvent<?> event) { handlers_.fireEvent(event); } public void onActivate() { // If we're already hooked up for some reason, unhook. // This shouldn't happen though. if (commandHandlerReg_ != null) { Debug.log("Warning: onActivate called twice without intervening onDeactivate"); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; } commandHandlerReg_ = commandBinder.bind(commands_, this); Scheduler.get().scheduleFinally(new ScheduledCommand() { public void execute() { // This has to be executed in a scheduleFinally because // Source.manageCommands gets called after this.onActivate, // and if we're going from a non-editor (like data view) to // an editor, setEnabled(true) will be called on the command // in manageCommands. commands_.reopenSourceDocWithEncoding().setEnabled( docUpdateSentinel_.getPath() != null); } }); view_.onActivate(); } public void onDeactivate() { externalEditCheckInvalidation_.invalidate(); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; } @Override public void onInitiallyLoaded() { checkForExternalEdit(); } public boolean onBeforeDismiss() { promptForSave(new Command() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }); return false; } private void promptForSave(final Command command) { if (dirtyState_.getValue()) { view_.ensureVisible(); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Unsaved Changes", "This document has unsaved changes!\n\n" + "Do you want to save changes before continuing?", true, new Operation() { public void execute() { saveThenExecute(null, command); } }, new Operation() { public void execute() { command.execute(); } }, null, "Save", "Don't Save", true); } else { command.execute(); } } private void saveThenExecute(String encodingOverride, final Command command) { final String path = docUpdateSentinel_.getPath(); if (path == null) { saveNewFile(null, encodingOverride, command); return; } withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { docUpdateSentinel_.save(path, null, encoding, new SaveProgressIndicator( FileSystemItem.createFile(path), null, command )); } }); } private void saveNewFile(final String suggestedPath, String encodingOverride, final Command executeOnSuccess) { withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { saveNewFileWithEncoding(suggestedPath, encoding, executeOnSuccess); } }); } private void withEncodingRequiredUnlessAscii( final String encodingOverride, final CommandWithArg<String> command) { final String encoding = StringUtil.firstNotNullOrEmpty(new String[] { encodingOverride, docUpdateSentinel_.getEncoding(), prefs_.defaultEncoding().getValue() }); if (StringUtil.isNullOrEmpty(encoding)) { if (docUpdateSentinel_.isAscii()) { // Don't bother asking when it's just ASCII command.execute(null); } else { withChooseEncoding(session_.getSessionInfo().getSystemEncoding(), new CommandWithArg<String>() { public void execute(String newEncoding) { command.execute(newEncoding); } }); } } else { command.execute(encoding); } } private void withChooseEncoding(final String defaultEncoding, final CommandWithArg<String> command) { server_.iconvlist(new SimpleRequestCallback<IconvListResult>() { @Override public void onResponseReceived(IconvListResult response) { // Stupid compiler. Use this Value shim to make the dialog available // in its own handler. final HasValue<ChooseEncodingDialog> d = new Value<ChooseEncodingDialog>(null); d.setValue(new ChooseEncodingDialog( response.getCommon(), response.getAll(), defaultEncoding, false, true, new OperationWithInput<String>() { public void execute(String newEncoding) { if (newEncoding == null) return; if (d.getValue().isSaveAsDefault()) { prefs_.defaultEncoding().setValue(newEncoding); server2_.setUiPrefs( session_.getSessionInfo().getUiPrefs(), new SimpleRequestCallback<Void>("Error Saving Preference")); } command.execute(newEncoding); } })); d.getValue().showModal(); } }); } private void saveNewFileWithEncoding(String suggestedPath, final String encoding, final Command executeOnSuccess) { FileSystemItem fsi = suggestedPath != null ? FileSystemItem.createFile(suggestedPath) : workbenchContext_.getDefaultFileDialogDir(); fileDialogs_.saveFile( "Save File", fileContext_, fsi, fileType_.getDefaultExtension(), new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem saveItem, ProgressIndicator indicator) { if (saveItem == null) return; try { workbenchContext_.setDefaultFileDialogDir( saveItem.getParentPath()); TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(saveItem); docUpdateSentinel_.save( saveItem.getPath(), fileType.getTypeId(), encoding, new SaveProgressIndicator(saveItem, fileType, executeOnSuccess)); events_.fireEvent( new SourceFileSavedEvent(saveItem.getPath())); } catch (Exception e) { indicator.onError(e.toString()); return; } indicator.onCompleted(); } }); } public void onDismiss() { docUpdateSentinel_.stop(); removePublishPdfHandler(); while (releaseOnDismiss_.size() > 0) releaseOnDismiss_.remove(0).removeHandler(); if (lastExecutedCode_ != null) { lastExecutedCode_.detach(); lastExecutedCode_ = null; } } public ReadOnlyValue<Boolean> dirtyState() { return dirtyState_; } public Widget toWidget() { return (Widget) view_; } public String getId() { return id_; } public HasValue<String> getName() { return name_; } public String getPath() { return docUpdateSentinel_.getPath(); } public ImageResource getIcon() { return fileType_.getDefaultIcon(); } public String getTabTooltip() { return getPath(); } @Handler void onReopenSourceDocWithEncoding() { withChooseEncoding( docUpdateSentinel_.getEncoding(), new CommandWithArg<String>() { public void execute(String encoding) { docUpdateSentinel_.reopenWithEncoding(encoding); } }); } @Handler void onSaveSourceDoc() { saveThenExecute(null, sourceOnSaveCommandIfApplicable()); } @Handler void onSaveSourceDocAs() { saveNewFile(docUpdateSentinel_.getPath(), null, sourceOnSaveCommandIfApplicable()); } @Handler void onSaveSourceDocWithEncoding() { withChooseEncoding( StringUtil.firstNotNullOrEmpty(new String[] { docUpdateSentinel_.getEncoding(), session_.getSessionInfo().getSystemEncoding() }), new CommandWithArg<String>() { public void execute(String encoding) { saveThenExecute(encoding, sourceOnSaveCommandIfApplicable()); } }); } @Handler void onPrintSourceDoc() { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { docDisplay_.print(); } }); } @Handler void onExtractFunction() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); String initialSelection = docDisplay_.getSelectionValue(); if (initialSelection == null || initialSelection.trim().length() == 0) { globalDisplay_.showErrorMessage("Extract Function", "Please select the code to extract " + "into a function."); return; } docDisplay_.fitSelectionToLines(false); final String code = docDisplay_.getSelectionValue(); if (code == null || code.trim().length() == 0) { globalDisplay_.showErrorMessage("Extract Function", "Please select the code to extract " + "into a function."); return; } Pattern leadingWhitespace = Pattern.create("^(\\s*)"); Match match = leadingWhitespace.match(code, 0); final String indentation = match == null ? "" : match.getGroup(1); server_.detectFreeVars(code, new ServerRequestCallback<JsArrayString>() { @Override public void onResponseReceived(final JsArrayString response) { doExtract(response); } @Override public void onError(ServerError error) { globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "Extract Function", "The selected code could not be " + "parsed.\n\n" + "Are you sure you want to continue?", new Operation() { public void execute() { doExtract(null); } }, false); } private void doExtract(final JsArrayString response) { globalDisplay_.promptForText( "Extract Function", "Function Name", "", new OperationWithInput<String>() { public void execute(String input) { String prefix = docDisplay_.getSelectionOffset(true) == 0 ? "" : "\n"; String args = response != null ? response.join(", ") : ""; docDisplay_.replaceSelection( prefix + indentation + input.trim() + " <- " + "function (" + args + ") {\n" + StringUtil.indent(code, " ") + "\n" + indentation + "}"); } }); } }); } @Handler void onCommentUncomment() { docDisplay_.fitSelectionToLines(true); String selection = docDisplay_.getSelectionValue(); // If any line's first non-whitespace character is not #, then the whole // selection should be commented. Exception: If the whole selection is // whitespace, then we comment out the whitespace. Match match = Pattern.create("^\\s*[^#\\s]").match(selection, 0); boolean uncomment = match == null && selection.trim().length() != 0; if (uncomment) selection = selection.replaceAll("((^|\\n)\\s*)# ?", "$1"); else { selection = "# " + selection.replaceAll("\\n", "\n# "); // If the selection ends at the very start of a line, we don't want // to comment out that line. This enables Shift+DownArrow to select // one line at a time. if (selection.endsWith("\n# ")) selection = selection.substring(0, selection.length() - 2); } docDisplay_.replaceSelection(selection); } @Handler void onExecuteCode() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); String code = docDisplay_.getSelectionValue(); if (code == null || code.length() == 0) { int row = docDisplay_.getSelectionStart().getRow(); setLastExecuted(Position.create(row, 0), Position.create(row, docDisplay_.getLength(row))); code = docDisplay_.getCurrentLine(); docDisplay_.moveSelectionToNextLine(true); } else { setLastExecuted(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); } if (code != null && code.trim().length() > 0) { events_.fireEvent(new SendToConsoleEvent(code, true)); } } private void setLastExecuted(Position start, Position end) { if (lastExecutedCode_ != null) { lastExecutedCode_.detach(); lastExecutedCode_ = null; } lastExecutedCode_ = docDisplay_.createAnchoredSelection(start, end); } @Handler void onExecuteAllCode() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); String code = docDisplay_.getCode(); if (fileType_.canCompilePDF()) { code = stangle(code); } code = code.replaceAll("^[ \t\n]*\n", ""); code = code.replaceAll("\n[ \t\n]*$", ""); events_.fireEvent(new SendToConsoleEvent(code, true)); } @Handler void onExecuteToCurrentLine() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); int row = docDisplay_.getSelectionEnd().getRow(); int col = docDisplay_.getLength(row); Position start = Position.create(0, 0); Position end = Position.create(row, col); String code = docDisplay_.getCode(start, end); setLastExecuted(start, end); events_.fireEvent(new SendToConsoleEvent(code, true)); } @Handler void onExecuteFromCurrentLine() { globalDisplay_.showMessage(MessageDialog.INFO, "RStudio", "Not yet implemented"); } @Handler void onExecuteCurrentFunction() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentFunction() returns // a FunctionStart with an end. docDisplay_.getFunctionTree(); FunctionStart currentFunction = docDisplay_.getCurrentFunction(); // Check if we're at the top level (i.e. not in a function), or in // an unclosed function if (currentFunction == null || currentFunction.getEnd() == null) return; Position start = currentFunction.getPreamble(); Position end = currentFunction.getEnd(); String code = docDisplay_.getCode(start, end); setLastExecuted(start, end); events_.fireEvent(new SendToConsoleEvent(code.trim(), true)); } @Handler void onJumpToFunction() { statusBar_.getFunction().click(); } @Handler public void onSetWorkingDirToActiveDoc() { // get path String activeDocPath = docUpdateSentinel_.getPath(); if (activeDocPath != null) { FileSystemItem wdPath = FileSystemItem.createFile(activeDocPath).getParentPath(); consoleDispatcher_.executeSetWd(wdPath, true); } else { globalDisplay_.showMessage( MessageDialog.WARNING, "Source File Not Saved", "The currently active source file is not saved so doesn't " + "have a directory to change into."); return; } } private static String stangle(String sweaveStr) { StringBuilder code = new StringBuilder(); Pattern pStart = Pattern.create("^<<.*>>=", "mg"); Pattern pNewLine = Pattern.create("\n"); Pattern pEnd = Pattern.create("\n@"); int pos = 0; Match mStart; while (null != (mStart = pStart.match(sweaveStr, pos))) { Match mNewLine = pNewLine.match(sweaveStr, mStart.getIndex()); if (mNewLine == null) break; Match mEnd = pEnd.match(sweaveStr, mNewLine.getIndex() + 1); if (mEnd == null) break; code.append(sweaveStr, mNewLine.getIndex() + 1, mEnd.getIndex() + 1); pos = mEnd.getIndex() + 2; } sweaveStr = code.toString(); return sweaveStr; } @Handler void onSourceActiveDocument() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); String code = docDisplay_.getCode(); if (code != null && code.trim().length() > 0) { boolean sweave = fileType_.canCompilePDF(); server_.saveActiveDocument(code, sweave, new SimpleRequestCallback<Void>() { @Override public void onResponseReceived(Void response) { consoleDispatcher_.executeSourceCommand( "~/.active-rstudio-document", "UTF-8", activeCodeIsAscii()); } }); } } private boolean activeCodeIsAscii() { String code = docDisplay_.getCode(); for (int i=0; i< code.length(); i++) { if (code.charAt(i) > 127) return false; } return true; } @Handler void onExecuteLastCode() { if (lastExecutedCode_ != null) { String code = lastExecutedCode_.getValue(); if (code != null && code.trim().length() > 0) { events_.fireEvent(new SendToConsoleEvent(code, true)); } } } @Handler void onPublishPDF() { // setup handler for PublishPdfEvent removePublishPdfHandler(); publishPdfReg_ = events_.addHandler(PublishPdfEvent.TYPE, new PublishPdfHandler() { public void onPublishPdf(PublishPdfEvent event) { // if this event applies to our document then handle it if ((docUpdateSentinel_ != null) && event.getPath().equals(docUpdateSentinel_.getPath())) { PublishPdfDialog pdfDialog = new PublishPdfDialog(); pdfDialog.showModal(); PublishPdf publishPdf = pPublishPdf_.get(); publishPdf.publish(id_, docDisplay_, docUpdateSentinel_, pdfDialog); } } }); // send publish to console handlePdfCommand("publishPdf"); } private void removePublishPdfHandler() { if (publishPdfReg_ != null) { publishPdfReg_.removeHandler(); publishPdfReg_ = null; } } @Handler void onCompilePDF() { handlePdfCommand("compilePdf"); } @Handler void onFindReplace() { view_.showFindReplace(); } void handlePdfCommand(final String function) { saveThenExecute(null, new Command() { public void execute() { String path = docUpdateSentinel_.getPath(); if (path != null) sendPdfFunctionToConsole(function, path); } }); } private void sendPdfFunctionToConsole(String function, String path) { // first validate the path to make sure it doesn't contain spaces FileSystemItem file = FileSystemItem.createFile(path); if (file.getName().indexOf(' ') != -1) { globalDisplay_.showErrorMessage( "Invalid Filename", "The file '" + file.getName() + "' cannot be compiled to " + "a PDF because TeX does not understand paths with spaces. " + "If you rename the file to remove spaces then " + "PDF compilation will work correctly."); return; } // build the SendToConsoleEvent and fire it String code = function + "(\"" + path + "\")"; final SendToConsoleEvent event = new SendToConsoleEvent(code, true); events_.fireEvent(event); } private Command sourceOnSaveCommandIfApplicable() { return new Command() { public void execute() { if (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { consoleDispatcher_.executeSourceCommand( docUpdateSentinel_.getPath(), docUpdateSentinel_.getEncoding(), activeCodeIsAscii()); } } }; } public void checkForExternalEdit() { if (!externalEditCheckInterval_.hasElapsed()) return; externalEditCheckInterval_.reset(); externalEditCheckInvalidation_.invalidate(); // If the doc has never been saved, don't even bother checking if (getPath() == null) return; final Token token = externalEditCheckInvalidation_.getInvalidationToken(); server_.checkForExternalEdit( id_, new ServerRequestCallback<CheckForExternalEditResult>() { @Override public void onResponseReceived(CheckForExternalEditResult response) { if (token.isInvalid()) return; if (response.isDeleted()) { if (ignoreDeletes_) return; globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Deleted", "The file " + name_.getValue() + " has been " + "deleted. Do you want to close this file now?", false, new Operation() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); ignoreDeletes_ = true; // Make sure it stays dirty dirtyState_.markDirty(false); } }, false ); } else if (response.isModified()) { ignoreDeletes_ = false; // Now we know it exists // Use StringUtil.formatDate(response.getLastModified())? if (!dirtyState_.getValue()) { docUpdateSentinel_.revert(); } else { externalEditCheckInterval_.reset(); globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Changed", "The file " + name_.getValue() + " has changed " + "on disk. Do you want to reload the file from " + "disk and discard your unsaved changes?", false, new Operation() { public void execute() { docUpdateSentinel_.revert(); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); docUpdateSentinel_.ignoreExternalEdit(); // Make sure it stays dirty dirtyState_.markDirty(false); } }, true ); } } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private StatusBar statusBar_; private TextFileType[] statusBarFileTypes_; private DocDisplay docDisplay_; private final UIPrefs prefs_; private Display view_; private final Commands commands_; private SourceServerOperations server_; private final WorkbenchServerOperations server2_; private EventBus events_; private final GlobalDisplay globalDisplay_; private final FileDialogs fileDialogs_; private final FileTypeRegistry fileTypeRegistry_; private final ConsoleDispatcher consoleDispatcher_; private final WorkbenchContext workbenchContext_; private final Session session_; private final FontSizeManager fontSizeManager_; private DocUpdateSentinel docUpdateSentinel_; private Value<String> name_ = new Value<String>(null); private TextFileType fileType_; private String id_; private HandlerRegistration commandHandlerReg_; private HandlerRegistration publishPdfReg_; private ArrayList<HandlerRegistration> releaseOnDismiss_ = new ArrayList<HandlerRegistration>(); private final DirtyState dirtyState_; private HandlerManager handlers_ = new HandlerManager(this); private FileSystemContext fileContext_; private final Provider<PublishPdf> pPublishPdf_; private boolean ignoreDeletes_; // Allows external edit checks to supercede one another private final Invalidation externalEditCheckInvalidation_ = new Invalidation(); // Prevents external edit checks from happening too soon after each other private final IntervalTracker externalEditCheckInterval_ = new IntervalTracker(1000, true); private AnchoredSelection lastExecutedCode_; }
src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/TextEditingTarget.java
/* * TextEditingTarget.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.workbench.views.source.editors.text; import com.google.gwt.core.client.*; import com.google.gwt.core.client.Scheduler.RepeatingCommand; import com.google.gwt.core.client.Scheduler.ScheduledCommand; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NativeEvent; import com.google.gwt.event.dom.client.*; import com.google.gwt.event.logical.shared.*; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.resources.client.ImageResource; import com.google.gwt.safehtml.shared.SafeHtmlBuilder; import com.google.gwt.user.client.Command; import com.google.gwt.user.client.ui.HasValue; import com.google.gwt.user.client.ui.MenuItem; import com.google.gwt.user.client.ui.UIObject; import com.google.gwt.user.client.ui.Widget; import com.google.inject.Inject; import com.google.inject.Provider; import org.rstudio.core.client.*; import org.rstudio.core.client.Invalidation.Token; import org.rstudio.core.client.command.AppCommand; import org.rstudio.core.client.command.CommandBinder; import org.rstudio.core.client.command.Handler; import org.rstudio.core.client.command.KeyboardShortcut; import org.rstudio.core.client.dom.DomUtils; import org.rstudio.core.client.events.EnsureVisibleHandler; import org.rstudio.core.client.events.HasEnsureVisibleHandlers; import org.rstudio.core.client.files.FileSystemContext; import org.rstudio.core.client.files.FileSystemItem; import org.rstudio.core.client.regex.Match; import org.rstudio.core.client.regex.Pattern; import org.rstudio.core.client.widget.*; import org.rstudio.studio.client.application.Desktop; import org.rstudio.studio.client.application.events.ChangeFontSizeEvent; import org.rstudio.studio.client.application.events.ChangeFontSizeHandler; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.common.*; import org.rstudio.studio.client.common.filetypes.FileType; import org.rstudio.studio.client.common.filetypes.FileTypeRegistry; import org.rstudio.studio.client.common.filetypes.TextFileType; import org.rstudio.studio.client.server.ServerError; import org.rstudio.studio.client.server.ServerRequestCallback; import org.rstudio.studio.client.server.Void; import org.rstudio.studio.client.workbench.WorkbenchContext; import org.rstudio.studio.client.workbench.commands.Commands; import org.rstudio.studio.client.workbench.model.ChangeTracker; import org.rstudio.studio.client.workbench.model.Session; import org.rstudio.studio.client.workbench.model.WorkbenchServerOperations; import org.rstudio.studio.client.workbench.prefs.model.UIPrefs; import org.rstudio.studio.client.workbench.ui.FontSizeManager; import org.rstudio.studio.client.workbench.views.console.events.SendToConsoleEvent; import org.rstudio.studio.client.workbench.views.source.editors.EditingTarget; import org.rstudio.studio.client.workbench.views.source.editors.text.ace.Position; import org.rstudio.studio.client.workbench.views.source.editors.text.events.*; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBar; import org.rstudio.studio.client.workbench.views.source.editors.text.status.StatusBarPopupMenu; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.ChooseEncodingDialog; import org.rstudio.studio.client.workbench.views.source.editors.text.TextEditingTarget.DocDisplay.AnchoredSelection; import org.rstudio.studio.client.workbench.views.source.editors.text.ui.PublishPdfDialog; import org.rstudio.studio.client.workbench.views.source.events.SourceFileSavedEvent; import org.rstudio.studio.client.workbench.views.source.model.*; import java.util.ArrayList; import java.util.HashSet; public class TextEditingTarget implements EditingTarget { interface MyCommandBinder extends CommandBinder<Commands, TextEditingTarget> { } private static final MyCommandBinder commandBinder = GWT.create(MyCommandBinder.class); public interface Display extends HasEnsureVisibleHandlers { void adaptToFileType(TextFileType fileType); HasValue<Boolean> getSourceOnSave(); void ensureVisible(); void showWarningBar(String warning); void hideWarningBar(); void showFindReplace(); void onActivate(); void setFontSize(double size); StatusBar getStatusBar(); boolean isAttached(); } public interface DocDisplay extends HasValueChangeHandlers<Void>, Widgetable, HasFocusHandlers, HasKeyDownHandlers { public interface AnchoredSelection { String getValue(); void apply(); void detach(); } void setFileType(TextFileType fileType); String getCode(); void setCode(String code, boolean preserveCursorPosition); void insertCode(String code, boolean blockMode); void focus(); void print(); String getSelectionValue(); String getCurrentLine(); void replaceSelection(String code); boolean moveSelectionToNextLine(boolean skipBlankLines); ChangeTracker getChangeTracker(); String getCode(Position start, Position end); AnchoredSelection createAnchoredSelection(Position start, Position end); void fitSelectionToLines(boolean expand); int getSelectionOffset(boolean start); // Fix bug 964 void onActivate(); void setFontSize(double size); void onVisibilityChanged(boolean visible); void setHighlightSelectedLine(boolean on); void setShowLineNumbers(boolean on); void setUseSoftTabs(boolean on); void setUseWrapMode(boolean on); void setTabSize(int tabSize); void setShowPrintMargin(boolean on); void setPrintMarginColumn(int column); HandlerRegistration addCursorChangedHandler(CursorChangedHandler handler); Position getCursorPosition(); void setCursorPosition(Position position); void moveCursorNearTop(); FunctionStart getCurrentFunction(); JsArray<FunctionStart> getFunctionTree(); HandlerRegistration addUndoRedoHandler(UndoRedoHandler handler); JavaScriptObject getCleanStateToken(); boolean checkCleanStateToken(JavaScriptObject token); Position getSelectionStart(); Position getSelectionEnd(); int getLength(int row); } private class SaveProgressIndicator implements ProgressIndicator { public SaveProgressIndicator(FileSystemItem file, TextFileType fileType, Command executeOnSuccess) { file_ = file; newFileType_ = fileType; executeOnSuccess_ = executeOnSuccess; } public void onProgress(String message) { } public void onCompleted() { if (newFileType_ != null) fileType_ = newFileType_; if (file_ != null) { ignoreDeletes_ = false; commands_.reopenSourceDocWithEncoding().setEnabled(true); name_.setValue(file_.getName(), true); // Make sure tooltip gets updated, even if name hasn't changed name_.fireChangeEvent(); dirtyState_.markClean(); } if (newFileType_ != null) { // Make sure the icon gets updated, even if name hasn't changed name_.fireChangeEvent(); updateStatusBarLanguage(); view_.adaptToFileType(newFileType_); events_.fireEvent(new FileTypeChangedEvent()); if (!fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { view_.getSourceOnSave().setValue(false, true); } } if (executeOnSuccess_ != null) executeOnSuccess_.execute(); } public void onError(String message) { globalDisplay_.showErrorMessage( "Error Saving File", message); } private final FileSystemItem file_; private final TextFileType newFileType_; private final Command executeOnSuccess_; } @Inject public TextEditingTarget(Commands commands, SourceServerOperations server, WorkbenchServerOperations server2, EventBus events, GlobalDisplay globalDisplay, FileDialogs fileDialogs, FileTypeRegistry fileTypeRegistry, ConsoleDispatcher consoleDispatcher, WorkbenchContext workbenchContext, Provider<PublishPdf> pPublishPdf, Session session, FontSizeManager fontSizeManager, DocDisplay docDisplay, UIPrefs prefs) { commands_ = commands; server_ = server; server2_ = server2; events_ = events; globalDisplay_ = globalDisplay; fileDialogs_ = fileDialogs; fileTypeRegistry_ = fileTypeRegistry; consoleDispatcher_ = consoleDispatcher; workbenchContext_ = workbenchContext; session_ = session; fontSizeManager_ = fontSizeManager; pPublishPdf_ = pPublishPdf; docDisplay_ = docDisplay; dirtyState_ = new DirtyState(docDisplay_, false); prefs_ = prefs; docDisplay_.addKeyDownHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { NativeEvent ne = event.getNativeEvent(); int mod = KeyboardShortcut.getModifierValue(ne); if ((mod == KeyboardShortcut.META || mod == KeyboardShortcut.CTRL) && ne.getKeyCode() == 'F') { event.preventDefault(); event.stopPropagation(); commands_.findReplace().execute(); } else if (mod == KeyboardShortcut.ALT && ne.getKeyCode() == 189) // hyphen { event.preventDefault(); event.stopPropagation(); docDisplay_.insertCode(" <- ", false); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_UP && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToPreviousFunction(); } else if (mod == KeyboardShortcut.CTRL && ne.getKeyCode() == KeyCodes.KEY_DOWN && fileType_ == FileTypeRegistry.R) { event.preventDefault(); event.stopPropagation(); jumpToNextFunction(); } } }); } private void jumpToPreviousFunction() { Position cursor = docDisplay_.getCursorPosition(); JsArray<FunctionStart> functions = docDisplay_.getFunctionTree(); FunctionStart jumpTo = findPreviousFunction(functions, cursor); docDisplay_.setCursorPosition(jumpTo.getPreamble()); docDisplay_.moveCursorNearTop(); } private FunctionStart findPreviousFunction(JsArray<FunctionStart> funcs, Position pos) { FunctionStart result = null; for (int i = 0; i < funcs.length(); i++) { FunctionStart child = funcs.get(i); if (child.getPreamble().compareTo(pos) >= 0) break; result = child; } if (result == null) return result; FunctionStart descendant = findPreviousFunction(result.getChildren(), pos); if (descendant != null) result = descendant; return result; } private void jumpToNextFunction() { Position cursor = docDisplay_.getCursorPosition(); JsArray<FunctionStart> functions = docDisplay_.getFunctionTree(); FunctionStart jumpTo = findNextFunction(functions, cursor); docDisplay_.setCursorPosition(jumpTo.getPreamble()); docDisplay_.moveCursorNearTop(); } private FunctionStart findNextFunction(JsArray<FunctionStart> funcs, Position pos) { for (int i = 0; i < funcs.length(); i++) { FunctionStart child = funcs.get(i); if (child.getPreamble().compareTo(pos) <= 0) { FunctionStart descendant = findNextFunction(child.getChildren(), pos); if (descendant != null) return descendant; } else { return child; } } return null; } public void initialize(SourceDocument document, FileSystemContext fileContext, FileType type, Provider<String> defaultNameProvider) { id_ = document.getId(); fileContext_ = fileContext; fileType_ = (TextFileType) type; view_ = new TextEditingTargetWidget(commands_, docDisplay_, fileType_, events_); docUpdateSentinel_ = new DocUpdateSentinel( server_, docDisplay_, document, globalDisplay_.getProgressIndicator("Save File"), dirtyState_, events_); name_.setValue(getNameFromDocument(document, defaultNameProvider), true); docDisplay_.setCode(document.getContents(), false); registerPrefs(); // Initialize sourceOnSave, and keep it in sync view_.getSourceOnSave().setValue(document.sourceOnSave(), false); view_.getSourceOnSave().addValueChangeHandler(new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> event) { docUpdateSentinel_.setSourceOnSave( event.getValue(), globalDisplay_.getProgressIndicator("Error Saving Setting")); } }); if (document.isDirty()) dirtyState_.markDirty(false); else dirtyState_.markClean(); docDisplay_.addValueChangeHandler(new ValueChangeHandler<Void>() { public void onValueChange(ValueChangeEvent<Void> event) { dirtyState_.markDirty(true); } }); docDisplay_.addFocusHandler(new FocusHandler() { public void onFocus(FocusEvent event) { Scheduler.get().scheduleFixedDelay(new RepeatingCommand() { public boolean execute() { if (view_.isAttached()) checkForExternalEdit(); return false; } }, 500); } }); if (fileType_.canCompilePDF() && !session_.getSessionInfo().isTexInstalled()) { server_.isTexInstalled(new ServerRequestCallback<Boolean>() { @Override public void onResponseReceived(Boolean response) { if (!response) { String warning; if (Desktop.isDesktop()) warning = "No TeX installation detected. Please install " + "TeX before compiling."; else warning = "This server does not have TeX installed. You " + "may not be able to compile."; view_.showWarningBar(warning); } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } releaseOnDismiss_.add(events_.addHandler( ChangeFontSizeEvent.TYPE, new ChangeFontSizeHandler() { public void onChangeFontSize(ChangeFontSizeEvent event) { view_.setFontSize(event.getFontSize()); } })); view_.setFontSize(fontSizeManager_.getSize()); final String rTypeId = FileTypeRegistry.R.getTypeId(); releaseOnDismiss_.add(prefs_.softWrapRFiles().addValueChangeHandler( new ValueChangeHandler<Boolean>() { public void onValueChange(ValueChangeEvent<Boolean> evt) { if (fileType_.getTypeId().equals(rTypeId)) view_.adaptToFileType(fileType_); } } )); initStatusBar(); } private void initStatusBar() { statusBar_ = view_.getStatusBar(); docDisplay_.addCursorChangedHandler(new CursorChangedHandler() { public void onCursorChanged(CursorChangedEvent event) { updateStatusBarPosition(); } }); updateStatusBarPosition(); updateStatusBarLanguage(); statusBarFileTypes_ = new TextFileType[] { FileTypeRegistry.R, FileTypeRegistry.TEXT, FileTypeRegistry.SWEAVE, FileTypeRegistry.RD, FileTypeRegistry.TEX, }; for (TextFileType fileType : statusBarFileTypes_) { statusBar_.getLanguage().addOptionValue(fileType.getLabel()); } statusBar_.getLanguage().addSelectionHandler(new SelectionHandler<String>() { public void onSelection(SelectionEvent<String> event) { String item = event.getSelectedItem(); for (TextFileType fileType : statusBarFileTypes_) { if (fileType.getLabel().equals(item)) { docUpdateSentinel_.changeFileType( fileType.getTypeId(), new SaveProgressIndicator(null, fileType, null)); break; } } } }); statusBar_.getFunction().addMouseDownHandler(new MouseDownHandler() { public void onMouseDown(MouseDownEvent event) { // Unlike the other status bar elements, the function outliner // needs its menu built on demand JsArray<FunctionStart> tree = docDisplay_.getFunctionTree(); final StatusBarPopupMenu menu = new StatusBarPopupMenu(); MenuItem defaultItem = addFunctionsToMenu( menu, tree, "", docDisplay_.getCurrentFunction()); if (defaultItem != null) { menu.selectItem(defaultItem); Scheduler.get().scheduleFinally(new RepeatingCommand() { public boolean execute() { menu.ensureSelectedIsVisible(); return false; } }); } menu.showRelativeToUpward((UIObject) statusBar_.getFunction()); } }); } private MenuItem addFunctionsToMenu(StatusBarPopupMenu menu, final JsArray<FunctionStart> funcs, String indent, FunctionStart defaultFunction) { MenuItem defaultMenuItem = null; for (int i = 0; i < funcs.length(); i++) { final FunctionStart func = funcs.get(i); SafeHtmlBuilder labelBuilder = new SafeHtmlBuilder(); labelBuilder.appendHtmlConstant(indent); labelBuilder.appendEscaped(func.getLabel()); final MenuItem menuItem = new MenuItem( labelBuilder.toSafeHtml(), new Command() { public void execute() { docDisplay_.setCursorPosition(func.getPreamble()); docDisplay_.moveCursorNearTop(); docDisplay_.focus(); } }); menu.addItem(menuItem); if (defaultFunction != null && defaultMenuItem == null && func.getLabel().equals(defaultFunction.getLabel()) && func.getPreamble().getRow() == defaultFunction.getPreamble().getRow() && func.getPreamble().getColumn() == defaultFunction.getPreamble().getColumn()) { defaultMenuItem = menuItem; } MenuItem childDefaultMenuItem = addFunctionsToMenu( menu, func.getChildren(), indent + "&nbsp;&nbsp;", defaultMenuItem == null ? defaultFunction : null); if (childDefaultMenuItem != null) defaultMenuItem = childDefaultMenuItem; } return defaultMenuItem; } private void updateStatusBarLanguage() { statusBar_.getLanguage().setValue(fileType_.getLabel()); boolean isR = fileType_ == FileTypeRegistry.R; statusBar_.setFunctionVisible(isR); if (isR) updateCurrentFunction(); } private void updateStatusBarPosition() { Position pos = docDisplay_.getCursorPosition(); statusBar_.getPosition().setValue((pos.getRow() + 1) + ":" + (pos.getColumn() + 1)); updateCurrentFunction(); } private void updateCurrentFunction() { Scheduler.get().scheduleDeferred( new ScheduledCommand() { public void execute() { FunctionStart function = docDisplay_.getCurrentFunction(); String label = function != null ? function.getLabel() : null; statusBar_.getFunction().setValue(label); } }); } private void registerPrefs() { releaseOnDismiss_.add(prefs_.highlightSelectedLine().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setHighlightSelectedLine(arg); }})); releaseOnDismiss_.add(prefs_.showLineNumbers().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setShowLineNumbers(arg); }})); releaseOnDismiss_.add(prefs_.useSpacesForTab().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setUseSoftTabs(arg); }})); releaseOnDismiss_.add(prefs_.numSpacesForTab().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay_.setTabSize(arg); }})); releaseOnDismiss_.add(prefs_.showMargin().bind( new CommandWithArg<Boolean>() { public void execute(Boolean arg) { docDisplay_.setShowPrintMargin(arg); }})); releaseOnDismiss_.add(prefs_.printMarginColumn().bind( new CommandWithArg<Integer>() { public void execute(Integer arg) { docDisplay_.setPrintMarginColumn(arg); }})); } private String getNameFromDocument(SourceDocument document, Provider<String> defaultNameProvider) { if (document.getPath() != null) return FileSystemItem.getNameFromPath(document.getPath()); String name = document.getProperties().getString("tempName"); if (!StringUtil.isNullOrEmpty(name)) return name; String defaultName = defaultNameProvider.get(); docUpdateSentinel_.setProperty("tempName", defaultName, null); return defaultName; } public long getFileSizeLimit() { return 5 * 1024 * 1024; } public long getLargeFileSize() { return Desktop.isDesktop() ? 1024 * 1024 : 512 * 1024; } public void insertCode(String source, boolean blockMode) { docDisplay_.insertCode(source, blockMode); } public HashSet<AppCommand> getSupportedCommands() { return fileType_.getSupportedCommands(commands_); } public void focus() { docDisplay_.focus(); } public HandlerRegistration addEnsureVisibleHandler(EnsureVisibleHandler handler) { return view_.addEnsureVisibleHandler(handler); } public HandlerRegistration addCloseHandler(CloseHandler<java.lang.Void> handler) { return handlers_.addHandler(CloseEvent.getType(), handler); } public void fireEvent(GwtEvent<?> event) { handlers_.fireEvent(event); } public void onActivate() { // If we're already hooked up for some reason, unhook. // This shouldn't happen though. if (commandHandlerReg_ != null) { Debug.log("Warning: onActivate called twice without intervening onDeactivate"); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; } commandHandlerReg_ = commandBinder.bind(commands_, this); Scheduler.get().scheduleFinally(new ScheduledCommand() { public void execute() { // This has to be executed in a scheduleFinally because // Source.manageCommands gets called after this.onActivate, // and if we're going from a non-editor (like data view) to // an editor, setEnabled(true) will be called on the command // in manageCommands. commands_.reopenSourceDocWithEncoding().setEnabled( docUpdateSentinel_.getPath() != null); } }); view_.onActivate(); } public void onDeactivate() { externalEditCheckInvalidation_.invalidate(); commandHandlerReg_.removeHandler(); commandHandlerReg_ = null; } @Override public void onInitiallyLoaded() { checkForExternalEdit(); } public boolean onBeforeDismiss() { promptForSave(new Command() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }); return false; } private void promptForSave(final Command command) { if (dirtyState_.getValue()) { view_.ensureVisible(); globalDisplay_.showYesNoMessage(GlobalDisplay.MSG_WARNING, "Unsaved Changes", "This document has unsaved changes!\n\n" + "Do you want to save changes before continuing?", true, new Operation() { public void execute() { saveThenExecute(null, command); } }, new Operation() { public void execute() { command.execute(); } }, null, "Save", "Don't Save", true); } else { command.execute(); } } private void saveThenExecute(String encodingOverride, final Command command) { final String path = docUpdateSentinel_.getPath(); if (path == null) { saveNewFile(null, encodingOverride, command); return; } withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { docUpdateSentinel_.save(path, null, encoding, new SaveProgressIndicator( FileSystemItem.createFile(path), null, command )); } }); } private void saveNewFile(final String suggestedPath, String encodingOverride, final Command executeOnSuccess) { withEncodingRequiredUnlessAscii( encodingOverride, new CommandWithArg<String>() { public void execute(String encoding) { saveNewFileWithEncoding(suggestedPath, encoding, executeOnSuccess); } }); } private void withEncodingRequiredUnlessAscii( final String encodingOverride, final CommandWithArg<String> command) { final String encoding = StringUtil.firstNotNullOrEmpty(new String[] { encodingOverride, docUpdateSentinel_.getEncoding(), prefs_.defaultEncoding().getValue() }); if (StringUtil.isNullOrEmpty(encoding)) { if (docUpdateSentinel_.isAscii()) { // Don't bother asking when it's just ASCII command.execute(null); } else { withChooseEncoding(session_.getSessionInfo().getSystemEncoding(), new CommandWithArg<String>() { public void execute(String newEncoding) { command.execute(newEncoding); } }); } } else { command.execute(encoding); } } private void withChooseEncoding(final String defaultEncoding, final CommandWithArg<String> command) { server_.iconvlist(new SimpleRequestCallback<IconvListResult>() { @Override public void onResponseReceived(IconvListResult response) { // Stupid compiler. Use this Value shim to make the dialog available // in its own handler. final HasValue<ChooseEncodingDialog> d = new Value<ChooseEncodingDialog>(null); d.setValue(new ChooseEncodingDialog( response.getCommon(), response.getAll(), defaultEncoding, false, true, new OperationWithInput<String>() { public void execute(String newEncoding) { if (newEncoding == null) return; if (d.getValue().isSaveAsDefault()) { prefs_.defaultEncoding().setValue(newEncoding); server2_.setUiPrefs( session_.getSessionInfo().getUiPrefs(), new SimpleRequestCallback<Void>("Error Saving Preference")); } command.execute(newEncoding); } })); d.getValue().showModal(); } }); } private void saveNewFileWithEncoding(String suggestedPath, final String encoding, final Command executeOnSuccess) { FileSystemItem fsi = suggestedPath != null ? FileSystemItem.createFile(suggestedPath) : workbenchContext_.getDefaultFileDialogDir(); fileDialogs_.saveFile( "Save File", fileContext_, fsi, fileType_.getDefaultExtension(), new ProgressOperationWithInput<FileSystemItem>() { public void execute(final FileSystemItem saveItem, ProgressIndicator indicator) { if (saveItem == null) return; try { workbenchContext_.setDefaultFileDialogDir( saveItem.getParentPath()); TextFileType fileType = fileTypeRegistry_.getTextTypeForFile(saveItem); docUpdateSentinel_.save( saveItem.getPath(), fileType.getTypeId(), encoding, new SaveProgressIndicator(saveItem, fileType, executeOnSuccess)); events_.fireEvent( new SourceFileSavedEvent(saveItem.getPath())); } catch (Exception e) { indicator.onError(e.toString()); return; } indicator.onCompleted(); } }); } public void onDismiss() { docUpdateSentinel_.stop(); removePublishPdfHandler(); while (releaseOnDismiss_.size() > 0) releaseOnDismiss_.remove(0).removeHandler(); if (lastExecutedCode_ != null) { lastExecutedCode_.detach(); lastExecutedCode_ = null; } } public ReadOnlyValue<Boolean> dirtyState() { return dirtyState_; } public Widget toWidget() { return (Widget) view_; } public String getId() { return id_; } public HasValue<String> getName() { return name_; } public String getPath() { return docUpdateSentinel_.getPath(); } public ImageResource getIcon() { return fileType_.getDefaultIcon(); } public String getTabTooltip() { return getPath(); } @Handler void onReopenSourceDocWithEncoding() { withChooseEncoding( docUpdateSentinel_.getEncoding(), new CommandWithArg<String>() { public void execute(String encoding) { docUpdateSentinel_.reopenWithEncoding(encoding); } }); } @Handler void onSaveSourceDoc() { saveThenExecute(null, sourceOnSaveCommandIfApplicable()); } @Handler void onSaveSourceDocAs() { saveNewFile(docUpdateSentinel_.getPath(), null, sourceOnSaveCommandIfApplicable()); } @Handler void onSaveSourceDocWithEncoding() { withChooseEncoding( StringUtil.firstNotNullOrEmpty(new String[] { docUpdateSentinel_.getEncoding(), session_.getSessionInfo().getSystemEncoding() }), new CommandWithArg<String>() { public void execute(String encoding) { saveThenExecute(encoding, sourceOnSaveCommandIfApplicable()); } }); } @Handler void onPrintSourceDoc() { Scheduler.get().scheduleDeferred(new ScheduledCommand() { public void execute() { docDisplay_.print(); } }); } @Handler void onExtractFunction() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); String initialSelection = docDisplay_.getSelectionValue(); if (initialSelection == null || initialSelection.trim().length() == 0) { globalDisplay_.showErrorMessage("Extract Function", "Please select the code to extract " + "into a function."); return; } docDisplay_.fitSelectionToLines(false); final String code = docDisplay_.getSelectionValue(); if (code == null || code.trim().length() == 0) { globalDisplay_.showErrorMessage("Extract Function", "Please select the code to extract " + "into a function."); return; } Pattern leadingWhitespace = Pattern.create("^(\\s*)"); Match match = leadingWhitespace.match(code, 0); final String indentation = match == null ? "" : match.getGroup(1); server_.detectFreeVars(code, new ServerRequestCallback<JsArrayString>() { @Override public void onResponseReceived(final JsArrayString response) { doExtract(response); } @Override public void onError(ServerError error) { globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "Extract Function", "The selected code could not be " + "parsed.\n\n" + "Are you sure you want to continue?", new Operation() { public void execute() { doExtract(null); } }, false); } private void doExtract(final JsArrayString response) { globalDisplay_.promptForText( "Extract Function", "Function Name", "", new OperationWithInput<String>() { public void execute(String input) { String prefix = docDisplay_.getSelectionOffset(true) == 0 ? "" : "\n"; String args = response != null ? response.join(", ") : ""; docDisplay_.replaceSelection( prefix + indentation + input.trim() + " <- " + "function (" + args + ") {\n" + StringUtil.indent(code, " ") + "\n" + indentation + "}"); } }); } }); } @Handler void onCommentUncomment() { docDisplay_.fitSelectionToLines(true); String selection = docDisplay_.getSelectionValue(); // If any line's first non-whitespace character is not #, then the whole // selection should be commented. Exception: If the whole selection is // whitespace, then we comment out the whitespace. Match match = Pattern.create("^\\s*[^#\\s]").match(selection, 0); boolean uncomment = match == null && selection.trim().length() != 0; if (uncomment) selection = selection.replaceAll("((^|\\n)\\s*)# ?", "$1"); else { selection = "# " + selection.replaceAll("\\n", "\n# "); // If the selection ends at the very start of a line, we don't want // to comment out that line. This enables Shift+DownArrow to select // one line at a time. if (selection.endsWith("\n# ")) selection = selection.substring(0, selection.length() - 2); } docDisplay_.replaceSelection(selection); } @Handler void onExecuteCode() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); boolean focusConsole = false; String code = docDisplay_.getSelectionValue(); if (code == null || code.length() == 0) { int row = docDisplay_.getSelectionStart().getRow(); setLastExecuted(Position.create(row, 0), Position.create(row, docDisplay_.getLength(row))); code = docDisplay_.getCurrentLine(); docDisplay_.moveSelectionToNextLine(true); } else { setLastExecuted(docDisplay_.getSelectionStart(), docDisplay_.getSelectionEnd()); focusConsole = true; } if (code != null && code.trim().length() > 0) { events_.fireEvent(new SendToConsoleEvent(code, true)); if (focusConsole) commands_.activateConsole().execute(); } } private void setLastExecuted(Position start, Position end) { if (lastExecutedCode_ != null) { lastExecutedCode_.detach(); lastExecutedCode_ = null; } lastExecutedCode_ = docDisplay_.createAnchoredSelection(start, end); } @Handler void onExecuteAllCode() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); String code = docDisplay_.getCode(); if (fileType_.canCompilePDF()) { code = stangle(code); } code = code.replaceAll("^[ \t\n]*\n", ""); code = code.replaceAll("\n[ \t\n]*$", ""); events_.fireEvent(new SendToConsoleEvent(code, true)); } @Handler void onExecuteToCurrentLine() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); int row = docDisplay_.getSelectionEnd().getRow(); int col = docDisplay_.getLength(row); Position start = Position.create(0, 0); Position end = Position.create(row, col); String code = docDisplay_.getCode(start, end); setLastExecuted(start, end); events_.fireEvent(new SendToConsoleEvent(code, true)); } @Handler void onExecuteFromCurrentLine() { globalDisplay_.showMessage(MessageDialog.INFO, "RStudio", "Not yet implemented"); } @Handler void onExecuteCurrentFunction() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); docDisplay_.focus(); // HACK: This is just to force the entire function tree to be built. // It's the easiest way to make sure getCurrentFunction() returns // a FunctionStart with an end. docDisplay_.getFunctionTree(); FunctionStart currentFunction = docDisplay_.getCurrentFunction(); // Check if we're at the top level (i.e. not in a function), or in // an unclosed function if (currentFunction == null || currentFunction.getEnd() == null) return; Position start = currentFunction.getPreamble(); Position end = currentFunction.getEnd(); String code = docDisplay_.getCode(start, end); setLastExecuted(start, end); events_.fireEvent(new SendToConsoleEvent(code.trim(), true)); } @Handler void onJumpToFunction() { statusBar_.getFunction().click(); } @Handler public void onSetWorkingDirToActiveDoc() { // get path String activeDocPath = docUpdateSentinel_.getPath(); if (activeDocPath != null) { FileSystemItem wdPath = FileSystemItem.createFile(activeDocPath).getParentPath(); consoleDispatcher_.executeSetWd(wdPath, true); } else { globalDisplay_.showMessage( MessageDialog.WARNING, "Source File Not Saved", "The currently active source file is not saved so doesn't " + "have a directory to change into."); return; } } private static String stangle(String sweaveStr) { StringBuilder code = new StringBuilder(); Pattern pStart = Pattern.create("^<<.*>>=", "mg"); Pattern pNewLine = Pattern.create("\n"); Pattern pEnd = Pattern.create("\n@"); int pos = 0; Match mStart; while (null != (mStart = pStart.match(sweaveStr, pos))) { Match mNewLine = pNewLine.match(sweaveStr, mStart.getIndex()); if (mNewLine == null) break; Match mEnd = pEnd.match(sweaveStr, mNewLine.getIndex() + 1); if (mEnd == null) break; code.append(sweaveStr, mNewLine.getIndex() + 1, mEnd.getIndex() + 1); pos = mEnd.getIndex() + 2; } sweaveStr = code.toString(); return sweaveStr; } @Handler void onSourceActiveDocument() { // Stops the console from thinking it has focus, and thus stealing it Element activeEl = DomUtils.getActiveElement(); if (activeEl != null) activeEl.blur(); String code = docDisplay_.getCode(); if (code != null && code.trim().length() > 0) { boolean sweave = fileType_.canCompilePDF(); server_.saveActiveDocument(code, sweave, new SimpleRequestCallback<Void>() { @Override public void onResponseReceived(Void response) { consoleDispatcher_.executeSourceCommand( "~/.active-rstudio-document", "UTF-8", activeCodeIsAscii()); } }); } } private boolean activeCodeIsAscii() { String code = docDisplay_.getCode(); for (int i=0; i< code.length(); i++) { if (code.charAt(i) > 127) return false; } return true; } @Handler void onExecuteLastCode() { if (lastExecutedCode_ != null) { String code = lastExecutedCode_.getValue(); if (code != null && code.trim().length() > 0) { events_.fireEvent(new SendToConsoleEvent(code, true)); } } } @Handler void onPublishPDF() { // setup handler for PublishPdfEvent removePublishPdfHandler(); publishPdfReg_ = events_.addHandler(PublishPdfEvent.TYPE, new PublishPdfHandler() { public void onPublishPdf(PublishPdfEvent event) { // if this event applies to our document then handle it if ((docUpdateSentinel_ != null) && event.getPath().equals(docUpdateSentinel_.getPath())) { PublishPdfDialog pdfDialog = new PublishPdfDialog(); pdfDialog.showModal(); PublishPdf publishPdf = pPublishPdf_.get(); publishPdf.publish(id_, docDisplay_, docUpdateSentinel_, pdfDialog); } } }); // send publish to console handlePdfCommand("publishPdf"); } private void removePublishPdfHandler() { if (publishPdfReg_ != null) { publishPdfReg_.removeHandler(); publishPdfReg_ = null; } } @Handler void onCompilePDF() { handlePdfCommand("compilePdf"); } @Handler void onFindReplace() { view_.showFindReplace(); } void handlePdfCommand(final String function) { saveThenExecute(null, new Command() { public void execute() { String path = docUpdateSentinel_.getPath(); if (path != null) sendPdfFunctionToConsole(function, path); } }); } private void sendPdfFunctionToConsole(String function, String path) { // first validate the path to make sure it doesn't contain spaces FileSystemItem file = FileSystemItem.createFile(path); if (file.getName().indexOf(' ') != -1) { globalDisplay_.showErrorMessage( "Invalid Filename", "The file '" + file.getName() + "' cannot be compiled to " + "a PDF because TeX does not understand paths with spaces. " + "If you rename the file to remove spaces then " + "PDF compilation will work correctly."); return; } // build the SendToConsoleEvent and fire it String code = function + "(\"" + path + "\")"; final SendToConsoleEvent event = new SendToConsoleEvent(code, true); events_.fireEvent(event); } private Command sourceOnSaveCommandIfApplicable() { return new Command() { public void execute() { if (fileType_.canSourceOnSave() && docUpdateSentinel_.sourceOnSave()) { consoleDispatcher_.executeSourceCommand( docUpdateSentinel_.getPath(), docUpdateSentinel_.getEncoding(), activeCodeIsAscii()); } } }; } public void checkForExternalEdit() { if (!externalEditCheckInterval_.hasElapsed()) return; externalEditCheckInterval_.reset(); externalEditCheckInvalidation_.invalidate(); // If the doc has never been saved, don't even bother checking if (getPath() == null) return; final Token token = externalEditCheckInvalidation_.getInvalidationToken(); server_.checkForExternalEdit( id_, new ServerRequestCallback<CheckForExternalEditResult>() { @Override public void onResponseReceived(CheckForExternalEditResult response) { if (token.isInvalid()) return; if (response.isDeleted()) { if (ignoreDeletes_) return; globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Deleted", "The file " + name_.getValue() + " has been " + "deleted. Do you want to close this file now?", false, new Operation() { public void execute() { CloseEvent.fire(TextEditingTarget.this, null); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); ignoreDeletes_ = true; // Make sure it stays dirty dirtyState_.markDirty(false); } }, false ); } else if (response.isModified()) { ignoreDeletes_ = false; // Now we know it exists // Use StringUtil.formatDate(response.getLastModified())? if (!dirtyState_.getValue()) { docUpdateSentinel_.revert(); } else { externalEditCheckInterval_.reset(); globalDisplay_.showYesNoMessage( GlobalDisplay.MSG_WARNING, "File Changed", "The file " + name_.getValue() + " has changed " + "on disk. Do you want to reload the file from " + "disk and discard your unsaved changes?", false, new Operation() { public void execute() { docUpdateSentinel_.revert(); } }, new Operation() { public void execute() { externalEditCheckInterval_.reset(); docUpdateSentinel_.ignoreExternalEdit(); // Make sure it stays dirty dirtyState_.markDirty(false); } }, true ); } } } @Override public void onError(ServerError error) { Debug.logError(error); } }); } private StatusBar statusBar_; private TextFileType[] statusBarFileTypes_; private DocDisplay docDisplay_; private final UIPrefs prefs_; private Display view_; private final Commands commands_; private SourceServerOperations server_; private final WorkbenchServerOperations server2_; private EventBus events_; private final GlobalDisplay globalDisplay_; private final FileDialogs fileDialogs_; private final FileTypeRegistry fileTypeRegistry_; private final ConsoleDispatcher consoleDispatcher_; private final WorkbenchContext workbenchContext_; private final Session session_; private final FontSizeManager fontSizeManager_; private DocUpdateSentinel docUpdateSentinel_; private Value<String> name_ = new Value<String>(null); private TextFileType fileType_; private String id_; private HandlerRegistration commandHandlerReg_; private HandlerRegistration publishPdfReg_; private ArrayList<HandlerRegistration> releaseOnDismiss_ = new ArrayList<HandlerRegistration>(); private final DirtyState dirtyState_; private HandlerManager handlers_ = new HandlerManager(this); private FileSystemContext fileContext_; private final Provider<PublishPdf> pPublishPdf_; private boolean ignoreDeletes_; // Allows external edit checks to supercede one another private final Invalidation externalEditCheckInvalidation_ = new Invalidation(); // Prevents external edit checks from happening too soon after each other private final IntervalTracker externalEditCheckInterval_ = new IntervalTracker(1000, true); private AnchoredSelection lastExecutedCode_; }
never focus the console after executing code
src/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/TextEditingTarget.java
never focus the console after executing code
<ide><path>rc/gwt/src/org/rstudio/studio/client/workbench/views/source/editors/text/TextEditingTarget.java <ide> activeEl.blur(); <ide> docDisplay_.focus(); <ide> <del> boolean focusConsole = false; <ide> String code = docDisplay_.getSelectionValue(); <ide> if (code == null || code.length() == 0) <ide> { <ide> { <ide> setLastExecuted(docDisplay_.getSelectionStart(), <ide> docDisplay_.getSelectionEnd()); <del> focusConsole = true; <ide> } <ide> <ide> if (code != null && code.trim().length() > 0) <ide> { <ide> events_.fireEvent(new SendToConsoleEvent(code, true)); <del> if (focusConsole) <del> commands_.activateConsole().execute(); <ide> } <ide> } <ide>
Java
apache-2.0
2657ed088b939bc34ac883e383426e4bad665ffc
0
baszero/yanel,baszero/yanel,baszero/yanel,wyona/yanel,wyona/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel
/* * Copyright 2007 Wyona */ package org.wyona.yanel.impl.resources.updatefinder; import org.apache.log4j.Category; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.ResourceResolver; import org.wyona.yanel.core.transformation.I18nTransformer; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.transformation.XIncludeTransformer; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.impl.resources.updatefinder.utils.*; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Collections; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.servlet.http.HttpServletRequest; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.hp.hpl.jena.rdf.model.*; /** * */ public class UpdateFinder extends Resource implements ViewableV2 { private static Category log = Category.getInstance(UpdateFinder.class); private String defaultLanguage; private String language = null; /** * */ public UpdateFinder() { } /** * */ public boolean exists() { return true; } /** * */ public long getSize() { return -1; } /** * */ public String getMimeType(String viewId) { if (viewId != null && viewId.equals("source")) return "application/xml"; return "application/xhtml+xml"; } /** * */ public View getView(String viewId) { View view = new View(); String mimeType = getMimeType(viewId); view.setMimeType(mimeType); try { org.wyona.yarep.core.Repository repo = getRealm().getRepository(); if (viewId != null && viewId.equals("source")) { view.setInputStream(new java.io.StringBufferInputStream(getScreen())); view.setMimeType("application/xml"); return view; } String[] xsltPath = getXSLTPath(getPath()); if (xsltPath != null) { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPath.length]; for (int i = 0; i < xsltPath.length; i++) { xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPath[i]) .getInputStream())); xsltHandlers[i].getTransformer().setParameter("yanel.path.name", PathUtil.getName(getPath())); xsltHandlers[i].getTransformer().setParameter("yanel.path", getPath()); xsltHandlers[i].getTransformer().setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); xsltHandlers[i].getTransformer().setParameter("yarep.back2realm", PathUtil.backToRealm(getPath())); xsltHandlers[i].getTransformer().setParameter("language", getRequestedLanguage()); } // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getRequestedLanguage(), getRealm().getDefaultLanguage()); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); ResourceResolver resolver = new ResourceResolver(this); xIncludeTransformer.setResolver(resolver); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): xmlReader.setContentHandler(xsltHandlers[0]); for (int i = 0; i < xsltHandlers.length - 1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i + 1])); } xsltHandlers[xsltHandlers.length - 1].setResult(new SAXResult(xIncludeTransformer)); xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(new java.io.StringBufferInputStream(getScreen()))); // write result into view: view.setInputStream(new ByteArrayInputStream(baos.toByteArray())); return view; } else { log.debug("Mime-Type: " + mimeType); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } } catch (Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")", e); } view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } /** * */ public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("source"); vd[1].setMimeType(getMimeType("source")); return vd; } /** * Generate screen */ private String getScreen() { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head><title>Yanel Updater</title>"); //sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "css/resource-creator.css\"/>"); sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-css/progressBar.css\"/>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/prototype.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/progressBar.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/sorttable.js\" type=\"text/javascript\"></script>"); //sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this) + "js/ajaxlookup.js\" type=\"text/javascript\"></script>"); if (request.getParameter("updateconfirmed") != null && request.getParameter("updateconfirmed").equals("updateconfirmed")) { try { Map bestUpdater = getBestUpdater(); String htmlHeadContent = "<meta http-equiv=\"refresh\" content=\"10; URL=" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/" + "?updatelink=" + request.getParameter("updatelink") + "&amp;requestingwebapp=" + request.getParameter("requestingwebapp") + "\"/>"; sb.append(htmlHeadContent); } catch (Exception e) { log.error(e.getMessage(), e); } } sb.append("</head>"); sb.append("<body>"); sb.append("<h1>Yanel Updater</h1>"); StringBuffer body = new StringBuffer(); Enumeration parameters = request.getParameterNames(); if (!parameters.hasMoreElements()) { body = plainRequest(); } else { if (request.getParameter("save-as") != null) { body = plainRequest(); } else if (request.getParameter("usecase") != null && request.getParameter("usecase").equals("update")) { body = getUpdateConfirmScreen(); } else if (request.getParameter("updateconfirmed") != null && request.getParameter("updateconfirmed").equals("updateconfirmed")) { body = getUpdateScreen(); } else { log.info("Fallback ..."); body = plainRequest(); } } sb.append(body); sb.append("</body>"); sb.append("</html>"); return sb.toString(); } /** * */ private StringBuffer plainRequest() { InstallInfo installInfo = null; try { installInfo = getInstallInfo(); } catch (Exception e) { log.error(e.getMessage(), e); return new StringBuffer("<p>Could not get install information. " + e.getMessage() + "</p>"); } UpdateInfo updateInfo = null; try { updateInfo = getUpdateInfo(); } catch (Exception e) { log.error(e.getMessage(), e); return new StringBuffer("<p>Could not get update information. " + e.getMessage() + "</p>"); } if (!installInfo.getInstalltype().equals("bin-snapshot")) { return new StringBuffer("<p>This Yanel was not installed from binary. You can only use the updater if you installed yanel from binary. Please use Subversion or get another source snapshot.</p><p>NOTE: In order to enhance the Yanel Updater resource developers might want to modify <a href=\"file://" + installInfo.getInstallRdfFilename() + "\">" + installInfo.getInstallRdfFilename() + "</a> by replacing the installtype \"source\" with \"bin-snapshot\" and also customize the version and revision!</p>"); } String idVersionRevisionCurrent = installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision(); StringBuffer htmlBodyContent = new StringBuffer(); // show installed version htmlBodyContent.append("<p>"); htmlBodyContent.append("Your installed yanel is: " + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision()); htmlBodyContent.append("</p>"); // TODO: implement getBestYanelWebapp() to get all yanel-webapp version which has an // yanel-updater which fits the targetRevision requirement of the current yanel and is not // already installed. ArrayList updatebleYanelVersions = null; try { updatebleYanelVersions = getSuitableYanelUpdates(installInfo, updateInfo); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get Updates. " + e.getMessage() + "</p>"); } if (updatebleYanelVersions == null) { htmlBodyContent.append("<p>"); htmlBodyContent.append("No updates found."); htmlBodyContent.append("</p>"); } else { HashMap newestYanel = (HashMap) updatebleYanelVersions.get(updatebleYanelVersions.size() - 1); String newestYanelName = (String) newestYanel.get("id") + "-v-" + (String) newestYanel.get("version") + "-r-" + (String) newestYanel.get("revision"); if (newestYanelName.equals(idVersionRevisionCurrent)) { htmlBodyContent.append("<p>"); htmlBodyContent.append("Your yanel is already the newest version."); htmlBodyContent.append("</p>"); } else { htmlBodyContent.append("<p>"); htmlBodyContent.append("Newest yanel is: " + newestYanelName); htmlBodyContent.append("<form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"usecase\" value=\"update\"></input><input type=\"hidden\" name=\"updatelink\" value=\"" + newestYanel.get("updateLink") + "\"/></form>"); htmlBodyContent.append("</p>"); } htmlBodyContent.append("<p>"); htmlBodyContent.append("All versions you can get:"); htmlBodyContent.append("</p>"); htmlBodyContent.append("<ul>"); for (int i = 0; i < updatebleYanelVersions.size(); i++) { HashMap versionDetails = (HashMap) updatebleYanelVersions.get(i); String idVersionRevisionItem = (String) versionDetails.get("id") + "-v-" + (String) versionDetails.get("version") + "-r-" + (String) versionDetails.get("revision"); htmlBodyContent.append("<li>" + versionDetails.get("title") + "<ul>" + "<li>Version: " + idVersionRevisionItem + "</li>" + "<li>Type: " + versionDetails.get("type") + "</li>" + "<li> ChangeLog: " + versionDetails.get("changeLog") + "</li>" + "<li> <form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"usecase\" value=\"update\"/><input type=\"hidden\" name=\"updatelink\" value=\"" + versionDetails.get("updateLink") + "\"/></form></li>" + "</ul></li>"); } htmlBodyContent.append("</ul>"); } // show installed versions try { htmlBodyContent.append("<p>"); htmlBodyContent.append("Installed versions:"); htmlBodyContent.append("</p>"); TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); Map contextAndWebapp = tomcatContextHandler.getContextAndWebapp(); htmlBodyContent.append("<table class=\"sortable\">"); htmlBodyContent.append("<thead>"); htmlBodyContent.append("<tr><th>Context</th><th>Webapp</th></tr>"); htmlBodyContent.append("</thead>"); htmlBodyContent.append("<tbody>"); Iterator iterator = contextAndWebapp.keySet().iterator(); while (iterator.hasNext()) { String context = (String) iterator.next(); String webapp = (String) contextAndWebapp.get(context); htmlBodyContent.append("<tr><td><a href=\"" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + context.replaceAll("/", "") + "\">" + context + "</a></td><td>" + webapp + "</td></tr>"); } htmlBodyContent.append("</tbody>"); htmlBodyContent.append("</table>"); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get installed versions. " + e.getMessage() + "</p>"); //return; } return htmlBodyContent; } /** * */ private StringBuffer getUpdateConfirmScreen() { StringBuffer htmlBodyContent = new StringBuffer(); try { UpdateInfo updateInfo = getUpdateInfo(); InstallInfo installInfo = getInstallInfo(); Map bestUpdater = getBestUpdater(); TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); HashMap versionDetails = updateInfo.getUpdateVersionDetail("updateLink", request.getParameter("updatelink")); String version = (String) versionDetails.get("version"); String revision = (String) versionDetails.get("revision"); String id = (String) versionDetails.get("id"); if (tomcatContextHandler.getWebappOfContext(bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")) != null) { htmlBodyContent.append("<p>Yanel will redirect you to the update-manager which will download and install " + id + "-v-" + version + "-r-" + revision + "</p>"); htmlBodyContent.append("<p>Do you want to continue?</p>"); htmlBodyContent.append("<p>"); htmlBodyContent.append("<form method=\"post\" action=\"" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"YES\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updateconfirmed\" value=\"updateconfirmed\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updatelink\" value=\"" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"requestingwebapp\" value=\"" + installInfo.getWebaName() + "\"/>"); //TODO here it should ask for a password which shoudl be set in the new updater htmlBodyContent.append("</form>"); htmlBodyContent.append("<form method=\"post\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"Cancel\"></input>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("</p>"); } else { htmlBodyContent.append("<p>Yanel will download the update-manager (" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + ") which will download and install " + id + "-v-" + version + "-r-" + revision + "</p>"); htmlBodyContent.append("<p>Do you want to continue?</p>"); htmlBodyContent.append("<p>"); htmlBodyContent.append("<form method=\"post\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"YES\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updateconfirmed\" value=\"updateconfirmed\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updatelink\" value=\"" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"requestingwebapp\" value=\"" + installInfo.getWebaName() + "\"/>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("<form method=\"post\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"Cancel\"></input>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("</p>"); } } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>An error occoured. Exception: " + e.getMessage() + "</p>"); } return htmlBodyContent; } /** * */ private StringBuffer getUpdateScreen() { StringBuffer htmlBodyContent = new StringBuffer(); try { String destDir = request.getSession().getServletContext().getRealPath(".") + File.separator + ".."; Map bestUpdater = getBestUpdater(); WarFetcher warFetcher = new WarFetcher(request, (String) bestUpdater.get("updateLink"), destDir); warFetcher.fetch(); //TODO here it should set a password for the updater TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); tomcatContextHandler.setContext(bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision"), bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")); htmlBodyContent.append("<p>"); htmlBodyContent.append("Update done.<br/>"); htmlBodyContent.append("You will be redirected to the updater which will automaticaly download and install the requested yanel."); htmlBodyContent.append("</p>"); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Update failed. Exception: " + e.getMessage() + "</p>"); } return htmlBodyContent; } private InstallInfo getInstallInfo() throws Exception { return new InstallInfo(request); } private UpdateInfo getUpdateInfo() throws Exception { return new UpdateInfo(getInstallInfo().getUpdateURL(), getInstallInfo()); } /** * Get Updater */ private HashMap getBestUpdater() throws Exception { InstallInfo installInfo = getInstallInfo(); UpdateInfo updateInfo = getUpdateInfo(); HashMap updateVersionDetails = updateInfo.getUpdateVersionDetail("updateLink", request.getParameter("updatelink")); VersionComparator versionComparator = new VersionComparator(); String updateId = (String) updateVersionDetails.get("id"); String updateVersion = (String) updateVersionDetails.get("version"); String updateRevision = (String) updateVersionDetails.get("revision"); ArrayList bestUpdater = updateInfo.getUpdateVersionsOf("type", "updater", installInfo.getRevision()); for (int i = 0; i < bestUpdater.size(); i++) { HashMap versionDetail = (HashMap) bestUpdater.get(i); log.error("DEBUG: Updater details: " + versionDetail); if (versionComparator.compare((String) versionDetail.get("targetApllicationMinRevision"), updateRevision) > 0 ) { bestUpdater.remove(i); } if (versionComparator.compare((String) versionDetail.get("targetApllicationMaxRevision"), updateRevision) < 0 ) { bestUpdater.remove(i); } } Collections.sort(bestUpdater, new UpdateInfoVersionComparator()); if (bestUpdater.size() < 1) { throw new Exception("No updater found for updating your current version (" + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision() + ") to your requested version (" + updateId + "-v-" + updateVersion + "-r-" + updateRevision + ")"); } return (HashMap) bestUpdater.get(bestUpdater.size() - 1); } /** * @return ArrayList with all updates which are matching the revision requirement and are not installed yet. or null if none. * @throws Exception */ private ArrayList getSuitableYanelUpdates(InstallInfo installInfo, UpdateInfo updateInfo) throws Exception { TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); ArrayList updates = updateInfo.getYanelUpdatesForYanelRevision(installInfo.getRevision()); if (updates == null) return null; for (int i = 0; i < updates.size(); i++) { HashMap versionDetail = (HashMap) updates.get(i); log.error("DEBUG: Update: " + versionDetail.get("id") + "-v-" + versionDetail.get("version") + "-r-" + versionDetail.get("revision")); for (int j = 0; j < tomcatContextHandler.getWebappNames().length; j++) { if (tomcatContextHandler.getWebappNames()[j].equals(versionDetail.get("id") + "-v-" + versionDetail.get("version") + "-r-" + versionDetail.get("revision"))) { updates.remove(i); } } } if (updates.size() < 1) return null; return updates; } /** * Get XSLT path */ private String[] getXSLTPath(String path) throws Exception { String[] xsltPath = getResourceConfigProperties("xslt"); if (xsltPath != null) return xsltPath; log.info("No XSLT Path within: " + path); return null; } }
src/realms/welcome-admin/yanel/resources/update-webapp/src/java/org/wyona/yanel/impl/resources/updatefinder/UpdateFinder.java
/* * Copyright 2007 Wyona */ package org.wyona.yanel.impl.resources.updatefinder; import org.apache.log4j.Category; import org.apache.xml.resolver.tools.CatalogResolver; import org.apache.xml.serializer.Serializer; import org.wyona.yanel.core.Path; import org.wyona.yanel.core.Resource; import org.wyona.yanel.core.ResourceConfiguration; import org.wyona.yanel.core.api.attributes.ViewableV2; import org.wyona.yanel.core.attributes.viewable.View; import org.wyona.yanel.core.attributes.viewable.ViewDescriptor; import org.wyona.yanel.core.serialization.SerializerFactory; import org.wyona.yanel.core.source.ResourceResolver; import org.wyona.yanel.core.transformation.I18nTransformer; import org.wyona.yanel.core.transformation.I18nTransformer2; import org.wyona.yanel.core.transformation.XIncludeTransformer; import org.wyona.yanel.core.util.PathUtil; import org.wyona.yanel.impl.resources.updatefinder.utils.*; import java.io.ByteArrayOutputStream; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URL; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.Iterator; import java.util.Collections; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.dom.DOMSource; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.sax.SAXTransformerFactory; import javax.xml.transform.sax.TransformerHandler; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.servlet.http.HttpServletRequest; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; import org.xml.sax.helpers.XMLReaderFactory; import com.hp.hpl.jena.rdf.model.*; /** * */ public class UpdateFinder extends Resource implements ViewableV2 { private static Category log = Category.getInstance(UpdateFinder.class); private String defaultLanguage; private String language = null; /** * */ public UpdateFinder() { } /** * */ public boolean exists() { return true; } /** * */ public long getSize() { return -1; } /** * */ public String getMimeType(String viewId) { if (viewId != null && viewId.equals("source")) return "application/xml"; return "application/xhtml+xml"; } /** * */ public View getView(String viewId) { View view = new View(); String mimeType = getMimeType(viewId); view.setMimeType(mimeType); try { org.wyona.yarep.core.Repository repo = getRealm().getRepository(); if (viewId != null && viewId.equals("source")) { view.setInputStream(new java.io.StringBufferInputStream(getScreen())); view.setMimeType("application/xml"); return view; } String[] xsltPath = getXSLTPath(getPath()); if (xsltPath != null) { // create reader: XMLReader xmlReader = XMLReaderFactory.createXMLReader(); CatalogResolver catalogResolver = new CatalogResolver(); xmlReader.setEntityResolver(catalogResolver); // create xslt transformer: SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance(); TransformerHandler[] xsltHandlers = new TransformerHandler[xsltPath.length]; for (int i = 0; i < xsltPath.length; i++) { xsltHandlers[i] = tf.newTransformerHandler(new StreamSource(repo.getNode(xsltPath[i]) .getInputStream())); xsltHandlers[i].getTransformer().setParameter("yanel.path.name", PathUtil.getName(getPath())); xsltHandlers[i].getTransformer().setParameter("yanel.path", getPath()); xsltHandlers[i].getTransformer().setParameter("yanel.back2context", PathUtil.backToContext(realm, getPath())); xsltHandlers[i].getTransformer().setParameter("yarep.back2realm", PathUtil.backToRealm(getPath())); xsltHandlers[i].getTransformer().setParameter("language", getRequestedLanguage()); } // create i18n transformer: I18nTransformer2 i18nTransformer = new I18nTransformer2("global", getRequestedLanguage(), getRealm().getDefaultLanguage()); i18nTransformer.setEntityResolver(catalogResolver); // create xinclude transformer: XIncludeTransformer xIncludeTransformer = new XIncludeTransformer(); ResourceResolver resolver = new ResourceResolver(this); xIncludeTransformer.setResolver(resolver); // create serializer: Serializer serializer = SerializerFactory.getSerializer(SerializerFactory.XHTML_STRICT); ByteArrayOutputStream baos = new ByteArrayOutputStream(); // chain everything together (create a pipeline): xmlReader.setContentHandler(xsltHandlers[0]); for (int i = 0; i < xsltHandlers.length - 1; i++) { xsltHandlers[i].setResult(new SAXResult(xsltHandlers[i + 1])); } xsltHandlers[xsltHandlers.length - 1].setResult(new SAXResult(xIncludeTransformer)); xIncludeTransformer.setResult(new SAXResult(i18nTransformer)); i18nTransformer.setResult(new SAXResult(serializer.asContentHandler())); serializer.setOutputStream(baos); // execute pipeline: xmlReader.parse(new InputSource(new java.io.StringBufferInputStream(getScreen()))); // write result into view: view.setInputStream(new ByteArrayInputStream(baos.toByteArray())); return view; } else { log.debug("Mime-Type: " + mimeType); view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } } catch (Exception e) { log.error(e + " (" + getPath() + ", " + getRealm() + ")", e); } view.setInputStream(new java.io.StringBufferInputStream(getScreen())); return view; } /** * */ public ViewDescriptor[] getViewDescriptors() { ViewDescriptor[] vd = new ViewDescriptor[2]; vd[0] = new ViewDescriptor("default"); vd[0].setMimeType(getMimeType(null)); vd[1] = new ViewDescriptor("source"); vd[1].setMimeType(getMimeType("source")); return vd; } /** * Generate screen */ private String getScreen() { StringBuffer sb = new StringBuffer("<?xml version=\"1.0\"?>"); sb.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">"); sb.append("<head><title>Yanel Updater</title>"); //sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getResourcesHtdocsPath(this) + "css/resource-creator.css\"/>"); sb.append("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-css/progressBar.css\"/>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/prototype.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/progressBar.js\" type=\"text/javascript\"></script>"); sb.append("<script src=\"" + PathUtil.getGlobalHtdocsPath(this) + "yanel-js/sorttable.js\" type=\"text/javascript\"></script>"); //sb.append("<script src=\"" + PathUtil.getResourcesHtdocsPath(this) + "js/ajaxlookup.js\" type=\"text/javascript\"></script>"); if (request.getParameter("updateconfirmed") != null && request.getParameter("updateconfirmed").equals("updateconfirmed")) { try { Map bestUpdater = getBestUpdater(); String htmlHeadContent = "<meta http-equiv=\"refresh\" content=\"10; URL=" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/" + "?updatelink=" + request.getParameter("updatelink") + "&amp;requestingwebapp=" + request.getParameter("requestingwebapp") + "\"/>"; sb.append(htmlHeadContent); } catch (Exception e) { log.error(e.getMessage(), e); } } sb.append("</head>"); sb.append("<body>"); sb.append("<h1>Yanel Updater</h1>"); StringBuffer body = new StringBuffer(); Enumeration parameters = request.getParameterNames(); if (!parameters.hasMoreElements()) { body = plainRequest(); } else { if (request.getParameter("save-as") != null) { body = plainRequest(); } else if (request.getParameter("update") != null && request.getParameter("update").equals("update")) { body = getUpdateConfirmScreen(); } else if (request.getParameter("updateconfirmed") != null && request.getParameter("updateconfirmed").equals("updateconfirmed")) { body = getUpdateScreen(); } else { log.info("Fallback ..."); body = plainRequest(); } } sb.append(body); sb.append("</body>"); sb.append("</html>"); return sb.toString(); } /** * */ private StringBuffer plainRequest() { InstallInfo installInfo = null; try { installInfo = getInstallInfo(); } catch (Exception e) { log.error(e.getMessage(), e); return new StringBuffer("<p>Could not get install information. " + e.getMessage() + "</p>"); } UpdateInfo updateInfo = null; try { updateInfo = getUpdateInfo(); } catch (Exception e) { log.error(e.getMessage(), e); return new StringBuffer("<p>Could not get update information. " + e.getMessage() + "</p>"); } if (!installInfo.getInstalltype().equals("bin-snapshot")) { return new StringBuffer("<p>This Yanel was not installed from binary. You can only use the updater if you installed yanel from binary. Please use Subversion or get another source snapshot.</p><p>NOTE: In order to enhance the Yanel Updater resource developers might want to modify <a href=\"file://" + installInfo.getInstallRdfFilename() + "\">" + installInfo.getInstallRdfFilename() + "</a> by replacing the installtype \"source\" with \"bin-snapshot\" and also customize the version and revision!</p>"); } String idVersionRevisionCurrent = installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision(); StringBuffer htmlBodyContent = new StringBuffer(); // show installed version htmlBodyContent.append("<p>"); htmlBodyContent.append("Your installed yanel is: " + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision()); htmlBodyContent.append("</p>"); // TODO: implement getBestYanelWebapp() to get all yanel-webapp version which has an // yanel-updater which fits the targetRevision requirement of the current yanel and is not // already installed. ArrayList updatebleYanelVersions = null; try { updatebleYanelVersions = getSuitableYanelUpdates(installInfo, updateInfo); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get Updates. " + e.getMessage() + "</p>"); } if (updatebleYanelVersions == null) { htmlBodyContent.append("<p>"); htmlBodyContent.append("No updates found."); htmlBodyContent.append("</p>"); } else { HashMap newestYanel = (HashMap) updatebleYanelVersions.get(updatebleYanelVersions.size() - 1); String newestYanelName = (String) newestYanel.get("id") + "-v-" + (String) newestYanel.get("version") + "-r-" + (String) newestYanel.get("revision"); if (newestYanelName.equals(idVersionRevisionCurrent)) { htmlBodyContent.append("<p>"); htmlBodyContent.append("Your yanel is already the newest version."); htmlBodyContent.append("</p>"); } else { htmlBodyContent.append("<p>"); htmlBodyContent.append("Newest yanel is: " + newestYanelName); htmlBodyContent.append("<form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"update\" value=\"update\"></input><input type=\"hidden\" name=\"updatelink\" value=\"" + newestYanel.get("updateLink") + "\"/></form>"); htmlBodyContent.append("</p>"); } htmlBodyContent.append("<p>"); htmlBodyContent.append("All versions you can get:"); htmlBodyContent.append("</p>"); htmlBodyContent.append("<ul>"); for (int i = 0; i < updatebleYanelVersions.size(); i++) { HashMap versionDetails = (HashMap) updatebleYanelVersions.get(i); String idVersionRevisionItem = (String) versionDetails.get("id") + "-v-" + (String) versionDetails.get("version") + "-r-" + (String) versionDetails.get("revision"); htmlBodyContent.append("<li>" + versionDetails.get("title") + "<ul>" + "<li>Version: " + idVersionRevisionItem + "</li>" + "<li>Type: " + versionDetails.get("type") + "</li>" + "<li> ChangeLog: " + versionDetails.get("changeLog") + "</li>" + "<li> <form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"update\" value=\"update\"/><input type=\"hidden\" name=\"updatelink\" value=\"" + versionDetails.get("updateLink") + "\"/></form></li>" + "</ul></li>"); } htmlBodyContent.append("</ul>"); } // show installed versions try { htmlBodyContent.append("<p>"); htmlBodyContent.append("Installed versions:"); htmlBodyContent.append("</p>"); TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); Map contextAndWebapp = tomcatContextHandler.getContextAndWebapp(); htmlBodyContent.append("<table class=\"sortable\">"); htmlBodyContent.append("<thead>"); htmlBodyContent.append("<tr><th>Context</th><th>Webapp</th></tr>"); htmlBodyContent.append("</thead>"); htmlBodyContent.append("<tbody>"); Iterator iterator = contextAndWebapp.keySet().iterator(); while (iterator.hasNext()) { String context = (String) iterator.next(); String webapp = (String) contextAndWebapp.get(context); htmlBodyContent.append("<tr><td><a href=\"" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + context.replaceAll("/", "") + "\">" + context + "</a></td><td>" + webapp + "</td></tr>"); } htmlBodyContent.append("</tbody>"); htmlBodyContent.append("</table>"); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Could not get installed versions. " + e.getMessage() + "</p>"); //return; } return htmlBodyContent; } /** * */ private StringBuffer getUpdateConfirmScreen() { StringBuffer htmlBodyContent = new StringBuffer(); try { UpdateInfo updateInfo = getUpdateInfo(); InstallInfo installInfo = getInstallInfo(); Map bestUpdater = getBestUpdater(); TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); HashMap versionDetails = updateInfo.getUpdateVersionDetail("updateLink", request.getParameter("updatelink")); String version = (String) versionDetails.get("version"); String revision = (String) versionDetails.get("revision"); String id = (String) versionDetails.get("id"); if (tomcatContextHandler.getWebappOfContext(bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")) != null) { htmlBodyContent.append("<p>Yanel will redirect you to the update-manager which will download and install " + id + "-v-" + version + "-r-" + revision + "</p>"); htmlBodyContent.append("<p>Do you want to continue?</p>"); htmlBodyContent.append("<p>"); htmlBodyContent.append("<form method=\"post\" action=\"" + "http://" + request.getServerName() + ":" + request.getServerPort() + "/" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + "/\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"YES\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updateconfirmed\" value=\"updateconfirmed\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updatelink\" value=\"" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"requestingwebapp\" value=\"" + installInfo.getWebaName() + "\"/>"); //TODO here it should ask for a password which shoudl be set in the new updater htmlBodyContent.append("</form>"); htmlBodyContent.append("<form method=\"post\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"Cancel\"></input>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("</p>"); } else { htmlBodyContent.append("<p>Yanel will download the update-manager (" + bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision") + ") which will download and install " + id + "-v-" + version + "-r-" + revision + "</p>"); htmlBodyContent.append("<p>Do you want to continue?</p>"); htmlBodyContent.append("<p>"); htmlBodyContent.append("<form method=\"post\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"YES\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updateconfirmed\" value=\"updateconfirmed\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"updatelink\" value=\"" + request.getParameter("updatelink") + "\"/>"); htmlBodyContent.append("<input type=\"hidden\" name=\"requestingwebapp\" value=\"" + installInfo.getWebaName() + "\"/>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("<form method=\"post\">"); htmlBodyContent.append("<input type=\"submit\" name=\"button\" value=\"Cancel\"></input>"); htmlBodyContent.append("</form>"); htmlBodyContent.append("</p>"); } } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>An error occoured. Exception: " + e.getMessage() + "</p>"); } return htmlBodyContent; } /** * */ private StringBuffer getUpdateScreen() { StringBuffer htmlBodyContent = new StringBuffer(); try { String destDir = request.getSession().getServletContext().getRealPath(".") + File.separator + ".."; Map bestUpdater = getBestUpdater(); WarFetcher warFetcher = new WarFetcher(request, (String) bestUpdater.get("updateLink"), destDir); warFetcher.fetch(); //TODO here it should set a password for the updater TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); tomcatContextHandler.setContext(bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision"), bestUpdater.get("id") + "-v-" + bestUpdater.get("version") + "-r-" + bestUpdater.get("revision")); htmlBodyContent.append("<p>"); htmlBodyContent.append("Update done.<br/>"); htmlBodyContent.append("You will be redirected to the updater which will automaticaly download and install the requested yanel."); htmlBodyContent.append("</p>"); } catch (Exception e) { log.error(e.getMessage(), e); htmlBodyContent.append("<p>Update failed. Exception: " + e.getMessage() + "</p>"); } return htmlBodyContent; } private InstallInfo getInstallInfo() throws Exception { return new InstallInfo(request); } private UpdateInfo getUpdateInfo() throws Exception { return new UpdateInfo(getInstallInfo().getUpdateURL(), getInstallInfo()); } private HashMap getBestUpdater() throws Exception { InstallInfo installInfo = getInstallInfo(); UpdateInfo updateInfo = getUpdateInfo(); HashMap updateVersionDetails = updateInfo.getUpdateVersionDetail("updateLink", request.getParameter("updatelink")); VersionComparator versionComparator = new VersionComparator(); String updateId = (String) updateVersionDetails.get("id"); String updateVersion = (String) updateVersionDetails.get("version"); String updateRevision = (String) updateVersionDetails.get("revision"); ArrayList bestUpdater = updateInfo.getUpdateVersionsOf("type", "updater", installInfo.getRevision()); for (int i = 0; i < bestUpdater.size(); i++) { HashMap versionDetail = (HashMap) bestUpdater.get(i); if (versionComparator.compare((String) versionDetail.get("targetApllicationMinRevision"), updateRevision) > 0 ) { bestUpdater.remove(i); } if (versionComparator.compare((String) versionDetail.get("targetApllicationMaxRevision"), updateRevision) < 0 ) { bestUpdater.remove(i); } } Collections.sort(bestUpdater, new UpdateInfoVersionComparator()); if (bestUpdater.size() < 1) { throw new Exception("No updater found for updating your current version(" + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision() + ") to your requested version (" + updateId + "-v-" + updateVersion + "-r-" + updateRevision + ")"); } return (HashMap) bestUpdater.get(bestUpdater.size() - 1); } /** * @return ArrayList with all updates which are matching the revision requirement and are not installed yet. or null if none. * @throws Exception */ private ArrayList getSuitableYanelUpdates(InstallInfo installInfo, UpdateInfo updateInfo) throws Exception { TomcatContextHandler tomcatContextHandler = new TomcatContextHandler(request); ArrayList updates = updateInfo.getYanelUpdatesForYanelRevision(installInfo.getRevision()); if (updates == null) return null; for (int i = 0; i < updates.size(); i++) { HashMap versionDetail = (HashMap) updates.get(i); log.error("DEBUG: Update: " + versionDetail.get("id") + "-v-" + versionDetail.get("version") + "-r-" + versionDetail.get("revision")); for (int j = 0; j < tomcatContextHandler.getWebappNames().length; j++) { if (tomcatContextHandler.getWebappNames()[j].equals(versionDetail.get("id") + "-v-" + versionDetail.get("version") + "-r-" + versionDetail.get("revision"))) { updates.remove(i); } } } if (updates.size() < 1) return null; return updates; } /** * Get XSLT path */ private String[] getXSLTPath(String path) throws Exception { String[] xsltPath = getResourceConfigProperties("xslt"); if (xsltPath != null) return xsltPath; log.info("No XSLT Path within: " + path); return null; } }
missing space added, usecase param introduced, javadoc fixed and logging statement added
src/realms/welcome-admin/yanel/resources/update-webapp/src/java/org/wyona/yanel/impl/resources/updatefinder/UpdateFinder.java
missing space added, usecase param introduced, javadoc fixed and logging statement added
<ide><path>rc/realms/welcome-admin/yanel/resources/update-webapp/src/java/org/wyona/yanel/impl/resources/updatefinder/UpdateFinder.java <ide> } else { <ide> if (request.getParameter("save-as") != null) { <ide> body = plainRequest(); <del> } else if (request.getParameter("update") != null && request.getParameter("update").equals("update")) { <add> } else if (request.getParameter("usecase") != null && request.getParameter("usecase").equals("update")) { <ide> body = getUpdateConfirmScreen(); <ide> } else if (request.getParameter("updateconfirmed") != null && request.getParameter("updateconfirmed").equals("updateconfirmed")) { <ide> body = getUpdateScreen(); <ide> } else { <ide> htmlBodyContent.append("<p>"); <ide> htmlBodyContent.append("Newest yanel is: " + newestYanelName); <del> htmlBodyContent.append("<form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"update\" value=\"update\"></input><input type=\"hidden\" name=\"updatelink\" value=\"" + newestYanel.get("updateLink") + "\"/></form>"); <add> htmlBodyContent.append("<form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"usecase\" value=\"update\"></input><input type=\"hidden\" name=\"updatelink\" value=\"" + newestYanel.get("updateLink") + "\"/></form>"); <ide> htmlBodyContent.append("</p>"); <ide> } <ide> <ide> + "<li> ChangeLog: " <ide> + versionDetails.get("changeLog") <ide> + "</li>" <del> + "<li> <form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"update\" value=\"update\"/><input type=\"hidden\" name=\"updatelink\" value=\"" <add> + "<li> <form method=\"GET\"><input type=\"submit\" name=\"button\" value=\"update\"></input><input type=\"hidden\" name=\"usecase\" value=\"update\"/><input type=\"hidden\" name=\"updatelink\" value=\"" <ide> + versionDetails.get("updateLink") + "\"/></form></li>" + "</ul></li>"); <ide> } <ide> htmlBodyContent.append("</ul>"); <ide> return new UpdateInfo(getInstallInfo().getUpdateURL(), getInstallInfo()); <ide> } <ide> <add> /** <add> * Get Updater <add> */ <ide> private HashMap getBestUpdater() throws Exception { <ide> InstallInfo installInfo = getInstallInfo(); <ide> UpdateInfo updateInfo = getUpdateInfo(); <ide> ArrayList bestUpdater = updateInfo.getUpdateVersionsOf("type", "updater", installInfo.getRevision()); <ide> for (int i = 0; i < bestUpdater.size(); i++) { <ide> HashMap versionDetail = (HashMap) bestUpdater.get(i); <add> log.error("DEBUG: Updater details: " + versionDetail); <ide> if (versionComparator.compare((String) versionDetail.get("targetApllicationMinRevision"), updateRevision) > 0 ) { <ide> bestUpdater.remove(i); <ide> } <ide> } <ide> Collections.sort(bestUpdater, new UpdateInfoVersionComparator()); <ide> if (bestUpdater.size() < 1) { <del> throw new Exception("No updater found for updating your current version(" + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision() + ") to your requested version (" + updateId + "-v-" + updateVersion + "-r-" + updateRevision + ")"); <add> throw new Exception("No updater found for updating your current version (" + installInfo.getId() + "-v-" + installInfo.getVersion() + "-r-" + installInfo.getRevision() + ") to your requested version (" + updateId + "-v-" + updateVersion + "-r-" + updateRevision + ")"); <ide> } <ide> return (HashMap) bestUpdater.get(bestUpdater.size() - 1); <ide> }
JavaScript
apache-2.0
7426403e31a947e5a1ce22cab57ea8dfa05ef8e8
0
contactlab/contactlab-ui-components,contactlab/contactlab-ui-components
Polymer({ is: 'elekti-mer', properties: { label: { type: String, }, name: { type: String, value: 'elekti' }, options: { type: Array, value: [{value: 0, label: 'Option 1'} ,{value: 1, label: 'Option 2'}] }, default: { type: Number }, value: { type: 'String', readonly: true }, open: { type: Boolean, value: false, readonly: true }, noSearch: { type: Boolean, value: false }, noResults: { type: String, value: 'No results found' } }, ready: function(){ var thisComp = this; this.input = this.$$('#' + this.dashify(this.name)); var n = this._searchKey(this.default) if((this.default || this.default === 0) && (typeof n == 'number')){ thisComp.input.value = thisComp.options[n].label; thisComp.value = thisComp.options[n].value; thisComp.activeInput('blur'); }; this.value = this.input.value; }, _searchKey: function(key){ var n; var thisComp = this; for(var i = 0; i < thisComp.options.length; i++){ (thisComp.options[i].value === key) ? n = i : null; } return n; }, _computeWrapperClass: function(open){ var arr = ['elekti-wrapper','']; open ? arr[1] = 'active' : arr[1] = ''; return arr.join(' '); }, dashify: function(str){ return str.replace(/ /g,'-'); }, updateValue: function(){ // this.value = this.input.value; }, highlightedElement: function(){ var search = this.input.value.toLowerCase(); var elems = this.$.list.querySelectorAll('li'); for(var i = 0; i < elems.length; i++){ var str = elems[i].innerHTML; ((search !== '') && (str.toLowerCase() === search) ) ? elems[i].classList.add('selected') : elems[i].classList.remove('selected'); } }, activeInput: function(type){ if(type === 'blur' && this.input.value !== ""){ this.input.classList.add('active'); }else{ this.input.classList.remove('active'); } }, selectElement: function(evt){ this.input.value = evt.target.innerHTML; this.value = evt.target.getAttribute('data-value'); this.activeInput('blur'); this.fire('change'); }, handleListVisibility: function(evt){ this.input.classList.add('active'); var thisComp = this; setTimeout(function(){ this._slideToggle(); this.open = this.$.list.classList.contains('visible'); this.highlightedElement(); }.bind(this),150); this.activeInput(evt.type); }, _slideToggle : function(){ this.$.list.classList.toggle('visible'); if(this.$.list.classList.contains('visible')){ this.$.list.style.height = (44 * this.options.length) + "px"; }else{ this.$.list.style.height = "0px" } }, dropOnly: function(){ if(this.noSearch){ this._slideToggle(); this.highlightedElement(); } }, searchElement: function(e){ var search = this.input.value.toLowerCase(); var elems = this.$.list.querySelectorAll('li'); for(var i = 0; i < elems.length; i++){ var str = elems[i].innerHTML; (str.toLowerCase().search(search) == -1) ? elems[i].classList.add('hide') : elems[i].classList.remove('hide'); } var results = this.$.list.querySelectorAll('li.hide'); ( results.length === elems.length ) ? this.$.noRes.classList.remove('hide') : this.$.noRes.classList.add('hide'); this.highlightedElement(); }, _viewLabel: function(label) { if(label.length > 0){ return true; } else { return false; } } });
elekti/script.js
Polymer({ is: 'elekti-mer', properties: { label: { type: String, }, name: { type: String, value: 'elekti' }, options: { type: Array, value: [{value: 0, label: 'Option 1'} ,{value: 1, label: 'Option 2'}] }, default: { type: Number }, value: { type: 'String', readonly: true }, open: { type: Boolean, value: false, readonly: true }, noSearch: { type: Boolean, value: false }, noResults: { type: String, value: 'No results found' } }, ready: function(){ var thisComp = this; this.input = this.$$('#' + this.dashify(this.name)); var n = this._searchKey(this.default) if((this.default || this.default === 0) && (typeof n == 'number')){ thisComp.input.value = thisComp.options[n].label; thisComp.value = thisComp.options[n].value; thisComp.activeInput('blur'); }; this.value = this.input.value; }, _searchKey: function(key){ var n; var thisComp = this; for(var i = 0; i < thisComp.options.length; i++){ (thisComp.options[i].value === key) ? n = i : null; } return n; }, _computeWrapperClass: function(open){ var arr = ['elekti-wrapper','']; open ? arr[1] = 'active' : arr[1] = ''; return arr.join(' '); }, dashify: function(str){ return str.replace(/ /g,'-'); }, updateValue: function(){ // this.value = this.input.value; }, highlightedElement: function(){ var search = this.input.value.toLowerCase(); var elems = this.$.list.querySelectorAll('li'); for(var i = 0; i < elems.length; i++){ var str = elems[i].innerHTML; ((search !== '') && (str.toLowerCase() === search) ) ? elems[i].classList.add('selected') : elems[i].classList.remove('selected'); } }, activeInput: function(type){ if(type === 'blur' && this.input.value !== ""){ this.input.classList.add('active'); }else{ this.input.classList.remove('active'); } }, selectElement: function(evt){ this.input.value = evt.target.innerHTML; this.value = evt.target.getAttribute('data-value'); this.activeInput('blur'); }, handleListVisibility: function(evt){ this.input.classList.add('active'); var thisComp = this; setTimeout(function(){ this._slideToggle(); this.open = this.$.list.classList.contains('visible'); this.highlightedElement(); }.bind(this),150); this.activeInput(evt.type); }, _slideToggle : function(){ this.$.list.classList.toggle('visible'); if(this.$.list.classList.contains('visible')){ this.$.list.style.height = (44 * this.options.length) + "px"; }else{ this.$.list.style.height = "0px" } }, dropOnly: function(){ if(this.noSearch){ this._slideToggle(); this.highlightedElement(); } }, searchElement: function(e){ var search = this.input.value.toLowerCase(); var elems = this.$.list.querySelectorAll('li'); for(var i = 0; i < elems.length; i++){ var str = elems[i].innerHTML; (str.toLowerCase().search(search) == -1) ? elems[i].classList.add('hide') : elems[i].classList.remove('hide'); } var results = this.$.list.querySelectorAll('li.hide'); ( results.length === elems.length ) ? this.$.noRes.classList.remove('hide') : this.$.noRes.classList.add('hide'); this.highlightedElement(); }, _viewLabel: function(label) { if(label.length > 0){ return true; } else { return false; } } });
<elekti-mer> fires a 'change' event when user click on an option
elekti/script.js
<elekti-mer> fires a 'change' event when user click on an option
<ide><path>lekti/script.js <ide> this.input.value = evt.target.innerHTML; <ide> this.value = evt.target.getAttribute('data-value'); <ide> this.activeInput('blur'); <add> this.fire('change'); <ide> }, <ide> handleListVisibility: function(evt){ <ide> this.input.classList.add('active');
Java
apache-2.0
55ddb04f786cb3291667e0c340f3cead09ba99eb
0
vrozov/incubator-apex-core,mt0803/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,PramodSSImmaneni/apex-core,vrozov/incubator-apex-core,PramodSSImmaneni/apex-core,vrozov/apex-core,tushargosavi/apex-core,klynchDS/incubator-apex-core,brightchen/incubator-apex-core,brightchen/apex-core,sandeshh/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,tushargosavi/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,tweise/incubator-apex-core,mattqzhang/apex-core,devtagare/incubator-apex-core,devtagare/incubator-apex-core,amberarrow/incubator-apex-core,PramodSSImmaneni/apex-core,deepak-narkhede/apex-core,ishark/incubator-apex-core,vrozov/apex-core,sandeshh/apex-core,deepak-narkhede/apex-core,simplifi-it/otterx,apache/incubator-apex-core,tweise/apex-core,sandeshh/apex-core,mt0803/incubator-apex-core,apache/incubator-apex-core,brightchen/apex-core,sandeshh/incubator-apex-core,chinmaykolhatkar/incubator-apex-core,andyperlitch/incubator-apex-core,tushargosavi/apex-core,tushargosavi/apex-core,tweise/incubator-apex-core,sandeshh/incubator-apex-core,apache/incubator-apex-core,MalharJenkins/incubator-apex-core,devtagare/incubator-apex-core,amberarrow/incubator-apex-core,simplifi-it/otterx,tweise/incubator-apex-core,simplifi-it/otterx,andyperlitch/incubator-apex-core,vrozov/apex-core,mattqzhang/apex-core,MalharJenkins/incubator-apex-core,sandeshh/apex-core,mattqzhang/apex-core,brightchen/incubator-apex-core,aniruddhas/incubator-apex-core,klynchDS/incubator-apex-core,ishark/incubator-apex-core,tushargosavi/incubator-apex-core,PramodSSImmaneni/incubator-apex-core,vrozov/incubator-apex-core,brightchen/apex-core,tweise/apex-core,tweise/apex-core,deepak-narkhede/apex-core,PramodSSImmaneni/incubator-apex-core,tushargosavi/incubator-apex-core,aniruddhas/incubator-apex-core,ishark/incubator-apex-core
/** * Copyright (c) 2012-2012 Malhar, Inc. * All rights reserved. */ package com.malhartech.stram; import com.malhartech.dag.DAG; import com.malhartech.dag.DAG.Operator; import com.malhartech.dag.GenericTestModule; import com.malhartech.dag.Module; import com.malhartech.dag.ModuleContext; import com.malhartech.dag.TestGeneratorInputModule; import com.malhartech.stram.PhysicalPlan.PTOperator; import com.malhartech.stram.StramLocalCluster.LocalStramChild; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest.RequestType; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat; import com.malhartech.stream.StramTestSupport; import java.io.File; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * */ public class CheckpointTest { private static final Logger LOG = LoggerFactory.getLogger(CheckpointTest.class); private static File testWorkDir = new File("target", CheckpointTest.class.getName()); @BeforeClass public static void setup() { try { FileContext.getLocalFSFileContext().delete( new Path(testWorkDir.getAbsolutePath()), true); } catch (Exception e) { throw new RuntimeException("could not cleanup test dir", e); } } /** * Test saving of node state at window boundary. * * @throws Exception */ @Test public void testBackup() throws Exception { DAG dag = new DAG(); // node with no inputs will be connected to window generator dag.addOperator("node1", TestGeneratorInputModule.class) .setProperty(TestGeneratorInputModule.KEY_MAX_TUPLES, "1"); dag.getConf().set(DAG.STRAM_CHECKPOINT_DIR, testWorkDir.getPath()); StreamingContainerManager dnm = new StreamingContainerManager(dag); Assert.assertEquals("number required containers", 1, dnm.getNumRequiredContainers()); String containerId = "container1"; StreamingContainerContext cc = dnm.assignContainerForTest(containerId, InetSocketAddress.createUnresolved("localhost", 0)); ManualScheduledExecutorService mses = new ManualScheduledExecutorService(1); WindowGenerator wingen = StramTestSupport.setupWindowGenerator(mses); LocalStramChild container = new LocalStramChild(containerId, null, wingen); container.setup(cc); mses.tick(1); // begin window 1 Assert.assertEquals("number operators", 1, container.getNodes().size()); Module node = container.getNode(cc.nodeList.get(0).id); ModuleContext context = container.getNodeContext(cc.nodeList.get(0).id); Assert.assertNotNull("node deployed " + cc.nodeList.get(0), node); Assert.assertEquals("nodeId", cc.nodeList.get(0).id, context.getId()); Assert.assertEquals("maxTupes", 1, ((TestGeneratorInputModule)node).getMaxTuples()); StramToNodeRequest backupRequest = new StramToNodeRequest(); backupRequest.setNodeId(context.getId()); backupRequest.setRequestType(RequestType.CHECKPOINT); ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse(); rsp.nodeRequests = Collections.singletonList(backupRequest); container.processHeartbeatResponse(rsp); mses.tick(1); // end window 1, begin window 2 // node to move to next window before we verify the checkpoint state // if (node.context.getLastProcessedWindowId() < 2) { // Thread.sleep(500); // } Assert.assertTrue("node >= window 1", 1 <= context.getLastProcessedWindowId()); File cpFile1 = new File(testWorkDir, backupRequest.getNodeId() + "/1"); Assert.assertTrue("checkpoint file not found: " + cpFile1, cpFile1.exists() && cpFile1.isFile()); StreamingNodeHeartbeat hbe = new StreamingNodeHeartbeat(); hbe.setNodeId(context.getId()); hbe.setLastBackupWindowId(1); ContainerHeartbeat hb = new ContainerHeartbeat(); hb.setContainerId(containerId); hb.setDnodeEntries(Collections.singletonList(hbe)); // fake heartbeat to propagate checkpoint dnm.processHeartbeat(hb); container.processHeartbeatResponse(rsp); mses.tick(1); // end window 2 File cpFile2 = new File(testWorkDir, backupRequest.getNodeId() + "/2"); Assert.assertTrue("checkpoint file not found: " + cpFile2, cpFile2.exists() && cpFile2.isFile()); // fake heartbeat to propagate checkpoint hbe.setLastBackupWindowId(2); dnm.processHeartbeat(hb); // purge checkpoints dnm.monitorHeartbeat(); Assert.assertTrue("checkpoint file not purged: " + cpFile1, !cpFile1.exists()); Assert.assertTrue("checkpoint file purged: " + cpFile2, cpFile2.exists() && cpFile2.isFile()); LOG.debug("Shutdown container {}", container.getContainerId()); container.teardown(); } @Test public void testRecoveryCheckpoint() throws Exception { DAG dag = new DAG(); Operator node1 = dag.addOperator("node1", GenericTestModule.class); Operator node2 = dag.addOperator("node2", GenericTestModule.class); dag.addStream("n1n2") .setSource(node1.getOutput(GenericTestModule.OUTPUT1)) .addSink(node2.getInput(GenericTestModule.INPUT1)); StreamingContainerManager dnm = new StreamingContainerManager(dag); PhysicalPlan deployer = dnm.getTopologyDeployer(); List<PTOperator> nodes1 = deployer.getOperators(node1); Assert.assertNotNull(nodes1); Assert.assertEquals(1, nodes1.size()); PTOperator pnode1 = nodes1.get(0); List<PTOperator> nodes2 = deployer.getOperators(node2); Assert.assertNotNull(nodes2); Assert.assertEquals(1, nodes2.size()); PTOperator pnode2 = nodes2.get(0); Map<PTOperator, Long> checkpoints = new HashMap<PTOperator, Long>(); long cp = dnm.updateRecoveryCheckpoints(pnode2, checkpoints); Assert.assertEquals("no checkpoints " + pnode2, 0, cp); cp = dnm.updateRecoveryCheckpoints(pnode1, new HashMap<PTOperator, Long>()); Assert.assertEquals("no checkpoints " + pnode1, 0, cp); // adding checkpoints to upstream only does not move recovery checkpoint pnode1.checkpointWindows.add(3L); pnode1.checkpointWindows.add(5L); cp = dnm.updateRecoveryCheckpoints(pnode1, new HashMap<PTOperator, Long>()); Assert.assertEquals("no checkpoints " + pnode1, 0L, cp); pnode2.checkpointWindows.add(3L); checkpoints = new HashMap<PTOperator, Long>(); cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints); Assert.assertEquals("checkpoint pnode1", 3L, cp); pnode2.checkpointWindows.add(4L); checkpoints = new HashMap<PTOperator, Long>(); cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints); Assert.assertEquals("checkpoint pnode1", 3L, cp); pnode1.checkpointWindows.add(1, 4L); Assert.assertEquals(pnode1.checkpointWindows, Arrays.asList(new Long[]{3L, 4L, 5L})); checkpoints = new HashMap<PTOperator, Long>(); cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints); Assert.assertEquals("checkpoint pnode1", 4L, cp); Assert.assertEquals(pnode1.checkpointWindows, Arrays.asList(new Long[]{4L, 5L})); } }
engine/src/test/java/com/malhartech/stram/CheckpointTest.java
/** * Copyright (c) 2012-2012 Malhar, Inc. * All rights reserved. */ package com.malhartech.stram; import java.io.File; import java.net.InetSocketAddress; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.hadoop.fs.FileContext; import org.apache.hadoop.fs.Path; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import scala.actors.threadpool.Arrays; import com.malhartech.dag.DAG; import com.malhartech.dag.DAG.Operator; import com.malhartech.dag.GenericTestModule; import com.malhartech.dag.Module; import com.malhartech.dag.ModuleContext; import com.malhartech.dag.TestGeneratorInputModule; import com.malhartech.stram.PhysicalPlan.PTOperator; import com.malhartech.stram.StramLocalCluster.LocalStramChild; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeat; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.ContainerHeartbeatResponse; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StramToNodeRequest.RequestType; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext; import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat; import com.malhartech.stream.StramTestSupport; /** * */ public class CheckpointTest { private static final Logger LOG = LoggerFactory.getLogger(CheckpointTest.class); private static File testWorkDir = new File("target", CheckpointTest.class.getName()); @BeforeClass public static void setup() { try { FileContext.getLocalFSFileContext().delete( new Path(testWorkDir.getAbsolutePath()), true); } catch (Exception e) { throw new RuntimeException("could not cleanup test dir", e); } } /** * Test saving of node state at window boundary. * * @throws Exception */ @Test public void testBackup() throws Exception { DAG dag = new DAG(); // node with no inputs will be connected to window generator dag.addOperator("node1", TestGeneratorInputModule.class) .setProperty(TestGeneratorInputModule.KEY_MAX_TUPLES, "1"); dag.getConf().set(DAG.STRAM_CHECKPOINT_DIR, testWorkDir.getPath()); StreamingContainerManager dnm = new StreamingContainerManager(dag); Assert.assertEquals("number required containers", 1, dnm.getNumRequiredContainers()); String containerId = "container1"; StreamingContainerContext cc = dnm.assignContainerForTest(containerId, InetSocketAddress.createUnresolved("localhost", 0)); ManualScheduledExecutorService mses = new ManualScheduledExecutorService(1); WindowGenerator wingen = StramTestSupport.setupWindowGenerator(mses); LocalStramChild container = new LocalStramChild(containerId, null, wingen); container.setup(cc); mses.tick(1); // begin window 1 Assert.assertEquals("number operators", 1, container.getNodes().size()); Module node = container.getNode(cc.nodeList.get(0).id); ModuleContext context = container.getNodeContext(cc.nodeList.get(0).id); Assert.assertNotNull("node deployed " + cc.nodeList.get(0), node); Assert.assertEquals("nodeId", cc.nodeList.get(0).id, context.getId()); Assert.assertEquals("maxTupes", 1, ((TestGeneratorInputModule)node).getMaxTuples()); StramToNodeRequest backupRequest = new StramToNodeRequest(); backupRequest.setNodeId(context.getId()); backupRequest.setRequestType(RequestType.CHECKPOINT); ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse(); rsp.nodeRequests = Collections.singletonList(backupRequest); container.processHeartbeatResponse(rsp); mses.tick(1); // end window 1, begin window 2 // node to move to next window before we verify the checkpoint state // if (node.context.getLastProcessedWindowId() < 2) { // Thread.sleep(500); // } Assert.assertTrue("node >= window 1", 1 <= context.getLastProcessedWindowId()); File cpFile1 = new File(testWorkDir, backupRequest.getNodeId() + "/1"); Assert.assertTrue("checkpoint file not found: " + cpFile1, cpFile1.exists() && cpFile1.isFile()); StreamingNodeHeartbeat hbe = new StreamingNodeHeartbeat(); hbe.setNodeId(context.getId()); hbe.setLastBackupWindowId(1); ContainerHeartbeat hb = new ContainerHeartbeat(); hb.setContainerId(containerId); hb.setDnodeEntries(Collections.singletonList(hbe)); // fake heartbeat to propagate checkpoint dnm.processHeartbeat(hb); container.processHeartbeatResponse(rsp); mses.tick(1); // end window 2 File cpFile2 = new File(testWorkDir, backupRequest.getNodeId() + "/2"); Assert.assertTrue("checkpoint file not found: " + cpFile2, cpFile2.exists() && cpFile2.isFile()); // fake heartbeat to propagate checkpoint hbe.setLastBackupWindowId(2); dnm.processHeartbeat(hb); // purge checkpoints dnm.monitorHeartbeat(); Assert.assertTrue("checkpoint file not purged: " + cpFile1, !cpFile1.exists()); Assert.assertTrue("checkpoint file purged: " + cpFile2, cpFile2.exists() && cpFile2.isFile()); LOG.debug("Shutdown container {}", container.getContainerId()); container.teardown(); } @Test public void testRecoveryCheckpoint() throws Exception { DAG dag = new DAG(); Operator node1 = dag.addOperator("node1", GenericTestModule.class); Operator node2 = dag.addOperator("node2", GenericTestModule.class); dag.addStream("n1n2") .setSource(node1.getOutput(GenericTestModule.OUTPUT1)) .addSink(node2.getInput(GenericTestModule.INPUT1)); StreamingContainerManager dnm = new StreamingContainerManager(dag); PhysicalPlan deployer = dnm.getTopologyDeployer(); List<PTOperator> nodes1 = deployer.getOperators(node1); Assert.assertNotNull(nodes1); Assert.assertEquals(1, nodes1.size()); PTOperator pnode1 = nodes1.get(0); List<PTOperator> nodes2 = deployer.getOperators(node2); Assert.assertNotNull(nodes2); Assert.assertEquals(1, nodes2.size()); PTOperator pnode2 = nodes2.get(0); Map<PTOperator, Long> checkpoints = new HashMap<PTOperator, Long>(); long cp = dnm.updateRecoveryCheckpoints(pnode2, checkpoints); Assert.assertEquals("no checkpoints " + pnode2, 0, cp); cp = dnm.updateRecoveryCheckpoints(pnode1, new HashMap<PTOperator, Long>()); Assert.assertEquals("no checkpoints " + pnode1, 0, cp); // adding checkpoints to upstream only does not move recovery checkpoint pnode1.checkpointWindows.add(3L); pnode1.checkpointWindows.add(5L); cp = dnm.updateRecoveryCheckpoints(pnode1, new HashMap<PTOperator, Long>()); Assert.assertEquals("no checkpoints " + pnode1, 0L, cp); pnode2.checkpointWindows.add(3L); checkpoints = new HashMap<PTOperator, Long>(); cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints); Assert.assertEquals("checkpoint pnode1", 3L, cp); pnode2.checkpointWindows.add(4L); checkpoints = new HashMap<PTOperator, Long>(); cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints); Assert.assertEquals("checkpoint pnode1", 3L, cp); pnode1.checkpointWindows.add(1, 4L); Assert.assertEquals(pnode1.checkpointWindows, Arrays.asList(new Long[]{3L, 4L, 5L})); checkpoints = new HashMap<PTOperator, Long>(); cp = dnm.updateRecoveryCheckpoints(pnode1, checkpoints); Assert.assertEquals("checkpoint pnode1", 4L, cp); Assert.assertEquals(pnode1.checkpointWindows, Arrays.asList(new Long[]{4L, 5L})); } }
removed dependency on scala package.
engine/src/test/java/com/malhartech/stram/CheckpointTest.java
removed dependency on scala package.
<ide><path>ngine/src/test/java/com/malhartech/stram/CheckpointTest.java <ide> * All rights reserved. <ide> */ <ide> package com.malhartech.stram; <del> <del>import java.io.File; <del>import java.net.InetSocketAddress; <del>import java.util.Collections; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <del> <del>import org.apache.hadoop.fs.FileContext; <del>import org.apache.hadoop.fs.Path; <del>import org.junit.Assert; <del>import org.junit.BeforeClass; <del>import org.junit.Test; <del>import org.slf4j.Logger; <del>import org.slf4j.LoggerFactory; <del> <del>import scala.actors.threadpool.Arrays; <ide> <ide> import com.malhartech.dag.DAG; <ide> import com.malhartech.dag.DAG.Operator; <ide> import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingContainerContext; <ide> import com.malhartech.stram.StreamingContainerUmbilicalProtocol.StreamingNodeHeartbeat; <ide> import com.malhartech.stream.StramTestSupport; <add>import java.io.File; <add>import java.net.InetSocketAddress; <add>import java.util.Arrays; <add>import java.util.Collections; <add>import java.util.HashMap; <add>import java.util.List; <add>import java.util.Map; <add>import org.apache.hadoop.fs.FileContext; <add>import org.apache.hadoop.fs.Path; <add>import org.junit.Assert; <add>import org.junit.BeforeClass; <add>import org.junit.Test; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <ide> <ide> /** <ide> *
Java
mit
6dc70317da2e7ed304bc9d6e01dd581e1a1fb760
0
dongritengfei/bestpractice
package com.bestpractice.controller; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.bestpractice.dao.mybatis.common.UUIDUtil; import com.bestpractice.dao.mybatis.model.BaseModel; import com.bestpractice.service.IDataService; public abstract class AbstractRestfullController<T extends BaseModel> implements IController<T> { private static class NumberEditor<T extends Number> extends CustomNumberEditor { public NumberEditor(Class<T> clazz) { super(clazz, true); } public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.trim().equals("")) { // Treat empty String as null value. super.setAsText("0"); } else { // Use default valueOf methods for parsing text. super.setAsText(text); } } } @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(int.class, null, new NumberEditor<Integer>(Integer.class)); binder.registerCustomEditor(long.class, null, new NumberEditor<Long>(Long.class)); binder.registerCustomEditor(short.class, null, new NumberEditor<Short>(Short.class)); binder.registerCustomEditor(byte.class, null, new NumberEditor<Byte>(Byte.class)); binder.registerCustomEditor(double.class, null, new NumberEditor<Double>(Double.class)); binder.registerCustomEditor(float.class, null, new NumberEditor<Float>(Float.class)); } /** * 获取该领域模型的Service * * @return */ public abstract IDataService<T> getService();; @RequestMapping("select") @ResponseBody public T select(String uuid) { T t = getService().select(uuid); return t; } @RequestMapping("selectList") @ResponseBody public Pager<T> selectList(T t, @RequestParam(value="beginPage", defaultValue="1")int beginPage, @RequestParam(value="pageSize", defaultValue="10000")int pageSize) { List<T> resultList = getService().selectList(t, beginPage, pageSize); int totalCount = getService().count(t); return new Pager<T>(resultList, totalCount); } @RequestMapping("count") @ResponseBody public int count(T t) { return getService().count(t); } @RequestMapping("insert") @ResponseBody public boolean insert(T t) { t.setUuid(UUIDUtil.uuid()); return getService().insert(t); } @RequestMapping("insertList") @ResponseBody public int insertList(List<T> list) { if(CollectionUtils.isNotEmpty(list)){ for(T t : list){ t.setUuid(UUIDUtil.uuid()); } } int count = getService().insertList(list); return count; } @RequestMapping("update") @ResponseBody public int update(T t) { int count = getService().update(t); return count; } @RequestMapping("delete") @ResponseBody public boolean delete(String uuid) { return getService().delete(uuid); } @RequestMapping("deleteList") @ResponseBody public int deleteList(List<String> uuidList) { int count = getService().deleteList(uuidList); return count; } }
bestpractice-dao-service/src/main/java/com/bestpractice/controller/AbstractRestfullController.java
package com.bestpractice.controller; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.propertyeditors.CustomNumberEditor; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.bestpractice.dao.mybatis.common.UUIDUtil; import com.bestpractice.dao.mybatis.model.BaseModel; import com.bestpractice.service.IDataService; public abstract class AbstractRestfullController<T extends BaseModel> implements IController<T> { private static class IntEditor extends CustomNumberEditor { public IntEditor() { super(Integer.class, true); } public void setAsText(String text) throws IllegalArgumentException { if (text == null || text.trim().equals("")) { // Treat empty String as null value. setValue(0); } else { // Use default valueOf methods for parsing text. super.setAsText(text); } } } @InitBinder public void initBinder(WebDataBinder binder) { binder.registerCustomEditor(int.class, null, new IntEditor()); } /** * 获取该领域模型的Service * * @return */ public abstract IDataService<T> getService();; @RequestMapping("select") @ResponseBody public T select(String uuid) { T t = getService().select(uuid); return t; } @RequestMapping("selectList") @ResponseBody public Pager<T> selectList(T t, @RequestParam(value="beginPage", defaultValue="1")int beginPage, @RequestParam(value="pageSize", defaultValue="10000")int pageSize) { List<T> resultList = getService().selectList(t, beginPage, pageSize); int totalCount = getService().count(t); return new Pager<T>(resultList, totalCount); } @RequestMapping("count") @ResponseBody public int count(T t) { return getService().count(t); } @RequestMapping("insert") @ResponseBody public boolean insert(T t) { t.setUuid(UUIDUtil.uuid()); return getService().insert(t); } @RequestMapping("insertList") @ResponseBody public int insertList(List<T> list) { if(CollectionUtils.isNotEmpty(list)){ for(T t : list){ t.setUuid(UUIDUtil.uuid()); } } int count = getService().insertList(list); return count; } @RequestMapping("update") @ResponseBody public int update(T t) { int count = getService().update(t); return count; } @RequestMapping("delete") @ResponseBody public boolean delete(String uuid) { return getService().delete(uuid); } @RequestMapping("deleteList") @ResponseBody public int deleteList(List<String> uuidList) { int count = getService().deleteList(uuidList); return count; } }
支持所有的数字类型的默认值绑定
bestpractice-dao-service/src/main/java/com/bestpractice/controller/AbstractRestfullController.java
支持所有的数字类型的默认值绑定
<ide><path>estpractice-dao-service/src/main/java/com/bestpractice/controller/AbstractRestfullController.java <ide> <ide> public abstract class AbstractRestfullController<T extends BaseModel> implements IController<T> { <ide> <del> private static class IntEditor extends CustomNumberEditor { <del> public IntEditor() { <del> super(Integer.class, true); <add> private static class NumberEditor<T extends Number> extends CustomNumberEditor { <add> public NumberEditor(Class<T> clazz) { <add> super(clazz, true); <ide> } <ide> <ide> public void setAsText(String text) throws IllegalArgumentException { <ide> if (text == null || text.trim().equals("")) { <ide> // Treat empty String as null value. <del> setValue(0); <add> super.setAsText("0"); <ide> } else { <ide> // Use default valueOf methods for parsing text. <ide> super.setAsText(text); <ide> <ide> @InitBinder <ide> public void initBinder(WebDataBinder binder) { <del> binder.registerCustomEditor(int.class, null, new IntEditor()); <add> binder.registerCustomEditor(int.class, null, new NumberEditor<Integer>(Integer.class)); <add> binder.registerCustomEditor(long.class, null, new NumberEditor<Long>(Long.class)); <add> binder.registerCustomEditor(short.class, null, new NumberEditor<Short>(Short.class)); <add> binder.registerCustomEditor(byte.class, null, new NumberEditor<Byte>(Byte.class)); <add> binder.registerCustomEditor(double.class, null, new NumberEditor<Double>(Double.class)); <add> binder.registerCustomEditor(float.class, null, new NumberEditor<Float>(Float.class)); <ide> } <ide> <ide> /**
JavaScript
agpl-3.0
68fd6f8253b08669addd8f85579a101d939621be
0
berdaniera/mapapp,berdaniera/mapapp,berdaniera/mapapp
Number.prototype.round = function(places) { return +(Math.round(this + "e+" + places) + "e-" + places); } var coo; var latd; var lond; var coors; var map = L.map('mapbox').setView([36, -78], 5); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', { maxZoom: 12, minZoom: 3, attribution: '', id: 'mapbox.streets' }).addTo(map); coo = map.getCenter(); if(coo.lat < 0){ latd='°S // '; }else{ latd='°N // '; } if(coo.lng < 0){ lond='°W'; }else{ lond='°E'; } coors = Math.abs(coo.lat.round(1)) + latd + Math.abs(coo.lng.round(1)) + lond; map.on('dragend', function(){ coo = map.getCenter(); if(coo.lat < 0){ latd='°S // '; }else{ latd='°N // '; } if(coo.lng < 0){ lond='°W'; }else{ lond='°E'; } coors = Math.abs(coo.lat.round(1)) + latd + Math.abs(coo.lng.round(1)) + lond; //console.log(coors); $("#coordinates").text(coors); }); // set clip $('input[name=cut]').change(function() { $(".crop").hide(); if($('input[name=cut]:checked').val()=="ctry"){ $("#ctry").show(); } else if($('input[name=cut]:checked').val()=="stat") { $("#stat").show(); } }); // set map window sizes function getMapSize(){ if($('input[name=size]:checked').val()=="1824"){ $("#price").text("$40"); $('#orderAmt').val("4000"); $("#price-final").text("$40"); if($('input[name=orient]:checked').val()=="landscape"){ // 1824 landscape $('#mapbox').width(440); $('#mapbox').height(280); } else { // 1824 portrait $('#mapbox').width(320); $('#mapbox').height(400); } } else { $("#price").text("$50"); $('#orderAmt').val("5000"); $("#price-final").text("$50"); if($('input[name=orient]:checked').val()=="landscape"){ //2436 landscape $('#mapbox').width(510); $('#mapbox').height(300); } else { //2436 portrait $('#mapbox').width(330); $('#mapbox').height(480); } } map.invalidateSize(); } // change size $('input[name=size]').change( getMapSize ); // change orientation $('input[name=orient]').change( getMapSize ); // check custom text $('input[name=customtext]').change(function(){ if($('input[name=customtext]').val().length>0){ $("#customtext").text($('input[name=customtext]').val().toUpperCase()); }else{ $("#customtext").text("CITY, STATE, COUNTRY"); } }); // reset $(function(){ $("button#backup").click(function(){ $('#checkout').hide(); $("button#proof").prop("disabled", false); }) }); $(function(){ $("button#backupa").click(function(){ $('#prooferr').hide(); $("button#proof").prop("disabled", false); }) }); // generate proof $(function(){ $("button#proof").click(function(){ console.log(map.getBounds()); $("#loading").show(); $("button#proof").prop("disabled", true); $('html, body').animate({ scrollTop: $("#loading").offset().top },500); var data = {}; data['xmin'] = map.getBounds()._southWest.lng; data['xmax'] = map.getBounds()._northEast.lng; data['ymin'] = map.getBounds()._southWest.lat; data['ymax'] = map.getBounds()._northEast.lat; var textm = $('input[name=customtext]').val().toUpperCase(); // title if (typeof textm == 'undefined') textm = ""; data['textm'] = textm; data['textc'] = coors;// coordinates data['size'] = $('input[name=size]:checked').val(); data['shape'] = $('input[name=orient]:checked').val(); if($('input[name=cut]:checked').val()=="ctry"){ data['clip'] = $('#countries').val(); } else if($('input[name=cut]:checked').val()=="stat") { data['clip'] = $("#states").val(); }else{ data['clip'] = ''; }; $.ajax({ type: 'POST', url:'/_proof', data: JSON.stringify(data), contentType: 'application/json;charset=UTF-8', success: function(response){ $('#orderId').val(response.result); $('#orderData').val(JSON.stringify(response.params)); var imgsrc = "/static/proofs/".concat(response.result,".png"); $("#loading").hide(); $('#checkout').show(); //$('#proofimg').css({'background-image':'url('+imgsrc+')', 'background-size':'cover', 'background-position':'center'}) $('#proofimg img').attr('src',imgsrc);//append('<img src="'+imgsrc+'">') }, error: function(error){ console.log(error); $('#prooferr').show(); $("#loading").hide(); } }); }); }); // check coupon $(function(){ $("button#coupon-check").click(function(){ var data = {}; data['coupon'] = $('input[name=coupon-code]').val(); $.ajax({ type: 'POST', url:'/_coupon-check', data: JSON.stringify(data), contentType: 'application/json;charset=UTF-8', success: function(response){ if(response.res==1){ var discount = 1 - response.disc; $('#coupon-group').attr("class","form-group has-success"); var discountprice = discount * parseInt($('#orderAmt').val()); $('#orderAmt').val(discountprice.toString()); discountprice = discountprice/100 $("#price-final").text("$"+discountprice.toString()); }else{ $('#coupon-group').attr("class","form-group has-warning"); } }, error: function(error){ console.log(error); } }); }); }); // email form $(function(){ $("button#email-list").click(function(){ var data = {}; data['email'] = $('input[name=email-list]').val(); $.ajax({ type: 'POST', url:'/_email-list', data: JSON.stringify(data), contentType: 'application/json;charset=UTF-8', success: function(response){ console.log(response.result); $('input[name=email-list]').val(""); $('#email-group').attr("class","form-group has-success"); }, error: function(error){ console.log(error); } }); }); }); // Collect payment $(function() { $("button#pay").click(function(event){ // Disable the submit button to prevent repeated clicks: $('button#pay').prop('disabled', true); // Request a token from Stripe: Stripe.card.createToken($('#payment-form'), stripeResponseHandler); // Prevent the form from being submitted: return false; }); }); function stripeResponseHandler(status, response) { if (response.error) { // Problem! // Show the errors on the form: $('#payment-form').find('.payment-errors').text(response.error.message); $('button#pay').prop('disabled', false); // Re-enable submission } else { // Token was created! // Get the token ID: var token = response.id; // Insert the token ID into the form so it gets submitted to the server: $('#payment-form').append($('<input type="hidden" name="stripeToken">').val(token)); // Submit the form: $('#payment-form').get(0).submit(); // console.log(token); } };
static/js/ellymap.js
Number.prototype.round = function(places) { return +(Math.round(this + "e+" + places) + "e-" + places); } var coo; var latd; var lond; var coors; var map = L.map('mapbox').setView([36, -78], 5); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpandmbXliNDBjZWd2M2x6bDk3c2ZtOTkifQ._QA7i5Mpkd_m30IGElHziw', { maxZoom: 12, minZoom: 3, attribution: '', id: 'mapbox.streets' }).addTo(map); coo = map.getCenter(); if(coo.lat < 0){ latd='°S // '; }else{ latd='°N // '; } if(coo.lng < 0){ lond='°W'; }else{ lond='°E'; } coors = Math.abs(coo.lat.round(1)) + latd + Math.abs(coo.lng.round(1)) + lond; map.on('dragend', function(){ coo = map.getCenter(); if(coo.lat < 0){ latd='°S // '; }else{ latd='°N // '; } if(coo.lng < 0){ lond='°W'; }else{ lond='°E'; } coors = Math.abs(coo.lat.round(1)) + latd + Math.abs(coo.lng.round(1)) + lond; //console.log(coors); $("#coordinates").text(coors); }); // set clip $('input[name=cut]').change(function() { $(".crop").hide(); if($('input[name=cut]:checked').val()=="ctry"){ $("#ctry").show(); } else if($('input[name=cut]:checked').val()=="stat") { $("#stat").show(); } }); // set map window sizes function getMapSize(){ if($('input[name=size]:checked').val()=="1824"){ $("#price").text("$40"); $('#orderAmt').val("4000"); $("#price-final").text("$40"); if($('input[name=orient]:checked').val()=="landscape"){ // 1824 landscape $('#mapbox').width(440); $('#mapbox').height(280); } else { // 1824 portrait $('#mapbox').width(320); $('#mapbox').height(400); } } else { $("#price").text("$50"); $('#orderAmt').val("5000"); $("#price-final").text("$50"); if($('input[name=orient]:checked').val()=="landscape"){ //2436 landscape $('#mapbox').width(510); $('#mapbox').height(300); } else { //2436 portrait $('#mapbox').width(330); $('#mapbox').height(480); } } map.invalidateSize(); } // change size $('input[name=size]').change( getMapSize() ); // change orientation $('input[name=orient]').change( getMapSize() ); // check custom text $('input[name=customtext]').change(function(){ if($('input[name=customtext]').val().length>0){ $("#customtext").text($('input[name=customtext]').val().toUpperCase()); }else{ $("#customtext").text("CITY, STATE, COUNTRY"); } }); // reset $(function(){ $("button#backup").click(function(){ $('#checkout').hide(); $("button#proof").prop("disabled", false); }) }); $(function(){ $("button#backupa").click(function(){ $('#prooferr').hide(); $("button#proof").prop("disabled", false); }) }); // generate proof $(function(){ $("button#proof").click(function(){ console.log(map.getBounds()); $("#loading").show(); $("button#proof").prop("disabled", true); $('html, body').animate({ scrollTop: $("#loading").offset().top },500); var data = {}; data['xmin'] = map.getBounds()._southWest.lng; data['xmax'] = map.getBounds()._northEast.lng; data['ymin'] = map.getBounds()._southWest.lat; data['ymax'] = map.getBounds()._northEast.lat; var textm = $('input[name=customtext]').val().toUpperCase(); // title if (typeof textm == 'undefined') textm = ""; data['textm'] = textm; data['textc'] = coors;// coordinates data['size'] = $('input[name=size]:checked').val(); data['shape'] = $('input[name=orient]:checked').val(); if($('input[name=cut]:checked').val()=="ctry"){ data['clip'] = $('#countries').val(); } else if($('input[name=cut]:checked').val()=="stat") { data['clip'] = $("#states").val(); }else{ data['clip'] = ''; }; $.ajax({ type: 'POST', url:'/_proof', data: JSON.stringify(data), contentType: 'application/json;charset=UTF-8', success: function(response){ $('#orderId').val(response.result); $('#orderData').val(JSON.stringify(response.params)); var imgsrc = "/static/proofs/".concat(response.result,".png"); $("#loading").hide(); $('#checkout').show(); //$('#proofimg').css({'background-image':'url('+imgsrc+')', 'background-size':'cover', 'background-position':'center'}) $('#proofimg img').attr('src',imgsrc);//append('<img src="'+imgsrc+'">') }, error: function(error){ console.log(error); $('#prooferr').show(); $("#loading").hide(); } }); }); }); // check coupon $(function(){ $("button#coupon-check").click(function(){ var data = {}; data['coupon'] = $('input[name=coupon-code]').val(); $.ajax({ type: 'POST', url:'/_coupon-check', data: JSON.stringify(data), contentType: 'application/json;charset=UTF-8', success: function(response){ if(response.res==1){ var discount = 1 - response.disc; $('#coupon-group').attr("class","form-group has-success"); var discountprice = discount * parseInt($('#orderAmt').val()); $('#orderAmt').val(discountprice.toString()); discountprice = discountprice/100 $("#price-final").text("$"+discountprice.toString()); }else{ $('#coupon-group').attr("class","form-group has-warning"); } }, error: function(error){ console.log(error); } }); }); }); // email form $(function(){ $("button#email-list").click(function(){ var data = {}; data['email'] = $('input[name=email-list]').val(); $.ajax({ type: 'POST', url:'/_email-list', data: JSON.stringify(data), contentType: 'application/json;charset=UTF-8', success: function(response){ console.log(response.result); $('input[name=email-list]').val(""); $('#email-group').attr("class","form-group has-success"); }, error: function(error){ console.log(error); } }); }); }); // Collect payment $(function() { $("button#pay").click(function(event){ // Disable the submit button to prevent repeated clicks: $('button#pay').prop('disabled', true); // Request a token from Stripe: Stripe.card.createToken($('#payment-form'), stripeResponseHandler); // Prevent the form from being submitted: return false; }); }); function stripeResponseHandler(status, response) { if (response.error) { // Problem! // Show the errors on the form: $('#payment-form').find('.payment-errors').text(response.error.message); $('button#pay').prop('disabled', false); // Re-enable submission } else { // Token was created! // Get the token ID: var token = response.id; // Insert the token ID into the form so it gets submitted to the server: $('#payment-form').append($('<input type="hidden" name="stripeToken">').val(token)); // Submit the form: $('#payment-form').get(0).submit(); // console.log(token); } };
fixing resize
static/js/ellymap.js
fixing resize
<ide><path>tatic/js/ellymap.js <ide> } <ide> <ide> // change size <del>$('input[name=size]').change( getMapSize() ); <add>$('input[name=size]').change( getMapSize ); <ide> // change orientation <del>$('input[name=orient]').change( getMapSize() ); <add>$('input[name=orient]').change( getMapSize ); <ide> <ide> // check custom text <ide> $('input[name=customtext]').change(function(){
Java
lgpl-2.1
85d25808b2bbce018fae1603f3d5a5bae5839c01
0
tomazzupan/wildfly,iweiss/wildfly,rhusar/wildfly,golovnin/wildfly,tadamski/wildfly,tadamski/wildfly,rhusar/wildfly,jstourac/wildfly,99sono/wildfly,iweiss/wildfly,pferraro/wildfly,tomazzupan/wildfly,pferraro/wildfly,iweiss/wildfly,99sono/wildfly,golovnin/wildfly,xasx/wildfly,wildfly/wildfly,golovnin/wildfly,wildfly/wildfly,pferraro/wildfly,jstourac/wildfly,99sono/wildfly,tomazzupan/wildfly,pferraro/wildfly,rhusar/wildfly,wildfly/wildfly,xasx/wildfly,xasx/wildfly,jstourac/wildfly,tadamski/wildfly,rhusar/wildfly,wildfly/wildfly,iweiss/wildfly,jstourac/wildfly
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.Handlers; import io.undertow.jsp.JspFileHandler; import io.undertow.jsp.JspServletBuilder; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.resource.CachingResourceManager; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.servlet.ServletExtension; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.AuthMethodConfig; import io.undertow.servlet.api.ClassIntrospecter; import io.undertow.servlet.api.ConfidentialPortManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ErrorPage; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.HttpMethodSecurityInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.InstanceHandle; import io.undertow.servlet.api.ListenerInfo; import io.undertow.servlet.api.LoginConfig; import io.undertow.servlet.api.MimeMapping; import io.undertow.servlet.api.SecurityConstraint; import io.undertow.servlet.api.ServletContainerInitializerInfo; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.api.ServletSecurityInfo; import io.undertow.servlet.api.ServletSessionConfig; import io.undertow.servlet.api.SessionManagerFactory; import io.undertow.servlet.api.ThreadSetupAction; import io.undertow.servlet.api.WebResourceCollection; import io.undertow.servlet.handlers.DefaultServlet; import io.undertow.servlet.handlers.ServletPathMatches; import io.undertow.servlet.util.ImmediateInstanceFactory; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.apache.jasper.servlet.JspServlet; import org.jboss.annotation.javaee.Icon; import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.version.Version; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.WebInjectionContainer; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.CookieConfigMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.ErrorPageMetaData; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.JspPropertyGroupMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LocaleEncodingMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.metadata.web.spec.MimeMappingMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.SessionTrackingModeType; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.VariableMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.modules.Module; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.jboss.security.audit.AuditManager; import org.jboss.security.auth.login.JASPIAuthenticationInfo; import org.jboss.security.authorization.config.AuthorizationModuleEntry; import org.jboss.security.authorization.modules.JACCAuthorizationModule; import org.jboss.security.config.ApplicationPolicy; import org.jboss.security.config.AuthorizationInfo; import org.jboss.security.config.SecurityConfiguration; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.JSPConfig; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.SessionCookieConfig; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.security.AuditNotificationReceiver; import org.wildfly.extension.undertow.security.JAASIdentityManagerImpl; import org.wildfly.extension.undertow.security.JbossAuthorizationManager; import org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor; import org.wildfly.extension.undertow.security.SecurityContextAssociationHandler; import org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction; import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager; import org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler; import org.wildfly.extension.undertow.security.jaspi.JASPIAuthenticationMechanism; import org.wildfly.extension.undertow.security.jaspi.JASPICSecurityContextFactory; import org.wildfly.extension.undertow.session.CodecSessionConfigWrapper; import org.wildfly.extension.undertow.session.SharedSessionManagerConfig; import org.xnio.IoUtils; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.AUTHENTICATE; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.DENY; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.PERMIT; /** * Service that builds up the undertow metadata. * * @author Stuart Douglas */ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> { public static final ServiceName SERVICE_NAME = ServiceName.of("UndertowDeploymentInfoService"); private static final String TEMP_DIR = "jboss.server.temp.dir"; public static final String DEFAULT_SERVLET_NAME = "default"; private DeploymentInfo deploymentInfo; private final JBossWebMetaData mergedMetaData; private final String deploymentName; private final TldsMetaData tldsMetaData; private final List<TldMetaData> sharedTlds; private final Module module; private final ScisMetaData scisMetaData; private final VirtualFile deploymentRoot; private final String jaccContextId; private final String securityDomain; private final List<ServletContextAttribute> attributes; private final String contextPath; private final List<SetupAction> setupActions; private final Set<VirtualFile> overlays; private final List<ExpressionFactoryWrapper> expressionFactoryWrappers; private final List<PredicatedHandler> predicatedHandlers; private final List<HandlerWrapper> initialHandlerChainWrappers; private final List<HandlerWrapper> innerHandlerChainWrappers; private final List<HandlerWrapper> outerHandlerChainWrappers; private final List<ThreadSetupAction> threadSetupActions; private final List<ServletExtension> servletExtensions; private final SharedSessionManagerConfig sharedSessionManagerConfig; private final boolean explodedDeployment; private final InjectedValue<UndertowService> undertowService = new InjectedValue<>(); private final InjectedValue<SessionManagerFactory> sessionManagerFactory = new InjectedValue<>(); private final InjectedValue<SessionIdentifierCodec> sessionIdentifierCodec = new InjectedValue<>(); private final InjectedValue<SecurityDomainContext> securityDomainContextValue = new InjectedValue<SecurityDomainContext>(); private final InjectedValue<ServletContainerService> container = new InjectedValue<>(); private final InjectedValue<PathManager> pathManagerInjector = new InjectedValue<PathManager>(); private final InjectedValue<ComponentRegistry> componentRegistryInjectedValue = new InjectedValue<>(); private final InjectedValue<Host> host = new InjectedValue<>(); private final Map<String, InjectedValue<Executor>> executorsByName = new HashMap<String, InjectedValue<Executor>>(); private UndertowDeploymentInfoService(final JBossWebMetaData mergedMetaData, final String deploymentName, final TldsMetaData tldsMetaData, final List<TldMetaData> sharedTlds, final Module module, final ScisMetaData scisMetaData, final VirtualFile deploymentRoot, final String jaccContextId, final String securityDomain, final List<ServletContextAttribute> attributes, final String contextPath, final List<SetupAction> setupActions, final Set<VirtualFile> overlays, final List<ExpressionFactoryWrapper> expressionFactoryWrappers, List<PredicatedHandler> predicatedHandlers, List<HandlerWrapper> initialHandlerChainWrappers, List<HandlerWrapper> innerHandlerChainWrappers, List<HandlerWrapper> outerHandlerChainWrappers, List<ThreadSetupAction> threadSetupActions, boolean explodedDeployment, List<ServletExtension> servletExtensions, SharedSessionManagerConfig sharedSessionManagerConfig) { this.mergedMetaData = mergedMetaData; this.deploymentName = deploymentName; this.tldsMetaData = tldsMetaData; this.sharedTlds = sharedTlds; this.module = module; this.scisMetaData = scisMetaData; this.deploymentRoot = deploymentRoot; this.jaccContextId = jaccContextId; this.securityDomain = securityDomain; this.attributes = attributes; this.contextPath = contextPath; this.setupActions = setupActions; this.overlays = overlays; this.expressionFactoryWrappers = expressionFactoryWrappers; this.predicatedHandlers = predicatedHandlers; this.initialHandlerChainWrappers = initialHandlerChainWrappers; this.innerHandlerChainWrappers = innerHandlerChainWrappers; this.outerHandlerChainWrappers = outerHandlerChainWrappers; this.threadSetupActions = threadSetupActions; this.explodedDeployment = explodedDeployment; this.servletExtensions = servletExtensions; this.sharedSessionManagerConfig = sharedSessionManagerConfig; } @Override public synchronized void start(final StartContext startContext) throws StartException { ClassLoader oldTccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); DeploymentInfo deploymentInfo = createServletConfig(); handleDistributable(deploymentInfo); handleIdentityManager(deploymentInfo); handleJASPIMechanism(deploymentInfo); handleJACCAuthorization(deploymentInfo); handleAdditionalAuthenticationMechanisms(deploymentInfo); if(mergedMetaData.isUseJBossAuthorization()) { deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager())); } SessionConfigMetaData sessionConfig = mergedMetaData.getSessionConfig(); if(sharedSessionManagerConfig != null && sharedSessionManagerConfig.getSessionConfig() != null) { sessionConfig = sharedSessionManagerConfig.getSessionConfig(); } ServletSessionConfig config = null; //default session config SessionCookieConfig defaultSessionConfig = container.getValue().getSessionCookieConfig(); if (defaultSessionConfig != null) { config = new ServletSessionConfig(); if (defaultSessionConfig.getName() != null) { config.setName(defaultSessionConfig.getName()); } if (defaultSessionConfig.getDomain() != null) { config.setDomain(defaultSessionConfig.getDomain()); } if (defaultSessionConfig.getHttpOnly() != null) { config.setHttpOnly(defaultSessionConfig.getHttpOnly()); } if (defaultSessionConfig.getSecure() != null) { config.setSecure(defaultSessionConfig.getSecure()); } if (defaultSessionConfig.getMaxAge() != null) { config.setMaxAge(defaultSessionConfig.getMaxAge()); } if (defaultSessionConfig.getComment() != null) { config.setComment(defaultSessionConfig.getComment()); } } if (sessionConfig != null) { if (sessionConfig.getSessionTimeoutSet()) { deploymentInfo.setDefaultSessionTimeout(sessionConfig.getSessionTimeout() * 60); } CookieConfigMetaData cookieConfig = sessionConfig.getCookieConfig(); if (config == null) { config = new ServletSessionConfig(); } if (cookieConfig != null) { if (cookieConfig.getName() != null) { config.setName(cookieConfig.getName()); } if (cookieConfig.getDomain() != null) { config.setDomain(cookieConfig.getDomain()); } if (cookieConfig.getComment() != null) { config.setComment(cookieConfig.getComment()); } config.setSecure(cookieConfig.getSecure()); config.setPath(cookieConfig.getPath()); config.setMaxAge(cookieConfig.getMaxAge()); config.setHttpOnly(cookieConfig.getHttpOnly()); } List<SessionTrackingModeType> modes = sessionConfig.getSessionTrackingModes(); if (modes != null && !modes.isEmpty()) { final Set<SessionTrackingMode> trackingModes = new HashSet<>(); for (SessionTrackingModeType mode : modes) { switch (mode) { case COOKIE: trackingModes.add(SessionTrackingMode.COOKIE); break; case SSL: trackingModes.add(SessionTrackingMode.SSL); break; case URL: trackingModes.add(SessionTrackingMode.URL); break; } } config.setSessionTrackingModes(trackingModes); } } if (config != null) { deploymentInfo.setServletSessionConfig(config); } for (final SetupAction action : setupActions) { deploymentInfo.addThreadSetupAction(new UndertowThreadSetupAction(action)); } if (initialHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : initialHandlerChainWrappers) { deploymentInfo.addInitialHandlerChainWrapper(handlerWrapper); } } if (innerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : innerHandlerChainWrappers) { deploymentInfo.addInnerHandlerChainWrapper(handlerWrapper); } } if (outerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : outerHandlerChainWrappers) { deploymentInfo.addOuterHandlerChainWrapper(handlerWrapper); } } if (threadSetupActions != null) { for (ThreadSetupAction threadSetupAction : threadSetupActions) { deploymentInfo.addThreadSetupAction(threadSetupAction); } } deploymentInfo.setServerName("WildFly "+ Version.AS_VERSION); if (undertowService.getValue().statisticsEnabled()){ deploymentInfo.setMetricsCollector(new UndertowMetricsCollector()); } this.deploymentInfo = deploymentInfo; } finally { Thread.currentThread().setContextClassLoader(oldTccl); } } @Override public synchronized void stop(final StopContext stopContext) { IoUtils.safeClose(this.deploymentInfo.getResourceManager()); this.deploymentInfo.setConfidentialPortManager(null); this.deploymentInfo = null; } @Override public synchronized DeploymentInfo getValue() throws IllegalStateException, IllegalArgumentException { return deploymentInfo; } /** * <p>Adds to the deployment the {@link JASPIAuthenticationMechanism}, if necessary. The handler will be added if the security domain * is configured with JASPI authentication.</p> * * @param deploymentInfo */ private void handleJASPIMechanism(final DeploymentInfo deploymentInfo) { ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null && JASPIAuthenticationInfo.class.isInstance(applicationPolicy.getAuthenticationInfo())) { String authMethod = null; LoginConfig loginConfig = deploymentInfo.getLoginConfig(); if (loginConfig != null && loginConfig.getAuthMethods().size() > 0) authMethod = loginConfig.getAuthMethods().get(0).getName(); deploymentInfo.setJaspiAuthenticationMechanism(new JASPIAuthenticationMechanism(this.securityDomain, authMethod)); deploymentInfo.setSecurityContextFactory(new JASPICSecurityContextFactory(this.securityDomain)); } } /** * <p> * Sets the {@link JACCAuthorizationManager} in the specified {@link DeploymentInfo} if the webapp security domain * has defined a JACC authorization module. * </p> * * @param deploymentInfo the {@link DeploymentInfo} instance. */ private void handleJACCAuthorization(final DeploymentInfo deploymentInfo) { // TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null) { AuthorizationInfo authzInfo = applicationPolicy.getAuthorizationInfo(); if (authzInfo != null) { for (AuthorizationModuleEntry entry : authzInfo.getModuleEntries()) { if (JACCAuthorizationModule.class.getName().equals(entry.getPolicyModuleName())) { deploymentInfo.setAuthorizationManager(new JACCAuthorizationManager()); break; } } } } } private void handleAdditionalAuthenticationMechanisms(final DeploymentInfo deploymentInfo){ for (Map.Entry<String,AuthenticationMechanism> am: host.getValue().getAdditionalAuthenticationMechanisms().entrySet()){ deploymentInfo.addFirstAuthenticationMechanism(am.getKey(), am.getValue()); } } private void handleIdentityManager(final DeploymentInfo deploymentInfo) { SecurityDomainContext sdc = securityDomainContextValue.getValue(); deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc)); AuditManager auditManager = sdc.getAuditManager(); if (auditManager != null && !mergedMetaData.isDisableAudit()) { deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager)); } deploymentInfo.setConfidentialPortManager(getConfidentialPortManager()); } private ConfidentialPortManager getConfidentialPortManager() { return new ConfidentialPortManager() { @Override public int getConfidentialPort(HttpServerExchange exchange) { int port = exchange.getConnection().getLocalAddress(InetSocketAddress.class).getPort(); return host.getValue().getServer().getValue().lookupSecurePort(port); } }; } private void handleDistributable(final DeploymentInfo deploymentInfo) { SessionManagerFactory managerFactory = this.sessionManagerFactory.getOptionalValue(); if (managerFactory != null) { deploymentInfo.setSessionManagerFactory(managerFactory); } SessionIdentifierCodec codec = this.sessionIdentifierCodec.getOptionalValue(); if (codec != null) { deploymentInfo.setSessionConfigWrapper(new CodecSessionConfigWrapper(codec)); } } /* This is to address WFLY-1894 but should probably be moved to some other place. */ private String resolveContextPath() { if (deploymentName.equals(host.getValue().getDefaultWebModule())) { return "/"; } else { return contextPath; } } private DeploymentInfo createServletConfig() throws StartException { final ComponentRegistry componentRegistry = componentRegistryInjectedValue.getValue(); try { if (!mergedMetaData.isMetadataComplete()) { mergedMetaData.resolveAnnotations(); } final DeploymentInfo d = new DeploymentInfo(); d.setContextPath(resolveContextPath()); if (mergedMetaData.getDescriptionGroup() != null) { d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName()); } d.setDeploymentName(deploymentName); d.setHostName(host.getValue().getName()); final ServletContainerService servletContainer = container.getValue(); try { //TODO: make the caching limits configurable ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment); resourceManager = new CachingResourceManager(100, 10 * 1024 * 1024, servletContainer.getBufferCache(), resourceManager, explodedDeployment ? 2000 : -1); d.setResourceManager(resourceManager); } catch (IOException e) { throw new StartException(e); } File tempFile = new File(pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath(), deploymentName); tempFile.mkdirs(); d.setTempDir(tempFile); d.setClassLoader(module.getClassLoader()); final String servletVersion = mergedMetaData.getServletVersion(); if (servletVersion != null) { d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + "")); d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + "")); } else { d.setMajorVersion(3); d.setMinorVersion(1); } //in most cases flush just hurts performance for no good reason d.setIgnoreFlush(servletContainer.isIgnoreFlush()); //controlls initizalization of filters on start of application d.setEagerFilterInit(servletContainer.isEagerFilterInit()); d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers()); d.setServletStackTraces(servletContainer.getStackTraces()); if (servletContainer.getSessionPersistenceManager() != null) { d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager()); } //for 2.2 apps we do not require a leading / in path mappings boolean is22OrOlder; if (d.getMajorVersion() == 1) { is22OrOlder = true; } else if (d.getMajorVersion() == 2) { is22OrOlder = d.getMinorVersion() < 3; } else { is22OrOlder = false; } JSPConfig jspConfig = servletContainer.getJspConfig(); final Set<String> seenMappings = new HashSet<>(); HashMap<String, TagLibraryInfo> tldInfo = createTldsInfo(tldsMetaData, sharedTlds); //default JSP servlet final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null; if (jspServlet != null) { //this would be null if jsp support is disabled HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData); JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new WebInjectionContainer(module.getClassLoader(), componentRegistryInjectedValue.getValue()))); if (mergedMetaData.getJspConfig() != null) { d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), propertyGroups.values())); } d.addServlet(jspServlet); final Set<String> jspPropertyGroupMappings = propertyGroups.keySet(); for (final String mapping : jspPropertyGroupMappings) { jspServlet.addMapping(mapping); } seenMappings.addAll(jspPropertyGroupMappings); //setup JSP expression factory wrapper if (!expressionFactoryWrappers.isEmpty()) { d.addListener(new ListenerInfo(JspInitializationListener.class)); d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers); } } d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry)); final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>(); if (mergedMetaData.getExecutorName() != null) { d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).getValue()); } if(servletExtensions != null) { for(ServletExtension extension : servletExtensions) { d.addServletExtension(extension); } } if (mergedMetaData.getServletMappings() != null) { for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) { List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName()); if (list == null) { servletMappings.put(mapping.getServletName(), list = new ArrayList<>()); } list.add(mapping); } } final List<JBossServletMetaData> servlets = new ArrayList<JBossServletMetaData>(); for (JBossServletMetaData servlet : mergedMetaData.getServlets()) { servlets.add(servlet); } if (servlets != null) { for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) { final ServletInfo s; if (servlet.getJspFile() != null) { s = new ServletInfo(servlet.getName(), JspServlet.class); s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile())); } else { if (servlet.getServletClass() == null) { if(DEFAULT_SERVLET_NAME.equals(servlet.getName())) { s = new ServletInfo(servlet.getName(), DefaultServlet.class); } else { throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName()); } } else { Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass); if (creator != null) { InstanceFactory<Servlet> factory = createInstanceFactory(creator); s = new ServletInfo(servlet.getName(), servletClass, factory); } else { s = new ServletInfo(servlet.getName(), servletClass); } } } s.setAsyncSupported(servlet.isAsyncSupported()) .setJspFile(servlet.getJspFile()) .setEnabled(servlet.isEnabled()); if (servlet.getRunAs() != null) { s.setRunAs(servlet.getRunAs().getRoleName()); } if (servlet.getLoadOnStartupSet()) {//todo why not cleanup api and just use int everywhere s.setLoadOnStartup(servlet.getLoadOnStartupInt()); } if (servlet.getExecutorName() != null) { s.setExecutor(executorsByName.get(servlet.getExecutorName()).getValue()); } handleServletMappings(is22OrOlder, seenMappings, servletMappings, s); if (servlet.getInitParam() != null) { for (ParamValueMetaData initParam : servlet.getInitParam()) { if (!s.getInitParams().containsKey(initParam.getParamName())) { s.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } if (servlet.getServletSecurity() != null) { ServletSecurityInfo securityInfo = new ServletSecurityInfo(); s.setServletSecurityInfo(securityInfo); securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())) .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed()); if (servlet.getServletSecurity().getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) { securityInfo.addHttpMethodSecurityInfo( new HttpMethodSecurityInfo() .setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())) .addRolesAllowed(method.getRolesAllowed()) .setMethod(method.getMethod())); } } } if (servlet.getSecurityRoleRefs() != null) { for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) { s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink()); } } if (servlet.getMultipartConfig() != null) { MultipartConfigMetaData mp = servlet.getMultipartConfig(); s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold())); } d.addServlet(s); } } //we explicitly add the default servlet, to allow it to be mapped if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) { ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class); handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet); d.addServlet(defaultServlet); } if (mergedMetaData.getFilters() != null) { for (final FilterMetaData filter : mergedMetaData.getFilters()) { Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass); FilterInfo f; if (creator != null) { InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator); f = new FilterInfo(filter.getName(), filterClass, instanceFactory); } else { f = new FilterInfo(filter.getName(), filterClass); } f.setAsyncSupported(filter.isAsyncSupported()); d.addFilter(f); if (filter.getInitParam() != null) { for (ParamValueMetaData initParam : filter.getInitParam()) { f.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } } if (mergedMetaData.getFilterMappings() != null) { for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) { if (mapping.getUrlPatterns() != null) { for (String url : mapping.getUrlPatterns()) { if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) { url = "/" + url; } if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST); } } } if (mapping.getServletNames() != null) { for (String servletName : mapping.getServletNames()) { if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST); } } } } } if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) { for (final ServletContainerInitializer sci : scisMetaData.getScis()) { final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci); d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci))); } } if (mergedMetaData.getListeners() != null) { for (ListenerMetaData listener : mergedMetaData.getListeners()) { addListener(module.getClassLoader(), componentRegistry, d, listener); } } if (mergedMetaData.getContextParams() != null) { for (ParamValueMetaData param : mergedMetaData.getContextParams()) { d.addInitParameter(param.getParamName(), param.getParamValue()); } } if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) { List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles(); for (String file : welcomeFiles) { if (file.startsWith("/")) { d.addWelcomePages(file.substring(1)); } else { d.addWelcomePages(file); } } } else { d.addWelcomePages("index.html", "index.htm", "index.jsp"); } if (mergedMetaData.getErrorPages() != null) { for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) { final ErrorPage errorPage; if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType())); } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode())); } else { errorPage = new ErrorPage(page.getLocation()); } d.addErrorPages(errorPage); } } if (mergedMetaData.getMimeMappings() != null) { for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) { d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType())); } } d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null); Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames(); if (mergedMetaData.getSecurityConstraints() != null) { for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) { SecurityConstraint securityConstraint = new SecurityConstraint() .setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee())); List<String> roleNames = constraint.getRoleNames(); if (constraint.getAuthConstraint() == null) { // no auth constraint means we permit the empty roles securityConstraint.setEmptyRoleSemantic(PERMIT); } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) { // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable // authentication only mode. // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow. securityConstraint.setEmptyRoleSemantic(AUTHENTICATE); } else { securityConstraint.addRolesAllowed(roleNames); } if (constraint.getResourceCollections() != null) { for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) { securityConstraint.addWebResourceCollection(new WebResourceCollection() .addHttpMethods(resourceCollection.getHttpMethods()) .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()) .addUrlPatterns(resourceCollection.getUrlPatterns())); } } d.addSecurityConstraint(securityConstraint); } } final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig(); if (loginConfig != null) { List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod()); if (loginConfig.getFormLoginConfig() != null) { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage())); } else { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName())); } for (AuthMethodConfig method : authMethod) { d.getLoginConfig().addLastAuthMethod(method); } } d.addSecurityRoles(mergedMetaData.getSecurityRoleNames()); Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap(); d.addThreadSetupAction(new SecurityContextThreadSetupAction(securityDomain, securityDomainContextValue.getValue(), principalVersusRolesMap)); d.addInnerHandlerChainWrapper(SecurityContextAssociationHandler.wrapper(mergedMetaData.getRunAsIdentity())); d.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); d.addLifecycleInterceptor(new RunAsLifecycleInterceptor(mergedMetaData.getRunAsIdentity())); if (principalVersusRolesMap != null) { for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) { d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue()); } } // Setup an deployer configured ServletContext attributes for (ServletContextAttribute attribute : attributes) { d.addServletContextAttribute(attribute.getName(), attribute.getValue()); } if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) { for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) { d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding()); } } if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) { d.addInitialHandlerChainWrapper(new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { if (predicatedHandlers.size() == 1) { PredicatedHandler ph = predicatedHandlers.get(0); return Handlers.predicate(ph.getPredicate(), ph.getHandler().wrap(handler), handler); } else { return Handlers.predicates(predicatedHandlers, handler); } } }); } if (mergedMetaData.getDefaultEncoding()!=null){ d.setDefaultEncoding(mergedMetaData.getDefaultEncoding()); }else if (servletContainer.getDefaultEncoding()!=null){ d.setDefaultEncoding(servletContainer.getDefaultEncoding()); } return d; } catch (ClassNotFoundException e) { throw new StartException(e); } } private void handleServletMappings(boolean is22OrOlder, Set<String> seenMappings, Map<String, List<ServletMappingMetaData>> servletMappings, ServletInfo s) { List<ServletMappingMetaData> mappings = servletMappings.get(s.getName()); if (mappings != null) { for (ServletMappingMetaData mapping : mappings) { for (String pattern : mapping.getUrlPatterns()) { if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) { pattern = "/" + pattern; } if (!seenMappings.contains(pattern)) { s.addMapping(pattern); seenMappings.add(pattern); } } } } } /** * Convert the authentication method name from the format specified in the web.xml to the format used by * {@link javax.servlet.http.HttpServletRequest}. * <p/> * If the auth method is not recognised then it is returned as-is. * * @return The converted auth method. * @throws NullPointerException if no configuredMethod is supplied. */ private static List<AuthMethodConfig> authMethod(String configuredMethod) { if (configuredMethod == null) { return Collections.singletonList(new AuthMethodConfig(HttpServletRequest.BASIC_AUTH)); } return AuthMethodParser.parse(configuredMethod, Collections.singletonMap("CLIENT-CERT", HttpServletRequest.CLIENT_CERT_AUTH)); } private static io.undertow.servlet.api.TransportGuaranteeType transportGuaranteeType(final TransportGuaranteeType type) { if (type == null) { return io.undertow.servlet.api.TransportGuaranteeType.NONE; } switch (type) { case CONFIDENTIAL: return io.undertow.servlet.api.TransportGuaranteeType.CONFIDENTIAL; case INTEGRAL: return io.undertow.servlet.api.TransportGuaranteeType.INTEGRAL; case NONE: return io.undertow.servlet.api.TransportGuaranteeType.NONE; } throw new RuntimeException("UNREACHABLE"); } private static HashMap<String, JspPropertyGroup> createJspConfig(JBossWebMetaData metaData) { final HashMap<String, JspPropertyGroup> result = new HashMap<>(); // JSP Config JspConfigMetaData config = metaData.getJspConfig(); if (config != null) { // JSP Property groups List<JspPropertyGroupMetaData> groups = config.getPropertyGroups(); if (groups != null) { for (JspPropertyGroupMetaData group : groups) { org.apache.jasper.deploy.JspPropertyGroup jspPropertyGroup = new org.apache.jasper.deploy.JspPropertyGroup(); for (String pattern : group.getUrlPatterns()) { jspPropertyGroup.addUrlPattern(pattern); } jspPropertyGroup.setElIgnored(group.getElIgnored()); jspPropertyGroup.setPageEncoding(group.getPageEncoding()); jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid()); jspPropertyGroup.setIsXml(group.getIsXml()); if (group.getIncludePreludes() != null) { for (String includePrelude : group.getIncludePreludes()) { jspPropertyGroup.addIncludePrelude(includePrelude); } } if (group.getIncludeCodas() != null) { for (String includeCoda : group.getIncludeCodas()) { jspPropertyGroup.addIncludeCoda(includeCoda); } } jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(group.getDeferredSyntaxAllowedAsLiteral()); jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces()); jspPropertyGroup.setDefaultContentType(group.getDefaultContentType()); jspPropertyGroup.setBuffer(group.getBuffer()); jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace()); for (String pattern : jspPropertyGroup.getUrlPatterns()) { // Split off the groups to individual mappings result.put(pattern, jspPropertyGroup); } } } } //it looks like jasper needs these in order of least specified to most specific final LinkedHashMap<String, JspPropertyGroup> ret = new LinkedHashMap<>(); final ArrayList<String> paths = new ArrayList<>(result.keySet()); Collections.sort(paths, new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return o1.length() - o2.length(); } }); for (String path : paths) { ret.put(path, result.get(path)); } return ret; } private static HashMap<String, TagLibraryInfo> createTldsInfo(final TldsMetaData tldsMetaData, List<TldMetaData> sharedTlds) throws ClassNotFoundException { final HashMap<String, TagLibraryInfo> ret = new HashMap<>(); if (tldsMetaData != null) { if (tldsMetaData.getTlds() != null) { for (Map.Entry<String, TldMetaData> tld : tldsMetaData.getTlds().entrySet()) { createTldInfo(tld.getKey(), tld.getValue(), ret); } } if (sharedTlds != null) { for (TldMetaData metaData : sharedTlds) { createTldInfo(null, metaData, ret); } } } return ret; } private static TagLibraryInfo createTldInfo(final String location, final TldMetaData tldMetaData, final HashMap<String, TagLibraryInfo> ret) throws ClassNotFoundException { String relativeLocation = location; String jarPath = null; if (relativeLocation != null && relativeLocation.startsWith("/WEB-INF/lib/")) { int pos = relativeLocation.indexOf('/', "/WEB-INF/lib/".length()); if (pos > 0) { jarPath = relativeLocation.substring(pos); if (jarPath.startsWith("/")) { jarPath = jarPath.substring(1); } relativeLocation = relativeLocation.substring(0, pos); } } TagLibraryInfo tagLibraryInfo = new TagLibraryInfo(); tagLibraryInfo.setTlibversion(tldMetaData.getTlibVersion()); if (tldMetaData.getJspVersion() == null) { tagLibraryInfo.setJspversion(tldMetaData.getVersion()); } else { tagLibraryInfo.setJspversion(tldMetaData.getJspVersion()); } tagLibraryInfo.setShortname(tldMetaData.getShortName()); tagLibraryInfo.setUri(tldMetaData.getUri()); if (tldMetaData.getDescriptionGroup() != null) { tagLibraryInfo.setInfo(tldMetaData.getDescriptionGroup().getDescription()); } // Validator if (tldMetaData.getValidator() != null) { TagLibraryValidatorInfo tagLibraryValidatorInfo = new TagLibraryValidatorInfo(); tagLibraryValidatorInfo.setValidatorClass(tldMetaData.getValidator().getValidatorClass()); if (tldMetaData.getValidator().getInitParams() != null) { for (ParamValueMetaData paramValueMetaData : tldMetaData.getValidator().getInitParams()) { tagLibraryValidatorInfo.addInitParam(paramValueMetaData.getParamName(), paramValueMetaData.getParamValue()); } } tagLibraryInfo.setValidator(tagLibraryValidatorInfo); } // Tag if (tldMetaData.getTags() != null) { for (TagMetaData tagMetaData : tldMetaData.getTags()) { TagInfo tagInfo = new TagInfo(); tagInfo.setTagName(tagMetaData.getName()); tagInfo.setTagClassName(tagMetaData.getTagClass()); tagInfo.setTagExtraInfo(tagMetaData.getTeiClass()); if (tagMetaData.getBodyContent() != null) { tagInfo.setBodyContent(tagMetaData.getBodyContent().toString()); } tagInfo.setDynamicAttributes(tagMetaData.getDynamicAttributes()); // Description group if (tagMetaData.getDescriptionGroup() != null) { DescriptionGroupMetaData descriptionGroup = tagMetaData.getDescriptionGroup(); if (descriptionGroup.getIcons() != null && descriptionGroup.getIcons().value() != null && (descriptionGroup.getIcons().value().length > 0)) { Icon icon = descriptionGroup.getIcons().value()[0]; tagInfo.setLargeIcon(icon.largeIcon()); tagInfo.setSmallIcon(icon.smallIcon()); } tagInfo.setInfoString(descriptionGroup.getDescription()); tagInfo.setDisplayName(descriptionGroup.getDisplayName()); } // Variable if (tagMetaData.getVariables() != null) { for (VariableMetaData variableMetaData : tagMetaData.getVariables()) { TagVariableInfo tagVariableInfo = new TagVariableInfo(); tagVariableInfo.setNameGiven(variableMetaData.getNameGiven()); tagVariableInfo.setNameFromAttribute(variableMetaData.getNameFromAttribute()); tagVariableInfo.setClassName(variableMetaData.getVariableClass()); tagVariableInfo.setDeclare(variableMetaData.getDeclare()); if (variableMetaData.getScope() != null) { tagVariableInfo.setScope(variableMetaData.getScope().toString()); } tagInfo.addTagVariableInfo(tagVariableInfo); } } // Attribute if (tagMetaData.getAttributes() != null) { for (AttributeMetaData attributeMetaData : tagMetaData.getAttributes()) { TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(); tagAttributeInfo.setName(attributeMetaData.getName()); tagAttributeInfo.setType(attributeMetaData.getType()); tagAttributeInfo.setReqTime(attributeMetaData.getRtexprvalue()); tagAttributeInfo.setRequired(attributeMetaData.getRequired()); tagAttributeInfo.setFragment(attributeMetaData.getFragment()); if (attributeMetaData.getDeferredValue() != null) { tagAttributeInfo.setDeferredValue("true"); tagAttributeInfo.setExpectedTypeName(attributeMetaData.getDeferredValue().getType()); } else { tagAttributeInfo.setDeferredValue("false"); } if (attributeMetaData.getDeferredMethod() != null) { tagAttributeInfo.setDeferredMethod("true"); tagAttributeInfo.setMethodSignature(attributeMetaData.getDeferredMethod().getMethodSignature()); } else { tagAttributeInfo.setDeferredMethod("false"); } tagInfo.addTagAttributeInfo(tagAttributeInfo); } } tagLibraryInfo.addTagInfo(tagInfo); } } // Tag files if (tldMetaData.getTagFiles() != null) { for (TagFileMetaData tagFileMetaData : tldMetaData.getTagFiles()) { TagFileInfo tagFileInfo = new TagFileInfo(); tagFileInfo.setName(tagFileMetaData.getName()); tagFileInfo.setPath(tagFileMetaData.getPath()); tagLibraryInfo.addTagFileInfo(tagFileInfo); } } // Function if (tldMetaData.getFunctions() != null) { for (FunctionMetaData functionMetaData : tldMetaData.getFunctions()) { FunctionInfo functionInfo = new FunctionInfo(); functionInfo.setName(functionMetaData.getName()); functionInfo.setFunctionClass(functionMetaData.getFunctionClass()); functionInfo.setFunctionSignature(functionMetaData.getFunctionSignature()); tagLibraryInfo.addFunctionInfo(functionInfo); } } if (jarPath == null && relativeLocation == null) { if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } } else if (jarPath == null) { tagLibraryInfo.setLocation(""); tagLibraryInfo.setPath(relativeLocation); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } ret.put(relativeLocation, tagLibraryInfo); } else { tagLibraryInfo.setLocation(relativeLocation); tagLibraryInfo.setPath(jarPath); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } if (jarPath.equals("META-INF/taglib.tld")) { ret.put(relativeLocation, tagLibraryInfo); } } return tagLibraryInfo; } private static void addListener(final ClassLoader classLoader, final ComponentRegistry components, final DeploymentInfo d, final ListenerMetaData listener) throws ClassNotFoundException { ListenerInfo l; final Class<? extends EventListener> listenerClass = (Class<? extends EventListener>) classLoader.loadClass(listener.getListenerClass()); ManagedReferenceFactory creator = components.createInstanceFactory(listenerClass); if (creator != null) { InstanceFactory<EventListener> factory = createInstanceFactory(creator); l = new ListenerInfo(listenerClass, factory); } else { l = new ListenerInfo(listenerClass); } d.addListener(l); } private static <T> InstanceFactory<T> createInstanceFactory(final ManagedReferenceFactory creator) { return new InstanceFactory<T>() { @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference instance = creator.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) instance.getInstance(); } @Override public void release() { instance.release(); } }; } }; } public void addInjectedExecutor(final String name, final InjectedValue<Executor> injected) { executorsByName.put(name, injected); } public InjectedValue<ServletContainerService> getContainer() { return container; } public InjectedValue<SecurityDomainContext> getSecurityDomainContextValue() { return securityDomainContextValue; } public Injector<SessionManagerFactory> getSessionManagerFactoryInjector() { return this.sessionManagerFactory; } public Injector<SessionIdentifierCodec> getSessionIdentifierCodecInjector() { return this.sessionIdentifierCodec; } public InjectedValue<UndertowService> getUndertowService() { return undertowService; } public InjectedValue<PathManager> getPathManagerInjector() { return pathManagerInjector; } public InjectedValue<ComponentRegistry> getComponentRegistryInjectedValue() { return componentRegistryInjectedValue; } public InjectedValue<Host> getHost() { return host; } private static class ComponentClassIntrospector implements ClassIntrospecter { private final ComponentRegistry componentRegistry; public ComponentClassIntrospector(final ComponentRegistry componentRegistry) { this.componentRegistry = componentRegistry; } @Override public <T> InstanceFactory<T> createInstanceFactory(final Class<T> clazz) throws NoSuchMethodException { final ManagedReferenceFactory component = componentRegistry.createInstanceFactory(clazz); return new ManagedReferenceInstanceFactory<>(component); } } private static class ManagedReferenceInstanceFactory<T> implements InstanceFactory<T> { private final ManagedReferenceFactory component; public ManagedReferenceInstanceFactory(final ManagedReferenceFactory component) { this.component = component; } @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference reference = component.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) reference.getInstance(); } @Override public void release() { reference.release(); } }; } } public static Builder builder() { return new Builder(); } public static class Builder { private JBossWebMetaData mergedMetaData; private String deploymentName; private TldsMetaData tldsMetaData; private List<TldMetaData> sharedTlds; private Module module; private ScisMetaData scisMetaData; private VirtualFile deploymentRoot; private String jaccContextId; private List<ServletContextAttribute> attributes; private String contextPath; private String securityDomain; private List<SetupAction> setupActions; private Set<VirtualFile> overlays; private List<ExpressionFactoryWrapper> expressionFactoryWrappers; private List<PredicatedHandler> predicatedHandlers; private List<HandlerWrapper> initialHandlerChainWrappers; private List<HandlerWrapper> innerHandlerChainWrappers; private List<HandlerWrapper> outerHandlerChainWrappers; private List<ThreadSetupAction> threadSetupActions; private List<ServletExtension> servletExtensions; private SharedSessionManagerConfig sharedSessionManagerConfig; private boolean explodedDeployment; Builder setMergedMetaData(final JBossWebMetaData mergedMetaData) { this.mergedMetaData = mergedMetaData; return this; } public Builder setDeploymentName(final String deploymentName) { this.deploymentName = deploymentName; return this; } public Builder setTldsMetaData(final TldsMetaData tldsMetaData) { this.tldsMetaData = tldsMetaData; return this; } public Builder setSharedTlds(final List<TldMetaData> sharedTlds) { this.sharedTlds = sharedTlds; return this; } public Builder setModule(final Module module) { this.module = module; return this; } public Builder setScisMetaData(final ScisMetaData scisMetaData) { this.scisMetaData = scisMetaData; return this; } public Builder setDeploymentRoot(final VirtualFile deploymentRoot) { this.deploymentRoot = deploymentRoot; return this; } public Builder setJaccContextId(final String jaccContextId) { this.jaccContextId = jaccContextId; return this; } public Builder setAttributes(final List<ServletContextAttribute> attributes) { this.attributes = attributes; return this; } public Builder setContextPath(final String contextPath) { this.contextPath = contextPath; return this; } public Builder setSetupActions(final List<SetupAction> setupActions) { this.setupActions = setupActions; return this; } public Builder setSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } public Builder setOverlays(final Set<VirtualFile> overlays) { this.overlays = overlays; return this; } public Builder setExpressionFactoryWrappers(final List<ExpressionFactoryWrapper> expressionFactoryWrappers) { this.expressionFactoryWrappers = expressionFactoryWrappers; return this; } public Builder setPredicatedHandlers(List<PredicatedHandler> predicatedHandlers) { this.predicatedHandlers = predicatedHandlers; return this; } public Builder setInitialHandlerChainWrappers(List<HandlerWrapper> initialHandlerChainWrappers) { this.initialHandlerChainWrappers = initialHandlerChainWrappers; return this; } public Builder setInnerHandlerChainWrappers(List<HandlerWrapper> innerHandlerChainWrappers) { this.innerHandlerChainWrappers = innerHandlerChainWrappers; return this; } public Builder setOuterHandlerChainWrappers(List<HandlerWrapper> outerHandlerChainWrappers) { this.outerHandlerChainWrappers = outerHandlerChainWrappers; return this; } public Builder setThreadSetupActions(List<ThreadSetupAction> threadSetupActions) { this.threadSetupActions = threadSetupActions; return this; } public Builder setExplodedDeployment(boolean explodedDeployment) { this.explodedDeployment = explodedDeployment; return this; } public List<ServletExtension> getServletExtensions() { return servletExtensions; } public Builder setServletExtensions(List<ServletExtension> servletExtensions) { this.servletExtensions = servletExtensions; return this; } public Builder setSharedSessionManagerConfig(SharedSessionManagerConfig sharedSessionManagerConfig) { this.sharedSessionManagerConfig = sharedSessionManagerConfig; return this; } public UndertowDeploymentInfoService createUndertowDeploymentInfoService() { return new UndertowDeploymentInfoService(mergedMetaData, deploymentName, tldsMetaData, sharedTlds, module, scisMetaData, deploymentRoot, jaccContextId, securityDomain, attributes, contextPath, setupActions, overlays, expressionFactoryWrappers, predicatedHandlers, initialHandlerChainWrappers, innerHandlerChainWrappers, outerHandlerChainWrappers, threadSetupActions, explodedDeployment, servletExtensions, sharedSessionManagerConfig); } } private static class UndertowThreadSetupAction implements ThreadSetupAction { private final Handle handle; private final SetupAction action; public UndertowThreadSetupAction(SetupAction action) { this.action = action; handle = new Handle() { @Override public void tearDown() { UndertowThreadSetupAction.this.action.teardown(Collections.<String, Object>emptyMap()); } }; } @Override public Handle setup(final HttpServerExchange exchange) { action.setup(Collections.<String, Object>emptyMap()); return handle; } } }
undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java
/* * JBoss, Home of Professional Open Source. * Copyright 2013, Red Hat, Inc., and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.wildfly.extension.undertow.deployment; import io.undertow.Handlers; import io.undertow.jsp.JspFileHandler; import io.undertow.jsp.JspServletBuilder; import io.undertow.security.api.AuthenticationMechanism; import io.undertow.server.HandlerWrapper; import io.undertow.server.HttpHandler; import io.undertow.server.HttpServerExchange; import io.undertow.server.handlers.builder.PredicatedHandler; import io.undertow.server.handlers.resource.CachingResourceManager; import io.undertow.server.handlers.resource.ResourceManager; import io.undertow.servlet.ServletExtension; import io.undertow.servlet.Servlets; import io.undertow.servlet.api.AuthMethodConfig; import io.undertow.servlet.api.ClassIntrospecter; import io.undertow.servlet.api.ConfidentialPortManager; import io.undertow.servlet.api.DeploymentInfo; import io.undertow.servlet.api.ErrorPage; import io.undertow.servlet.api.FilterInfo; import io.undertow.servlet.api.HttpMethodSecurityInfo; import io.undertow.servlet.api.InstanceFactory; import io.undertow.servlet.api.InstanceHandle; import io.undertow.servlet.api.ListenerInfo; import io.undertow.servlet.api.LoginConfig; import io.undertow.servlet.api.MimeMapping; import io.undertow.servlet.api.SecurityConstraint; import io.undertow.servlet.api.ServletContainerInitializerInfo; import io.undertow.servlet.api.ServletInfo; import io.undertow.servlet.api.ServletSecurityInfo; import io.undertow.servlet.api.ServletSessionConfig; import io.undertow.servlet.api.SessionManagerFactory; import io.undertow.servlet.api.ThreadSetupAction; import io.undertow.servlet.api.WebResourceCollection; import io.undertow.servlet.handlers.DefaultServlet; import io.undertow.servlet.handlers.ServletPathMatches; import io.undertow.servlet.util.ImmediateInstanceFactory; import org.apache.jasper.deploy.FunctionInfo; import org.apache.jasper.deploy.JspPropertyGroup; import org.apache.jasper.deploy.TagAttributeInfo; import org.apache.jasper.deploy.TagFileInfo; import org.apache.jasper.deploy.TagInfo; import org.apache.jasper.deploy.TagLibraryInfo; import org.apache.jasper.deploy.TagLibraryValidatorInfo; import org.apache.jasper.deploy.TagVariableInfo; import org.apache.jasper.servlet.JspServlet; import org.jboss.annotation.javaee.Icon; import org.jboss.as.controller.services.path.PathManager; import org.jboss.as.ee.component.ComponentRegistry; import org.jboss.as.naming.ManagedReference; import org.jboss.as.naming.ManagedReferenceFactory; import org.jboss.as.security.plugins.SecurityDomainContext; import org.jboss.as.server.deployment.SetupAction; import org.jboss.as.version.Version; import org.jboss.as.web.common.ExpressionFactoryWrapper; import org.jboss.as.web.common.ServletContextAttribute; import org.jboss.as.web.common.WebInjectionContainer; import org.jboss.as.web.session.SessionIdentifierCodec; import org.jboss.metadata.javaee.spec.DescriptionGroupMetaData; import org.jboss.metadata.javaee.spec.ParamValueMetaData; import org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData; import org.jboss.metadata.web.jboss.JBossServletMetaData; import org.jboss.metadata.web.jboss.JBossWebMetaData; import org.jboss.metadata.web.spec.AttributeMetaData; import org.jboss.metadata.web.spec.CookieConfigMetaData; import org.jboss.metadata.web.spec.DispatcherType; import org.jboss.metadata.web.spec.EmptyRoleSemanticType; import org.jboss.metadata.web.spec.ErrorPageMetaData; import org.jboss.metadata.web.spec.FilterMappingMetaData; import org.jboss.metadata.web.spec.FilterMetaData; import org.jboss.metadata.web.spec.FunctionMetaData; import org.jboss.metadata.web.spec.HttpMethodConstraintMetaData; import org.jboss.metadata.web.spec.JspConfigMetaData; import org.jboss.metadata.web.spec.JspPropertyGroupMetaData; import org.jboss.metadata.web.spec.ListenerMetaData; import org.jboss.metadata.web.spec.LocaleEncodingMetaData; import org.jboss.metadata.web.spec.LoginConfigMetaData; import org.jboss.metadata.web.spec.MimeMappingMetaData; import org.jboss.metadata.web.spec.MultipartConfigMetaData; import org.jboss.metadata.web.spec.SecurityConstraintMetaData; import org.jboss.metadata.web.spec.ServletMappingMetaData; import org.jboss.metadata.web.spec.SessionConfigMetaData; import org.jboss.metadata.web.spec.SessionTrackingModeType; import org.jboss.metadata.web.spec.TagFileMetaData; import org.jboss.metadata.web.spec.TagMetaData; import org.jboss.metadata.web.spec.TldMetaData; import org.jboss.metadata.web.spec.TransportGuaranteeType; import org.jboss.metadata.web.spec.VariableMetaData; import org.jboss.metadata.web.spec.WebResourceCollectionMetaData; import org.jboss.modules.Module; import org.jboss.msc.inject.Injector; import org.jboss.msc.service.Service; import org.jboss.msc.service.ServiceName; import org.jboss.msc.service.StartContext; import org.jboss.msc.service.StartException; import org.jboss.msc.service.StopContext; import org.jboss.msc.value.InjectedValue; import org.jboss.security.audit.AuditManager; import org.jboss.security.auth.login.JASPIAuthenticationInfo; import org.jboss.security.authorization.config.AuthorizationModuleEntry; import org.jboss.security.authorization.modules.JACCAuthorizationModule; import org.jboss.security.config.ApplicationPolicy; import org.jboss.security.config.AuthorizationInfo; import org.jboss.security.config.SecurityConfiguration; import org.jboss.vfs.VirtualFile; import org.wildfly.extension.undertow.Host; import org.wildfly.extension.undertow.JSPConfig; import org.wildfly.extension.undertow.ServletContainerService; import org.wildfly.extension.undertow.SessionCookieConfig; import org.wildfly.extension.undertow.logging.UndertowLogger; import org.wildfly.extension.undertow.UndertowService; import org.wildfly.extension.undertow.security.AuditNotificationReceiver; import org.wildfly.extension.undertow.security.JAASIdentityManagerImpl; import org.wildfly.extension.undertow.security.JbossAuthorizationManager; import org.wildfly.extension.undertow.security.RunAsLifecycleInterceptor; import org.wildfly.extension.undertow.security.SecurityContextAssociationHandler; import org.wildfly.extension.undertow.security.SecurityContextThreadSetupAction; import org.wildfly.extension.undertow.security.jacc.JACCAuthorizationManager; import org.wildfly.extension.undertow.security.jacc.JACCContextIdHandler; import org.wildfly.extension.undertow.security.jaspi.JASPIAuthenticationMechanism; import org.wildfly.extension.undertow.security.jaspi.JASPICSecurityContextFactory; import org.wildfly.extension.undertow.session.CodecSessionConfigWrapper; import org.wildfly.extension.undertow.session.SharedSessionManagerConfig; import org.xnio.IoUtils; import javax.servlet.Filter; import javax.servlet.Servlet; import javax.servlet.ServletContainerInitializer; import javax.servlet.SessionTrackingMode; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.EventListener; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.Executor; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.AUTHENTICATE; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.DENY; import static io.undertow.servlet.api.SecurityInfo.EmptyRoleSemantic.PERMIT; /** * Service that builds up the undertow metadata. * * @author Stuart Douglas */ public class UndertowDeploymentInfoService implements Service<DeploymentInfo> { public static final ServiceName SERVICE_NAME = ServiceName.of("UndertowDeploymentInfoService"); private static final String TEMP_DIR = "jboss.server.temp.dir"; public static final String DEFAULT_SERVLET_NAME = "default"; private DeploymentInfo deploymentInfo; private final JBossWebMetaData mergedMetaData; private final String deploymentName; private final TldsMetaData tldsMetaData; private final List<TldMetaData> sharedTlds; private final Module module; private final ScisMetaData scisMetaData; private final VirtualFile deploymentRoot; private final String jaccContextId; private final String securityDomain; private final List<ServletContextAttribute> attributes; private final String contextPath; private final List<SetupAction> setupActions; private final Set<VirtualFile> overlays; private final List<ExpressionFactoryWrapper> expressionFactoryWrappers; private final List<PredicatedHandler> predicatedHandlers; private final List<HandlerWrapper> initialHandlerChainWrappers; private final List<HandlerWrapper> innerHandlerChainWrappers; private final List<HandlerWrapper> outerHandlerChainWrappers; private final List<ThreadSetupAction> threadSetupActions; private final List<ServletExtension> servletExtensions; private final SharedSessionManagerConfig sharedSessionManagerConfig; private final boolean explodedDeployment; private final InjectedValue<UndertowService> undertowService = new InjectedValue<>(); private final InjectedValue<SessionManagerFactory> sessionManagerFactory = new InjectedValue<>(); private final InjectedValue<SessionIdentifierCodec> sessionIdentifierCodec = new InjectedValue<>(); private final InjectedValue<SecurityDomainContext> securityDomainContextValue = new InjectedValue<SecurityDomainContext>(); private final InjectedValue<ServletContainerService> container = new InjectedValue<>(); private final InjectedValue<PathManager> pathManagerInjector = new InjectedValue<PathManager>(); private final InjectedValue<ComponentRegistry> componentRegistryInjectedValue = new InjectedValue<>(); private final InjectedValue<Host> host = new InjectedValue<>(); private final Map<String, InjectedValue<Executor>> executorsByName = new HashMap<String, InjectedValue<Executor>>(); private UndertowDeploymentInfoService(final JBossWebMetaData mergedMetaData, final String deploymentName, final TldsMetaData tldsMetaData, final List<TldMetaData> sharedTlds, final Module module, final ScisMetaData scisMetaData, final VirtualFile deploymentRoot, final String jaccContextId, final String securityDomain, final List<ServletContextAttribute> attributes, final String contextPath, final List<SetupAction> setupActions, final Set<VirtualFile> overlays, final List<ExpressionFactoryWrapper> expressionFactoryWrappers, List<PredicatedHandler> predicatedHandlers, List<HandlerWrapper> initialHandlerChainWrappers, List<HandlerWrapper> innerHandlerChainWrappers, List<HandlerWrapper> outerHandlerChainWrappers, List<ThreadSetupAction> threadSetupActions, boolean explodedDeployment, List<ServletExtension> servletExtensions, SharedSessionManagerConfig sharedSessionManagerConfig) { this.mergedMetaData = mergedMetaData; this.deploymentName = deploymentName; this.tldsMetaData = tldsMetaData; this.sharedTlds = sharedTlds; this.module = module; this.scisMetaData = scisMetaData; this.deploymentRoot = deploymentRoot; this.jaccContextId = jaccContextId; this.securityDomain = securityDomain; this.attributes = attributes; this.contextPath = contextPath; this.setupActions = setupActions; this.overlays = overlays; this.expressionFactoryWrappers = expressionFactoryWrappers; this.predicatedHandlers = predicatedHandlers; this.initialHandlerChainWrappers = initialHandlerChainWrappers; this.innerHandlerChainWrappers = innerHandlerChainWrappers; this.outerHandlerChainWrappers = outerHandlerChainWrappers; this.threadSetupActions = threadSetupActions; this.explodedDeployment = explodedDeployment; this.servletExtensions = servletExtensions; this.sharedSessionManagerConfig = sharedSessionManagerConfig; } @Override public synchronized void start(final StartContext startContext) throws StartException { ClassLoader oldTccl = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(module.getClassLoader()); DeploymentInfo deploymentInfo = createServletConfig(); handleDistributable(deploymentInfo); handleIdentityManager(deploymentInfo); handleJASPIMechanism(deploymentInfo); handleJACCAuthorization(deploymentInfo); handleAdditionalAuthenticationMechanisms(deploymentInfo); if(mergedMetaData.isUseJBossAuthorization()) { deploymentInfo.setAuthorizationManager(new JbossAuthorizationManager(deploymentInfo.getAuthorizationManager())); } SessionConfigMetaData sessionConfig = mergedMetaData.getSessionConfig(); if(sharedSessionManagerConfig != null && sharedSessionManagerConfig.getSessionConfig() != null) { sessionConfig = sharedSessionManagerConfig.getSessionConfig(); } ServletSessionConfig config = null; //default session config SessionCookieConfig defaultSessionConfig = container.getValue().getSessionCookieConfig(); if (defaultSessionConfig != null) { config = new ServletSessionConfig(); if (defaultSessionConfig.getName() != null) { config.setName(defaultSessionConfig.getName()); } if (defaultSessionConfig.getDomain() != null) { config.setDomain(defaultSessionConfig.getDomain()); } if (defaultSessionConfig.getHttpOnly() != null) { config.setHttpOnly(defaultSessionConfig.getHttpOnly()); } if (defaultSessionConfig.getSecure() != null) { config.setSecure(defaultSessionConfig.getSecure()); } if (defaultSessionConfig.getMaxAge() != null) { config.setMaxAge(defaultSessionConfig.getMaxAge()); } if (defaultSessionConfig.getComment() != null) { config.setComment(defaultSessionConfig.getComment()); } } if (sessionConfig != null) { if (sessionConfig.getSessionTimeoutSet()) { deploymentInfo.setDefaultSessionTimeout(sessionConfig.getSessionTimeout() * 60); } CookieConfigMetaData cookieConfig = sessionConfig.getCookieConfig(); if (config == null) { config = new ServletSessionConfig(); } if (cookieConfig != null) { if (cookieConfig.getName() != null) { config.setName(cookieConfig.getName()); } if (cookieConfig.getDomain() != null) { config.setDomain(cookieConfig.getDomain()); } if (cookieConfig.getComment() != null) { config.setComment(cookieConfig.getComment()); } config.setSecure(cookieConfig.getSecure()); config.setPath(cookieConfig.getPath()); config.setMaxAge(cookieConfig.getMaxAge()); config.setHttpOnly(cookieConfig.getHttpOnly()); } List<SessionTrackingModeType> modes = sessionConfig.getSessionTrackingModes(); if (modes != null && !modes.isEmpty()) { final Set<SessionTrackingMode> trackingModes = new HashSet<>(); for (SessionTrackingModeType mode : modes) { switch (mode) { case COOKIE: trackingModes.add(SessionTrackingMode.COOKIE); break; case SSL: trackingModes.add(SessionTrackingMode.SSL); break; case URL: trackingModes.add(SessionTrackingMode.URL); break; } } config.setSessionTrackingModes(trackingModes); } } if (config != null) { deploymentInfo.setServletSessionConfig(config); } for (final SetupAction action : setupActions) { deploymentInfo.addThreadSetupAction(new UndertowThreadSetupAction(action)); } if (initialHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : initialHandlerChainWrappers) { deploymentInfo.addInitialHandlerChainWrapper(handlerWrapper); } } if (innerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : innerHandlerChainWrappers) { deploymentInfo.addInnerHandlerChainWrapper(handlerWrapper); } } if (outerHandlerChainWrappers != null) { for (HandlerWrapper handlerWrapper : outerHandlerChainWrappers) { deploymentInfo.addOuterHandlerChainWrapper(handlerWrapper); } } if (threadSetupActions != null) { for (ThreadSetupAction threadSetupAction : threadSetupActions) { deploymentInfo.addThreadSetupAction(threadSetupAction); } } deploymentInfo.setServerName("WildFly "+ Version.AS_VERSION); if (undertowService.getValue().statisticsEnabled()){ deploymentInfo.setMetricsCollector(new UndertowMetricsCollector()); } this.deploymentInfo = deploymentInfo; } finally { Thread.currentThread().setContextClassLoader(oldTccl); } } @Override public synchronized void stop(final StopContext stopContext) { IoUtils.safeClose(this.deploymentInfo.getResourceManager()); this.deploymentInfo.setConfidentialPortManager(null); this.deploymentInfo = null; } @Override public synchronized DeploymentInfo getValue() throws IllegalStateException, IllegalArgumentException { return deploymentInfo; } /** * <p>Adds to the deployment the {@link JASPIAuthenticationMechanism}, if necessary. The handler will be added if the security domain * is configured with JASPI authentication.</p> * * @param deploymentInfo */ private void handleJASPIMechanism(final DeploymentInfo deploymentInfo) { ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null && JASPIAuthenticationInfo.class.isInstance(applicationPolicy.getAuthenticationInfo())) { String authMethod = null; LoginConfig loginConfig = deploymentInfo.getLoginConfig(); if (loginConfig != null && loginConfig.getAuthMethods().size() > 0) authMethod = loginConfig.getAuthMethods().get(0).getName(); deploymentInfo.setJaspiAuthenticationMechanism(new JASPIAuthenticationMechanism(this.securityDomain, authMethod)); deploymentInfo.setSecurityContextFactory(new JASPICSecurityContextFactory(this.securityDomain)); } } /** * <p> * Sets the {@link JACCAuthorizationManager} in the specified {@link DeploymentInfo} if the webapp security domain * has defined a JACC authorization module. * </p> * * @param deploymentInfo the {@link DeploymentInfo} instance. */ private void handleJACCAuthorization(final DeploymentInfo deploymentInfo) { // TODO make the authorization manager implementation configurable in Undertow or jboss-web.xml ApplicationPolicy applicationPolicy = SecurityConfiguration.getApplicationPolicy(this.securityDomain); if (applicationPolicy != null) { AuthorizationInfo authzInfo = applicationPolicy.getAuthorizationInfo(); if (authzInfo != null) { for (AuthorizationModuleEntry entry : authzInfo.getModuleEntries()) { if (JACCAuthorizationModule.class.getName().equals(entry.getPolicyModuleName())) { deploymentInfo.setAuthorizationManager(new JACCAuthorizationManager()); break; } } } } } private void handleAdditionalAuthenticationMechanisms(final DeploymentInfo deploymentInfo){ for (Map.Entry<String,AuthenticationMechanism> am: host.getValue().getAdditionalAuthenticationMechanisms().entrySet()){ deploymentInfo.addFirstAuthenticationMechanism(am.getKey(), am.getValue()); } } private void handleIdentityManager(final DeploymentInfo deploymentInfo) { SecurityDomainContext sdc = securityDomainContextValue.getValue(); deploymentInfo.setIdentityManager(new JAASIdentityManagerImpl(sdc)); AuditManager auditManager = sdc.getAuditManager(); if (auditManager != null && !mergedMetaData.isDisableAudit()) { deploymentInfo.addNotificationReceiver(new AuditNotificationReceiver(auditManager)); } deploymentInfo.setConfidentialPortManager(getConfidentialPortManager()); } private ConfidentialPortManager getConfidentialPortManager() { return new ConfidentialPortManager() { @Override public int getConfidentialPort(HttpServerExchange exchange) { int port = exchange.getConnection().getLocalAddress(InetSocketAddress.class).getPort(); return host.getValue().getServer().getValue().lookupSecurePort(port); } }; } private void handleDistributable(final DeploymentInfo deploymentInfo) { SessionManagerFactory managerFactory = this.sessionManagerFactory.getOptionalValue(); if (managerFactory != null) { deploymentInfo.setSessionManagerFactory(managerFactory); } SessionIdentifierCodec codec = this.sessionIdentifierCodec.getOptionalValue(); if (codec != null) { deploymentInfo.setSessionConfigWrapper(new CodecSessionConfigWrapper(codec)); } } /* This is to address WFLY-1894 but should probably be moved to some other place. */ private String resolveContextPath() { if (deploymentName.equals(host.getValue().getDefaultWebModule())) { return "/"; } else { return contextPath; } } private DeploymentInfo createServletConfig() throws StartException { final ComponentRegistry componentRegistry = componentRegistryInjectedValue.getValue(); try { if (!mergedMetaData.isMetadataComplete()) { mergedMetaData.resolveAnnotations(); } final DeploymentInfo d = new DeploymentInfo(); d.setContextPath(resolveContextPath()); if (mergedMetaData.getDescriptionGroup() != null) { d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName()); } d.setDeploymentName(deploymentName); final ServletContainerService servletContainer = container.getValue(); try { //TODO: make the caching limits configurable ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment); resourceManager = new CachingResourceManager(100, 10 * 1024 * 1024, servletContainer.getBufferCache(), resourceManager, explodedDeployment ? 2000 : -1); d.setResourceManager(resourceManager); } catch (IOException e) { throw new StartException(e); } File tempFile = new File(pathManagerInjector.getValue().getPathEntry(TEMP_DIR).resolvePath(), deploymentName); tempFile.mkdirs(); d.setTempDir(tempFile); d.setClassLoader(module.getClassLoader()); final String servletVersion = mergedMetaData.getServletVersion(); if (servletVersion != null) { d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + "")); d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + "")); } else { d.setMajorVersion(3); d.setMinorVersion(1); } //in most cases flush just hurts performance for no good reason d.setIgnoreFlush(servletContainer.isIgnoreFlush()); //controlls initizalization of filters on start of application d.setEagerFilterInit(servletContainer.isEagerFilterInit()); d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers()); d.setServletStackTraces(servletContainer.getStackTraces()); if (servletContainer.getSessionPersistenceManager() != null) { d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager()); } //for 2.2 apps we do not require a leading / in path mappings boolean is22OrOlder; if (d.getMajorVersion() == 1) { is22OrOlder = true; } else if (d.getMajorVersion() == 2) { is22OrOlder = d.getMinorVersion() < 3; } else { is22OrOlder = false; } JSPConfig jspConfig = servletContainer.getJspConfig(); final Set<String> seenMappings = new HashSet<>(); HashMap<String, TagLibraryInfo> tldInfo = createTldsInfo(tldsMetaData, sharedTlds); //default JSP servlet final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null; if (jspServlet != null) { //this would be null if jsp support is disabled HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData); JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new WebInjectionContainer(module.getClassLoader(), componentRegistryInjectedValue.getValue()))); if (mergedMetaData.getJspConfig() != null) { d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), propertyGroups.values())); } d.addServlet(jspServlet); final Set<String> jspPropertyGroupMappings = propertyGroups.keySet(); for (final String mapping : jspPropertyGroupMappings) { jspServlet.addMapping(mapping); } seenMappings.addAll(jspPropertyGroupMappings); //setup JSP expression factory wrapper if (!expressionFactoryWrappers.isEmpty()) { d.addListener(new ListenerInfo(JspInitializationListener.class)); d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers); } } d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry)); final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>(); if (mergedMetaData.getExecutorName() != null) { d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).getValue()); } if(servletExtensions != null) { for(ServletExtension extension : servletExtensions) { d.addServletExtension(extension); } } if (mergedMetaData.getServletMappings() != null) { for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) { List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName()); if (list == null) { servletMappings.put(mapping.getServletName(), list = new ArrayList<>()); } list.add(mapping); } } final List<JBossServletMetaData> servlets = new ArrayList<JBossServletMetaData>(); for (JBossServletMetaData servlet : mergedMetaData.getServlets()) { servlets.add(servlet); } if (servlets != null) { for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) { final ServletInfo s; if (servlet.getJspFile() != null) { s = new ServletInfo(servlet.getName(), JspServlet.class); s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile())); } else { if (servlet.getServletClass() == null) { if(DEFAULT_SERVLET_NAME.equals(servlet.getName())) { s = new ServletInfo(servlet.getName(), DefaultServlet.class); } else { throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName()); } } else { Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass); if (creator != null) { InstanceFactory<Servlet> factory = createInstanceFactory(creator); s = new ServletInfo(servlet.getName(), servletClass, factory); } else { s = new ServletInfo(servlet.getName(), servletClass); } } } s.setAsyncSupported(servlet.isAsyncSupported()) .setJspFile(servlet.getJspFile()) .setEnabled(servlet.isEnabled()); if (servlet.getRunAs() != null) { s.setRunAs(servlet.getRunAs().getRoleName()); } if (servlet.getLoadOnStartupSet()) {//todo why not cleanup api and just use int everywhere s.setLoadOnStartup(servlet.getLoadOnStartupInt()); } if (servlet.getExecutorName() != null) { s.setExecutor(executorsByName.get(servlet.getExecutorName()).getValue()); } handleServletMappings(is22OrOlder, seenMappings, servletMappings, s); if (servlet.getInitParam() != null) { for (ParamValueMetaData initParam : servlet.getInitParam()) { if (!s.getInitParams().containsKey(initParam.getParamName())) { s.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } if (servlet.getServletSecurity() != null) { ServletSecurityInfo securityInfo = new ServletSecurityInfo(); s.setServletSecurityInfo(securityInfo); securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())) .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed()); if (servlet.getServletSecurity().getHttpMethodConstraints() != null) { for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) { securityInfo.addHttpMethodSecurityInfo( new HttpMethodSecurityInfo() .setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT) .setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())) .addRolesAllowed(method.getRolesAllowed()) .setMethod(method.getMethod())); } } } if (servlet.getSecurityRoleRefs() != null) { for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) { s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink()); } } if (servlet.getMultipartConfig() != null) { MultipartConfigMetaData mp = servlet.getMultipartConfig(); s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold())); } d.addServlet(s); } } //we explicitly add the default servlet, to allow it to be mapped if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) { ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class); handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet); d.addServlet(defaultServlet); } if (mergedMetaData.getFilters() != null) { for (final FilterMetaData filter : mergedMetaData.getFilters()) { Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass()); ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass); FilterInfo f; if (creator != null) { InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator); f = new FilterInfo(filter.getName(), filterClass, instanceFactory); } else { f = new FilterInfo(filter.getName(), filterClass); } f.setAsyncSupported(filter.isAsyncSupported()); d.addFilter(f); if (filter.getInitParam() != null) { for (ParamValueMetaData initParam : filter.getInitParam()) { f.addInitParam(initParam.getParamName(), initParam.getParamValue()); } } } } if (mergedMetaData.getFilterMappings() != null) { for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) { if (mapping.getUrlPatterns() != null) { for (String url : mapping.getUrlPatterns()) { if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) { url = "/" + url; } if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST); } } } if (mapping.getServletNames() != null) { for (String servletName : mapping.getServletNames()) { if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) { for (DispatcherType dispatcher : mapping.getDispatchers()) { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.valueOf(dispatcher.name())); } } else { d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST); } } } } } if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) { for (final ServletContainerInitializer sci : scisMetaData.getScis()) { final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci); d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci))); } } if (mergedMetaData.getListeners() != null) { for (ListenerMetaData listener : mergedMetaData.getListeners()) { addListener(module.getClassLoader(), componentRegistry, d, listener); } } if (mergedMetaData.getContextParams() != null) { for (ParamValueMetaData param : mergedMetaData.getContextParams()) { d.addInitParameter(param.getParamName(), param.getParamValue()); } } if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) { List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles(); for (String file : welcomeFiles) { if (file.startsWith("/")) { d.addWelcomePages(file.substring(1)); } else { d.addWelcomePages(file); } } } else { d.addWelcomePages("index.html", "index.htm", "index.jsp"); } if (mergedMetaData.getErrorPages() != null) { for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) { final ErrorPage errorPage; if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType())); } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) { errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode())); } else { errorPage = new ErrorPage(page.getLocation()); } d.addErrorPages(errorPage); } } if (mergedMetaData.getMimeMappings() != null) { for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) { d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType())); } } d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null); Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames(); if (mergedMetaData.getSecurityConstraints() != null) { for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) { SecurityConstraint securityConstraint = new SecurityConstraint() .setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee())); List<String> roleNames = constraint.getRoleNames(); if (constraint.getAuthConstraint() == null) { // no auth constraint means we permit the empty roles securityConstraint.setEmptyRoleSemantic(PERMIT); } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) { // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable // authentication only mode. // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow. securityConstraint.setEmptyRoleSemantic(AUTHENTICATE); } else { securityConstraint.addRolesAllowed(roleNames); } if (constraint.getResourceCollections() != null) { for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) { securityConstraint.addWebResourceCollection(new WebResourceCollection() .addHttpMethods(resourceCollection.getHttpMethods()) .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()) .addUrlPatterns(resourceCollection.getUrlPatterns())); } } d.addSecurityConstraint(securityConstraint); } } final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig(); if (loginConfig != null) { List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod()); if (loginConfig.getFormLoginConfig() != null) { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage())); } else { d.setLoginConfig(new LoginConfig(loginConfig.getRealmName())); } for (AuthMethodConfig method : authMethod) { d.getLoginConfig().addLastAuthMethod(method); } } d.addSecurityRoles(mergedMetaData.getSecurityRoleNames()); Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap(); d.addThreadSetupAction(new SecurityContextThreadSetupAction(securityDomain, securityDomainContextValue.getValue(), principalVersusRolesMap)); d.addInnerHandlerChainWrapper(SecurityContextAssociationHandler.wrapper(mergedMetaData.getRunAsIdentity())); d.addOuterHandlerChainWrapper(JACCContextIdHandler.wrapper(jaccContextId)); d.addLifecycleInterceptor(new RunAsLifecycleInterceptor(mergedMetaData.getRunAsIdentity())); if (principalVersusRolesMap != null) { for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) { d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue()); } } // Setup an deployer configured ServletContext attributes for (ServletContextAttribute attribute : attributes) { d.addServletContextAttribute(attribute.getName(), attribute.getValue()); } if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) { for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) { d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding()); } } if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) { d.addInitialHandlerChainWrapper(new HandlerWrapper() { @Override public HttpHandler wrap(HttpHandler handler) { if (predicatedHandlers.size() == 1) { PredicatedHandler ph = predicatedHandlers.get(0); return Handlers.predicate(ph.getPredicate(), ph.getHandler().wrap(handler), handler); } else { return Handlers.predicates(predicatedHandlers, handler); } } }); } if (mergedMetaData.getDefaultEncoding()!=null){ d.setDefaultEncoding(mergedMetaData.getDefaultEncoding()); }else if (servletContainer.getDefaultEncoding()!=null){ d.setDefaultEncoding(servletContainer.getDefaultEncoding()); } return d; } catch (ClassNotFoundException e) { throw new StartException(e); } } private void handleServletMappings(boolean is22OrOlder, Set<String> seenMappings, Map<String, List<ServletMappingMetaData>> servletMappings, ServletInfo s) { List<ServletMappingMetaData> mappings = servletMappings.get(s.getName()); if (mappings != null) { for (ServletMappingMetaData mapping : mappings) { for (String pattern : mapping.getUrlPatterns()) { if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) { pattern = "/" + pattern; } if (!seenMappings.contains(pattern)) { s.addMapping(pattern); seenMappings.add(pattern); } } } } } /** * Convert the authentication method name from the format specified in the web.xml to the format used by * {@link javax.servlet.http.HttpServletRequest}. * <p/> * If the auth method is not recognised then it is returned as-is. * * @return The converted auth method. * @throws NullPointerException if no configuredMethod is supplied. */ private static List<AuthMethodConfig> authMethod(String configuredMethod) { if (configuredMethod == null) { return Collections.singletonList(new AuthMethodConfig(HttpServletRequest.BASIC_AUTH)); } return AuthMethodParser.parse(configuredMethod, Collections.singletonMap("CLIENT-CERT", HttpServletRequest.CLIENT_CERT_AUTH)); } private static io.undertow.servlet.api.TransportGuaranteeType transportGuaranteeType(final TransportGuaranteeType type) { if (type == null) { return io.undertow.servlet.api.TransportGuaranteeType.NONE; } switch (type) { case CONFIDENTIAL: return io.undertow.servlet.api.TransportGuaranteeType.CONFIDENTIAL; case INTEGRAL: return io.undertow.servlet.api.TransportGuaranteeType.INTEGRAL; case NONE: return io.undertow.servlet.api.TransportGuaranteeType.NONE; } throw new RuntimeException("UNREACHABLE"); } private static HashMap<String, JspPropertyGroup> createJspConfig(JBossWebMetaData metaData) { final HashMap<String, JspPropertyGroup> result = new HashMap<>(); // JSP Config JspConfigMetaData config = metaData.getJspConfig(); if (config != null) { // JSP Property groups List<JspPropertyGroupMetaData> groups = config.getPropertyGroups(); if (groups != null) { for (JspPropertyGroupMetaData group : groups) { org.apache.jasper.deploy.JspPropertyGroup jspPropertyGroup = new org.apache.jasper.deploy.JspPropertyGroup(); for (String pattern : group.getUrlPatterns()) { jspPropertyGroup.addUrlPattern(pattern); } jspPropertyGroup.setElIgnored(group.getElIgnored()); jspPropertyGroup.setPageEncoding(group.getPageEncoding()); jspPropertyGroup.setScriptingInvalid(group.getScriptingInvalid()); jspPropertyGroup.setIsXml(group.getIsXml()); if (group.getIncludePreludes() != null) { for (String includePrelude : group.getIncludePreludes()) { jspPropertyGroup.addIncludePrelude(includePrelude); } } if (group.getIncludeCodas() != null) { for (String includeCoda : group.getIncludeCodas()) { jspPropertyGroup.addIncludeCoda(includeCoda); } } jspPropertyGroup.setDeferredSyntaxAllowedAsLiteral(group.getDeferredSyntaxAllowedAsLiteral()); jspPropertyGroup.setTrimDirectiveWhitespaces(group.getTrimDirectiveWhitespaces()); jspPropertyGroup.setDefaultContentType(group.getDefaultContentType()); jspPropertyGroup.setBuffer(group.getBuffer()); jspPropertyGroup.setErrorOnUndeclaredNamespace(group.getErrorOnUndeclaredNamespace()); for (String pattern : jspPropertyGroup.getUrlPatterns()) { // Split off the groups to individual mappings result.put(pattern, jspPropertyGroup); } } } } //it looks like jasper needs these in order of least specified to most specific final LinkedHashMap<String, JspPropertyGroup> ret = new LinkedHashMap<>(); final ArrayList<String> paths = new ArrayList<>(result.keySet()); Collections.sort(paths, new Comparator<String>() { @Override public int compare(final String o1, final String o2) { return o1.length() - o2.length(); } }); for (String path : paths) { ret.put(path, result.get(path)); } return ret; } private static HashMap<String, TagLibraryInfo> createTldsInfo(final TldsMetaData tldsMetaData, List<TldMetaData> sharedTlds) throws ClassNotFoundException { final HashMap<String, TagLibraryInfo> ret = new HashMap<>(); if (tldsMetaData != null) { if (tldsMetaData.getTlds() != null) { for (Map.Entry<String, TldMetaData> tld : tldsMetaData.getTlds().entrySet()) { createTldInfo(tld.getKey(), tld.getValue(), ret); } } if (sharedTlds != null) { for (TldMetaData metaData : sharedTlds) { createTldInfo(null, metaData, ret); } } } return ret; } private static TagLibraryInfo createTldInfo(final String location, final TldMetaData tldMetaData, final HashMap<String, TagLibraryInfo> ret) throws ClassNotFoundException { String relativeLocation = location; String jarPath = null; if (relativeLocation != null && relativeLocation.startsWith("/WEB-INF/lib/")) { int pos = relativeLocation.indexOf('/', "/WEB-INF/lib/".length()); if (pos > 0) { jarPath = relativeLocation.substring(pos); if (jarPath.startsWith("/")) { jarPath = jarPath.substring(1); } relativeLocation = relativeLocation.substring(0, pos); } } TagLibraryInfo tagLibraryInfo = new TagLibraryInfo(); tagLibraryInfo.setTlibversion(tldMetaData.getTlibVersion()); if (tldMetaData.getJspVersion() == null) { tagLibraryInfo.setJspversion(tldMetaData.getVersion()); } else { tagLibraryInfo.setJspversion(tldMetaData.getJspVersion()); } tagLibraryInfo.setShortname(tldMetaData.getShortName()); tagLibraryInfo.setUri(tldMetaData.getUri()); if (tldMetaData.getDescriptionGroup() != null) { tagLibraryInfo.setInfo(tldMetaData.getDescriptionGroup().getDescription()); } // Validator if (tldMetaData.getValidator() != null) { TagLibraryValidatorInfo tagLibraryValidatorInfo = new TagLibraryValidatorInfo(); tagLibraryValidatorInfo.setValidatorClass(tldMetaData.getValidator().getValidatorClass()); if (tldMetaData.getValidator().getInitParams() != null) { for (ParamValueMetaData paramValueMetaData : tldMetaData.getValidator().getInitParams()) { tagLibraryValidatorInfo.addInitParam(paramValueMetaData.getParamName(), paramValueMetaData.getParamValue()); } } tagLibraryInfo.setValidator(tagLibraryValidatorInfo); } // Tag if (tldMetaData.getTags() != null) { for (TagMetaData tagMetaData : tldMetaData.getTags()) { TagInfo tagInfo = new TagInfo(); tagInfo.setTagName(tagMetaData.getName()); tagInfo.setTagClassName(tagMetaData.getTagClass()); tagInfo.setTagExtraInfo(tagMetaData.getTeiClass()); if (tagMetaData.getBodyContent() != null) { tagInfo.setBodyContent(tagMetaData.getBodyContent().toString()); } tagInfo.setDynamicAttributes(tagMetaData.getDynamicAttributes()); // Description group if (tagMetaData.getDescriptionGroup() != null) { DescriptionGroupMetaData descriptionGroup = tagMetaData.getDescriptionGroup(); if (descriptionGroup.getIcons() != null && descriptionGroup.getIcons().value() != null && (descriptionGroup.getIcons().value().length > 0)) { Icon icon = descriptionGroup.getIcons().value()[0]; tagInfo.setLargeIcon(icon.largeIcon()); tagInfo.setSmallIcon(icon.smallIcon()); } tagInfo.setInfoString(descriptionGroup.getDescription()); tagInfo.setDisplayName(descriptionGroup.getDisplayName()); } // Variable if (tagMetaData.getVariables() != null) { for (VariableMetaData variableMetaData : tagMetaData.getVariables()) { TagVariableInfo tagVariableInfo = new TagVariableInfo(); tagVariableInfo.setNameGiven(variableMetaData.getNameGiven()); tagVariableInfo.setNameFromAttribute(variableMetaData.getNameFromAttribute()); tagVariableInfo.setClassName(variableMetaData.getVariableClass()); tagVariableInfo.setDeclare(variableMetaData.getDeclare()); if (variableMetaData.getScope() != null) { tagVariableInfo.setScope(variableMetaData.getScope().toString()); } tagInfo.addTagVariableInfo(tagVariableInfo); } } // Attribute if (tagMetaData.getAttributes() != null) { for (AttributeMetaData attributeMetaData : tagMetaData.getAttributes()) { TagAttributeInfo tagAttributeInfo = new TagAttributeInfo(); tagAttributeInfo.setName(attributeMetaData.getName()); tagAttributeInfo.setType(attributeMetaData.getType()); tagAttributeInfo.setReqTime(attributeMetaData.getRtexprvalue()); tagAttributeInfo.setRequired(attributeMetaData.getRequired()); tagAttributeInfo.setFragment(attributeMetaData.getFragment()); if (attributeMetaData.getDeferredValue() != null) { tagAttributeInfo.setDeferredValue("true"); tagAttributeInfo.setExpectedTypeName(attributeMetaData.getDeferredValue().getType()); } else { tagAttributeInfo.setDeferredValue("false"); } if (attributeMetaData.getDeferredMethod() != null) { tagAttributeInfo.setDeferredMethod("true"); tagAttributeInfo.setMethodSignature(attributeMetaData.getDeferredMethod().getMethodSignature()); } else { tagAttributeInfo.setDeferredMethod("false"); } tagInfo.addTagAttributeInfo(tagAttributeInfo); } } tagLibraryInfo.addTagInfo(tagInfo); } } // Tag files if (tldMetaData.getTagFiles() != null) { for (TagFileMetaData tagFileMetaData : tldMetaData.getTagFiles()) { TagFileInfo tagFileInfo = new TagFileInfo(); tagFileInfo.setName(tagFileMetaData.getName()); tagFileInfo.setPath(tagFileMetaData.getPath()); tagLibraryInfo.addTagFileInfo(tagFileInfo); } } // Function if (tldMetaData.getFunctions() != null) { for (FunctionMetaData functionMetaData : tldMetaData.getFunctions()) { FunctionInfo functionInfo = new FunctionInfo(); functionInfo.setName(functionMetaData.getName()); functionInfo.setFunctionClass(functionMetaData.getFunctionClass()); functionInfo.setFunctionSignature(functionMetaData.getFunctionSignature()); tagLibraryInfo.addFunctionInfo(functionInfo); } } if (jarPath == null && relativeLocation == null) { if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } } else if (jarPath == null) { tagLibraryInfo.setLocation(""); tagLibraryInfo.setPath(relativeLocation); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } ret.put(relativeLocation, tagLibraryInfo); } else { tagLibraryInfo.setLocation(relativeLocation); tagLibraryInfo.setPath(jarPath); if (!ret.containsKey(tagLibraryInfo.getUri())) { ret.put(tagLibraryInfo.getUri(), tagLibraryInfo); } if (jarPath.equals("META-INF/taglib.tld")) { ret.put(relativeLocation, tagLibraryInfo); } } return tagLibraryInfo; } private static void addListener(final ClassLoader classLoader, final ComponentRegistry components, final DeploymentInfo d, final ListenerMetaData listener) throws ClassNotFoundException { ListenerInfo l; final Class<? extends EventListener> listenerClass = (Class<? extends EventListener>) classLoader.loadClass(listener.getListenerClass()); ManagedReferenceFactory creator = components.createInstanceFactory(listenerClass); if (creator != null) { InstanceFactory<EventListener> factory = createInstanceFactory(creator); l = new ListenerInfo(listenerClass, factory); } else { l = new ListenerInfo(listenerClass); } d.addListener(l); } private static <T> InstanceFactory<T> createInstanceFactory(final ManagedReferenceFactory creator) { return new InstanceFactory<T>() { @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference instance = creator.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) instance.getInstance(); } @Override public void release() { instance.release(); } }; } }; } public void addInjectedExecutor(final String name, final InjectedValue<Executor> injected) { executorsByName.put(name, injected); } public InjectedValue<ServletContainerService> getContainer() { return container; } public InjectedValue<SecurityDomainContext> getSecurityDomainContextValue() { return securityDomainContextValue; } public Injector<SessionManagerFactory> getSessionManagerFactoryInjector() { return this.sessionManagerFactory; } public Injector<SessionIdentifierCodec> getSessionIdentifierCodecInjector() { return this.sessionIdentifierCodec; } public InjectedValue<UndertowService> getUndertowService() { return undertowService; } public InjectedValue<PathManager> getPathManagerInjector() { return pathManagerInjector; } public InjectedValue<ComponentRegistry> getComponentRegistryInjectedValue() { return componentRegistryInjectedValue; } public InjectedValue<Host> getHost() { return host; } private static class ComponentClassIntrospector implements ClassIntrospecter { private final ComponentRegistry componentRegistry; public ComponentClassIntrospector(final ComponentRegistry componentRegistry) { this.componentRegistry = componentRegistry; } @Override public <T> InstanceFactory<T> createInstanceFactory(final Class<T> clazz) throws NoSuchMethodException { final ManagedReferenceFactory component = componentRegistry.createInstanceFactory(clazz); return new ManagedReferenceInstanceFactory<>(component); } } private static class ManagedReferenceInstanceFactory<T> implements InstanceFactory<T> { private final ManagedReferenceFactory component; public ManagedReferenceInstanceFactory(final ManagedReferenceFactory component) { this.component = component; } @Override public InstanceHandle<T> createInstance() throws InstantiationException { final ManagedReference reference = component.getReference(); return new InstanceHandle<T>() { @Override public T getInstance() { return (T) reference.getInstance(); } @Override public void release() { reference.release(); } }; } } public static Builder builder() { return new Builder(); } public static class Builder { private JBossWebMetaData mergedMetaData; private String deploymentName; private TldsMetaData tldsMetaData; private List<TldMetaData> sharedTlds; private Module module; private ScisMetaData scisMetaData; private VirtualFile deploymentRoot; private String jaccContextId; private List<ServletContextAttribute> attributes; private String contextPath; private String securityDomain; private List<SetupAction> setupActions; private Set<VirtualFile> overlays; private List<ExpressionFactoryWrapper> expressionFactoryWrappers; private List<PredicatedHandler> predicatedHandlers; private List<HandlerWrapper> initialHandlerChainWrappers; private List<HandlerWrapper> innerHandlerChainWrappers; private List<HandlerWrapper> outerHandlerChainWrappers; private List<ThreadSetupAction> threadSetupActions; private List<ServletExtension> servletExtensions; private SharedSessionManagerConfig sharedSessionManagerConfig; private boolean explodedDeployment; Builder setMergedMetaData(final JBossWebMetaData mergedMetaData) { this.mergedMetaData = mergedMetaData; return this; } public Builder setDeploymentName(final String deploymentName) { this.deploymentName = deploymentName; return this; } public Builder setTldsMetaData(final TldsMetaData tldsMetaData) { this.tldsMetaData = tldsMetaData; return this; } public Builder setSharedTlds(final List<TldMetaData> sharedTlds) { this.sharedTlds = sharedTlds; return this; } public Builder setModule(final Module module) { this.module = module; return this; } public Builder setScisMetaData(final ScisMetaData scisMetaData) { this.scisMetaData = scisMetaData; return this; } public Builder setDeploymentRoot(final VirtualFile deploymentRoot) { this.deploymentRoot = deploymentRoot; return this; } public Builder setJaccContextId(final String jaccContextId) { this.jaccContextId = jaccContextId; return this; } public Builder setAttributes(final List<ServletContextAttribute> attributes) { this.attributes = attributes; return this; } public Builder setContextPath(final String contextPath) { this.contextPath = contextPath; return this; } public Builder setSetupActions(final List<SetupAction> setupActions) { this.setupActions = setupActions; return this; } public Builder setSecurityDomain(final String securityDomain) { this.securityDomain = securityDomain; return this; } public Builder setOverlays(final Set<VirtualFile> overlays) { this.overlays = overlays; return this; } public Builder setExpressionFactoryWrappers(final List<ExpressionFactoryWrapper> expressionFactoryWrappers) { this.expressionFactoryWrappers = expressionFactoryWrappers; return this; } public Builder setPredicatedHandlers(List<PredicatedHandler> predicatedHandlers) { this.predicatedHandlers = predicatedHandlers; return this; } public Builder setInitialHandlerChainWrappers(List<HandlerWrapper> initialHandlerChainWrappers) { this.initialHandlerChainWrappers = initialHandlerChainWrappers; return this; } public Builder setInnerHandlerChainWrappers(List<HandlerWrapper> innerHandlerChainWrappers) { this.innerHandlerChainWrappers = innerHandlerChainWrappers; return this; } public Builder setOuterHandlerChainWrappers(List<HandlerWrapper> outerHandlerChainWrappers) { this.outerHandlerChainWrappers = outerHandlerChainWrappers; return this; } public Builder setThreadSetupActions(List<ThreadSetupAction> threadSetupActions) { this.threadSetupActions = threadSetupActions; return this; } public Builder setExplodedDeployment(boolean explodedDeployment) { this.explodedDeployment = explodedDeployment; return this; } public List<ServletExtension> getServletExtensions() { return servletExtensions; } public Builder setServletExtensions(List<ServletExtension> servletExtensions) { this.servletExtensions = servletExtensions; return this; } public Builder setSharedSessionManagerConfig(SharedSessionManagerConfig sharedSessionManagerConfig) { this.sharedSessionManagerConfig = sharedSessionManagerConfig; return this; } public UndertowDeploymentInfoService createUndertowDeploymentInfoService() { return new UndertowDeploymentInfoService(mergedMetaData, deploymentName, tldsMetaData, sharedTlds, module, scisMetaData, deploymentRoot, jaccContextId, securityDomain, attributes, contextPath, setupActions, overlays, expressionFactoryWrappers, predicatedHandlers, initialHandlerChainWrappers, innerHandlerChainWrappers, outerHandlerChainWrappers, threadSetupActions, explodedDeployment, servletExtensions, sharedSessionManagerConfig); } } private static class UndertowThreadSetupAction implements ThreadSetupAction { private final Handle handle; private final SetupAction action; public UndertowThreadSetupAction(SetupAction action) { this.action = action; handle = new Handle() { @Override public void tearDown() { UndertowThreadSetupAction.this.action.teardown(Collections.<String, Object>emptyMap()); } }; } @Override public Handle setup(final HttpServerExchange exchange) { action.setup(Collections.<String, Object>emptyMap()); return handle; } } }
ServletContext.getVirtualServerName always returns "localhost" I experimented with the new getVirtualServerName method introduced for interface ServletContext in servlet spec 3.1. The JavaDoc states: Returns the primary name of the virtual host on which this context is deployed. The name may or may not be a valid host name. However Wildfly always seems to return "localhost" instead of the virtual host name specified in XML configuration files. My host config in standalone.xml looks like this: <host name="default-host" alias="www.sample.com">. I expected that getVirtualServerName returns "default-host" in this case. getVirtualServerName is implemented like this: "return deployment.getDeploymentInfo().getHostName();". However DeploymentInfo.setHostName is never called during startup. If I did not misunderstand what getVirtualServerName is supposed to deliver, something similar to my proposed patch should fix the problem. Sorry, I only looked at Wildfly source code for the first time today in a debugger and was unable to verify if my proposed patch compiles :( Hope a more experienced developer can have a quick look.
undertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java
ServletContext.getVirtualServerName always returns "localhost"
<ide><path>ndertow/src/main/java/org/wildfly/extension/undertow/deployment/UndertowDeploymentInfoService.java <ide> d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName()); <ide> } <ide> d.setDeploymentName(deploymentName); <add> d.setHostName(host.getValue().getName()); <ide> final ServletContainerService servletContainer = container.getValue(); <ide> try { <ide> //TODO: make the caching limits configurable
Java
apache-2.0
4d10ba1ebe6a738a6be4b35a25476c05d6f4c645
0
GwtMaterialDesign/gwt-material-table,GwtMaterialDesign/gwt-material-table,GwtMaterialDesign/gwt-material-table
package gwt.material.design.client.data; import gwt.material.design.client.data.component.CategoryComponent; import gwt.material.design.client.data.loader.LoadCallback; import gwt.material.design.client.data.loader.LoadConfig; import gwt.material.design.client.data.loader.LoadResult; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Map {@link DataSource} that supports infinite loading with categories. */ public class MapDataSource<T> implements DataSource<T>, HasDataView<T> { private Logger logger = Logger.getLogger(ListDataSource.class.getName()); private Map<String, List<T>> dataMap = new HashMap<>(); private DataView<T> dataView; @Override public void load(LoadConfig<T> loadConfig, LoadCallback<T> callback) { try { List<T> flatMap = new ArrayList<>(); if(dataView.isUseCategories()) { for (CategoryComponent category : loadConfig.getOpenCategories()) { flatMap.addAll(dataMap.get(category.getName())); } } else { flatMap.addAll(dataMap.get(AbstractDataView.ORPHAN_PATTERN)); } callback.onSuccess(new LoadResult<>(flatMap, loadConfig.getOffset(), flatMap.size(), cacheData())); } catch (IndexOutOfBoundsException ex) { // Silently ignore index out of bounds exceptions logger.log(Level.FINE, "ListDataSource threw index out of bounds.", ex); callback.onFailure(ex); } } public void add(Collection<T> list) { for(T item : list) { String category = null; if(dataView.isUseCategories()) { category = dataView.getRowFactory().getCategory(item); } if(category == null) { category = AbstractDataView.ORPHAN_PATTERN; } List<T> data = dataMap.computeIfAbsent(category, k -> new ArrayList<>()); data.add(item); } } public boolean cacheData() { return true; } @Override public boolean useRemoteSort() { return false; } @Override public final void setDataView(DataView<T> dataView) { this.dataView = dataView; } @Override public final DataView<T> getDataView() { return dataView; } }
src/main/java/gwt/material/design/client/data/MapDataSource.java
package gwt.material.design.client.data; import gwt.material.design.client.data.component.CategoryComponent; import gwt.material.design.client.data.loader.LoadCallback; import gwt.material.design.client.data.loader.LoadConfig; import gwt.material.design.client.data.loader.LoadResult; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * Map {@link DataSource} that supports infinite loading with categories. */ public class MapDataSource<T> implements DataSource<T>, HasDataView<T> { private Logger logger = Logger.getLogger(ListDataSource.class.getName()); private Map<String, List<T>> dataMap = new HashMap<>(); private DataView<T> dataView; @Override public void load(LoadConfig<T> loadConfig, LoadCallback<T> callback) { try { List<T> flatMap = new ArrayList<>(); if(dataView.isUseCategories()) { for (CategoryComponent category : loadConfig.getOpenCategories()) { flatMap.addAll(dataMap.get(category.getName())); } } else { flatMap.addAll(dataMap.get(AbstractDataView.ORPHAN_PATTERN)); } callback.onSuccess(new LoadResult<>(flatMap, loadConfig.getOffset(), flatMap.size(), cacheData())); } catch (IndexOutOfBoundsException ex) { // Silently ignore index out of bounds exceptions logger.log(Level.FINE, "ListDataSource threw index out of bounds.", ex); callback.onFailure(ex); } } public void add(List<T> list) { for(T item : list) { String category = null; if(dataView.isUseCategories()) { category = dataView.getRowFactory().getCategory(item); } if(category == null) { category = AbstractDataView.ORPHAN_PATTERN; } List<T> data = dataMap.computeIfAbsent(category, k -> new ArrayList<>()); data.add(item); } } public boolean cacheData() { return true; } @Override public boolean useRemoteSort() { return false; } @Override public final void setDataView(DataView<T> dataView) { this.dataView = dataView; } @Override public final DataView<T> getDataView() { return dataView; } }
Make MapDataSource#add Collection rather than List.
src/main/java/gwt/material/design/client/data/MapDataSource.java
Make MapDataSource#add Collection rather than List.
<ide><path>rc/main/java/gwt/material/design/client/data/MapDataSource.java <ide> import gwt.material.design.client.data.loader.LoadResult; <ide> <ide> import java.util.ArrayList; <add>import java.util.Collection; <ide> import java.util.HashMap; <ide> import java.util.List; <ide> import java.util.Map; <ide> } <ide> } <ide> <del> public void add(List<T> list) { <add> public void add(Collection<T> list) { <ide> for(T item : list) { <ide> String category = null; <ide> if(dataView.isUseCategories()) {
Java
apache-2.0
d50e18e95e020adbbfb18f7032fa2f841eaabe3a
0
kageiit/buck,kageiit/buck,shs96c/buck,LegNeato/buck,brettwooldridge/buck,nguyentruongtho/buck,Addepar/buck,SeleniumHQ/buck,brettwooldridge/buck,LegNeato/buck,brettwooldridge/buck,facebook/buck,shybovycha/buck,shs96c/buck,shybovycha/buck,Addepar/buck,LegNeato/buck,shs96c/buck,clonetwin26/buck,clonetwin26/buck,LegNeato/buck,ilya-klyuchnikov/buck,brettwooldridge/buck,JoelMarcey/buck,clonetwin26/buck,shs96c/buck,Addepar/buck,rmaz/buck,nguyentruongtho/buck,Addepar/buck,SeleniumHQ/buck,facebook/buck,shs96c/buck,romanoid/buck,shybovycha/buck,nguyentruongtho/buck,rmaz/buck,JoelMarcey/buck,SeleniumHQ/buck,zpao/buck,rmaz/buck,ilya-klyuchnikov/buck,kageiit/buck,romanoid/buck,brettwooldridge/buck,ilya-klyuchnikov/buck,facebook/buck,facebook/buck,SeleniumHQ/buck,shs96c/buck,rmaz/buck,LegNeato/buck,shybovycha/buck,clonetwin26/buck,shs96c/buck,Addepar/buck,clonetwin26/buck,SeleniumHQ/buck,clonetwin26/buck,shs96c/buck,Addepar/buck,SeleniumHQ/buck,romanoid/buck,clonetwin26/buck,LegNeato/buck,zpao/buck,JoelMarcey/buck,shybovycha/buck,shs96c/buck,LegNeato/buck,shybovycha/buck,Addepar/buck,clonetwin26/buck,JoelMarcey/buck,shs96c/buck,SeleniumHQ/buck,rmaz/buck,Addepar/buck,romanoid/buck,ilya-klyuchnikov/buck,shybovycha/buck,brettwooldridge/buck,shybovycha/buck,rmaz/buck,Addepar/buck,clonetwin26/buck,kageiit/buck,Addepar/buck,romanoid/buck,ilya-klyuchnikov/buck,ilya-klyuchnikov/buck,rmaz/buck,shybovycha/buck,brettwooldridge/buck,clonetwin26/buck,romanoid/buck,JoelMarcey/buck,clonetwin26/buck,clonetwin26/buck,romanoid/buck,Addepar/buck,shs96c/buck,JoelMarcey/buck,romanoid/buck,nguyentruongtho/buck,rmaz/buck,SeleniumHQ/buck,zpao/buck,SeleniumHQ/buck,LegNeato/buck,nguyentruongtho/buck,shs96c/buck,rmaz/buck,LegNeato/buck,ilya-klyuchnikov/buck,nguyentruongtho/buck,JoelMarcey/buck,kageiit/buck,LegNeato/buck,shybovycha/buck,facebook/buck,shybovycha/buck,kageiit/buck,JoelMarcey/buck,ilya-klyuchnikov/buck,JoelMarcey/buck,rmaz/buck,zpao/buck,ilya-klyuchnikov/buck,romanoid/buck,LegNeato/buck,JoelMarcey/buck,SeleniumHQ/buck,zpao/buck,brettwooldridge/buck,JoelMarcey/buck,facebook/buck,facebook/buck,LegNeato/buck,ilya-klyuchnikov/buck,romanoid/buck,brettwooldridge/buck,brettwooldridge/buck,nguyentruongtho/buck,romanoid/buck,brettwooldridge/buck,JoelMarcey/buck,zpao/buck,SeleniumHQ/buck,zpao/buck,rmaz/buck,rmaz/buck,ilya-klyuchnikov/buck,SeleniumHQ/buck,Addepar/buck,ilya-klyuchnikov/buck,ilya-klyuchnikov/buck,shs96c/buck,brettwooldridge/buck,brettwooldridge/buck,rmaz/buck,JoelMarcey/buck,romanoid/buck,Addepar/buck,LegNeato/buck,SeleniumHQ/buck,clonetwin26/buck,shybovycha/buck,kageiit/buck,shybovycha/buck,romanoid/buck
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.jvm.common.ResourceValidator; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRules; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.util.MoreCollectors; import com.facebook.buck.util.RichStream; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.nio.file.Path; import java.util.Objects; import java.util.Optional; import java.util.SortedSet; import javax.annotation.Nullable; public final class DefaultJavaLibraryBuilder { public interface DefaultJavaLibraryConstructor { DefaultJavaLibrary newInstance( BuildTarget buildTarget, final ProjectFilesystem projectFilesystem, ImmutableSortedSet<BuildRule> buildDeps, SourcePathResolver resolver, JarBuildStepsFactory jarBuildStepsFactory, Optional<SourcePath> proguardConfig, SortedSet<BuildRule> fullJarDeclaredDeps, ImmutableSortedSet<BuildRule> fullJarExportedDeps, ImmutableSortedSet<BuildRule> fullJarProvidedDeps, @Nullable BuildTarget abiJar, Optional<String> mavenCoords, ImmutableSortedSet<BuildTarget> tests, boolean requiredForSourceAbi); } protected final BuildTarget libraryTarget; protected final BuildTarget initialBuildTarget; protected final ProjectFilesystem projectFilesystem; protected final BuildRuleParams initialParams; @Nullable private final JavaBuckConfig javaBuckConfig; protected final TargetGraph targetGraph; protected final BuildRuleResolver buildRuleResolver; protected final SourcePathResolver sourcePathResolver; protected final CellPathResolver cellRoots; protected final SourcePathRuleFinder ruleFinder; protected final ConfiguredCompilerFactory configuredCompilerFactory; protected DefaultJavaLibraryConstructor constructor = DefaultJavaLibrary::new; protected ImmutableSortedSet<SourcePath> srcs = ImmutableSortedSet.of(); protected ImmutableSortedSet<SourcePath> resources = ImmutableSortedSet.of(); protected Optional<SourcePath> proguardConfig = Optional.empty(); protected ImmutableList<String> postprocessClassesCommands = ImmutableList.of(); protected Optional<Path> resourcesRoot = Optional.empty(); protected Optional<SourcePath> unbundledResourcesRoot = Optional.empty(); protected Optional<SourcePath> manifestFile = Optional.empty(); protected Optional<String> mavenCoords = Optional.empty(); protected ImmutableSortedSet<BuildTarget> tests = ImmutableSortedSet.of(); protected RemoveClassesPatternsMatcher classesToRemoveFromJar = RemoveClassesPatternsMatcher.EMPTY; protected ExtraClasspathFromContextFunction extraClasspathFromContextFunction = ExtraClasspathFromContextFunction.EMPTY; protected boolean sourceAbisAllowed = true; @Nullable protected JavacOptions initialJavacOptions = null; @Nullable protected JavaLibraryDeps deps = null; @Nullable private JavaLibraryDescription.CoreArg args = null; public DefaultJavaLibraryBuilder( TargetGraph targetGraph, BuildTarget initialBuildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams initialParams, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, ConfiguredCompilerFactory configuredCompilerFactory, @Nullable JavaBuckConfig javaBuckConfig) { libraryTarget = HasJavaAbi.isLibraryTarget(initialBuildTarget) ? initialBuildTarget : HasJavaAbi.getLibraryTarget(initialBuildTarget); this.targetGraph = targetGraph; this.initialBuildTarget = initialBuildTarget; this.projectFilesystem = projectFilesystem; this.initialParams = initialParams; this.buildRuleResolver = buildRuleResolver; this.cellRoots = cellRoots; this.configuredCompilerFactory = configuredCompilerFactory; this.javaBuckConfig = javaBuckConfig; ruleFinder = new SourcePathRuleFinder(buildRuleResolver); sourcePathResolver = DefaultSourcePathResolver.from(ruleFinder); } public DefaultJavaLibraryBuilder( TargetGraph targetGraph, BuildTarget initialBuildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams initialParams, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, ConfiguredCompilerFactory configuredCompilerFactory) { this( targetGraph, initialBuildTarget, projectFilesystem, initialParams, buildRuleResolver, cellRoots, configuredCompilerFactory, null); } public DefaultJavaLibraryBuilder setConstructor(DefaultJavaLibraryConstructor constructor) { this.constructor = constructor; return this; } public DefaultJavaLibraryBuilder setArgs(JavaLibraryDescription.CoreArg args) { this.args = args; return setSrcs(args.getSrcs()) .setResources(args.getResources()) .setResourcesRoot(args.getResourcesRoot()) .setUnbundledResourcesRoot(args.getUnbundledResourcesRoot()) .setProguardConfig(args.getProguardConfig()) .setPostprocessClassesCommands(args.getPostprocessClassesCommands()) .setDeps(JavaLibraryDeps.newInstance(args, buildRuleResolver)) .setTests(args.getTests()) .setManifestFile(args.getManifestFile()) .setMavenCoords(args.getMavenCoords()) .setSourceAbisAllowed(args.getGenerateAbiFromSource().orElse(sourceAbisAllowed)) .setClassesToRemoveFromJar(new RemoveClassesPatternsMatcher(args.getRemoveClasses())); } public DefaultJavaLibraryBuilder setDeps(JavaLibraryDeps deps) { this.deps = deps; return this; } public DefaultJavaLibraryBuilder setJavacOptions(JavacOptions javacOptions) { this.initialJavacOptions = javacOptions; return this; } public DefaultJavaLibraryBuilder setExtraClasspathFromContextFunction( ExtraClasspathFromContextFunction extraClasspathFromContextFunction) { this.extraClasspathFromContextFunction = extraClasspathFromContextFunction; return this; } public DefaultJavaLibraryBuilder setSourceAbisAllowed(boolean sourceAbisAllowed) { this.sourceAbisAllowed = sourceAbisAllowed; return this; } public DefaultJavaLibraryBuilder setSrcs(ImmutableSortedSet<SourcePath> srcs) { this.srcs = srcs; return this; } public DefaultJavaLibraryBuilder setResources(ImmutableSortedSet<SourcePath> resources) { this.resources = ResourceValidator.validateResources(sourcePathResolver, projectFilesystem, resources); return this; } public DefaultJavaLibraryBuilder setProguardConfig(Optional<SourcePath> proguardConfig) { this.proguardConfig = proguardConfig; return this; } public DefaultJavaLibraryBuilder setPostprocessClassesCommands( ImmutableList<String> postprocessClassesCommands) { this.postprocessClassesCommands = postprocessClassesCommands; return this; } public DefaultJavaLibraryBuilder setResourcesRoot(Optional<Path> resourcesRoot) { this.resourcesRoot = resourcesRoot; return this; } public DefaultJavaLibraryBuilder setUnbundledResourcesRoot( Optional<SourcePath> unbundledResourcesRoot) { this.unbundledResourcesRoot = unbundledResourcesRoot; return this; } public DefaultJavaLibraryBuilder setManifestFile(Optional<SourcePath> manifestFile) { this.manifestFile = manifestFile; return this; } public DefaultJavaLibraryBuilder setMavenCoords(Optional<String> mavenCoords) { this.mavenCoords = mavenCoords; return this; } public DefaultJavaLibraryBuilder setTests(ImmutableSortedSet<BuildTarget> tests) { this.tests = tests; return this; } public DefaultJavaLibraryBuilder setClassesToRemoveFromJar( RemoveClassesPatternsMatcher classesToRemoveFromJar) { this.classesToRemoveFromJar = classesToRemoveFromJar; return this; } @Nullable public JavaLibraryDeps getDeps() { return deps; } public final DefaultJavaLibrary build() { BuilderHelper helper = newHelper(); return helper.build(); } public final BuildRule buildAbi() { return newHelper().buildAbi(); } protected BuilderHelper newHelper() { return new BuilderHelper(); } private class BuilderHelper { @Nullable private DefaultJavaLibrary libraryRule; @Nullable private CalculateAbiFromSource sourceAbiRule; @Nullable private ImmutableSortedSet<BuildRule> finalBuildDeps; @Nullable private ImmutableSortedSet<BuildRule> finalFullJarDeclaredDeps; @Nullable private ImmutableSortedSet<BuildRule> compileTimeClasspathUnfilteredFullDeps; @Nullable private ImmutableSortedSet<BuildRule> compileTimeClasspathFullDeps; @Nullable private ImmutableSortedSet<BuildRule> compileTimeClasspathAbiDeps; @Nullable private ZipArchiveDependencySupplier abiClasspath; @Nullable private JarBuildStepsFactory jarBuildStepsFactory; @Nullable private BuildTarget abiJar; @Nullable private JavacOptions javacOptions; @Nullable private ConfiguredCompiler configuredCompiler; protected DefaultJavaLibrary build() { return getLibraryRule(false); } protected BuildRule buildAbi() { if (HasJavaAbi.isClassAbiTarget(initialBuildTarget)) { return buildAbiFromClasses(); } else if (HasJavaAbi.isSourceAbiTarget(initialBuildTarget)) { CalculateAbiFromSource abiRule = getSourceAbiRule(false); getLibraryRule(true); return abiRule; } else if (HasJavaAbi.isVerifiedSourceAbiTarget(initialBuildTarget)) { BuildRule classAbi = buildRuleResolver.requireRule(HasJavaAbi.getClassAbiJar(libraryTarget)); BuildRule sourceAbi = buildRuleResolver.requireRule(HasJavaAbi.getSourceAbiJar(libraryTarget)); return new CompareAbis( initialBuildTarget, projectFilesystem, initialParams .withDeclaredDeps(ImmutableSortedSet.of(classAbi, sourceAbi)) .withoutExtraDeps(), sourcePathResolver, classAbi.getSourcePathToOutput(), sourceAbi.getSourcePathToOutput(), javaBuckConfig.getSourceAbiVerificationMode()); } throw new AssertionError( String.format( "%s is not an ABI target but went down the ABI codepath", initialBuildTarget)); } @Nullable protected BuildTarget getAbiJar() { if (!willProduceOutputJar()) { return null; } if (abiJar == null) { if (shouldBuildAbiFromSource()) { JavaBuckConfig.SourceAbiVerificationMode sourceAbiVerificationMode = javaBuckConfig.getSourceAbiVerificationMode(); abiJar = sourceAbiVerificationMode == JavaBuckConfig.SourceAbiVerificationMode.OFF ? HasJavaAbi.getSourceAbiJar(libraryTarget) : HasJavaAbi.getVerifiedSourceAbiJar(libraryTarget); } else { abiJar = HasJavaAbi.getClassAbiJar(libraryTarget); } } return abiJar; } private boolean willProduceOutputJar() { return !srcs.isEmpty() || !resources.isEmpty() || manifestFile.isPresent(); } private boolean willProduceSourceAbi() { return willProduceOutputJar() && shouldBuildAbiFromSource(); } private boolean shouldBuildAbiFromSource() { return isCompilingJava() && !srcs.isEmpty() && sourceAbisEnabled() && sourceAbisAllowed && postprocessClassesCommands.isEmpty(); } private boolean isCompilingJava() { return getConfiguredCompiler() instanceof JavacToJarStepFactory; } private boolean sourceAbisEnabled() { return javaBuckConfig != null && javaBuckConfig.shouldGenerateAbisFromSource(); } private DefaultJavaLibrary getLibraryRule(boolean addToIndex) { if (libraryRule == null) { ImmutableSortedSet.Builder<BuildRule> buildDepsBuilder = ImmutableSortedSet.naturalOrder(); buildDepsBuilder.addAll(getFinalBuildDeps()); CalculateAbiFromSource sourceAbiRule = null; if (willProduceSourceAbi()) { sourceAbiRule = getSourceAbiRule(true); buildDepsBuilder.add(sourceAbiRule); } libraryRule = constructor.newInstance( initialBuildTarget, projectFilesystem, buildDepsBuilder.build(), sourcePathResolver, getJarBuildStepsFactory(), proguardConfig, getFinalFullJarDeclaredDeps(), Preconditions.checkNotNull(deps).getExportedDeps(), Preconditions.checkNotNull(deps).getProvidedDeps(), getAbiJar(), mavenCoords, tests, getRequiredForSourceAbi()); if (sourceAbiRule != null) { libraryRule.setSourceAbi(sourceAbiRule); } if (addToIndex) { buildRuleResolver.addToIndex(libraryRule); } } return libraryRule; } protected final boolean getRequiredForSourceAbi() { return args != null && args.getRequiredForSourceAbi(); } private CalculateAbiFromSource getSourceAbiRule(boolean addToIndex) { BuildTarget abiTarget = HasJavaAbi.getSourceAbiJar(libraryTarget); if (sourceAbiRule == null) { sourceAbiRule = new CalculateAbiFromSource( abiTarget, projectFilesystem, getFinalBuildDeps(), ruleFinder, getJarBuildStepsFactory()); if (addToIndex) { buildRuleResolver.addToIndex(sourceAbiRule); } } return sourceAbiRule; } private BuildRule buildAbiFromClasses() { BuildTarget abiTarget = HasJavaAbi.getClassAbiJar(libraryTarget); BuildRule libraryRule = buildRuleResolver.requireRule(libraryTarget); return CalculateAbiFromClasses.of( abiTarget, ruleFinder, projectFilesystem, initialParams, Preconditions.checkNotNull(libraryRule.getSourcePathToOutput()), javaBuckConfig != null && javaBuckConfig.getSourceAbiVerificationMode() != JavaBuckConfig.SourceAbiVerificationMode.OFF); } protected final ImmutableSortedSet<BuildRule> getFinalFullJarDeclaredDeps() { if (finalFullJarDeclaredDeps == null) { finalFullJarDeclaredDeps = ImmutableSortedSet.copyOf( Iterables.concat( Preconditions.checkNotNull(deps).getDeps(), getConfiguredCompiler().getDeclaredDeps(ruleFinder))); } return finalFullJarDeclaredDeps; } protected final ImmutableSortedSet<SourcePath> getFinalCompileTimeClasspathSourcePaths() { ImmutableSortedSet<BuildRule> buildRules = configuredCompilerFactory.compileAgainstAbis() ? getCompileTimeClasspathAbiDeps() : getCompileTimeClasspathFullDeps(); return buildRules .stream() .map(BuildRule::getSourcePathToOutput) .filter(Objects::nonNull) .collect(MoreCollectors.toImmutableSortedSet()); } protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathFullDeps() { if (compileTimeClasspathFullDeps == null) { compileTimeClasspathFullDeps = getCompileTimeClasspathUnfilteredFullDeps() .stream() .filter(dep -> dep instanceof HasJavaAbi) .collect(MoreCollectors.toImmutableSortedSet()); } return compileTimeClasspathFullDeps; } protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathAbiDeps() { if (compileTimeClasspathAbiDeps == null) { compileTimeClasspathAbiDeps = JavaLibraryRules.getAbiRules(buildRuleResolver, getCompileTimeClasspathFullDeps()); } return compileTimeClasspathAbiDeps; } protected final ZipArchiveDependencySupplier getAbiClasspath() { if (abiClasspath == null) { abiClasspath = new ZipArchiveDependencySupplier( ruleFinder, getCompileTimeClasspathAbiDeps() .stream() .map(BuildRule::getSourcePathToOutput) .collect(MoreCollectors.toImmutableSortedSet())); } return abiClasspath; } protected final ConfiguredCompiler getConfiguredCompiler() { if (configuredCompiler == null) { configuredCompiler = configuredCompilerFactory.configure(args, getJavacOptions(), buildRuleResolver); } return configuredCompiler; } protected final ImmutableSortedSet<BuildRule> getFinalBuildDeps() { if (finalBuildDeps == null) { ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder(); depsBuilder // We always need the non-classpath deps, whether directly specified or specified via // query .addAll( Sets.difference(initialParams.getBuildDeps(), getCompileTimeClasspathFullDeps())) .addAll( Sets.difference( getCompileTimeClasspathUnfilteredFullDeps(), getCompileTimeClasspathFullDeps())) // It's up to the compiler to use an ABI jar for these deps if appropriate, so we can // add them unconditionally .addAll(getConfiguredCompiler().getBuildDeps(ruleFinder)) // We always need the ABI deps (at least for rulekey computation) // TODO(jkeljo): It's actually incorrect to use ABIs for rulekey computation for languages // that can't compile against them. Generally the reason they can't compile against ABIs // is that the ABI generation for that language isn't fully correct. .addAll(getCompileTimeClasspathAbiDeps()); if (!configuredCompilerFactory.compileAgainstAbis()) { depsBuilder.addAll(getCompileTimeClasspathFullDeps()); } finalBuildDeps = depsBuilder.build(); } return finalBuildDeps; } protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathUnfilteredFullDeps() { if (compileTimeClasspathUnfilteredFullDeps == null) { Iterable<BuildRule> firstOrderDeps = Iterables.concat(getFinalFullJarDeclaredDeps(), deps.getProvidedDeps()); ImmutableSortedSet<BuildRule> rulesExportedByDependencies = BuildRules.getExportedRules(firstOrderDeps); compileTimeClasspathUnfilteredFullDeps = RichStream.from(Iterables.concat(firstOrderDeps, rulesExportedByDependencies)) .collect(MoreCollectors.toImmutableSortedSet()); } return compileTimeClasspathUnfilteredFullDeps; } protected final JarBuildStepsFactory getJarBuildStepsFactory() { if (jarBuildStepsFactory == null) { jarBuildStepsFactory = new JarBuildStepsFactory( projectFilesystem, ruleFinder, getConfiguredCompiler(), srcs, resources, resourcesRoot, manifestFile, postprocessClassesCommands, getAbiClasspath(), configuredCompilerFactory.trackClassUsage(getJavacOptions()), getFinalCompileTimeClasspathSourcePaths(), classesToRemoveFromJar, getRequiredForSourceAbi()); } return jarBuildStepsFactory; } protected final JavacOptions getJavacOptions() { if (javacOptions == null) { javacOptions = Preconditions.checkNotNull(initialJavacOptions); } return javacOptions; } } protected Javac getJavac() { return JavacFactory.create(ruleFinder, Preconditions.checkNotNull(javaBuckConfig), args); } }
src/com/facebook/buck/jvm/java/DefaultJavaLibraryBuilder.java
/* * Copyright 2017-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.jvm.java; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.jvm.common.ResourceValidator; import com.facebook.buck.model.BuildTarget; import com.facebook.buck.rules.BuildRule; import com.facebook.buck.rules.BuildRuleParams; import com.facebook.buck.rules.BuildRuleResolver; import com.facebook.buck.rules.BuildRules; import com.facebook.buck.rules.CellPathResolver; import com.facebook.buck.rules.DefaultSourcePathResolver; import com.facebook.buck.rules.SourcePath; import com.facebook.buck.rules.SourcePathResolver; import com.facebook.buck.rules.SourcePathRuleFinder; import com.facebook.buck.rules.TargetGraph; import com.facebook.buck.util.MoreCollectors; import com.facebook.buck.util.RichStream; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.nio.file.Path; import java.util.Objects; import java.util.Optional; import java.util.SortedSet; import javax.annotation.Nullable; public final class DefaultJavaLibraryBuilder { public interface DefaultJavaLibraryConstructor { DefaultJavaLibrary newInstance( BuildTarget buildTarget, final ProjectFilesystem projectFilesystem, ImmutableSortedSet<BuildRule> buildDeps, SourcePathResolver resolver, JarBuildStepsFactory jarBuildStepsFactory, Optional<SourcePath> proguardConfig, SortedSet<BuildRule> fullJarDeclaredDeps, ImmutableSortedSet<BuildRule> fullJarExportedDeps, ImmutableSortedSet<BuildRule> fullJarProvidedDeps, @Nullable BuildTarget abiJar, Optional<String> mavenCoords, ImmutableSortedSet<BuildTarget> tests, boolean requiredForSourceAbi); } protected final BuildTarget libraryTarget; protected final BuildTarget initialBuildTarget; protected final ProjectFilesystem projectFilesystem; protected final BuildRuleParams initialParams; @Nullable private final JavaBuckConfig javaBuckConfig; protected final TargetGraph targetGraph; protected final BuildRuleResolver buildRuleResolver; protected final SourcePathResolver sourcePathResolver; protected final CellPathResolver cellRoots; protected final SourcePathRuleFinder ruleFinder; protected final ConfiguredCompilerFactory configuredCompilerFactory; protected DefaultJavaLibraryConstructor constructor = DefaultJavaLibrary::new; protected ImmutableSortedSet<SourcePath> srcs = ImmutableSortedSet.of(); protected ImmutableSortedSet<SourcePath> resources = ImmutableSortedSet.of(); protected Optional<SourcePath> proguardConfig = Optional.empty(); protected ImmutableList<String> postprocessClassesCommands = ImmutableList.of(); protected Optional<Path> resourcesRoot = Optional.empty(); protected Optional<SourcePath> unbundledResourcesRoot = Optional.empty(); protected Optional<SourcePath> manifestFile = Optional.empty(); protected Optional<String> mavenCoords = Optional.empty(); protected ImmutableSortedSet<BuildTarget> tests = ImmutableSortedSet.of(); protected RemoveClassesPatternsMatcher classesToRemoveFromJar = RemoveClassesPatternsMatcher.EMPTY; protected ExtraClasspathFromContextFunction extraClasspathFromContextFunction = ExtraClasspathFromContextFunction.EMPTY; protected boolean sourceAbisAllowed = true; @Nullable protected JavacOptions initialJavacOptions = null; @Nullable protected JavaLibraryDeps deps = null; @Nullable private JavaLibraryDescription.CoreArg args = null; public DefaultJavaLibraryBuilder( TargetGraph targetGraph, BuildTarget initialBuildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams initialParams, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, ConfiguredCompilerFactory configuredCompilerFactory, @Nullable JavaBuckConfig javaBuckConfig) { libraryTarget = HasJavaAbi.isLibraryTarget(initialBuildTarget) ? initialBuildTarget : HasJavaAbi.getLibraryTarget(initialBuildTarget); this.targetGraph = targetGraph; this.initialBuildTarget = initialBuildTarget; this.projectFilesystem = projectFilesystem; this.initialParams = initialParams; this.buildRuleResolver = buildRuleResolver; this.cellRoots = cellRoots; this.configuredCompilerFactory = configuredCompilerFactory; this.javaBuckConfig = javaBuckConfig; ruleFinder = new SourcePathRuleFinder(buildRuleResolver); sourcePathResolver = DefaultSourcePathResolver.from(ruleFinder); } public DefaultJavaLibraryBuilder( TargetGraph targetGraph, BuildTarget initialBuildTarget, ProjectFilesystem projectFilesystem, BuildRuleParams initialParams, BuildRuleResolver buildRuleResolver, CellPathResolver cellRoots, ConfiguredCompilerFactory configuredCompilerFactory) { this( targetGraph, initialBuildTarget, projectFilesystem, initialParams, buildRuleResolver, cellRoots, configuredCompilerFactory, null); } public DefaultJavaLibraryBuilder setConstructor(DefaultJavaLibraryConstructor constructor) { this.constructor = constructor; return this; } public DefaultJavaLibraryBuilder setArgs(JavaLibraryDescription.CoreArg args) { this.args = args; return setSrcs(args.getSrcs()) .setResources(args.getResources()) .setResourcesRoot(args.getResourcesRoot()) .setUnbundledResourcesRoot(args.getUnbundledResourcesRoot()) .setProguardConfig(args.getProguardConfig()) .setPostprocessClassesCommands(args.getPostprocessClassesCommands()) .setDeps(JavaLibraryDeps.newInstance(args, buildRuleResolver)) .setTests(args.getTests()) .setManifestFile(args.getManifestFile()) .setMavenCoords(args.getMavenCoords()) .setSourceAbisAllowed(args.getGenerateAbiFromSource().orElse(sourceAbisAllowed)) .setClassesToRemoveFromJar(new RemoveClassesPatternsMatcher(args.getRemoveClasses())); } public DefaultJavaLibraryBuilder setDeps(JavaLibraryDeps deps) { this.deps = deps; return this; } public DefaultJavaLibraryBuilder setJavacOptions(JavacOptions javacOptions) { this.initialJavacOptions = javacOptions; return this; } public DefaultJavaLibraryBuilder setExtraClasspathFromContextFunction( ExtraClasspathFromContextFunction extraClasspathFromContextFunction) { this.extraClasspathFromContextFunction = extraClasspathFromContextFunction; return this; } public DefaultJavaLibraryBuilder setSourceAbisAllowed(boolean sourceAbisAllowed) { this.sourceAbisAllowed = sourceAbisAllowed; return this; } public DefaultJavaLibraryBuilder setSrcs(ImmutableSortedSet<SourcePath> srcs) { this.srcs = srcs; return this; } public DefaultJavaLibraryBuilder setResources(ImmutableSortedSet<SourcePath> resources) { this.resources = ResourceValidator.validateResources(sourcePathResolver, projectFilesystem, resources); return this; } public DefaultJavaLibraryBuilder setProguardConfig(Optional<SourcePath> proguardConfig) { this.proguardConfig = proguardConfig; return this; } public DefaultJavaLibraryBuilder setPostprocessClassesCommands( ImmutableList<String> postprocessClassesCommands) { this.postprocessClassesCommands = postprocessClassesCommands; return this; } public DefaultJavaLibraryBuilder setResourcesRoot(Optional<Path> resourcesRoot) { this.resourcesRoot = resourcesRoot; return this; } public DefaultJavaLibraryBuilder setUnbundledResourcesRoot( Optional<SourcePath> unbundledResourcesRoot) { this.unbundledResourcesRoot = unbundledResourcesRoot; return this; } public DefaultJavaLibraryBuilder setManifestFile(Optional<SourcePath> manifestFile) { this.manifestFile = manifestFile; return this; } public DefaultJavaLibraryBuilder setMavenCoords(Optional<String> mavenCoords) { this.mavenCoords = mavenCoords; return this; } public DefaultJavaLibraryBuilder setTests(ImmutableSortedSet<BuildTarget> tests) { this.tests = tests; return this; } public DefaultJavaLibraryBuilder setClassesToRemoveFromJar( RemoveClassesPatternsMatcher classesToRemoveFromJar) { this.classesToRemoveFromJar = classesToRemoveFromJar; return this; } @Nullable public JavaLibraryDeps getDeps() { return deps; } public final DefaultJavaLibrary build() { BuilderHelper helper = newHelper(); return helper.build(); } public final BuildRule buildAbi() { return newHelper().buildAbi(); } protected BuilderHelper newHelper() { return new BuilderHelper(); } private class BuilderHelper { @Nullable private DefaultJavaLibrary libraryRule; @Nullable private CalculateAbiFromSource sourceAbiRule; @Nullable private ImmutableSortedSet<BuildRule> finalBuildDeps; @Nullable private ImmutableSortedSet<BuildRule> finalFullJarDeclaredDeps; @Nullable private ImmutableSortedSet<BuildRule> compileTimeClasspathUnfilteredFullDeps; @Nullable private ImmutableSortedSet<BuildRule> compileTimeClasspathFullDeps; @Nullable private ImmutableSortedSet<BuildRule> compileTimeClasspathAbiDeps; @Nullable private ZipArchiveDependencySupplier abiClasspath; @Nullable private JarBuildStepsFactory jarBuildStepsFactory; @Nullable private BuildTarget abiJar; @Nullable private JavacOptions javacOptions; @Nullable private ConfiguredCompiler configuredCompiler; protected DefaultJavaLibrary build() { return getLibraryRule(false); } protected BuildRule buildAbi() { if (HasJavaAbi.isClassAbiTarget(initialBuildTarget)) { return buildAbiFromClasses(); } else if (HasJavaAbi.isSourceAbiTarget(initialBuildTarget)) { CalculateAbiFromSource abiRule = getSourceAbiRule(false); getLibraryRule(true); return abiRule; } else if (HasJavaAbi.isVerifiedSourceAbiTarget(initialBuildTarget)) { BuildRule classAbi = buildRuleResolver.requireRule(HasJavaAbi.getClassAbiJar(libraryTarget)); BuildRule sourceAbi = buildRuleResolver.requireRule(HasJavaAbi.getSourceAbiJar(libraryTarget)); return new CompareAbis( initialBuildTarget, projectFilesystem, initialParams .withDeclaredDeps(ImmutableSortedSet.of(classAbi, sourceAbi)) .withoutExtraDeps(), sourcePathResolver, classAbi.getSourcePathToOutput(), sourceAbi.getSourcePathToOutput(), javaBuckConfig.getSourceAbiVerificationMode()); } throw new AssertionError( String.format( "%s is not an ABI target but went down the ABI codepath", initialBuildTarget)); } @Nullable protected BuildTarget getAbiJar() { if (!willProduceOutputJar()) { return null; } if (abiJar == null) { if (shouldBuildAbiFromSource()) { JavaBuckConfig.SourceAbiVerificationMode sourceAbiVerificationMode = javaBuckConfig.getSourceAbiVerificationMode(); abiJar = sourceAbiVerificationMode == JavaBuckConfig.SourceAbiVerificationMode.OFF ? HasJavaAbi.getSourceAbiJar(libraryTarget) : HasJavaAbi.getVerifiedSourceAbiJar(libraryTarget); } else { abiJar = HasJavaAbi.getClassAbiJar(libraryTarget); } } return abiJar; } private boolean willProduceOutputJar() { return !srcs.isEmpty() || !resources.isEmpty() || manifestFile.isPresent(); } private boolean willProduceSourceAbi() { return willProduceOutputJar() && shouldBuildAbiFromSource(); } private boolean shouldBuildAbiFromSource() { return isCompilingJava() && !srcs.isEmpty() && sourceAbisEnabled() && sourceAbisAllowed && postprocessClassesCommands.isEmpty(); } private boolean isCompilingJava() { return getConfiguredCompiler() instanceof JavacToJarStepFactory; } private boolean sourceAbisEnabled() { return javaBuckConfig != null && javaBuckConfig.shouldGenerateAbisFromSource(); } private DefaultJavaLibrary getLibraryRule(boolean addToIndex) { if (libraryRule == null) { ImmutableSortedSet.Builder<BuildRule> buildDepsBuilder = ImmutableSortedSet.naturalOrder(); buildDepsBuilder.addAll(getFinalBuildDeps()); CalculateAbiFromSource sourceAbiRule = null; if (willProduceSourceAbi()) { sourceAbiRule = getSourceAbiRule(true); buildDepsBuilder.add(sourceAbiRule); } libraryRule = constructor.newInstance( initialBuildTarget, projectFilesystem, buildDepsBuilder.build(), sourcePathResolver, getJarBuildStepsFactory(), proguardConfig, getFinalFullJarDeclaredDeps(), Preconditions.checkNotNull(deps).getExportedDeps(), Preconditions.checkNotNull(deps).getProvidedDeps(), getAbiJar(), mavenCoords, tests, getRequiredForSourceAbi()); if (sourceAbiRule != null) { libraryRule.setSourceAbi(sourceAbiRule); } if (addToIndex) { buildRuleResolver.addToIndex(libraryRule); } } return libraryRule; } protected final boolean getRequiredForSourceAbi() { return args != null && args.getRequiredForSourceAbi(); } private CalculateAbiFromSource getSourceAbiRule(boolean addToIndex) { BuildTarget abiTarget = HasJavaAbi.getSourceAbiJar(libraryTarget); if (sourceAbiRule == null) { sourceAbiRule = new CalculateAbiFromSource( abiTarget, projectFilesystem, getFinalBuildDeps(), ruleFinder, getJarBuildStepsFactory()); if (addToIndex) { buildRuleResolver.addToIndex(sourceAbiRule); } } return sourceAbiRule; } private BuildRule buildAbiFromClasses() { BuildTarget abiTarget = HasJavaAbi.getClassAbiJar(libraryTarget); BuildRule libraryRule = buildRuleResolver.requireRule(libraryTarget); return CalculateAbiFromClasses.of( abiTarget, ruleFinder, projectFilesystem, initialParams, Preconditions.checkNotNull(libraryRule.getSourcePathToOutput()), javaBuckConfig != null && javaBuckConfig.getSourceAbiVerificationMode() != JavaBuckConfig.SourceAbiVerificationMode.OFF); } protected final ImmutableSortedSet<BuildRule> getFinalFullJarDeclaredDeps() { if (finalFullJarDeclaredDeps == null) { finalFullJarDeclaredDeps = buildFinalFullJarDeclaredDeps(); } return finalFullJarDeclaredDeps; } protected ImmutableSortedSet<BuildRule> buildFinalFullJarDeclaredDeps() { return ImmutableSortedSet.copyOf( Iterables.concat( Preconditions.checkNotNull(deps).getDeps(), getConfiguredCompiler().getDeclaredDeps(ruleFinder))); } protected final ImmutableSortedSet<SourcePath> getFinalCompileTimeClasspathSourcePaths() { ImmutableSortedSet<BuildRule> buildRules = configuredCompilerFactory.compileAgainstAbis() ? getCompileTimeClasspathAbiDeps() : getCompileTimeClasspathFullDeps(); return buildRules .stream() .map(BuildRule::getSourcePathToOutput) .filter(Objects::nonNull) .collect(MoreCollectors.toImmutableSortedSet()); } protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathFullDeps() { if (compileTimeClasspathFullDeps == null) { compileTimeClasspathFullDeps = getCompileTimeClasspathUnfilteredFullDeps() .stream() .filter(dep -> dep instanceof HasJavaAbi) .collect(MoreCollectors.toImmutableSortedSet()); } return compileTimeClasspathFullDeps; } protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathAbiDeps() { if (compileTimeClasspathAbiDeps == null) { compileTimeClasspathAbiDeps = buildCompileTimeClasspathAbiDeps(); } return compileTimeClasspathAbiDeps; } protected final ZipArchiveDependencySupplier getAbiClasspath() { if (abiClasspath == null) { abiClasspath = buildAbiClasspath(); } return abiClasspath; } protected final ConfiguredCompiler getConfiguredCompiler() { if (configuredCompiler == null) { configuredCompiler = buildConfiguredCompiler(); } return configuredCompiler; } protected final ImmutableSortedSet<BuildRule> getFinalBuildDeps() { if (finalBuildDeps == null) { ImmutableSortedSet.Builder<BuildRule> depsBuilder = ImmutableSortedSet.naturalOrder(); depsBuilder // We always need the non-classpath deps, whether directly specified or specified via // query .addAll( Sets.difference(initialParams.getBuildDeps(), getCompileTimeClasspathFullDeps())) .addAll( Sets.difference( getCompileTimeClasspathUnfilteredFullDeps(), getCompileTimeClasspathFullDeps())) // It's up to the compiler to use an ABI jar for these deps if appropriate, so we can // add them unconditionally .addAll(getConfiguredCompiler().getBuildDeps(ruleFinder)) // We always need the ABI deps (at least for rulekey computation) // TODO(jkeljo): It's actually incorrect to use ABIs for rulekey computation for languages // that can't compile against them. Generally the reason they can't compile against ABIs // is that the ABI generation for that language isn't fully correct. .addAll(getCompileTimeClasspathAbiDeps()); if (!configuredCompilerFactory.compileAgainstAbis()) { depsBuilder.addAll(getCompileTimeClasspathFullDeps()); } finalBuildDeps = depsBuilder.build(); } return finalBuildDeps; } protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathUnfilteredFullDeps() { if (compileTimeClasspathUnfilteredFullDeps == null) { Iterable<BuildRule> firstOrderDeps = Iterables.concat(getFinalFullJarDeclaredDeps(), deps.getProvidedDeps()); ImmutableSortedSet<BuildRule> rulesExportedByDependencies = BuildRules.getExportedRules(firstOrderDeps); compileTimeClasspathUnfilteredFullDeps = RichStream.from(Iterables.concat(firstOrderDeps, rulesExportedByDependencies)) .collect(MoreCollectors.toImmutableSortedSet()); } return compileTimeClasspathUnfilteredFullDeps; } protected ImmutableSortedSet<BuildRule> buildCompileTimeClasspathAbiDeps() { return JavaLibraryRules.getAbiRules(buildRuleResolver, getCompileTimeClasspathFullDeps()); } protected ZipArchiveDependencySupplier buildAbiClasspath() { return new ZipArchiveDependencySupplier( ruleFinder, getCompileTimeClasspathAbiDeps() .stream() .map(BuildRule::getSourcePathToOutput) .collect(MoreCollectors.toImmutableSortedSet())); } protected ConfiguredCompiler buildConfiguredCompiler() { return configuredCompilerFactory.configure(args, getJavacOptions(), buildRuleResolver); } protected final JarBuildStepsFactory getJarBuildStepsFactory() { if (jarBuildStepsFactory == null) { jarBuildStepsFactory = buildJarBuildStepsFactory(); } return jarBuildStepsFactory; } protected JarBuildStepsFactory buildJarBuildStepsFactory() { return new JarBuildStepsFactory( projectFilesystem, ruleFinder, getConfiguredCompiler(), srcs, resources, resourcesRoot, manifestFile, postprocessClassesCommands, getAbiClasspath(), configuredCompilerFactory.trackClassUsage(getJavacOptions()), getFinalCompileTimeClasspathSourcePaths(), classesToRemoveFromJar, getRequiredForSourceAbi()); } protected final JavacOptions getJavacOptions() { if (javacOptions == null) { javacOptions = buildJavacOptions(); } return javacOptions; } protected JavacOptions buildJavacOptions() { return Preconditions.checkNotNull(initialJavacOptions); } } protected Javac getJavac() { return JavacFactory.create(ruleFinder, Preconditions.checkNotNull(javaBuckConfig), args); } }
DefaultJavaLibraryBuilder: Inline a bunch of `buildXXX` methods. Summary: These were intended to be overridden by the now-no-longer-needed subclasses. Test Plan: CI Reviewed By: asp2insp fbshipit-source-id: 2d7085e
src/com/facebook/buck/jvm/java/DefaultJavaLibraryBuilder.java
DefaultJavaLibraryBuilder: Inline a bunch of `buildXXX` methods.
<ide><path>rc/com/facebook/buck/jvm/java/DefaultJavaLibraryBuilder.java <ide> <ide> protected final ImmutableSortedSet<BuildRule> getFinalFullJarDeclaredDeps() { <ide> if (finalFullJarDeclaredDeps == null) { <del> finalFullJarDeclaredDeps = buildFinalFullJarDeclaredDeps(); <add> finalFullJarDeclaredDeps = <add> ImmutableSortedSet.copyOf( <add> Iterables.concat( <add> Preconditions.checkNotNull(deps).getDeps(), <add> getConfiguredCompiler().getDeclaredDeps(ruleFinder))); <ide> } <ide> <ide> return finalFullJarDeclaredDeps; <del> } <del> <del> protected ImmutableSortedSet<BuildRule> buildFinalFullJarDeclaredDeps() { <del> return ImmutableSortedSet.copyOf( <del> Iterables.concat( <del> Preconditions.checkNotNull(deps).getDeps(), <del> getConfiguredCompiler().getDeclaredDeps(ruleFinder))); <ide> } <ide> <ide> protected final ImmutableSortedSet<SourcePath> getFinalCompileTimeClasspathSourcePaths() { <ide> <ide> protected final ImmutableSortedSet<BuildRule> getCompileTimeClasspathAbiDeps() { <ide> if (compileTimeClasspathAbiDeps == null) { <del> compileTimeClasspathAbiDeps = buildCompileTimeClasspathAbiDeps(); <add> compileTimeClasspathAbiDeps = <add> JavaLibraryRules.getAbiRules(buildRuleResolver, getCompileTimeClasspathFullDeps()); <ide> } <ide> <ide> return compileTimeClasspathAbiDeps; <ide> <ide> protected final ZipArchiveDependencySupplier getAbiClasspath() { <ide> if (abiClasspath == null) { <del> abiClasspath = buildAbiClasspath(); <add> abiClasspath = <add> new ZipArchiveDependencySupplier( <add> ruleFinder, <add> getCompileTimeClasspathAbiDeps() <add> .stream() <add> .map(BuildRule::getSourcePathToOutput) <add> .collect(MoreCollectors.toImmutableSortedSet())); <ide> } <ide> <ide> return abiClasspath; <ide> <ide> protected final ConfiguredCompiler getConfiguredCompiler() { <ide> if (configuredCompiler == null) { <del> configuredCompiler = buildConfiguredCompiler(); <add> configuredCompiler = <add> configuredCompilerFactory.configure(args, getJavacOptions(), buildRuleResolver); <ide> } <ide> <ide> return configuredCompiler; <ide> return compileTimeClasspathUnfilteredFullDeps; <ide> } <ide> <del> protected ImmutableSortedSet<BuildRule> buildCompileTimeClasspathAbiDeps() { <del> return JavaLibraryRules.getAbiRules(buildRuleResolver, getCompileTimeClasspathFullDeps()); <del> } <del> <del> protected ZipArchiveDependencySupplier buildAbiClasspath() { <del> return new ZipArchiveDependencySupplier( <del> ruleFinder, <del> getCompileTimeClasspathAbiDeps() <del> .stream() <del> .map(BuildRule::getSourcePathToOutput) <del> .collect(MoreCollectors.toImmutableSortedSet())); <del> } <del> <del> protected ConfiguredCompiler buildConfiguredCompiler() { <del> return configuredCompilerFactory.configure(args, getJavacOptions(), buildRuleResolver); <del> } <del> <ide> protected final JarBuildStepsFactory getJarBuildStepsFactory() { <ide> if (jarBuildStepsFactory == null) { <del> jarBuildStepsFactory = buildJarBuildStepsFactory(); <add> jarBuildStepsFactory = <add> new JarBuildStepsFactory( <add> projectFilesystem, <add> ruleFinder, <add> getConfiguredCompiler(), <add> srcs, <add> resources, <add> resourcesRoot, <add> manifestFile, <add> postprocessClassesCommands, <add> getAbiClasspath(), <add> configuredCompilerFactory.trackClassUsage(getJavacOptions()), <add> getFinalCompileTimeClasspathSourcePaths(), <add> classesToRemoveFromJar, <add> getRequiredForSourceAbi()); <ide> } <ide> return jarBuildStepsFactory; <del> } <del> <del> protected JarBuildStepsFactory buildJarBuildStepsFactory() { <del> return new JarBuildStepsFactory( <del> projectFilesystem, <del> ruleFinder, <del> getConfiguredCompiler(), <del> srcs, <del> resources, <del> resourcesRoot, <del> manifestFile, <del> postprocessClassesCommands, <del> getAbiClasspath(), <del> configuredCompilerFactory.trackClassUsage(getJavacOptions()), <del> getFinalCompileTimeClasspathSourcePaths(), <del> classesToRemoveFromJar, <del> getRequiredForSourceAbi()); <ide> } <ide> <ide> protected final JavacOptions getJavacOptions() { <ide> if (javacOptions == null) { <del> javacOptions = buildJavacOptions(); <add> javacOptions = Preconditions.checkNotNull(initialJavacOptions); <ide> } <ide> return javacOptions; <del> } <del> <del> protected JavacOptions buildJavacOptions() { <del> return Preconditions.checkNotNull(initialJavacOptions); <ide> } <ide> } <ide>
Java
apache-2.0
068827e6b7d1eec9884e56bcb91e31f8439877a9
0
gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom,gchq/stroom
/* * Copyright 2016 Crown Copyright * * 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 stroom.query.api; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import stroom.util.shared.HasDisplayValue; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; import java.util.Arrays; @JsonPropertyOrder({"op", "children"}) @XmlType(name = "ExpressionOperator", propOrder = {"op", "children"}) public class ExpressionOperator extends ExpressionItem { private static final long serialVersionUID = 6602004424564268512L; private Op op = Op.AND; private ExpressionItem[] children; public ExpressionOperator() { } public ExpressionOperator(final Boolean enabled, final Op op, final ExpressionItem[] children) { super(enabled); this.op = op; this.children = children; } @XmlElement(name = "op") public Op getOp() { return op; } public void setOp(final Op op) { this.op = op; } @XmlElementWrapper(name = "children") @XmlElements({ @XmlElement(name = "operator", type = ExpressionOperator.class), @XmlElement(name = "term", type = ExpressionTerm.class) }) public ExpressionItem[] getChildren() { return children; } public void setChildren(final ExpressionItem[] children) { this.children = children; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; final ExpressionOperator that = (ExpressionOperator) o; if (op != that.op) return false; // Probably incorrect - comparing Object[] arrays with Arrays.equals return Arrays.equals(children, that.children); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (op != null ? op.hashCode() : 0); result = 31 * result + Arrays.hashCode(children); return result; } @Override public void append(final StringBuilder sb, final String pad, final boolean singleLine) { if (enabled()) { if (!singleLine && sb.length() > 0) { sb.append("\n"); sb.append(pad); } sb.append(op); if (singleLine) { sb.append(" {"); } if (children != null) { final String padding = pad + " "; for (final ExpressionItem expressionItem : children) { if (expressionItem.enabled()) { if (!singleLine) { sb.append("\n"); sb.append(pad); } expressionItem.append(sb, padding, singleLine); if (singleLine) { sb.append(", "); } } } if (singleLine) { sb.setLength(sb.length() - ", ".length()); } } if (singleLine) { sb.append("} "); } } } public enum Op implements HasDisplayValue { AND("AND"), OR("OR"), NOT("NOT"); private final String displayValue; Op(final String displayValue) { this.displayValue = displayValue; } @Override public String getDisplayValue() { return displayValue; } } }
stroom-query-api/src/main/java/stroom/query/api/ExpressionOperator.java
/* * Copyright 2016 Crown Copyright * * 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 stroom.query.api; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import stroom.util.shared.HasDisplayValue; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlType; @JsonPropertyOrder({"op", "children"}) @XmlType(name = "ExpressionOperator", propOrder = {"op", "children"}) public class ExpressionOperator extends ExpressionItem { private static final long serialVersionUID = 6602004424564268512L; private Op op = Op.AND; private ExpressionItem[] children; public ExpressionOperator() { } public ExpressionOperator(final Boolean enabled, final Op op, final ExpressionItem[] children) { super(enabled); this.op = op; this.children = children; } @XmlElement(name = "op") public Op getOp() { return op; } public void setOp(final Op op) { this.op = op; } @XmlElementWrapper(name = "children") @XmlElements({ @XmlElement(name = "operator", type = ExpressionOperator.class), @XmlElement(name = "term", type = ExpressionTerm.class) }) public ExpressionItem[] getChildren() { return children; } public void setChildren(final ExpressionItem[] children) { this.children = children; } @Override public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; if (!super.equals(o)) return false; final ExpressionOperator that = (ExpressionOperator) o; if (op != that.op) return false; return children != null ? children.equals(that.children) : that.children == null; } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + (op != null ? op.hashCode() : 0); result = 31 * result + (children != null ? children.hashCode() : 0); return result; } @Override public void append(final StringBuilder sb, final String pad, final boolean singleLine) { if (enabled()) { if (!singleLine && sb.length() > 0) { sb.append("\n"); sb.append(pad); } sb.append(op); if (singleLine) { sb.append(" {"); } if (children != null) { final String padding = pad + " "; for (final ExpressionItem expressionItem : children) { if (expressionItem.enabled()) { if (!singleLine) { sb.append("\n"); sb.append(pad); } expressionItem.append(sb, padding, singleLine); if (singleLine) { sb.append(", "); } } } if (singleLine) { sb.setLength(sb.length() - ", ".length()); } } if (singleLine) { sb.append("} "); } } } public enum Op implements HasDisplayValue { AND("AND"), OR("OR"), NOT("NOT"); private final String displayValue; Op(final String displayValue) { this.displayValue = displayValue; } @Override public String getDisplayValue() { return displayValue; } } }
Fixed equality
stroom-query-api/src/main/java/stroom/query/api/ExpressionOperator.java
Fixed equality
<ide><path>troom-query-api/src/main/java/stroom/query/api/ExpressionOperator.java <ide> import javax.xml.bind.annotation.XmlElementWrapper; <ide> import javax.xml.bind.annotation.XmlElements; <ide> import javax.xml.bind.annotation.XmlType; <add>import java.util.Arrays; <ide> <ide> @JsonPropertyOrder({"op", "children"}) <ide> @XmlType(name = "ExpressionOperator", propOrder = {"op", "children"}) <ide> final ExpressionOperator that = (ExpressionOperator) o; <ide> <ide> if (op != that.op) return false; <del> return children != null ? children.equals(that.children) : that.children == null; <add> // Probably incorrect - comparing Object[] arrays with Arrays.equals <add> return Arrays.equals(children, that.children); <ide> } <ide> <ide> @Override <ide> public int hashCode() { <ide> int result = super.hashCode(); <ide> result = 31 * result + (op != null ? op.hashCode() : 0); <del> result = 31 * result + (children != null ? children.hashCode() : 0); <add> result = 31 * result + Arrays.hashCode(children); <ide> return result; <ide> } <ide>
JavaScript
mit
b0c1bc975a8de47687199a3d5895b6f94c892dff
0
jonschlinkert/deep-filter-object
'use strict'; var filterObject = require('filter-object'); var isObject = require('isobject'); /** * Expose `deepFilter` */ module.exports = deepFilter; function deepFilter(obj, patterns, options, i) { if (obj == null) { throw new Error('deep-filter-object expects an object'); } if (arguments.length === 1) return obj; obj = filterObject(obj, patterns, options); var res = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = obj[key]; if (isObject(value)) { res[key] = deepFilter(value, patterns, options); } else { res[key] = value; } } } return res; };
index.js
'use strict'; var filterObject = require('filter-object'); var isObject = require('isobject'); module.exports = function deepFilter(obj, patterns) { if (obj == null) { throw new Error('deep-filter-object expects an object'); } if (arguments.length === 1) { return obj; } obj = filterObject(obj, patterns); var o = {}; for (var key in obj) { if (obj.hasOwnProperty(key)) { var value = obj[key]; if (isObject(value)) { o[key] = deepFilter(value, patterns); } else { o[key] = value; } } } return o; };
optimizations, pass options to filter-object
index.js
optimizations, pass options to filter-object
<ide><path>ndex.js <ide> var filterObject = require('filter-object'); <ide> var isObject = require('isobject'); <ide> <del>module.exports = function deepFilter(obj, patterns) { <add>/** <add> * Expose `deepFilter` <add> */ <add> <add>module.exports = deepFilter; <add> <add> <add>function deepFilter(obj, patterns, options, i) { <ide> if (obj == null) { <ide> throw new Error('deep-filter-object expects an object'); <ide> } <del> if (arguments.length === 1) { <del> return obj; <del> } <ide> <del> obj = filterObject(obj, patterns); <del> var o = {}; <add> if (arguments.length === 1) return obj; <add> <add> obj = filterObject(obj, patterns, options); <add> var res = {}; <ide> <ide> for (var key in obj) { <ide> if (obj.hasOwnProperty(key)) { <ide> var value = obj[key]; <ide> <ide> if (isObject(value)) { <del> o[key] = deepFilter(value, patterns); <add> res[key] = deepFilter(value, patterns, options); <ide> } else { <del> o[key] = value; <add> res[key] = value; <ide> } <ide> } <ide> } <del> return o; <add> return res; <ide> };
Java
apache-2.0
3004ebf520dd3aeaa158a4ea3908de512b2e41dd
0
MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab
package org.myrobotlab.service; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.repo.ServiceType; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.I2CControl; import org.slf4j.Logger; /** * * MPU6050 - MPU-6050 sensor contains a MEMS accelerometer and a MEMS gyro in a single chip. * It is very accurate, as it contains 16-bits analog to digital conversion hardware for each channel. * Therefore it captures the x, y, and z channel at the same time. * http://playground.arduino.cc/Main/MPU-6050 * */ public class Mpu6050 extends Service{ private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Mpu6050.class); StringBuilder debugRX = new StringBuilder(); transient I2CControl controller; // Default i2cAddress public int busAddress = 1; public int deviceAddress = 0x68; public String type = "MPU-6050"; public static final int MPU6050_ADDRESS_AD0_LOW = 0x68; // address pin low (GND), default for InvenSense evaluation board public static final int MPU6050_ADDRESS_AD0_HIGH = 0x69; // address pin high (VCC) public static final int MPU6050_DEFAULT_ADDRESS = MPU6050_ADDRESS_AD0_LOW; public static final int MPU6050_RA_XG_OFFS_TC = 0x00; //[7] PWR_MODE, [6:1] XG_OFFS_TC, [0] OTP_BNK_VLD public static final int MPU6050_RA_YG_OFFS_TC = 0x01; //[7] PWR_MODE, [6:1] YG_OFFS_TC, [0] OTP_BNK_VLD public static final int MPU6050_RA_ZG_OFFS_TC = 0x02; //[7] PWR_MODE, [6:1] ZG_OFFS_TC, [0] OTP_BNK_VLD public static final int MPU6050_RA_X_FINE_GAIN = 0x03; //[7:0] X_FINE_GAIN public static final int MPU6050_RA_Y_FINE_GAIN = 0x04; //[7:0] Y_FINE_GAIN public static final int MPU6050_RA_Z_FINE_GAIN = 0x05; //[7:0] Z_FINE_GAIN public static final int MPU6050_RA_XA_OFFS_H = 0x06; //[15:0] XA_OFFS public static final int MPU6050_RA_XA_OFFS_L_TC = 0x07; public static final int MPU6050_RA_YA_OFFS_H = 0x08; //[15:0] YA_OFFS public static final int MPU6050_RA_YA_OFFS_L_TC = 0x09; public static final int MPU6050_RA_ZA_OFFS_H = 0x0A; //[15:0] ZA_OFFS public static final int MPU6050_RA_ZA_OFFS_L_TC = 0x0B; public static final int MPU6050_RA_SELF_TEST_X = 0x0D; //[7:5] XA_TEST[4-2], [4:0] XG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_Y = 0x0E; //[7:5] YA_TEST[4-2], [4:0] YG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_Z = 0x0F; //[7:5] ZA_TEST[4-2], [4:0] ZG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_A = 0x10; //[5:4] XA_TEST[1-0], [3:2] YA_TEST[1-0], [1:0] ZA_TEST[1-0] public static final int MPU6050_RA_XG_OFFS_USRH = 0x13; //[15:0] XG_OFFS_USR public static final int MPU6050_RA_XG_OFFS_USRL = 0x14; public static final int MPU6050_RA_YG_OFFS_USRH = 0x15; //[15:0] YG_OFFS_USR public static final int MPU6050_RA_YG_OFFS_USRL = 0x16; public static final int MPU6050_RA_ZG_OFFS_USRH = 0x17; //[15:0] ZG_OFFS_USR public static final int MPU6050_RA_ZG_OFFS_USRL = 0x18; public static final int MPU6050_RA_SMPLRT_DIV = 0x19; public static final int MPU6050_RA_CONFIG = 0x1A; public static final int MPU6050_RA_GYRO_CONFIG = 0x1B; public static final int MPU6050_RA_ACCEL_CONFIG = 0x1C; public static final int MPU6050_RA_FF_THR = 0x1D; public static final int MPU6050_RA_FF_DUR = 0x1E; public static final int MPU6050_RA_MOT_THR = 0x1F; public static final int MPU6050_RA_MOT_DUR = 0x20; public static final int MPU6050_RA_ZRMOT_THR = 0x21; public static final int MPU6050_RA_ZRMOT_DUR = 0x22; public static final int MPU6050_RA_FIFO_EN = 0x23; public static final int MPU6050_RA_I2C_MST_CTRL = 0x24; public static final int MPU6050_RA_I2C_SLV0_ADDR = 0x25; public static final int MPU6050_RA_I2C_SLV0_REG = 0x26; public static final int MPU6050_RA_I2C_SLV0_CTRL = 0x27; public static final int MPU6050_RA_I2C_SLV1_ADDR = 0x28; public static final int MPU6050_RA_I2C_SLV1_REG = 0x29; public static final int MPU6050_RA_I2C_SLV1_CTRL = 0x2A; public static final int MPU6050_RA_I2C_SLV2_ADDR = 0x2B; public static final int MPU6050_RA_I2C_SLV2_REG = 0x2C; public static final int MPU6050_RA_I2C_SLV2_CTRL = 0x2D; public static final int MPU6050_RA_I2C_SLV3_ADDR = 0x2E; public static final int MPU6050_RA_I2C_SLV3_REG = 0x2F; public static final int MPU6050_RA_I2C_SLV3_CTRL = 0x30; public static final int MPU6050_RA_I2C_SLV4_ADDR = 0x31; public static final int MPU6050_RA_I2C_SLV4_REG = 0x32; public static final int MPU6050_RA_I2C_SLV4_DO = 0x33; public static final int MPU6050_RA_I2C_SLV4_CTRL = 0x34; public static final int MPU6050_RA_I2C_SLV4_DI = 0x35; public static final int MPU6050_RA_I2C_MST_STATUS = 0x36; public static final int MPU6050_RA_INT_PIN_CFG = 0x37; public static final int MPU6050_RA_INT_ENABLE = 0x38; public static final int MPU6050_RA_DMP_INT_STATUS = 0x39; public static final int MPU6050_RA_INT_STATUS = 0x3A; public static final int MPU6050_RA_ACCEL_XOUT_H = 0x3B; public static final int MPU6050_RA_ACCEL_XOUT_L = 0x3C; public static final int MPU6050_RA_ACCEL_YOUT_H = 0x3D; public static final int MPU6050_RA_ACCEL_YOUT_L = 0x3E; public static final int MPU6050_RA_ACCEL_ZOUT_H = 0x3F; public static final int MPU6050_RA_ACCEL_ZOUT_L = 0x40; public static final int MPU6050_RA_TEMP_OUT_H = 0x41; public static final int MPU6050_RA_TEMP_OUT_L = 0x42; public static final int MPU6050_RA_GYRO_XOUT_H = 0x43; public static final int MPU6050_RA_GYRO_XOUT_L = 0x44; public static final int MPU6050_RA_GYRO_YOUT_H = 0x45; public static final int MPU6050_RA_GYRO_YOUT_L = 0x46; public static final int MPU6050_RA_GYRO_ZOUT_H = 0x47; public static final int MPU6050_RA_GYRO_ZOUT_L = 0x48; public static final int MPU6050_RA_EXT_SENS_DATA_00 = 0x49; public static final int MPU6050_RA_EXT_SENS_DATA_01 = 0x4A; public static final int MPU6050_RA_EXT_SENS_DATA_02 = 0x4B; public static final int MPU6050_RA_EXT_SENS_DATA_03 = 0x4C; public static final int MPU6050_RA_EXT_SENS_DATA_04 = 0x4D; public static final int MPU6050_RA_EXT_SENS_DATA_05 = 0x4E; public static final int MPU6050_RA_EXT_SENS_DATA_06 = 0x4F; public static final int MPU6050_RA_EXT_SENS_DATA_07 = 0x50; public static final int MPU6050_RA_EXT_SENS_DATA_08 = 0x51; public static final int MPU6050_RA_EXT_SENS_DATA_09 = 0x52; public static final int MPU6050_RA_EXT_SENS_DATA_10 = 0x53; public static final int MPU6050_RA_EXT_SENS_DATA_11 = 0x54; public static final int MPU6050_RA_EXT_SENS_DATA_12 = 0x55; public static final int MPU6050_RA_EXT_SENS_DATA_13 = 0x56; public static final int MPU6050_RA_EXT_SENS_DATA_14 = 0x57; public static final int MPU6050_RA_EXT_SENS_DATA_15 = 0x58; public static final int MPU6050_RA_EXT_SENS_DATA_16 = 0x59; public static final int MPU6050_RA_EXT_SENS_DATA_17 = 0x5A; public static final int MPU6050_RA_EXT_SENS_DATA_18 = 0x5B; public static final int MPU6050_RA_EXT_SENS_DATA_19 = 0x5C; public static final int MPU6050_RA_EXT_SENS_DATA_20 = 0x5D; public static final int MPU6050_RA_EXT_SENS_DATA_21 = 0x5E; public static final int MPU6050_RA_EXT_SENS_DATA_22 = 0x5F; public static final int MPU6050_RA_EXT_SENS_DATA_23 = 0x60; public static final int MPU6050_RA_MOT_DETECT_STATUS = 0x61; public static final int MPU6050_RA_I2C_SLV0_DO = 0x63; public static final int MPU6050_RA_I2C_SLV1_DO = 0x64; public static final int MPU6050_RA_I2C_SLV2_DO = 0x65; public static final int MPU6050_RA_I2C_SLV3_DO = 0x66; public static final int MPU6050_RA_I2C_MST_DELAY_CTRL = 0x67; public static final int MPU6050_RA_SIGNAL_PATH_RESET = 0x68; public static final int MPU6050_RA_MOT_DETECT_CTRL = 0x69; public static final int MPU6050_RA_USER_CTRL = 0x6A; public static final int MPU6050_RA_PWR_MGMT_1 = 0x6B; public static final int MPU6050_RA_PWR_MGMT_2 = 0x6C; public static final int MPU6050_RA_BANK_SEL = 0x6D; public static final int MPU6050_RA_MEM_START_ADDR = 0x6E; public static final int MPU6050_RA_MEM_R_W = 0x6F; public static final int MPU6050_RA_DMP_CFG_1 = 0x70; public static final int MPU6050_RA_DMP_CFG_2 = 0x71; public static final int MPU6050_RA_FIFO_COUNTH = 0x72; public static final int MPU6050_RA_FIFO_COUNTL = 0x73; public static final int MPU6050_RA_FIFO_R_W = 0x74; public static final int MPU6050_RA_WHO_AM_I = 0x75; public static final int MPU6050_SELF_TEST_XA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_XA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_XA_2_BIT = 0x05; public static final int MPU6050_SELF_TEST_XA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_YA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_YA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_YA_2_BIT = 0x03; public static final int MPU6050_SELF_TEST_YA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_ZA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_ZA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_ZA_2_BIT = 0x01; public static final int MPU6050_SELF_TEST_ZA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_XG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_XG_1_LENGTH = 0x05; public static final int MPU6050_SELF_TEST_YG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_YG_1_LENGTH = 0x05; public static final int MPU6050_SELF_TEST_ZG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_ZG_1_LENGTH = 0x05; public static final int MPU6050_TC_PWR_MODE_BIT = 7; public static final int MPU6050_TC_OFFSET_BIT = 6; public static final int MPU6050_TC_OFFSET_LENGTH = 6; public static final int MPU6050_TC_OTP_BNK_VLD_BIT = 0; public static final int MPU6050_VDDIO_LEVEL_VLOGIC = 0; public static final int MPU6050_VDDIO_LEVEL_VDD = 1; public static final int MPU6050_CFG_EXT_SYNC_SET_BIT = 5; public static final int MPU6050_CFG_EXT_SYNC_SET_LENGTH = 3; public static final int MPU6050_CFG_DLPF_CFG_BIT = 2; public static final int MPU6050_CFG_DLPF_CFG_LENGTH = 3; public static final int MPU6050_EXT_SYNC_DISABLED = 0x0; public static final int MPU6050_EXT_SYNC_TEMP_OUT_L = 0x1; public static final int MPU6050_EXT_SYNC_GYRO_XOUT_L = 0x2; public static final int MPU6050_EXT_SYNC_GYRO_YOUT_L = 0x3; public static final int MPU6050_EXT_SYNC_GYRO_ZOUT_L = 0x4; public static final int MPU6050_EXT_SYNC_ACCEL_XOUT_L = 0x5; public static final int MPU6050_EXT_SYNC_ACCEL_YOUT_L = 0x6; public static final int MPU6050_EXT_SYNC_ACCEL_ZOUT_L = 0x7; public static final int MPU6050_DLPF_BW_256 = 0x00; public static final int MPU6050_DLPF_BW_188 = 0x01; public static final int MPU6050_DLPF_BW_98 = 0x02; public static final int MPU6050_DLPF_BW_42 = 0x03; public static final int MPU6050_DLPF_BW_20 = 0x04; public static final int MPU6050_DLPF_BW_10 = 0x05; public static final int MPU6050_DLPF_BW_5 = 0x06; public static final int MPU6050_GCONFIG_FS_SEL_BIT = 4; public static final int MPU6050_GCONFIG_FS_SEL_LENGTH = 2; public static final int MPU6050_GYRO_FS_250 = 0x00; public static final int MPU6050_GYRO_FS_500 = 0x01; public static final int MPU6050_GYRO_FS_1000 = 0x02; public static final int MPU6050_GYRO_FS_2000 = 0x03; public static final int MPU6050_ACONFIG_XA_ST_BIT = 7; public static final int MPU6050_ACONFIG_YA_ST_BIT = 6; public static final int MPU6050_ACONFIG_ZA_ST_BIT = 5; public static final int MPU6050_ACONFIG_AFS_SEL_BIT = 4; public static final int MPU6050_ACONFIG_AFS_SEL_LENGTH = 2; public static final int MPU6050_ACONFIG_ACCEL_HPF_BIT = 2; public static final int MPU6050_ACONFIG_ACCEL_HPF_LENGTH = 3; public static final int MPU6050_ACCEL_FS_2 = 0x00; public static final int MPU6050_ACCEL_FS_4 = 0x01; public static final int MPU6050_ACCEL_FS_8 = 0x02; public static final int MPU6050_ACCEL_FS_16 = 0x03; public static final int MPU6050_DHPF_RESET = 0x00; public static final int MPU6050_DHPF_5 = 0x01; public static final int MPU6050_DHPF_2P5 = 0x02; public static final int MPU6050_DHPF_1P25 = 0x03; public static final int MPU6050_DHPF_0P63 = 0x04; public static final int MPU6050_DHPF_HOLD = 0x07; public static final int MPU6050_TEMP_FIFO_EN_BIT = 7; public static final int MPU6050_XG_FIFO_EN_BIT = 6; public static final int MPU6050_YG_FIFO_EN_BIT = 5; public static final int MPU6050_ZG_FIFO_EN_BIT = 4; public static final int MPU6050_ACCEL_FIFO_EN_BIT = 3; public static final int MPU6050_SLV2_FIFO_EN_BIT = 2; public static final int MPU6050_SLV1_FIFO_EN_BIT = 1; public static final int MPU6050_SLV0_FIFO_EN_BIT = 0; public static final int MPU6050_MULT_MST_EN_BIT = 7; public static final int MPU6050_WAIT_FOR_ES_BIT = 6; public static final int MPU6050_SLV_3_FIFO_EN_BIT = 5; public static final int MPU6050_I2C_MST_P_NSR_BIT = 4; public static final int MPU6050_I2C_MST_CLK_BIT = 3; public static final int MPU6050_I2C_MST_CLK_LENGTH = 4; public static final int MPU6050_CLOCK_DIV_348 = 0x0; public static final int MPU6050_CLOCK_DIV_333 = 0x1; public static final int MPU6050_CLOCK_DIV_320 = 0x2; public static final int MPU6050_CLOCK_DIV_308 = 0x3; public static final int MPU6050_CLOCK_DIV_296 = 0x4; public static final int MPU6050_CLOCK_DIV_286 = 0x5; public static final int MPU6050_CLOCK_DIV_276 = 0x6; public static final int MPU6050_CLOCK_DIV_267 = 0x7; public static final int MPU6050_CLOCK_DIV_258 = 0x8; public static final int MPU6050_CLOCK_DIV_500 = 0x9; public static final int MPU6050_CLOCK_DIV_471 = 0xA; public static final int MPU6050_CLOCK_DIV_444 = 0xB; public static final int MPU6050_CLOCK_DIV_421 = 0xC; public static final int MPU6050_CLOCK_DIV_400 = 0xD; public static final int MPU6050_CLOCK_DIV_381 = 0xE; public static final int MPU6050_CLOCK_DIV_364 = 0xF; public static final int MPU6050_I2C_SLV_RW_BIT = 7; public static final int MPU6050_I2C_SLV_ADDR_BIT = 6; public static final int MPU6050_I2C_SLV_ADDR_LENGTH = 7; public static final int MPU6050_I2C_SLV_EN_BIT = 7; public static final int MPU6050_I2C_SLV_BYTE_SW_BIT = 6; public static final int MPU6050_I2C_SLV_REG_DIS_BIT = 5; public static final int MPU6050_I2C_SLV_GRP_BIT = 4; public static final int MPU6050_I2C_SLV_LEN_BIT = 3; public static final int MPU6050_I2C_SLV_LEN_LENGTH = 4; public static final int MPU6050_I2C_SLV4_RW_BIT = 7; public static final int MPU6050_I2C_SLV4_ADDR_BIT = 6; public static final int MPU6050_I2C_SLV4_ADDR_LENGTH = 7; public static final int MPU6050_I2C_SLV4_EN_BIT = 7; public static final int MPU6050_I2C_SLV4_INT_EN_BIT = 6; public static final int MPU6050_I2C_SLV4_REG_DIS_BIT = 5; public static final int MPU6050_I2C_SLV4_MST_DLY_BIT = 4; public static final int MPU6050_I2C_SLV4_MST_DLY_LENGTH = 5; public static final int MPU6050_MST_PASS_THROUGH_BIT = 7; public static final int MPU6050_MST_I2C_SLV4_DONE_BIT = 6; public static final int MPU6050_MST_I2C_LOST_ARB_BIT = 5; public static final int MPU6050_MST_I2C_SLV4_NACK_BIT = 4; public static final int MPU6050_MST_I2C_SLV3_NACK_BIT = 3; public static final int MPU6050_MST_I2C_SLV2_NACK_BIT = 2; public static final int MPU6050_MST_I2C_SLV1_NACK_BIT = 1; public static final int MPU6050_MST_I2C_SLV0_NACK_BIT = 0; public static final int MPU6050_INTCFG_INT_LEVEL_BIT = 7; public static final int MPU6050_INTCFG_INT_OPEN_BIT = 6; public static final int MPU6050_INTCFG_LATCH_INT_EN_BIT = 5; public static final int MPU6050_INTCFG_INT_RD_CLEAR_BIT = 4; public static final int MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT = 3; public static final int MPU6050_INTCFG_FSYNC_INT_EN_BIT = 2; public static final int MPU6050_INTCFG_I2C_BYPASS_EN_BIT = 1; public static final int MPU6050_INTCFG_CLKOUT_EN_BIT = 0; public static final int MPU6050_INTMODE_ACTIVEHIGH = 0x00; public static final int MPU6050_INTMODE_ACTIVELOW = 0x01; public static final int MPU6050_INTDRV_PUSHPULL = 0x00; public static final int MPU6050_INTDRV_OPENDRAIN = 0x01; public static final int MPU6050_INTLATCH_50USPULSE = 0x00; public static final int MPU6050_INTLATCH_WAITCLEAR = 0x01; public static final int MPU6050_INTCLEAR_STATUSREAD = 0x00; public static final int MPU6050_INTCLEAR_ANYREAD = 0x01; public static final int MPU6050_INTERRUPT_FF_BIT = 7; public static final int MPU6050_INTERRUPT_MOT_BIT = 6; public static final int MPU6050_INTERRUPT_ZMOT_BIT = 5; public static final int MPU6050_INTERRUPT_FIFO_OFLOW_BIT = 4; public static final int MPU6050_INTERRUPT_I2C_MST_INT_BIT = 3; public static final int MPU6050_INTERRUPT_PLL_RDY_INT_BIT = 2; public static final int MPU6050_INTERRUPT_DMP_INT_BIT = 1; public static final int MPU6050_INTERRUPT_DATA_RDY_BIT = 0; // TODO: figure out what these actually do // UMPL source code is not very obivous public static final int MPU6050_DMPINT_5_BIT = 5; public static final int MPU6050_DMPINT_4_BIT = 4; public static final int MPU6050_DMPINT_3_BIT = 3; public static final int MPU6050_DMPINT_2_BIT = 2; public static final int MPU6050_DMPINT_1_BIT = 1; public static final int MPU6050_DMPINT_0_BIT = 0; public static final int MPU6050_MOTION_MOT_XNEG_BIT = 7; public static final int MPU6050_MOTION_MOT_XPOS_BIT = 6; public static final int MPU6050_MOTION_MOT_YNEG_BIT = 5; public static final int MPU6050_MOTION_MOT_YPOS_BIT = 4; public static final int MPU6050_MOTION_MOT_ZNEG_BIT = 3; public static final int MPU6050_MOTION_MOT_ZPOS_BIT = 2; public static final int MPU6050_MOTION_MOT_ZRMOT_BIT = 0; public static final int MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT = 7; public static final int MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT = 4; public static final int MPU6050_DELAYCTRL_I2C_SLV3_DLY_EN_BIT = 3; public static final int MPU6050_DELAYCTRL_I2C_SLV2_DLY_EN_BIT = 2; public static final int MPU6050_DELAYCTRL_I2C_SLV1_DLY_EN_BIT = 1; public static final int MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT = 0; public static final int MPU6050_PATHRESET_GYRO_RESET_BIT = 2; public static final int MPU6050_PATHRESET_ACCEL_RESET_BIT = 1; public static final int MPU6050_PATHRESET_TEMP_RESET_BIT = 0; public static final int MPU6050_DETECT_ACCEL_ON_DELAY_BIT = 5; public static final int MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH = 2; public static final int MPU6050_DETECT_FF_COUNT_BIT = 3; public static final int MPU6050_DETECT_FF_COUNT_LENGTH = 2; public static final int MPU6050_DETECT_MOT_COUNT_BIT = 1; public static final int MPU6050_DETECT_MOT_COUNT_LENGTH = 2; public static final int MPU6050_DETECT_DECREMENT_RESET = 0x0; public static final int MPU6050_DETECT_DECREMENT_1 = 0x1; public static final int MPU6050_DETECT_DECREMENT_2 = 0x2; public static final int MPU6050_DETECT_DECREMENT_4 = 0x3; public static final int MPU6050_USERCTRL_DMP_EN_BIT = 7; public static final int MPU6050_USERCTRL_FIFO_EN_BIT = 6; public static final int MPU6050_USERCTRL_I2C_MST_EN_BIT = 5; public static final int MPU6050_USERCTRL_I2C_IF_DIS_BIT = 4; public static final int MPU6050_USERCTRL_DMP_RESET_BIT = 3; public static final int MPU6050_USERCTRL_FIFO_RESET_BIT = 2; public static final int MPU6050_USERCTRL_I2C_MST_RESET_BIT = 1; public static final int MPU6050_USERCTRL_SIG_COND_RESET_BIT = 0; public static final int MPU6050_PWR1_DEVICE_RESET_BIT = 7; public static final int MPU6050_PWR1_SLEEP_BIT = 6; public static final int MPU6050_PWR1_CYCLE_BIT = 5; public static final int MPU6050_PWR1_TEMP_DIS_BIT = 3; public static final int MPU6050_PWR1_CLKSEL_BIT = 2; public static final int MPU6050_PWR1_CLKSEL_LENGTH = 3; public static final int MPU6050_CLOCK_INTERNAL = 0x00; public static final int MPU6050_CLOCK_PLL_XGYRO = 0x01; public static final int MPU6050_CLOCK_PLL_YGYRO = 0x02; public static final int MPU6050_CLOCK_PLL_ZGYRO = 0x03; public static final int MPU6050_CLOCK_PLL_EXT32K = 0x04; public static final int MPU6050_CLOCK_PLL_EXT19M = 0x05; public static final int MPU6050_CLOCK_KEEP_RESET = 0x07; public static final int MPU6050_PWR2_LP_WAKE_CTRL_BIT = 7; public static final int MPU6050_PWR2_LP_WAKE_CTRL_LENGTH = 2; public static final int MPU6050_PWR2_STBY_XA_BIT = 5; public static final int MPU6050_PWR2_STBY_YA_BIT = 4; public static final int MPU6050_PWR2_STBY_ZA_BIT = 3; public static final int MPU6050_PWR2_STBY_XG_BIT = 2; public static final int MPU6050_PWR2_STBY_YG_BIT = 1; public static final int MPU6050_PWR2_STBY_ZG_BIT = 0; public static final int MPU6050_WAKE_FREQ_1P25 = 0x0; public static final int MPU6050_WAKE_FREQ_2P5 = 0x1; public static final int MPU6050_WAKE_FREQ_5 = 0x2; public static final int MPU6050_WAKE_FREQ_10 = 0x3; public static final int MPU6050_BANKSEL_PRFTCH_EN_BIT = 6; public static final int MPU6050_BANKSEL_CFG_USER_BANK_BIT = 5; public static final int MPU6050_BANKSEL_MEM_SEL_BIT = 4; public static final int MPU6050_BANKSEL_MEM_SEL_LENGTH = 5; public static final int MPU6050_WHO_AM_I_BIT = 6; public static final int MPU6050_WHO_AM_I_LENGTH = 6; public static final int MPU6050_DMP_MEMORY_BANKS = 8; public static final int MPU6050_DMP_MEMORY_BANK_SIZE = 256; public static final int MPU6050_DMP_MEMORY_CHUNK_SIZE = 16; public static final byte ACCEL_XOUT_H = 0x3B; public static int accelX; public static int accelY; public static int accelZ; public static double temperature; public static int gyroX; public static int gyroY; public static int gyroZ; // this block of memory gets written to the MPU on start-up, and it seems // to be volatile memory, so it has to be done each time (it only takes ~1 // second though) public static final int[] dmpMemory = { // bank 0, 256 bytes 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82, 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC, 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4, 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10, // bank 1, 256 bytes 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8, 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C, 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0, // bank 2, 256 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bank 3, 256 bytes 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F, 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2, 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF, 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C, 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1, 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01, 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80, 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80, 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E, 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9, 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0, 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86, 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1, 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86, // bank 4, 256 bytes 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA, 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C, 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8, 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3, 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84, 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5, 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3, 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1, 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5, 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A, 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8, 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87, // bank 5, 256 bytes 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8, 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68, 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D, 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94, 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56, 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA, 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A, 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60, 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97, 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04, 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78, 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79, 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68, 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68, // bank 6, 256 bytes 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04, 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66, 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31, 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60, 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76, 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56, 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD, 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91, 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE, 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9, 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD, 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E, 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8, 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89, 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79, // bank 7, 138 bytes (remainder) 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA, 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB, 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3, 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3, 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC, 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF }; // thanks to Noah Zerkin for piecing this stuff together! public static final int[] dmpConfig = { // BANK OFFSET LENGTH [DATA] 0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration 0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration 0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration 0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration 0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration 0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration 0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration 0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration 0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02 0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10 0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11 0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12 0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20 0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21 0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22 0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors 0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion 0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update 0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone // SPECIAL 0x01 = enable interrupts 0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION 0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt 0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion 0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer 0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro 0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo 0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo 0x02, 0x16, 0x02, 0x00, 0x01 // D_0_22 inv_set_fifo_rate // This very last 0x01 WAS a 0x09, which drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz, // 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very noisy data. // DMP output frequency is calculated easily using this equation: (200Hz / (1 + value)) // It is important to make sure the host processor can keep up with reading and processing // the FIFO output at the desired rate. Handling FIFO overflow cleanly is also a good idea. }; public static final int[] dmpUpdates = { 0x01, 0xB2, 0x02, 0xFF, 0xFF, 0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35, 0x01, 0x6A, 0x02, 0x06, 0x00, 0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00, 0x01, 0x62, 0x02, 0x00, 0x00, 0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00 }; private int[] buffer = new int[14]; private int bytebuffer; int timeout = 0; public static void main(String[] args) { LoggingFactory.getInstance().configure(); try { Mpu6050 mpu6050 = (Mpu6050) Runtime.start("mpu6050", "Mpu6050"); Runtime.start("gui", "GUIService"); /* Arduino arduino = (Arduino) Runtime.start("Arduino","Arduino"); arduino.connect("COM4"); mpu6050.setController(arduino); */ RasPi raspi = (RasPi) Runtime.start("RasPi","RasPi"); mpu6050.setController(raspi); mpu6050.dmpInitialize(); } catch (Exception e) { Logging.logError(e); } } public Mpu6050(String n) { super(n); } @Override public void startService() { super.startService(); } public boolean setController(I2CControl controller) { if (controller == null) { error("setting null as controller"); return false; } log.info(String.format("%s setController %s", getName(), controller.getName())); this.controller = controller; controller.createDevice(busAddress, deviceAddress, type); broadcastState(); return true; } /** * This method creates the i2c device */ public boolean setDeviceAddress(int DeviceAddress){ if (controller != null) { if (deviceAddress != DeviceAddress){ controller.releaseDevice(busAddress,deviceAddress); controller.createDevice(busAddress, DeviceAddress, type); } } log.info(String.format("Setting device address to x%02X", deviceAddress)); deviceAddress = DeviceAddress; return true; } /** * This method reads all the 7 raw values in one go * accelX * accelY * accelZ * temperature ( In degrees Celcius ) * gyroX * gyroY * gyroZ * */ public void readRaw(){ // Set the start address to read from byte[] writebuffer = {ACCEL_XOUT_H}; controller.i2cWrite(busAddress, deviceAddress, writebuffer, writebuffer.length); // The Arduino example executes a request_from() // Not sure if this will do the trick // Request 14 bytes from the MPU-6050 byte[] readbuffer = new byte[14]; controller.i2cWrite(busAddress, deviceAddress, readbuffer, readbuffer.length); // Fill the variables with the result from the read operation accelX = readbuffer[0]<<8 + readbuffer[1] & 0xFF; accelY = readbuffer[2]<<8 + readbuffer[3] & 0xFF; accelZ = readbuffer[4]<<8 + readbuffer[5] & 0xFF; int temp = readbuffer[6]<<8 + readbuffer[7] & 0xFF; gyroX = readbuffer[8]<<8 + readbuffer[9] & 0xFF; gyroY = readbuffer[10]<<8 + readbuffer[11] & 0xFF; gyroZ = readbuffer[12]<<8 + readbuffer[13] & 0xFF; // Convert temp to degrees Celcius temperature = temp / 340.0 + 36.53; } public int dmpInitialize(){ // reset device log.info("Resetting MPU6050..."); reset(); delay(30); // wait after reset // disable sleep mode log.info("Disabling sleep mode..."); setSleepEnabled(false); // get MPU hardware revision log.info("Selecting user bank 16..."); setMemoryBank(0x10, true, true); log.info("Selecting memory byte 6..."); setMemoryStartAddress(0x06); log.info("Checking hardware revision..."); log.info(String.format("Revision @ user[16][6] = x%02X", readMemoryByte())); log.info("Resetting memory bank selection to 0..."); setMemoryBank(0, false, false); // check OTP bank valid log.info("Reading OTP bank valid flag..."); log.info(String.format("OTP bank is %b", getOTPBankValid())); // get X/Y/Z gyro offsets log.info("Reading gyro offset TC values..."); int xgOffsetTC = getXGyroOffsetTC(); int ygOffsetTC = getYGyroOffsetTC(); int zgOffsetTC = getZGyroOffsetTC(); log.info(String.format("X gyro offset = %s", xgOffsetTC)); log.info(String.format("Y gyro offset = %s", ygOffsetTC)); log.info(String.format("Z gyro offset = %S", zgOffsetTC)); // setup weird slave stuff (?) log.info("Setting slave 0 address to 0x7F..."); setSlaveAddress(0, 0x7F); log.info("Disabling I2C Master mode..."); setI2CMasterModeEnabled(false); log.info("Setting slave 0 address to 0x68 (self)..."); setSlaveAddress(0, 0x68); log.info("Resetting I2C Master control..."); resetI2CMaster(); delay(20); // load DMP code into memory banks log.info(String.format("Writing DMP code to MPU memory banks (%s) bytes", dmpMemory.length)); if (writeProgMemoryBlock(dmpMemory, dmpMemory.length)) { log.info("Success! DMP code written and verified."); // write DMP configuration log.info(String.format("Writing DMP configuration to MPU memory banks (%s bytes in config def)",dmpConfig.length)); if (writeProgDMPConfigurationSet(dmpConfig, dmpConfig.length)) { log.info("Success! DMP configuration written and verified."); log.info("Setting clock source to Z Gyro..."); setClockSource(MPU6050_CLOCK_PLL_ZGYRO); log.info("Setting DMP and FIFO_OFLOW interrupts enabled..."); setIntEnabled(0x12); log.info("Setting sample rate to 200Hz..."); setRate(4); // 1khz / (1 + 4) = 200 Hz log.info("Setting external frame sync to TEMP_OUT_L[0]..."); setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L); log.info("Setting DLPF bandwidth to 42Hz..."); setDLPFMode(MPU6050_DLPF_BW_42); log.info("Setting gyro sensitivity to +/- 2000 deg/sec..."); setFullScaleGyroRange(MPU6050_GYRO_FS_2000); log.info("Setting DMP configuration bytes (function unknown)..."); setDMPConfig1(0x03); setDMPConfig2(0x00); log.info("Clearing OTP Bank flag..."); setOTPBankValid(false); log.info("Setting X/Y/Z gyro offset TCs to previous values..."); setXGyroOffsetTC(xgOffsetTC); setYGyroOffsetTC(ygOffsetTC); setZGyroOffsetTC(zgOffsetTC); //log.info("Setting X/Y/Z gyro user offsets to zero...")); //setXGyroOffset(0); //setYGyroOffset(0); //setZGyroOffset(0); log.info("Writing final memory update 1/7 (function unknown)..."); int[] dmpUpdate = new int[13]; int j; int pos = 0; int bank = 0, address = 0, dataSize = 0; for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Writing final memory update 2/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Resetting FIFO..."); resetFIFO(); log.info("Reading FIFO count..."); int fifoCount = getFIFOCount(); int[] fifoBuffer = new int[128]; log.info(String.format("Current FIFO count=%s",fifoCount)); getFIFOBytes(fifoBuffer, fifoCount); log.info("Setting motion detection threshold to 2..."); setMotionDetectionThreshold(2); log.info("Setting zero-motion detection threshold to 156..."); setZeroMotionDetectionThreshold(156); log.info("Setting motion detection duration to 80..."); setMotionDetectionDuration(80); log.info("Setting zero-motion detection duration to 0..."); setZeroMotionDetectionDuration(0); log.info("Resetting FIFO..."); resetFIFO(); log.info("Enabling FIFO..."); setFIFOEnabled(true); log.info("Enabling DMP..."); setDMPEnabled(true); log.info("Resetting DMP..."); resetDMP(); log.info("Writing final memory update 3/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Writing final memory update 4/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Writing final memory update 5/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Waiting for FIFO count > 2..."); while ((fifoCount = getFIFOCount()) < 3); log.info(String.format("Current FIFO count=%s",fifoCount)); log.info("Reading FIFO data..."); getFIFOBytes(fifoBuffer, fifoCount); log.info("Reading interrupt status..."); log.info(String.format("Current interrupt status=x%02X",getIntStatus())); log.info("Reading final memory update 6/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Waiting for FIFO count > 2..."); while ((fifoCount = getFIFOCount()) < 3); log.info(String.format("Current FIFO count=%s",fifoCount)); log.info("Reading FIFO data..."); getFIFOBytes(fifoBuffer, fifoCount); log.info("Reading interrupt status..."); log.info(String.format("Current interrupt status=x%02X",getIntStatus())); log.info("Writing final memory update 7/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("DMP is good to go! Finally."); log.info("Disabling DMP (you turn it on later)..."); setDMPEnabled(false); log.info("Setting up internal 42-byte (default) DMP packet buffer..."); int dmpPacketSize = 42; /*if ((dmpPacketBuffer = (int *)malloc(42)) == 0) { return 3; // TODO: proper error code for no memory }*/ log.info("Resetting FIFO and clearing INT status one last time..."); resetFIFO(); getIntStatus(); } else { log.info("ERROR! DMP configuration verification failed."); return 2; // configuration block loading failed } } else { log.info("ERROR! DMP code verification failed."); return 1; // main binary block loading failed } return 0; } public void delay(int ms){ try { Thread.sleep(ms); } catch (InterruptedException e) { // TODO Auto-generated catch block Logging.logError(e); } // wait after reset } public void initialize() { setClockSource(MPU6050_CLOCK_PLL_XGYRO); setFullScaleGyroRange(MPU6050_GYRO_FS_250); setFullScaleAccelRange(MPU6050_ACCEL_FS_2); setSleepEnabled(false); // thanks to Jack Elston for pointing this one out! } /** Verify the I2C connection. * Make sure the device is connected and responds as expected. * @return True if connection is valid, false otherwise */ public boolean testConnection() { return getDeviceID() == 0x34; } // AUX_VDDIO register (InvenSense demo code calls this RA_*G_OFFS_TC) /** Get the auxiliary I2C supply voltage level. * When set to 1, the auxiliary I2C bus high logic level is VDD. When cleared to * 0, the auxiliary I2C bus high logic level is VLOGIC. This does not apply to * the MPU-6000, which does not have a VLOGIC pin. * @return I2C supply voltage level (0=VLOGIC, 1=VDD) */ public int getAuxVDDIOLevel() { I2CdevReadBit(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_PWR_MODE_BIT, bytebuffer); return bytebuffer; } /** Set the auxiliary I2C supply voltage level. * When set to 1, the auxiliary I2C bus high logic level is VDD. When cleared to * 0, the auxiliary I2C bus high logic level is VLOGIC. This does not apply to * the MPU-6000, which does not have a VLOGIC pin. * @param level I2C supply voltage level (0=VLOGIC, 1=VDD) */ void setAuxVDDIOLevel(int level) { boolean bitbuffer = (level != 0); I2CdevWriteBit(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_PWR_MODE_BIT, bitbuffer); } // SMPLRT_DIV register /** Get gyroscope output rate divider. * The sensor register output, FIFO output, DMP sampling, Motion detection, Zero * Motion detection, and Free Fall detection are all based on the Sample Rate. * The Sample Rate is generated by dividing the gyroscope output rate by * SMPLRT_DIV: * * Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV) * * where Gyroscope Output Rate = 8kHz when the DLPF is disabled (DLPF_CFG = 0 or * 7), and 1kHz when the DLPF is enabled (see Register 26). * * Note: The accelerometer output rate is 1kHz. This means that for a Sample * Rate greater than 1kHz, the same accelerometer sample may be output to the * FIFO, DMP, and sensor registers more than once. * * For a diagram of the gyroscope and accelerometer signal paths, see Section 8 * of the MPU-6000/MPU-6050 Product Specification document. * * @return Current sample rate * @see MPU6050_RA_SMPLRT_DIV */ int getRate() { I2CdevReadByte(deviceAddress, MPU6050_RA_SMPLRT_DIV, bytebuffer); return bytebuffer; } /** Set gyroscope sample rate divider. * @param rate New sample rate divider * @see getRate() * @see MPU6050_RA_SMPLRT_DIV */ void setRate(int rate) { I2CdevWriteByte(deviceAddress, MPU6050_RA_SMPLRT_DIV, rate); } // CONFIG register /** Get external FSYNC configuration. * Configures the external Frame Synchronization (FSYNC) pin sampling. An * external signal connected to the FSYNC pin can be sampled by configuring * EXT_SYNC_SET. Signal changes to the FSYNC pin are latched so that short * strobes may be captured. The latched FSYNC signal will be sampled at the * Sampling Rate, as defined in register 25. After sampling, the latch will * reset to the current FSYNC signal state. * * The sampled value will be reported in place of the least significant bit in * a sensor data register determined by the value of EXT_SYNC_SET according to * the following table. * * <pre> * EXT_SYNC_SET | FSYNC Bit Location * -------------+------------------- * 0 | Input disabled * 1 | TEMP_OUT_L[0] * 2 | GYRO_XOUT_L[0] * 3 | GYRO_YOUT_L[0] * 4 | GYRO_ZOUT_L[0] * 5 | ACCEL_XOUT_L[0] * 6 | ACCEL_YOUT_L[0] * 7 | ACCEL_ZOUT_L[0] * </pre> * * @return FSYNC configuration value */ int getExternalFrameSync() { I2CdevReadBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_EXT_SYNC_SET_BIT, MPU6050_CFG_EXT_SYNC_SET_LENGTH, bytebuffer); return bytebuffer; } /** Set external FSYNC configuration. * @see getExternalFrameSync() * @see MPU6050_RA_CONFIG * @param sync New FSYNC configuration value */ void setExternalFrameSync(int sync) { I2CdevWriteBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_EXT_SYNC_SET_BIT, MPU6050_CFG_EXT_SYNC_SET_LENGTH, sync); } /** Get digital low-pass filter configuration. * The DLPF_CFG parameter sets the digital low pass filter configuration. It * also determines the internal sampling rate used by the device as shown in * the table below. * * Note: The accelerometer output rate is 1kHz. This means that for a Sample * Rate greater than 1kHz, the same accelerometer sample may be output to the * FIFO, DMP, and sensor registers more than once. * * <pre> * | ACCELEROMETER | GYROSCOPE * DLPF_CFG | Bandwidth | Delay | Bandwidth | Delay | Sample Rate * ---------+-----------+--------+-----------+--------+------------- * 0 | 260Hz | 0ms | 256Hz | 0.98ms | 8kHz * 1 | 184Hz | 2.0ms | 188Hz | 1.9ms | 1kHz * 2 | 94Hz | 3.0ms | 98Hz | 2.8ms | 1kHz * 3 | 44Hz | 4.9ms | 42Hz | 4.8ms | 1kHz * 4 | 21Hz | 8.5ms | 20Hz | 8.3ms | 1kHz * 5 | 10Hz | 13.8ms | 10Hz | 13.4ms | 1kHz * 6 | 5Hz | 19.0ms | 5Hz | 18.6ms | 1kHz * 7 | -- Reserved -- | -- Reserved -- | Reserved * </pre> * * @return DLFP configuration * @see MPU6050_RA_CONFIG * @see MPU6050_CFG_DLPF_CFG_BIT * @see MPU6050_CFG_DLPF_CFG_LENGTH */ int getDLPFMode() { I2CdevReadBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_DLPF_CFG_BIT, MPU6050_CFG_DLPF_CFG_LENGTH, bytebuffer); return bytebuffer; } /** Set digital low-pass filter configuration. * @param mode New DLFP configuration setting * @see getDLPFBandwidth() * @see MPU6050_DLPF_BW_256 * @see MPU6050_RA_CONFIG * @see MPU6050_CFG_DLPF_CFG_BIT * @see MPU6050_CFG_DLPF_CFG_LENGTH */ void setDLPFMode(int mode) { I2CdevWriteBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_DLPF_CFG_BIT, MPU6050_CFG_DLPF_CFG_LENGTH, mode); } // GYRO_CONFIG register /** Get full-scale gyroscope range. * The FS_SEL parameter allows setting the full-scale range of the gyro sensors, * as described in the table below. * * <pre> * 0 = +/- 250 degrees/sec * 1 = +/- 500 degrees/sec * 2 = +/- 1000 degrees/sec * 3 = +/- 2000 degrees/sec * </pre> * * @return Current full-scale gyroscope range setting * @see MPU6050_GYRO_FS_250 * @see MPU6050_RA_GYRO_CONFIG * @see MPU6050_GCONFIG_FS_SEL_BIT * @see MPU6050_GCONFIG_FS_SEL_LENGTH */ int getFullScaleGyroRange() { I2CdevReadBits(deviceAddress, MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, bytebuffer); return bytebuffer; } /** Set full-scale gyroscope range. * @param range New full-scale gyroscope range value * @see getFullScaleRange() * @see MPU6050_GYRO_FS_250 * @see MPU6050_RA_GYRO_CONFIG * @see MPU6050_GCONFIG_FS_SEL_BIT * @see MPU6050_GCONFIG_FS_SEL_LENGTH */ void setFullScaleGyroRange(int range) { I2CdevWriteBits(deviceAddress, MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, range); } // SELF TEST FACTORY TRIM VALUES /** Get self-test factory trim value for accelerometer X axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_X */ int getAccelXSelfTestFactoryTrim() { int buffer0 = 0; int buffer1 = 0; I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_X, buffer0); I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_A, buffer1); return (buffer0>>3) | ((buffer1>>4) & 0x03); } /** Get self-test factory trim value for accelerometer Y axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Y */ int getAccelYSelfTestFactoryTrim() { int buffer0 = 0; int buffer1 = 0; I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_Y, buffer0); I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_A, buffer1); return (buffer0>>3) | ((buffer1>>2) & 0x03); } /** Get self-test factory trim value for accelerometer Z axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Z */ int getAccelZSelfTestFactoryTrim() { I2CdevReadBytes(deviceAddress, MPU6050_RA_SELF_TEST_Z, 2, buffer); return (buffer[0]>>3) | (buffer[1] & 0x03); } /** Get self-test factory trim value for gyro X axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_X */ int getGyroXSelfTestFactoryTrim() { I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_X, bytebuffer); return (bytebuffer & 0x1F); } /** Get self-test factory trim value for gyro Y axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Y */ int getGyroYSelfTestFactoryTrim() { I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_Y, bytebuffer); return (bytebuffer & 0x1F); } /** Get self-test factory trim value for gyro Z axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Z */ int getGyroZSelfTestFactoryTrim() { I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_Z, bytebuffer); return (bytebuffer & 0x1F); } // ACCEL_CONFIG register /** Get self-test enabled setting for accelerometer X axis. * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelXSelfTest() { I2CdevReadBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_XA_ST_BIT, bytebuffer); return bytebuffer != 0; } /** Get self-test enabled setting for accelerometer X axis. * @param enabled Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelXSelfTest(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_XA_ST_BIT, enabled); } /** Get self-test enabled value for accelerometer Y axis. * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelYSelfTest() { I2CdevReadBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_YA_ST_BIT, bytebuffer); return bytebuffer != 0; } /** Get self-test enabled value for accelerometer Y axis. * @param enabled Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelYSelfTest(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_YA_ST_BIT, enabled); } /** Get self-test enabled value for accelerometer Z axis. * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelZSelfTest() { I2CdevReadBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ZA_ST_BIT, bytebuffer); return bytebuffer != 0; } /** Set self-test enabled value for accelerometer Z axis. * @param enabled Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelZSelfTest(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ZA_ST_BIT, enabled); } /** Get full-scale accelerometer range. * The FS_SEL parameter allows setting the full-scale range of the accelerometer * sensors, as described in the table below. * * <pre> * 0 = +/- 2g * 1 = +/- 4g * 2 = +/- 8g * 3 = +/- 16g * </pre> * * @return Current full-scale accelerometer range setting * @see MPU6050_ACCEL_FS_2 * @see MPU6050_RA_ACCEL_CONFIG * @see MPU6050_ACONFIG_AFS_SEL_BIT * @see MPU6050_ACONFIG_AFS_SEL_LENGTH */ int getFullScaleAccelRange() { I2CdevReadBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, bytebuffer); return bytebuffer; } /** Set full-scale accelerometer range. * @param range New full-scale accelerometer range setting * @see getFullScaleAccelRange() */ void setFullScaleAccelRange(int range) { I2CdevWriteBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, range); } /** Get the high-pass filter configuration. * The DHPF is a filter module in the path leading to motion detectors (Free * Fall, Motion threshold, and Zero Motion). The high pass filter output is not * available to the data registers (see Figure in Section 8 of the MPU-6000/ * MPU-6050 Product Specification document). * * The high pass filter has three modes: * * <pre> * Reset: The filter output settles to zero within one sample. This * effectively disables the high pass filter. This mode may be toggled * to quickly settle the filter. * * On: The high pass filter will pass signals above the cut off frequency. * * Hold: When triggered, the filter holds the present sample. The filter * output will be the difference between the input sample and the held * sample. * </pre> * * <pre> * ACCEL_HPF | Filter Mode | Cut-off Frequency * ----------+-------------+------------------ * 0 | Reset | None * 1 | On | 5Hz * 2 | On | 2.5Hz * 3 | On | 1.25Hz * 4 | On | 0.63Hz * 7 | Hold | None * </pre> * * @return Current high-pass filter configuration * @see MPU6050_DHPF_RESET * @see MPU6050_RA_ACCEL_CONFIG */ int getDHPFMode() { I2CdevReadBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ACCEL_HPF_BIT, MPU6050_ACONFIG_ACCEL_HPF_LENGTH, bytebuffer); return bytebuffer; } /** Set the high-pass filter configuration. * @param bandwidth New high-pass filter configuration * @see setDHPFMode() * @see MPU6050_DHPF_RESET * @see MPU6050_RA_ACCEL_CONFIG */ void setDHPFMode(int bandwidth) { I2CdevWriteBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ACCEL_HPF_BIT, MPU6050_ACONFIG_ACCEL_HPF_LENGTH, bandwidth); } // FF_THR register /** Get free-fall event acceleration threshold. * This register configures the detection threshold for Free Fall event * detection. The unit of FF_THR is 1LSB = 2mg. Free Fall is detected when the * absolute value of the accelerometer measurements for the three axes are each * less than the detection threshold. This condition increments the Free Fall * duration counter (Register 30). The Free Fall interrupt is triggered when the * Free Fall duration counter reaches the time specified in FF_DUR. * * For more details on the Free Fall detection interrupt, see Section 8.2 of the * MPU-6000/MPU-6050 Product Specification document as well as Registers 56 and * 58 of this document. * * @return Current free-fall acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_FF_THR */ int getFreefallDetectionThreshold() { I2CdevReadByte(deviceAddress, MPU6050_RA_FF_THR, bytebuffer); return bytebuffer; } /** Get free-fall event acceleration threshold. * @param threshold New free-fall acceleration threshold value (LSB = 2mg) * @see getFreefallDetectionThreshold() * @see MPU6050_RA_FF_THR */ void setFreefallDetectionThreshold(int threshold) { I2CdevWriteByte(deviceAddress, MPU6050_RA_FF_THR, threshold); } // FF_DUR register /** Get free-fall event duration threshold. * This register configures the duration counter threshold for Free Fall event * detection. The duration counter ticks at 1kHz, therefore FF_DUR has a unit * of 1 LSB = 1 ms. * * The Free Fall duration counter increments while the absolute value of the * accelerometer measurements are each less than the detection threshold * (Register 29). The Free Fall interrupt is triggered when the Free Fall * duration counter reaches the time specified in this register. * * For more details on the Free Fall detection interrupt, see Section 8.2 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers 56 * and 58 of this document. * * @return Current free-fall duration threshold value (LSB = 1ms) * @see MPU6050_RA_FF_DUR */ int getFreefallDetectionDuration() { I2CdevReadByte(deviceAddress, MPU6050_RA_FF_DUR, bytebuffer); return bytebuffer; } /** Get free-fall event duration threshold. * @param duration New free-fall duration threshold value (LSB = 1ms) * @see getFreefallDetectionDuration() * @see MPU6050_RA_FF_DUR */ void setFreefallDetectionDuration(int duration) { I2CdevWriteByte(deviceAddress, MPU6050_RA_FF_DUR, duration); } // MOT_THR register /** Get motion detection event acceleration threshold. * This register configures the detection threshold for Motion interrupt * generation. The unit of MOT_THR is 1LSB = 2mg. Motion is detected when the * absolute value of any of the accelerometer measurements exceeds this Motion * detection threshold. This condition increments the Motion detection duration * counter (Register 32). The Motion detection interrupt is triggered when the * Motion Detection counter reaches the time count specified in MOT_DUR * (Register 32). * * The Motion interrupt will indicate the axis and polarity of detected motion * in MOT_DETECT_STATUS (Register 97). * * For more details on the Motion detection interrupt, see Section 8.3 of the * MPU-6000/MPU-6050 Product Specification document as well as Registers 56 and * 58 of this document. * * @return Current motion detection acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_MOT_THR */ int getMotionDetectionThreshold() { I2CdevReadByte(deviceAddress, MPU6050_RA_MOT_THR, bytebuffer); return bytebuffer; } /** Set motion detection event acceleration threshold. * @param threshold New motion detection acceleration threshold value (LSB = 2mg) * @see getMotionDetectionThreshold() * @see MPU6050_RA_MOT_THR */ void setMotionDetectionThreshold(int threshold) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MOT_THR, threshold); } // MOT_DUR register /** Get motion detection event duration threshold. * This register configures the duration counter threshold for Motion interrupt * generation. The duration counter ticks at 1 kHz, therefore MOT_DUR has a unit * of 1LSB = 1ms. The Motion detection duration counter increments when the * absolute value of any of the accelerometer measurements exceeds the Motion * detection threshold (Register 31). The Motion detection interrupt is * triggered when the Motion detection counter reaches the time count specified * in this register. * * For more details on the Motion detection interrupt, see Section 8.3 of the * MPU-6000/MPU-6050 Product Specification document. * * @return Current motion detection duration threshold value (LSB = 1ms) * @see MPU6050_RA_MOT_DUR */ int getMotionDetectionDuration() { I2CdevReadByte(deviceAddress, MPU6050_RA_MOT_DUR, bytebuffer); return bytebuffer; } /** Set motion detection event duration threshold. * @param duration New motion detection duration threshold value (LSB = 1ms) * @see getMotionDetectionDuration() * @see MPU6050_RA_MOT_DUR */ void setMotionDetectionDuration(int duration) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MOT_DUR, duration); } // ZRMOT_THR register /** Get zero motion detection event acceleration threshold. * This register configures the detection threshold for Zero Motion interrupt * generation. The unit of ZRMOT_THR is 1LSB = 2mg. Zero Motion is detected when * the absolute value of the accelerometer measurements for the 3 axes are each * less than the detection threshold. This condition increments the Zero Motion * duration counter (Register 34). The Zero Motion interrupt is triggered when * the Zero Motion duration counter reaches the time count specified in * ZRMOT_DUR (Register 34). * * Unlike Free Fall or Motion detection, Zero Motion detection triggers an * interrupt both when Zero Motion is first detected and when Zero Motion is no * longer detected. * * When a zero motion event is detected, a Zero Motion Status will be indicated * in the MOT_DETECT_STATUS register (Register 97). When a motion-to-zero-motion * condition is detected, the status bit is set to 1. When a zero-motion-to- * motion condition is detected, the status bit is set to 0. * * For more details on the Zero Motion detection interrupt, see Section 8.4 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers 56 * and 58 of this document. * * @return Current zero motion detection acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_ZRMOT_THR */ int getZeroMotionDetectionThreshold() { I2CdevReadByte(deviceAddress, MPU6050_RA_ZRMOT_THR, bytebuffer); return bytebuffer; } /** Set zero motion detection event acceleration threshold. * @param threshold New zero motion detection acceleration threshold value (LSB = 2mg) * @see getZeroMotionDetectionThreshold() * @see MPU6050_RA_ZRMOT_THR */ void setZeroMotionDetectionThreshold(int threshold) { I2CdevWriteByte(deviceAddress, MPU6050_RA_ZRMOT_THR, threshold); } // ZRMOT_DUR register /** Get zero motion detection event duration threshold. * This register configures the duration counter threshold for Zero Motion * interrupt generation. The duration counter ticks at 16 Hz, therefore * ZRMOT_DUR has a unit of 1 LSB = 64 ms. The Zero Motion duration counter * increments while the absolute value of the accelerometer measurements are * each less than the detection threshold (Register 33). The Zero Motion * interrupt is triggered when the Zero Motion duration counter reaches the time * count specified in this register. * * For more details on the Zero Motion detection interrupt, see Section 8.4 of * the MPU-6000/MPU-6050 Product Specification document, as well as Registers 56 * and 58 of this document. * * @return Current zero motion detection duration threshold value (LSB = 64ms) * @see MPU6050_RA_ZRMOT_DUR */ int getZeroMotionDetectionDuration() { I2CdevReadByte(deviceAddress, MPU6050_RA_ZRMOT_DUR, bytebuffer); return bytebuffer; } /** Set zero motion detection event duration threshold. * @param duration New zero motion detection duration threshold value (LSB = 1ms) * @see getZeroMotionDetectionDuration() * @see MPU6050_RA_ZRMOT_DUR */ void setZeroMotionDetectionDuration(int duration) { I2CdevWriteByte(deviceAddress, MPU6050_RA_ZRMOT_DUR, duration); } // FIFO_EN register /** Get temperature FIFO enabled value. * When set to 1, this bit enables TEMP_OUT_H and TEMP_OUT_L (Registers 65 and * 66) to be written into the FIFO buffer. * @return Current temperature FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getTempFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_TEMP_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set temperature FIFO enabled value. * @param enabled New temperature FIFO enabled value * @see getTempFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setTempFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_TEMP_FIFO_EN_BIT, enabled); } /** Get gyroscope X-axis FIFO enabled value. * When set to 1, this bit enables GYRO_XOUT_H and GYRO_XOUT_L (Registers 67 and * 68) to be written into the FIFO buffer. * @return Current gyroscope X-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getXGyroFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_XG_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set gyroscope X-axis FIFO enabled value. * @param enabled New gyroscope X-axis FIFO enabled value * @see getXGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setXGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_XG_FIFO_EN_BIT, enabled); } /** Get gyroscope Y-axis FIFO enabled value. * When set to 1, this bit enables GYRO_YOUT_H and GYRO_YOUT_L (Registers 69 and * 70) to be written into the FIFO buffer. * @return Current gyroscope Y-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getYGyroFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_YG_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set gyroscope Y-axis FIFO enabled value. * @param enabled New gyroscope Y-axis FIFO enabled value * @see getYGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setYGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_YG_FIFO_EN_BIT, enabled); } /** Get gyroscope Z-axis FIFO enabled value. * When set to 1, this bit enables GYRO_ZOUT_H and GYRO_ZOUT_L (Registers 71 and * 72) to be written into the FIFO buffer. * @return Current gyroscope Z-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getZGyroFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ZG_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set gyroscope Z-axis FIFO enabled value. * @param enabled New gyroscope Z-axis FIFO enabled value * @see getZGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setZGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ZG_FIFO_EN_BIT, enabled); } /** Get accelerometer FIFO enabled value. * When set to 1, this bit enables ACCEL_XOUT_H, ACCEL_XOUT_L, ACCEL_YOUT_H, * ACCEL_YOUT_L, ACCEL_ZOUT_H, and ACCEL_ZOUT_L (Registers 59 to 64) to be * written into the FIFO buffer. * @return Current accelerometer FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getAccelFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ACCEL_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set accelerometer FIFO enabled value. * @param enabled New accelerometer FIFO enabled value * @see getAccelFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setAccelFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ACCEL_FIFO_EN_BIT, enabled); } /** Get Slave 2 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 2 to be written into the FIFO buffer. * @return Current Slave 2 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave2FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV2_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 2 FIFO enabled value. * @param enabled New Slave 2 FIFO enabled value * @see getSlave2FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave2FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV2_FIFO_EN_BIT, enabled); } /** Get Slave 1 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 1 to be written into the FIFO buffer. * @return Current Slave 1 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave1FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV1_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 1 FIFO enabled value. * @param enabled New Slave 1 FIFO enabled value * @see getSlave1FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave1FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV1_FIFO_EN_BIT, enabled); } /** Get Slave 0 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 0 to be written into the FIFO buffer. * @return Current Slave 0 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave0FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV0_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 0 FIFO enabled value. * @param enabled New Slave 0 FIFO enabled value * @see getSlave0FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave0FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV0_FIFO_EN_BIT, enabled); } // I2C_MST_CTRL register /** Get multi-master enabled value. * Multi-master capability allows multiple I2C masters to operate on the same * bus. In circuits where multi-master capability is required, set MULT_MST_EN * to 1. This will increase current drawn by approximately 30uA. * * In circuits where multi-master capability is required, the state of the I2C * bus must always be monitored by each separate I2C Master. Before an I2C * Master can assume arbitration of the bus, it must first confirm that no other * I2C Master has arbitration of the bus. When MULT_MST_EN is set to 1, the * MPU-60X0's bus arbitration detection logic is turned on, enabling it to * detect when the bus is available. * * @return Current multi-master enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getMultiMasterEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_MULT_MST_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set multi-master enabled value. * @param enabled New multi-master enabled value * @see getMultiMasterEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setMultiMasterEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_MULT_MST_EN_BIT, enabled); } /** Get wait-for-external-sensor-data enabled value. * When the WAIT_FOR_ES bit is set to 1, the Data Ready interrupt will be * delayed until External Sensor data from the Slave Devices are loaded into the * EXT_SENS_DATA registers. This is used to ensure that both the internal sensor * data (i.e. from gyro and accel) and external sensor data have been loaded to * their respective data registers (i.e. the data is synced) when the Data Ready * interrupt is triggered. * * @return Current wait-for-external-sensor-data enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getWaitForExternalSensorEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_WAIT_FOR_ES_BIT, bytebuffer); return bytebuffer != 0; } /** Set wait-for-external-sensor-data enabled value. * @param enabled New wait-for-external-sensor-data enabled value * @see getWaitForExternalSensorEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setWaitForExternalSensorEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_WAIT_FOR_ES_BIT, enabled); } /** Get Slave 3 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 3 to be written into the FIFO buffer. * @return Current Slave 3 FIFO enabled value * @see MPU6050_RA_MST_CTRL */ boolean getSlave3FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_SLV_3_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 3 FIFO enabled value. * @param enabled New Slave 3 FIFO enabled value * @see getSlave3FIFOEnabled() * @see MPU6050_RA_MST_CTRL */ void setSlave3FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_SLV_3_FIFO_EN_BIT, enabled); } /** Get slave read/write transition enabled value. * The I2C_MST_P_NSR bit configures the I2C Master's transition from one slave * read to the next slave read. If the bit equals 0, there will be a restart * between reads. If the bit equals 1, there will be a stop followed by a start * of the following read. When a write transaction follows a read transaction, * the stop followed by a start of the successive write will be always used. * * @return Current slave read/write transition enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getSlaveReadWriteTransitionEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_P_NSR_BIT, bytebuffer); return bytebuffer != 0; } /** Set slave read/write transition enabled value. * @param enabled New slave read/write transition enabled value * @see getSlaveReadWriteTransitionEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setSlaveReadWriteTransitionEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_P_NSR_BIT, enabled); } /** Get I2C master clock speed. * I2C_MST_CLK is a 4 bit unsigned value which configures a divider on the * MPU-60X0 internal 8MHz clock. It sets the I2C master clock speed according to * the following table: * * <pre> * I2C_MST_CLK | I2C Master Clock Speed | 8MHz Clock Divider * ------------+------------------------+------------------- * 0 | 348kHz | 23 * 1 | 333kHz | 24 * 2 | 320kHz | 25 * 3 | 308kHz | 26 * 4 | 296kHz | 27 * 5 | 286kHz | 28 * 6 | 276kHz | 29 * 7 | 267kHz | 30 * 8 | 258kHz | 31 * 9 | 500kHz | 16 * 10 | 471kHz | 17 * 11 | 444kHz | 18 * 12 | 421kHz | 19 * 13 | 400kHz | 20 * 14 | 381kHz | 21 * 15 | 364kHz | 22 * </pre> * * @return Current I2C master clock speed * @see MPU6050_RA_I2C_MST_CTRL */ int getMasterClockSpeed() { I2CdevReadBits(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_CLK_BIT, MPU6050_I2C_MST_CLK_LENGTH, bytebuffer); return bytebuffer; } /** Set I2C master clock speed. * @reparam speed Current I2C master clock speed * @see MPU6050_RA_I2C_MST_CTRL */ void setMasterClockSpeed(int speed) { I2CdevWriteBits(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_CLK_BIT, MPU6050_I2C_MST_CLK_LENGTH, speed); } // I2C_SLV* registers (Slave 0-3) /** Get the I2C address of the specified slave (0-3). * Note that Bit 7 (MSB) controls read/write mode. If Bit 7 is set, it's a read * operation, and if it is cleared, then it's a write operation. The remaining * bits (6-0) are the 7-bit device address of the slave device. * * In read mode, the result of the read is placed in the lowest available * EXT_SENS_DATA register. For further information regarding the allocation of * read results, please refer to the EXT_SENS_DATA register description * (Registers 73 - 96). * * The MPU-6050 supports a total of five slaves, but Slave 4 has unique * characteristics, and so it has its own functions (getSlave4* and setSlave4*). * * I2C data transactions are performed at the Sample Rate, as defined in * Register 25. The user is responsible for ensuring that I2C data transactions * to and from each enabled Slave can be completed within a single period of the * Sample Rate. * * The I2C slave access rate can be reduced relative to the Sample Rate. This * reduced access rate is determined by I2C_MST_DLY (Register 52). Whether a * slave's access rate is reduced relative to the Sample Rate is determined by * I2C_MST_DELAY_CTRL (Register 103). * * The processing order for the slaves is fixed. The sequence followed for * processing the slaves is Slave 0, Slave 1, Slave 2, Slave 3 and Slave 4. If a * particular Slave is disabled it will be skipped. * * Each slave can either be accessed at the sample rate or at a reduced sample * rate. In a case where some slaves are accessed at the Sample Rate and some * slaves are accessed at the reduced rate, the sequence of accessing the slaves * (Slave 0 to Slave 4) is still followed. However, the reduced rate slaves will * be skipped if their access rate dictates that they should not be accessed * during that particular cycle. For further information regarding the reduced * access rate, please refer to Register 52. Whether a slave is accessed at the * Sample Rate or at the reduced rate is determined by the Delay Enable bits in * Register 103. * * @param num Slave number (0-3) * @return Current address for specified slave * @see MPU6050_RA_I2C_SLV0_ADDR */ int getSlaveAddress(int num) { if (num > 3) return 0; I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV0_ADDR + num*3, bytebuffer); return bytebuffer; } /** Set the I2C address of the specified slave (0-3). * @param num Slave number (0-3) * @param address New address for specified slave * @see getSlaveAddress() * @see MPU6050_RA_I2C_SLV0_ADDR */ void setSlaveAddress(int num, int address) { if (num > 3) return; I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV0_ADDR + num*3, address); } /** Get the active internal register for the specified slave (0-3). * Read/write operations for this slave will be done to whatever internal * register address is stored in this MPU register. * * The MPU-6050 supports a total of five slaves, but Slave 4 has unique * characteristics, and so it has its own functions. * * @param num Slave number (0-3) * @return Current active register for specified slave * @see MPU6050_RA_I2C_SLV0_REG */ int getSlaveRegister(int num) { if (num > 3) return 0; I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV0_REG + num*3, bytebuffer); return bytebuffer; } /** Set the active internal register for the specified slave (0-3). * @param num Slave number (0-3) * @param reg New active register for specified slave * @see getSlaveRegister() * @see MPU6050_RA_I2C_SLV0_REG */ void setSlaveRegister(int num, int reg) { if (num > 3) return; I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV0_REG + num*3, reg); } /** Get the enabled value for the specified slave (0-3). * When set to 1, this bit enables Slave 0 for data transfer operations. When * cleared to 0, this bit disables Slave 0 from data transfer operations. * @param num Slave number (0-3) * @return Current enabled value for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveEnabled(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set the enabled value for the specified slave (0-3). * @param num Slave number (0-3) * @param enabled New enabled value for specified slave * @see getSlaveEnabled() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveEnabled(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_EN_BIT, enabled); } /** Get word pair byte-swapping enabled for the specified slave (0-3). * When set to 1, this bit enables byte swapping. When byte swapping is enabled, * the high and low bytes of a word pair are swapped. Please refer to * I2C_SLV0_GRP for the pairing convention of the word pairs. When cleared to 0, * bytes transferred to and from Slave 0 will be written to EXT_SENS_DATA * registers in the order they were transferred. * * @param num Slave number (0-3) * @return Current word pair byte-swapping enabled value for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWordByteSwap(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_BYTE_SW_BIT, bytebuffer); return bytebuffer != 0; } /** Set word pair byte-swapping enabled for the specified slave (0-3). * @param num Slave number (0-3) * @param enabled New word pair byte-swapping enabled value for specified slave * @see getSlaveWordByteSwap() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWordByteSwap(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_BYTE_SW_BIT, enabled); } /** Get write mode for the specified slave (0-3). * When set to 1, the transaction will read or write data only. When cleared to * 0, the transaction will write a register address prior to reading or writing * data. This should equal 0 when specifying the register address within the * Slave device to/from which the ensuing data transaction will take place. * * @param num Slave number (0-3) * @return Current write mode for specified slave (0 = register address + data, 1 = data only) * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWriteMode(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_REG_DIS_BIT, bytebuffer); return bytebuffer != 0; } /** Set write mode for the specified slave (0-3). * @param num Slave number (0-3) * @param mode New write mode for specified slave (0 = register address + data, 1 = data only) * @see getSlaveWriteMode() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWriteMode(int num, boolean mode) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_REG_DIS_BIT, mode); } /** Get word pair grouping order offset for the specified slave (0-3). * This sets specifies the grouping order of word pairs received from registers. * When cleared to 0, bytes from register addresses 0 and 1, 2 and 3, etc (even, * then odd register addresses) are paired to form a word. When set to 1, bytes * from register addresses are paired 1 and 2, 3 and 4, etc. (odd, then even * register addresses) are paired to form a word. * * @param num Slave number (0-3) * @return Current word pair grouping order offset for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWordGroupOffset(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_GRP_BIT, bytebuffer); return bytebuffer != 0; } /** Set word pair grouping order offset for the specified slave (0-3). * @param num Slave number (0-3) * @param enabled New word pair grouping order offset for specified slave * @see getSlaveWordGroupOffset() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWordGroupOffset(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_GRP_BIT, enabled); } /** Get number of bytes to read for the specified slave (0-3). * Specifies the number of bytes transferred to and from Slave 0. Clearing this * bit to 0 is equivalent to disabling the register by writing 0 to I2C_SLV0_EN. * @param num Slave number (0-3) * @return Number of bytes to read for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ int getSlaveDataLength(int num) { if (num > 3) return 0; I2CdevReadBits(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_LEN_BIT, MPU6050_I2C_SLV_LEN_LENGTH, bytebuffer); return bytebuffer; } /** Set number of bytes to read for the specified slave (0-3). * @param num Slave number (0-3) * @param length Number of bytes to read for specified slave * @see getSlaveDataLength() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveDataLength(int num, int length) { if (num > 3) return; I2CdevWriteBits(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_LEN_BIT, MPU6050_I2C_SLV_LEN_LENGTH, length); } // I2C_SLV* registers (Slave 4) /** Get the I2C address of Slave 4. * Note that Bit 7 (MSB) controls read/write mode. If Bit 7 is set, it's a read * operation, and if it is cleared, then it's a write operation. The remaining * bits (6-0) are the 7-bit device address of the slave device. * * @return Current address for Slave 4 * @see getSlaveAddress() * @see MPU6050_RA_I2C_SLV4_ADDR */ int getSlave4Address() { I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV4_ADDR, bytebuffer); return bytebuffer; } /** Set the I2C address of Slave 4. * @param address New address for Slave 4 * @see getSlave4Address() * @see MPU6050_RA_I2C_SLV4_ADDR */ void setSlave4Address(int address) { I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV4_ADDR, address); } /** Get the active internal register for the Slave 4. * Read/write operations for this slave will be done to whatever internal * register address is stored in this MPU register. * * @return Current active register for Slave 4 * @see MPU6050_RA_I2C_SLV4_REG */ int getSlave4Register() { I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV4_REG, bytebuffer); return bytebuffer; } /** Set the active internal register for Slave 4. * @param reg New active register for Slave 4 * @see getSlave4Register() * @see MPU6050_RA_I2C_SLV4_REG */ void setSlave4Register(int reg) { I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV4_REG, reg); } /** Set new byte to write to Slave 4. * This register stores the data to be written into the Slave 4. If I2C_SLV4_RW * is set 1 (set to read), this register has no effect. * @param data New byte to write to Slave 4 * @see MPU6050_RA_I2C_SLV4_DO */ void setSlave4OutputByte(int data) { I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV4_DO, data); } /** Get the enabled value for the Slave 4. * When set to 1, this bit enables Slave 4 for data transfer operations. When * cleared to 0, this bit disables Slave 4 from data transfer operations. * @return Current enabled value for Slave 4 * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4Enabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set the enabled value for Slave 4. * @param enabled New enabled value for Slave 4 * @see getSlave4Enabled() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4Enabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_EN_BIT, enabled); } /** Get the enabled value for Slave 4 transaction interrupts. * When set to 1, this bit enables the generation of an interrupt signal upon * completion of a Slave 4 transaction. When cleared to 0, this bit disables the * generation of an interrupt signal upon completion of a Slave 4 transaction. * The interrupt status can be observed in Register 54. * * @return Current enabled value for Slave 4 transaction interrupts. * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4InterruptEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_INT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set the enabled value for Slave 4 transaction interrupts. * @param enabled New enabled value for Slave 4 transaction interrupts. * @see getSlave4InterruptEnabled() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4InterruptEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_INT_EN_BIT, enabled); } /** Get write mode for Slave 4. * When set to 1, the transaction will read or write data only. When cleared to * 0, the transaction will write a register address prior to reading or writing * data. This should equal 0 when specifying the register address within the * Slave device to/from which the ensuing data transaction will take place. * * @return Current write mode for Slave 4 (0 = register address + data, 1 = data only) * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4WriteMode() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_REG_DIS_BIT, bytebuffer); return bytebuffer != 0; } /** Set write mode for the Slave 4. * @param mode New write mode for Slave 4 (0 = register address + data, 1 = data only) * @see getSlave4WriteMode() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4WriteMode(boolean mode) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_REG_DIS_BIT, mode); } /** Get Slave 4 master delay value. * This configures the reduced access rate of I2C slaves relative to the Sample * Rate. When a slave's access rate is decreased relative to the Sample Rate, * the slave is accessed every: * * 1 / (1 + I2C_MST_DLY) samples * * This base Sample Rate in turn is determined by SMPLRT_DIV (register 25) and * DLPF_CFG (register 26). Whether a slave's access rate is reduced relative to * the Sample Rate is determined by I2C_MST_DELAY_CTRL (register 103). For * further information regarding the Sample Rate, please refer to register 25. * * @return Current Slave 4 master delay value * @see MPU6050_RA_I2C_SLV4_CTRL */ int getSlave4MasterDelay() { I2CdevReadBits(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_MST_DLY_BIT, MPU6050_I2C_SLV4_MST_DLY_LENGTH, bytebuffer); return bytebuffer; } /** Set Slave 4 master delay value. * @param delay New Slave 4 master delay value * @see getSlave4MasterDelay() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4MasterDelay(int delay) { I2CdevWriteBits(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_MST_DLY_BIT, MPU6050_I2C_SLV4_MST_DLY_LENGTH, delay); } /** Get last available byte read from Slave 4. * This register stores the data read from Slave 4. This field is populated * after a read transaction. * @return Last available byte read from to Slave 4 * @see MPU6050_RA_I2C_SLV4_DI */ int getSlate4InputByte() { I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV4_DI, bytebuffer); return bytebuffer; } // I2C_MST_STATUS register /** Get FSYNC interrupt status. * This bit reflects the status of the FSYNC interrupt from an external device * into the MPU-60X0. This is used as a way to pass an external interrupt * through the MPU-60X0 to the host application processor. When set to 1, this * bit will cause an interrupt if FSYNC_INT_EN is asserted in INT_PIN_CFG * (Register 55). * @return FSYNC interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getPassthroughStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_PASS_THROUGH_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 4 transaction done status. * Automatically sets to 1 when a Slave 4 transaction has completed. This * triggers an interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register * (Register 56) is asserted and if the SLV_4_DONE_INT bit is asserted in the * I2C_SLV4_CTRL register (Register 52). * @return Slave 4 transaction done status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave4IsDone() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV4_DONE_BIT, bytebuffer); return bytebuffer != 0; } /** Get master arbitration lost status. * This bit automatically sets to 1 when the I2C Master has lost arbitration of * the auxiliary I2C bus (an error condition). This triggers an interrupt if the * I2C_MST_INT_EN bit in the INT_ENABLE register (Register 56) is asserted. * @return Master arbitration lost status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getLostArbitration() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_LOST_ARB_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 4 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 4. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 4 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave4Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV4_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 3 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 3. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 3 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave3Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV3_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 2 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 2. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 2 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave2Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV2_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 1 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 1. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 1 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave1Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV1_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 0 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 0. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 0 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave0Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV0_NACK_BIT, bytebuffer); return bytebuffer != 0; } // INT_PIN_CFG register /** Get interrupt logic level mode. * Will be set 0 for active-high, 1 for active-low. * @return Current interrupt mode (0=active-high, 1=active-low) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_LEVEL_BIT */ boolean getInterruptMode() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_LEVEL_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt logic level mode. * @param mode New interrupt mode (0=active-high, 1=active-low) * @see getInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_LEVEL_BIT */ void setInterruptMode(boolean mode) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_LEVEL_BIT, mode); } /** Get interrupt drive mode. * Will be set 0 for push-pull, 1 for open-drain. * @return Current interrupt drive mode (0=push-pull, 1=open-drain) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_OPEN_BIT */ boolean getInterruptDrive() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_OPEN_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt drive mode. * @param drive New interrupt drive mode (0=push-pull, 1=open-drain) * @see getInterruptDrive() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_OPEN_BIT */ void setInterruptDrive(boolean drive) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_OPEN_BIT, drive); } /** Get interrupt latch mode. * Will be set 0 for 50us-pulse, 1 for latch-until-int-cleared. * @return Current latch mode (0=50us-pulse, 1=latch-until-int-cleared) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_LATCH_INT_EN_BIT */ boolean getInterruptLatch() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_LATCH_INT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt latch mode. * @param latch New latch mode (0=50us-pulse, 1=latch-until-int-cleared) * @see getInterruptLatch() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_LATCH_INT_EN_BIT */ void setInterruptLatch(boolean latch) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_LATCH_INT_EN_BIT, latch); } /** Get interrupt latch clear mode. * Will be set 0 for status-read-only, 1 for any-register-read. * @return Current latch clear mode (0=status-read-only, 1=any-register-read) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_RD_CLEAR_BIT */ boolean getInterruptLatchClear() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_RD_CLEAR_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt latch clear mode. * @param clear New latch clear mode (0=status-read-only, 1=any-register-read) * @see getInterruptLatchClear() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_RD_CLEAR_BIT */ void setInterruptLatchClear(boolean clear) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_RD_CLEAR_BIT, clear); } /** Get FSYNC interrupt logic level mode. * @return Current FSYNC interrupt mode (0=active-high, 1=active-low) * @see getFSyncInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT */ boolean getFSyncInterruptLevel() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT, bytebuffer); return bytebuffer != 0; } /** Set FSYNC interrupt logic level mode. * @param mode New FSYNC interrupt mode (0=active-high, 1=active-low) * @see getFSyncInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT */ void setFSyncInterruptLevel(boolean level) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT, level); } /** Get FSYNC pin interrupt enabled setting. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled setting * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_EN_BIT */ boolean getFSyncInterruptEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set FSYNC pin interrupt enabled setting. * @param enabled New FSYNC pin interrupt enabled setting * @see getFSyncInterruptEnabled() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_EN_BIT */ void setFSyncInterruptEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_EN_BIT, enabled); } /** Get I2C bypass enabled status. * When this bit is equal to 1 and I2C_MST_EN (Register 106 bit[5]) is equal to * 0, the host application processor will be able to directly access the * auxiliary I2C bus of the MPU-60X0. When this bit is equal to 0, the host * application processor will not be able to directly access the auxiliary I2C * bus of the MPU-60X0 regardless of the state of I2C_MST_EN (Register 106 * bit[5]). * @return Current I2C bypass enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_I2C_BYPASS_EN_BIT */ boolean getI2CBypassEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set I2C bypass enabled status. * When this bit is equal to 1 and I2C_MST_EN (Register 106 bit[5]) is equal to * 0, the host application processor will be able to directly access the * auxiliary I2C bus of the MPU-60X0. When this bit is equal to 0, the host * application processor will not be able to directly access the auxiliary I2C * bus of the MPU-60X0 regardless of the state of I2C_MST_EN (Register 106 * bit[5]). * @param enabled New I2C bypass enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_I2C_BYPASS_EN_BIT */ void setI2CBypassEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT, enabled); } /** Get reference clock output enabled status. * When this bit is equal to 1, a reference clock output is provided at the * CLKOUT pin. When this bit is equal to 0, the clock output is disabled. For * further information regarding CLKOUT, please refer to the MPU-60X0 Product * Specification document. * @return Current reference clock output enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_CLKOUT_EN_BIT */ boolean getClockOutputEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_CLKOUT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set reference clock output enabled status. * When this bit is equal to 1, a reference clock output is provided at the * CLKOUT pin. When this bit is equal to 0, the clock output is disabled. For * further information regarding CLKOUT, please refer to the MPU-60X0 Product * Specification document. * @param enabled New reference clock output enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_CLKOUT_EN_BIT */ void setClockOutputEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_CLKOUT_EN_BIT, enabled); } // INT_ENABLE register /** Get full interrupt enabled status. * Full register byte for all interrupts, for quick reading. Each bit will be * set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ int getIntEnabled() { I2CdevReadByte(deviceAddress, MPU6050_RA_INT_ENABLE, bytebuffer); return bytebuffer; } /** Set full interrupt enabled status. * Full register byte for all interrupts, for quick reading. Each bit should be * set 0 for disabled, 1 for enabled. * @param enabled New interrupt enabled status * @see getIntFreefallEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ void setIntEnabled(int enabled) { I2CdevWriteByte(deviceAddress, MPU6050_RA_INT_ENABLE, enabled); } /** Get Free Fall interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ boolean getIntFreefallEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FF_BIT, bytebuffer); return bytebuffer != 0; } /** Set Free Fall interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntFreefallEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ void setIntFreefallEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FF_BIT, enabled); } /** Get Motion Detection interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_MOT_BIT **/ boolean getIntMotionEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_MOT_BIT, bytebuffer); return bytebuffer != 0; } /** Set Motion Detection interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntMotionEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_MOT_BIT **/ void setIntMotionEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_MOT_BIT, enabled); } /** Get Zero Motion Detection interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_ZMOT_BIT **/ boolean getIntZeroMotionEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_ZMOT_BIT, bytebuffer); return bytebuffer != 0; } /** Set Zero Motion Detection interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntZeroMotionEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_ZMOT_BIT **/ void setIntZeroMotionEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_ZMOT_BIT, enabled); } /** Get FIFO Buffer Overflow interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT **/ boolean getIntFIFOBufferOverflowEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, bytebuffer); return bytebuffer != 0; } /** Set FIFO Buffer Overflow interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntFIFOBufferOverflowEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT **/ void setIntFIFOBufferOverflowEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, enabled); } /** Get I2C Master interrupt enabled status. * This enables any of the I2C Master interrupt sources to generate an * interrupt. Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT **/ boolean getIntI2CMasterEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_I2C_MST_INT_BIT, bytebuffer); return bytebuffer != 0; } /** Set I2C Master interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntI2CMasterEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT **/ void setIntI2CMasterEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_I2C_MST_INT_BIT, enabled); } /** Get Data Ready interrupt enabled setting. * This event occurs each time a write operation to all of the sensor registers * has been completed. Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ boolean getIntDataReadyEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DATA_RDY_BIT, bytebuffer); return bytebuffer != 0; } /** Set Data Ready interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntDataReadyEnabled() * @see MPU6050_RA_INT_CFG * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ void setIntDataReadyEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DATA_RDY_BIT, enabled); } // INT_STATUS register /** Get full set of interrupt status bits. * These bits clear to 0 after the register has been read. Very useful * for getting multiple INT statuses, since each single bit read clears * all of them because it has to read the whole byte. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS */ int getIntStatus() { I2CdevReadByte(deviceAddress, MPU6050_RA_INT_STATUS, bytebuffer); return bytebuffer; } /** Get Free Fall interrupt status. * This bit automatically sets to 1 when a Free Fall interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_FF_BIT */ boolean getIntFreefallStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_FF_BIT, bytebuffer); return bytebuffer != 0; } /** Get Motion Detection interrupt status. * This bit automatically sets to 1 when a Motion Detection interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_MOT_BIT */ boolean getIntMotionStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_MOT_BIT, bytebuffer); return bytebuffer != 0; } /** Get Zero Motion Detection interrupt status. * This bit automatically sets to 1 when a Zero Motion Detection interrupt has * been generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_ZMOT_BIT */ boolean getIntZeroMotionStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_ZMOT_BIT, bytebuffer); return bytebuffer != 0; } /** Get FIFO Buffer Overflow interrupt status. * This bit automatically sets to 1 when a Free Fall interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT */ boolean getIntFIFOBufferOverflowStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, bytebuffer); return bytebuffer != 0; } /** Get I2C Master interrupt status. * This bit automatically sets to 1 when an I2C Master interrupt has been * generated. For a list of I2C Master interrupts, please refer to Register 54. * The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT */ boolean getIntI2CMasterStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_I2C_MST_INT_BIT, bytebuffer); return bytebuffer != 0; } /** Get Data Ready interrupt status. * This bit automatically sets to 1 when a Data Ready interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ boolean getIntDataReadyStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_DATA_RDY_BIT, bytebuffer); return bytebuffer != 0; } // ACCEL_*OUT_* registers /** Get raw 9-axis motion sensor readings (accel/gyro/compass). * FUNCTION NOT FULLY IMPLEMENTED YET. * @param ax 16-bit signed integer container for accelerometer X-axis value * @param ay 16-bit signed integer container for accelerometer Y-axis value * @param az 16-bit signed integer container for accelerometer Z-axis value * @param gx 16-bit signed integer container for gyroscope X-axis value * @param gy 16-bit signed integer container for gyroscope Y-axis value * @param gz 16-bit signed integer container for gyroscope Z-axis value * @param mx 16-bit signed integer container for magnetometer X-axis value * @param my 16-bit signed integer container for magnetometer Y-axis value * @param mz 16-bit signed integer container for magnetometer Z-axis value * @see getMotion6() * @see getAcceleration() * @see getRotation() * @see MPU6050_RA_ACCEL_XOUT_H */ void getMotion9(int ax, int ay, int az, int gx, int gy, int gz, int mx, int my, int mz) { getMotion6(ax, ay, az, gx, gy, gz); // TODO: magnetometer integration } /** Get raw 6-axis motion sensor readings (accel/gyro). * Retrieves all currently available motion sensor values. * @param ax 16-bit signed integer container for accelerometer X-axis value * @param ay 16-bit signed integer container for accelerometer Y-axis value * @param az 16-bit signed integer container for accelerometer Z-axis value * @param gx 16-bit signed integer container for gyroscope X-axis value * @param gy 16-bit signed integer container for gyroscope Y-axis value * @param gz 16-bit signed integer container for gyroscope Z-axis value * @see getAcceleration() * @see getRotation() * @see MPU6050_RA_ACCEL_XOUT_H */ void getMotion6(int ax, int ay, int az, int gx, int gy, int gz) { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_XOUT_H, 14, buffer); ax = (((int)buffer[0]) << 8) | buffer[1]; ay = (((int)buffer[2]) << 8) | buffer[3]; az = (((int)buffer[4]) << 8) | buffer[5]; gx = (((int)buffer[8]) << 8) | buffer[9]; gy = (((int)buffer[10]) << 8) | buffer[11]; gz = (((int)buffer[12]) << 8) | buffer[13]; } /** Get 3-axis accelerometer readings. * These registers store the most recent accelerometer measurements. * Accelerometer measurements are written to these registers at the Sample Rate * as defined in Register 25. * * The accelerometer measurement registers, along with the temperature * measurement registers, gyroscope measurement registers, and external sensor * data registers, are composed of two sets of registers: an internal register * set and a user-facing read register set. * * The data within the accelerometer sensors' internal register set is always * updated at the Sample Rate. Meanwhile, the user-facing read register set * duplicates the internal register set's data values whenever the serial * interface is idle. This guarantees that a burst read of sensor registers will * read measurements from the same sampling instant. Note that if burst reads * are not used, the user is responsible for ensuring a set of single byte reads * correspond to a single sampling instant by checking the Data Ready interrupt. * * Each 16-bit accelerometer measurement has a full scale defined in ACCEL_FS * (Register 28). For each full scale setting, the accelerometers' sensitivity * per LSB in ACCEL_xOUT is shown in the table below: * * <pre> * AFS_SEL | Full Scale Range | LSB Sensitivity * --------+------------------+---------------- * 0 | +/- 2g | 8192 LSB/mg * 1 | +/- 4g | 4096 LSB/mg * 2 | +/- 8g | 2048 LSB/mg * 3 | +/- 16g | 1024 LSB/mg * </pre> * * @param x 16-bit signed integer container for X-axis acceleration * @param y 16-bit signed integer container for Y-axis acceleration * @param z 16-bit signed integer container for Z-axis acceleration * @see MPU6050_RA_GYRO_XOUT_H */ void getAcceleration(int x, int y, int z) { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_XOUT_H, 6, buffer); x = (((int)buffer[0]) << 8) | buffer[1]; y = (((int)buffer[2]) << 8) | buffer[3]; z = (((int)buffer[4]) << 8) | buffer[5]; } /** Get X-axis accelerometer reading. * @return X-axis acceleration measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_ACCEL_XOUT_H */ int getAccelerationX() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_XOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Y-axis accelerometer reading. * @return Y-axis acceleration measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_ACCEL_YOUT_H */ int getAccelerationY() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_YOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Z-axis accelerometer reading. * @return Z-axis acceleration measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_ACCEL_ZOUT_H */ int getAccelerationZ() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_ZOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // TEMP_OUT_* registers /** Get current internal temperature. * @return Temperature reading in 16-bit 2's complement format * @see MPU6050_RA_TEMP_OUT_H */ int getTemperature() { I2CdevReadBytes(deviceAddress, MPU6050_RA_TEMP_OUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // GYRO_*OUT_* registers /** Get 3-axis gyroscope readings. * These gyroscope measurement registers, along with the accelerometer * measurement registers, temperature measurement registers, and external sensor * data registers, are composed of two sets of registers: an internal register * set and a user-facing read register set. * The data within the gyroscope sensors' internal register set is always * updated at the Sample Rate. Meanwhile, the user-facing read register set * duplicates the internal register set's data values whenever the serial * interface is idle. This guarantees that a burst read of sensor registers will * read measurements from the same sampling instant. Note that if burst reads * are not used, the user is responsible for ensuring a set of single byte reads * correspond to a single sampling instant by checking the Data Ready interrupt. * * Each 16-bit gyroscope measurement has a full scale defined in FS_SEL * (Register 27). For each full scale setting, the gyroscopes' sensitivity per * LSB in GYRO_xOUT is shown in the table below: * * <pre> * FS_SEL | Full Scale Range | LSB Sensitivity * -------+--------------------+---------------- * 0 | +/- 250 degrees/s | 131 LSB/deg/s * 1 | +/- 500 degrees/s | 65.5 LSB/deg/s * 2 | +/- 1000 degrees/s | 32.8 LSB/deg/s * 3 | +/- 2000 degrees/s | 16.4 LSB/deg/s * </pre> * * @param x 16-bit signed integer container for X-axis rotation * @param y 16-bit signed integer container for Y-axis rotation * @param z 16-bit signed integer container for Z-axis rotation * @see getMotion6() * @see MPU6050_RA_GYRO_XOUT_H */ void getRotation(int x, int y, int z) { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_XOUT_H, 6, buffer); x = (((int)buffer[0]) << 8) | buffer[1]; y = (((int)buffer[2]) << 8) | buffer[3]; z = (((int)buffer[4]) << 8) | buffer[5]; } /** Get X-axis gyroscope reading. * @return X-axis rotation measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_GYRO_XOUT_H */ int getRotationX() { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_XOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Y-axis gyroscope reading. * @return Y-axis rotation measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_GYRO_YOUT_H */ int getRotationY() { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_YOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Z-axis gyroscope reading. * @return Z-axis rotation measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_GYRO_ZOUT_H */ int getRotationZ() { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_ZOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // EXT_SENS_DATA_* registers /** Read single byte from external sensor data register. * These registers store data read from external sensors by the Slave 0, 1, 2, * and 3 on the auxiliary I2C interface. Data read by Slave 4 is stored in * I2C_SLV4_DI (Register 53). * * External sensor data is written to these registers at the Sample Rate as * defined in Register 25. This access rate can be reduced by using the Slave * Delay Enable registers (Register 103). * * External sensor data registers, along with the gyroscope measurement * registers, accelerometer measurement registers, and temperature measurement * registers, are composed of two sets of registers: an internal register set * and a user-facing read register set. * * The data within the external sensors' internal register set is always updated * at the Sample Rate (or the reduced access rate) whenever the serial interface * is idle. This guarantees that a burst read of sensor registers will read * measurements from the same sampling instant. Note that if burst reads are not * used, the user is responsible for ensuring a set of single byte reads * correspond to a single sampling instant by checking the Data Ready interrupt. * * Data is placed in these external sensor data registers according to * I2C_SLV0_CTRL, I2C_SLV1_CTRL, I2C_SLV2_CTRL, and I2C_SLV3_CTRL (Registers 39, * 42, 45, and 48). When more than zero bytes are read (I2C_SLVx_LEN > 0) from * an enabled slave (I2C_SLVx_EN = 1), the slave is read at the Sample Rate (as * defined in Register 25) or delayed rate (if specified in Register 52 and * 103). During each Sample cycle, slave reads are performed in order of Slave * number. If all slaves are enabled with more than zero bytes to be read, the * order will be Slave 0, followed by Slave 1, Slave 2, and Slave 3. * * Each enabled slave will have EXT_SENS_DATA registers associated with it by * number of bytes read (I2C_SLVx_LEN) in order of slave number, starting from * EXT_SENS_DATA_00. Note that this means enabling or disabling a slave may * change the higher numbered slaves' associated registers. Furthermore, if * fewer total bytes are being read from the external sensors as a result of * such a change, then the data remaining in the registers which no longer have * an associated slave device (i.e. high numbered registers) will remain in * these previously allocated registers unless reset. * * If the sum of the read lengths of all SLVx transactions exceed the number of * available EXT_SENS_DATA registers, the excess bytes will be dropped. There * are 24 EXT_SENS_DATA registers and hence the total read lengths between all * the slaves cannot be greater than 24 or some bytes will be lost. * * Note: Slave 4's behavior is distinct from that of Slaves 0-3. For further * information regarding the characteristics of Slave 4, please refer to * Registers 49 to 53. * * EXAMPLE: * Suppose that Slave 0 is enabled with 4 bytes to be read (I2C_SLV0_EN = 1 and * I2C_SLV0_LEN = 4) while Slave 1 is enabled with 2 bytes to be read so that * I2C_SLV1_EN = 1 and I2C_SLV1_LEN = 2. In such a situation, EXT_SENS_DATA _00 * through _03 will be associated with Slave 0, while EXT_SENS_DATA _04 and 05 * will be associated with Slave 1. If Slave 2 is enabled as well, registers * starting from EXT_SENS_DATA_06 will be allocated to Slave 2. * * If Slave 2 is disabled while Slave 3 is enabled in this same situation, then * registers starting from EXT_SENS_DATA_06 will be allocated to Slave 3 * instead. * * REGISTER ALLOCATION FOR DYNAMIC DISABLE VS. NORMAL DISABLE: * If a slave is disabled at any time, the space initially allocated to the * slave in the EXT_SENS_DATA register, will remain associated with that slave. * This is to avoid dynamic adjustment of the register allocation. * * The allocation of the EXT_SENS_DATA registers is recomputed only when (1) all * slaves are disabled, or (2) the I2C_MST_RST bit is set (Register 106). * * This above is also true if one of the slaves gets NACKed and stops * functioning. * * @param position Starting position (0-23) * @return Byte read from register */ int getExternalSensorByte(int position) { I2CdevReadByte(deviceAddress, MPU6050_RA_EXT_SENS_DATA_00 + position, bytebuffer); return bytebuffer; } /** Read word (2 bytes) from external sensor data registers. * @param position Starting position (0-21) * @return Word read from register * @see getExternalSensorByte() */ int getExternalSensorWord(int position) { I2CdevReadBytes(deviceAddress, MPU6050_RA_EXT_SENS_DATA_00 + position, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Read double word (4 bytes) from external sensor data registers. * @param position Starting position (0-20) * @return Double word read from registers * @see getExternalSensorByte() */ int getExternalSensorDWord(int position) { I2CdevReadBytes(deviceAddress, MPU6050_RA_EXT_SENS_DATA_00 + position, 4, buffer); return (((int)buffer[0]) << 24) | (((int)buffer[1]) << 16) | (((int)buffer[2]) << 8) | buffer[3]; } // MOT_DETECT_STATUS register /** Get full motion detection status register content (all bits). * @return Motion detection status byte * @see MPU6050_RA_MOT_DETECT_STATUS */ int getMotionStatus() { I2CdevReadByte(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, bytebuffer); return bytebuffer; } /** Get X-axis negative motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_XNEG_BIT */ boolean getXNegMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_XNEG_BIT, bytebuffer); return bytebuffer != 0; } /** Get X-axis positive motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_XPOS_BIT */ boolean getXPosMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_XPOS_BIT, bytebuffer); return bytebuffer != 0; } /** Get Y-axis negative motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_YNEG_BIT */ boolean getYNegMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_YNEG_BIT, bytebuffer); return bytebuffer != 0; } /** Get Y-axis positive motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_YPOS_BIT */ boolean getYPosMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_YPOS_BIT, bytebuffer); return bytebuffer != 0; } /** Get Z-axis negative motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZNEG_BIT */ boolean getZNegMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZNEG_BIT, bytebuffer); return bytebuffer != 0; } /** Get Z-axis positive motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZPOS_BIT */ boolean getZPosMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZPOS_BIT, bytebuffer); return bytebuffer != 0; } /** Get zero motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZRMOT_BIT */ boolean getZeroMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZRMOT_BIT, bytebuffer); return bytebuffer != 0; } // I2C_SLV*_DO register /** Write byte to Data Output container for specified slave. * This register holds the output data written into Slave when Slave is set to * write mode. For further information regarding Slave control, please * refer to Registers 37 to 39 and immediately following. * @param num Slave number (0-3) * @param data Byte to write * @see MPU6050_RA_I2C_SLV0_DO */ void setSlaveOutputByte(int num, int data) { if (num > 3) return; I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV0_DO + num, data); } // I2C_MST_DELAY_CTRL register /** Get external data shadow delay enabled status. * This register is used to specify the timing of external sensor data * shadowing. When DELAY_ES_SHADOW is set to 1, shadowing of external * sensor data is delayed until all data has been received. * @return Current external data shadow delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT */ boolean getExternalShadowDelayEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT, bytebuffer); return bytebuffer != 0; } /** Set external data shadow delay enabled status. * @param enabled New external data shadow delay enabled status. * @see getExternalShadowDelayEnabled() * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT */ void setExternalShadowDelayEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT, enabled); } /** Get slave delay enabled status. * When a particular slave delay is enabled, the rate of access for the that * slave device is reduced. When a slave's access rate is decreased relative to * the Sample Rate, the slave is accessed every: * * 1 / (1 + I2C_MST_DLY) Samples * * This base Sample Rate in turn is determined by SMPLRT_DIV (register * 25) * and DLPF_CFG (register 26). * * For further information regarding I2C_MST_DLY, please refer to register 52. * For further information regarding the Sample Rate, please refer to register 25. * * @param num Slave number (0-4) * @return Current slave delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT */ boolean getSlaveDelayEnabled(int num) { // MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT is 4, SLV3 is 3, etc. if (num > 4) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, num, bytebuffer); return bytebuffer != 0; } /** Set slave delay enabled status. * @param num Slave number (0-4) * @param enabled New slave delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT */ void setSlaveDelayEnabled(int num, boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, num, enabled); } // SIGNAL_PATH_RESET register /** Reset gyroscope signal path. * The reset will revert the signal path analog to digital converters and * filters to their power up configurations. * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_GYRO_RESET_BIT */ void resetGyroscopePath() { I2CdevWriteBit(deviceAddress, MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_GYRO_RESET_BIT, true); } /** Reset accelerometer signal path. * The reset will revert the signal path analog to digital converters and * filters to their power up configurations. * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_ACCEL_RESET_BIT */ void resetAccelerometerPath() { I2CdevWriteBit(deviceAddress, MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_ACCEL_RESET_BIT, true); } /** Reset temperature sensor signal path. * The reset will revert the signal path analog to digital converters and * filters to their power up configurations. * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_TEMP_RESET_BIT */ void resetTemperaturePath() { I2CdevWriteBit(deviceAddress, MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_TEMP_RESET_BIT, true); } // MOT_DETECT_CTRL register /** Get accelerometer power-on delay. * The accelerometer data path provides samples to the sensor registers, Motion * detection, Zero Motion detection, and Free Fall detection modules. The * signal path contains filters which must be flushed on wake-up with new * samples before the detection modules begin operations. The default wake-up * delay, of 4ms can be lengthened by up to 3ms. This additional delay is * specified in ACCEL_ON_DELAY in units of 1 LSB = 1 ms. The user may select * any value above zero unless instructed otherwise by InvenSense. Please refer * to Section 8 of the MPU-6000/MPU-6050 Product Specification document for * further information regarding the detection modules. * @return Current accelerometer power-on delay * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_ACCEL_ON_DELAY_BIT */ int getAccelerometerPowerOnDelay() { I2CdevReadBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_ACCEL_ON_DELAY_BIT, MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH, bytebuffer); return bytebuffer; } /** Set accelerometer power-on delay. * @param delay New accelerometer power-on delay (0-3) * @see getAccelerometerPowerOnDelay() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_ACCEL_ON_DELAY_BIT */ void setAccelerometerPowerOnDelay(int delay) { I2CdevWriteBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_ACCEL_ON_DELAY_BIT, MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH, delay); } /** Get Free Fall detection counter decrement configuration. * Detection is registered by the Free Fall detection module after accelerometer * measurements meet their respective threshold conditions over a specified * number of samples. When the threshold conditions are met, the corresponding * detection counter increments by 1. The user may control the rate at which the * detection counter decrements when the threshold condition is not met by * configuring FF_COUNT. The decrement rate can be set according to the * following table: * * <pre> * FF_COUNT | Counter Decrement * ---------+------------------ * 0 | Reset * 1 | 1 * 2 | 2 * 3 | 4 * </pre> * * When FF_COUNT is configured to 0 (reset), any non-qualifying sample will * reset the counter to 0. For further information on Free Fall detection, * please refer to Registers 29 to 32. * * @return Current decrement configuration * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_FF_COUNT_BIT */ int getFreefallDetectionCounterDecrement() { I2CdevReadBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_FF_COUNT_BIT, MPU6050_DETECT_FF_COUNT_LENGTH, bytebuffer); return bytebuffer; } /** Set Free Fall detection counter decrement configuration. * @param decrement New decrement configuration value * @see getFreefallDetectionCounterDecrement() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_FF_COUNT_BIT */ void setFreefallDetectionCounterDecrement(int decrement) { I2CdevWriteBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_FF_COUNT_BIT, MPU6050_DETECT_FF_COUNT_LENGTH, decrement); } /** Get Motion detection counter decrement configuration. * Detection is registered by the Motion detection module after accelerometer * measurements meet their respective threshold conditions over a specified * number of samples. When the threshold conditions are met, the corresponding * detection counter increments by 1. The user may control the rate at which the * detection counter decrements when the threshold condition is not met by * configuring MOT_COUNT. The decrement rate can be set according to the * following table: * * <pre> * MOT_COUNT | Counter Decrement * ----------+------------------ * 0 | Reset * 1 | 1 * 2 | 2 * 3 | 4 * </pre> * * When MOT_COUNT is configured to 0 (reset), any non-qualifying sample will * reset the counter to 0. For further information on Motion detection, * please refer to Registers 29 to 32. * */ int getMotionDetectionCounterDecrement() { I2CdevReadBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_MOT_COUNT_BIT, MPU6050_DETECT_MOT_COUNT_LENGTH, bytebuffer); return bytebuffer; } /** Set Motion detection counter decrement configuration. * @param decrement New decrement configuration value * @see getMotionDetectionCounterDecrement() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_MOT_COUNT_BIT */ void setMotionDetectionCounterDecrement(int decrement) { I2CdevWriteBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_MOT_COUNT_BIT, MPU6050_DETECT_MOT_COUNT_LENGTH, decrement); } // USER_CTRL register /** Get FIFO enabled status. * When this bit is set to 0, the FIFO buffer is disabled. The FIFO buffer * cannot be written to or read from while disabled. The FIFO buffer's state * does not change unless the MPU-60X0 is power cycled. * @return Current FIFO enabled status * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_EN_BIT */ boolean getFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set FIFO enabled status. * @param enabled New FIFO enabled status * @see getFIFOEnabled() * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_EN_BIT */ void setFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT, enabled); } /** Get I2C Master Mode enabled status. * When this mode is enabled, the MPU-60X0 acts as the I2C Master to the * external sensor slave devices on the auxiliary I2C bus. When this bit is * cleared to 0, the auxiliary I2C bus lines (AUX_DA and AUX_CL) are logically * driven by the primary I2C bus (SDA and SCL). This is a precondition to * enabling Bypass Mode. For further information regarding Bypass Mode, please * refer to Register 55. * @return Current I2C Master Mode enabled status * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_EN_BIT */ boolean getI2CMasterModeEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set I2C Master Mode enabled status. * @param enabled New I2C Master Mode enabled status * @see getI2CMasterModeEnabled() * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_EN_BIT */ void setI2CMasterModeEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT, enabled); } /** Switch from I2C to SPI mode (MPU-6000 only) * If this is set, the primary SPI interface will be enabled in place of the * disabled primary I2C interface. */ void switchSPIEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_IF_DIS_BIT, enabled); } /** Reset the FIFO. * This bit resets the FIFO buffer when set to 1 while FIFO_EN equals 0. This * bit automatically clears to 0 after the reset has been triggered. * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_RESET_BIT */ void resetFIFO() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_RESET_BIT, true); } /** Reset the I2C Master. * This bit resets the I2C Master when set to 1 while I2C_MST_EN equals 0. * This bit automatically clears to 0 after the reset has been triggered. * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_RESET_BIT */ void resetI2CMaster() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_RESET_BIT, true); } /** Reset all sensor registers and signal paths. * When set to 1, this bit resets the signal paths for all sensors (gyroscopes, * accelerometers, and temperature sensor). This operation will also clear the * sensor registers. This bit automatically clears to 0 after the reset has been * triggered. * * When resetting only the signal path (and not the sensor registers), please * use Register 104, SIGNAL_PATH_RESET. * * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_SIG_COND_RESET_BIT */ void resetSensors() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_SIG_COND_RESET_BIT, true); } // PWR_MGMT_1 register /** Trigger a full device reset. * A small delay of ~50ms may be desirable after triggering a reset. * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_DEVICE_RESET_BIT */ void reset() { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_DEVICE_RESET_BIT, true); } /** Get sleep mode status. * Setting the SLEEP bit in the register puts the device into very low power * sleep mode. In this mode, only the serial interface and internal registers * remain active, allowing for a very low standby current. Clearing this bit * puts the device back into normal mode. To save power, the individual standby * selections for each of the gyros should be used if any gyro axis is not used * by the application. * @return Current sleep mode enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_SLEEP_BIT */ boolean getSleepEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, bytebuffer); return bytebuffer != 0; } /** Set sleep mode status. * @param enabled New sleep mode enabled status * @see getSleepEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_SLEEP_BIT */ void setSleepEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, enabled); } /** Get wake cycle enabled status. * When this bit is set to 1 and SLEEP is disabled, the MPU-60X0 will cycle * between sleep mode and waking up to take a single sample of data from active * sensors at a rate determined by LP_WAKE_CTRL (register 108). * @return Current sleep mode enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CYCLE_BIT */ boolean getWakeCycleEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CYCLE_BIT, bytebuffer); return bytebuffer != 0; } /** Set wake cycle enabled status. * @param enabled New sleep mode enabled status * @see getWakeCycleEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CYCLE_BIT */ void setWakeCycleEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CYCLE_BIT, enabled); } /** Get temperature sensor enabled status. * Control the usage of the internal temperature sensor. * * Note: this register stores the *disabled* value, but for consistency with the * rest of the code, the function is named and used with standard true/false * values to indicate whether the sensor is enabled or disabled, respectively. * * @return Current temperature sensor enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_TEMP_DIS_BIT */ boolean getTempSensorEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_TEMP_DIS_BIT, bytebuffer); return bytebuffer != 0; // 1 is actually disabled here } /** Set temperature sensor enabled status. * Note: this register stores the *disabled* value, but for consistency with the * rest of the code, the function is named and used with standard true/false * values to indicate whether the sensor is enabled or disabled, respectively. * * @param enabled New temperature sensor enabled status * @see getTempSensorEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_TEMP_DIS_BIT */ void setTempSensorEnabled(boolean enabled) { // 1 is actually disabled here I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_TEMP_DIS_BIT, !enabled); } /** Get clock source setting. * @return Current clock source setting * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CLKSEL_BIT * @see MPU6050_PWR1_CLKSEL_LENGTH */ int getClockSource() { I2CdevReadBits(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, bytebuffer); return bytebuffer; } /** Set clock source setting. * An internal 8MHz oscillator, gyroscope based clock, or external sources can * be selected as the MPU-60X0 clock source. When the internal 8 MHz oscillator * or an external source is chosen as the clock source, the MPU-60X0 can operate * in low power modes with the gyroscopes disabled. * * Upon power up, the MPU-60X0 clock source defaults to the internal oscillator. * However, it is highly recommended that the device be configured to use one of * the gyroscopes (or an external clock source) as the clock reference for * improved stability. The clock source can be selected according to the following table: * * <pre> * CLK_SEL | Clock Source * --------+-------------------------------------- * 0 | Internal oscillator * 1 | PLL with X Gyro reference * 2 | PLL with Y Gyro reference * 3 | PLL with Z Gyro reference * 4 | PLL with external 32.768kHz reference * 5 | PLL with external 19.2MHz reference * 6 | Reserved * 7 | Stops the clock and keeps the timing generator in reset * </pre> * * @param source New clock source setting * @see getClockSource() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CLKSEL_BIT * @see MPU6050_PWR1_CLKSEL_LENGTH */ void setClockSource(int source) { I2CdevWriteBits(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, source); } // PWR_MGMT_2 register /** Get wake frequency in Accel-Only Low Power Mode. * The MPU-60X0 can be put into Accerlerometer Only Low Power Mode by setting * PWRSEL to 1 in the Power Management 1 register (Register 107). In this mode, * the device will power off all devices except for the primary I2C interface, * waking only the accelerometer at fixed intervals to take a single * measurement. The frequency of wake-ups can be configured with LP_WAKE_CTRL * as shown below: * * <pre> * LP_WAKE_CTRL | Wake-up Frequency * -------------+------------------ * 0 | 1.25 Hz * 1 | 2.5 Hz * 2 | 5 Hz * 3 | 10 Hz * </pre> * * For further information regarding the MPU-60X0's power modes, please refer to * Register 107. * * @return Current wake frequency * @see MPU6050_RA_PWR_MGMT_2 */ int getWakeFrequency() { I2CdevReadBits(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_LP_WAKE_CTRL_BIT, MPU6050_PWR2_LP_WAKE_CTRL_LENGTH, bytebuffer); return bytebuffer; } /** Set wake frequency in Accel-Only Low Power Mode. * @param frequency New wake frequency * @see MPU6050_RA_PWR_MGMT_2 */ void setWakeFrequency(int frequency) { I2CdevWriteBits(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_LP_WAKE_CTRL_BIT, MPU6050_PWR2_LP_WAKE_CTRL_LENGTH, frequency); } /** Get X-axis accelerometer standby enabled status. * If enabled, the X-axis will not gather or report data (or use power). * @return Current X-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XA_BIT */ boolean getStandbyXAccelEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XA_BIT, bytebuffer); return bytebuffer != 0; } /** Set X-axis accelerometer standby enabled status. * @param New X-axis standby enabled status * @see getStandbyXAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XA_BIT */ void setStandbyXAccelEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XA_BIT, enabled); } /** Get Y-axis accelerometer standby enabled status. * If enabled, the Y-axis will not gather or report data (or use power). * @return Current Y-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YA_BIT */ boolean getStandbyYAccelEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YA_BIT, bytebuffer); return bytebuffer != 0; } /** Set Y-axis accelerometer standby enabled status. * @param New Y-axis standby enabled status * @see getStandbyYAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YA_BIT */ void setStandbyYAccelEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YA_BIT, enabled); } /** Get Z-axis accelerometer standby enabled status. * If enabled, the Z-axis will not gather or report data (or use power). * @return Current Z-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZA_BIT */ boolean getStandbyZAccelEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZA_BIT, bytebuffer); return bytebuffer != 0; } /** Set Z-axis accelerometer standby enabled status. * @param New Z-axis standby enabled status * @see getStandbyZAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZA_BIT */ void setStandbyZAccelEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZA_BIT, enabled); } /** Get X-axis gyroscope standby enabled status. * If enabled, the X-axis will not gather or report data (or use power). * @return Current X-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XG_BIT */ boolean getStandbyXGyroEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XG_BIT, bytebuffer); return bytebuffer != 0; } /** Set X-axis gyroscope standby enabled status. * @param New X-axis standby enabled status * @see getStandbyXGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XG_BIT */ void setStandbyXGyroEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XG_BIT, enabled); } /** Get Y-axis gyroscope standby enabled status. * If enabled, the Y-axis will not gather or report data (or use power). * @return Current Y-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YG_BIT */ boolean getStandbyYGyroEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YG_BIT, bytebuffer); return bytebuffer != 0; } /** Set Y-axis gyroscope standby enabled status. * @param New Y-axis standby enabled status * @see getStandbyYGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YG_BIT */ void setStandbyYGyroEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YG_BIT, enabled); } /** Get Z-axis gyroscope standby enabled status. * If enabled, the Z-axis will not gather or report data (or use power). * @return Current Z-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZG_BIT */ boolean getStandbyZGyroEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZG_BIT, bytebuffer); return bytebuffer != 0; } /** Set Z-axis gyroscope standby enabled status. * @param New Z-axis standby enabled status * @see getStandbyZGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZG_BIT */ void setStandbyZGyroEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZG_BIT, enabled); } // FIFO_COUNT* registers /** Get current FIFO buffer size. * This value indicates the number of bytes stored in the FIFO buffer. This * number is in turn the number of bytes that can be read from the FIFO buffer * and it is directly proportional to the number of samples available given the * set of sensor data bound to be stored in the FIFO (register 35 and 36). * @return Current FIFO buffer size */ int getFIFOCount() { I2CdevReadBytes(deviceAddress, MPU6050_RA_FIFO_COUNTH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // FIFO_R_W register /** Get byte from FIFO buffer. * This register is used to read and write data from the FIFO buffer. Data is * written to the FIFO in order of register number (from lowest to highest). If * all the FIFO enable flags (see below) are enabled and all External Sensor * Data registers (Registers 73 to 96) are associated with a Slave device, the * contents of registers 59 through 96 will be written in order at the Sample * Rate. * * The contents of the sensor data registers (Registers 59 to 96) are written * into the FIFO buffer when their corresponding FIFO enable flags are set to 1 * in FIFO_EN (Register 35). An additional flag for the sensor data registers * associated with I2C Slave 3 can be found in I2C_MST_CTRL (Register 36). * * If the FIFO buffer has overflowed, the status bit FIFO_OFLOW_INT is * automatically set to 1. This bit is located in INT_STATUS (Register 58). * When the FIFO buffer has overflowed, the oldest data will be lost and new * data will be written to the FIFO. * * If the FIFO buffer is empty, reading this register will return the last byte * that was previously read from the FIFO until new data is available. The user * should check FIFO_COUNT to ensure that the FIFO buffer is not read when * empty. * * @return Byte from FIFO buffer */ int getFIFOByte() { I2CdevReadByte(deviceAddress, MPU6050_RA_FIFO_R_W, bytebuffer); return bytebuffer; } void getFIFOBytes(int[] data, int length) { if(length > 0){ I2CdevReadBytes(deviceAddress, MPU6050_RA_FIFO_R_W, length, data); } else { data = new int[0]; } } /** Write byte to FIFO buffer. * @see getFIFOByte() * @see MPU6050_RA_FIFO_R_W */ void setFIFOByte(int data) { I2CdevWriteByte(deviceAddress, MPU6050_RA_FIFO_R_W, data); } // WHO_AM_I register /** Get Device ID. * This register is used to verify the identity of the device (0b110100, 0x34). * @return Device ID (6 bits only! should be 0x34) * @see MPU6050_RA_WHO_AM_I * @see MPU6050_WHO_AM_I_BIT * @see MPU6050_WHO_AM_I_LENGTH */ int getDeviceID() { I2CdevReadBits(deviceAddress, MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, bytebuffer); return bytebuffer; } /** Set Device ID. * Write a new ID into the WHO_AM_I register (no idea why this should ever be * necessary though). * @param id New device ID to set. * @see getDeviceID() * @see MPU6050_RA_WHO_AM_I * @see MPU6050_WHO_AM_I_BIT * @see MPU6050_WHO_AM_I_LENGTH */ void setDeviceID(int id) { I2CdevWriteBits(deviceAddress, MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, id); } // ======== UNDOCUMENTED/DMP REGISTERS/METHODS ======== // XG_OFFS_TC register int getOTPBankValid() { I2CdevReadBit(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OTP_BNK_VLD_BIT, bytebuffer); return bytebuffer; } void setOTPBankValid(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OTP_BNK_VLD_BIT, enabled); } int getXGyroOffsetTC() { I2CdevReadBits(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, bytebuffer); return bytebuffer; } void setXGyroOffsetTC(int offset) { I2CdevWriteBits(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // YG_OFFS_TC register int getYGyroOffsetTC() { I2CdevReadBits(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, bytebuffer); return bytebuffer; } void setYGyroOffsetTC(int offset) { I2CdevWriteBits(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // ZG_OFFS_TC register int getZGyroOffsetTC() { I2CdevReadBits(deviceAddress, MPU6050_RA_ZG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, bytebuffer); return bytebuffer; } void setZGyroOffsetTC(int offset) { I2CdevWriteBits(deviceAddress, MPU6050_RA_ZG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // X_FINE_GAIN register int getXFineGain() { I2CdevReadByte(deviceAddress, MPU6050_RA_X_FINE_GAIN, bytebuffer); return bytebuffer; } void setXFineGain(int gain) { I2CdevWriteByte(deviceAddress, MPU6050_RA_X_FINE_GAIN, gain); } // Y_FINE_GAIN register int getYFineGain() { I2CdevReadByte(deviceAddress, MPU6050_RA_Y_FINE_GAIN, bytebuffer); return bytebuffer; } void setYFineGain(int gain) { I2CdevWriteByte(deviceAddress, MPU6050_RA_Y_FINE_GAIN, gain); } // Z_FINE_GAIN register int getZFineGain() { I2CdevReadByte(deviceAddress, MPU6050_RA_Z_FINE_GAIN, bytebuffer); return bytebuffer; } void setZFineGain(int gain) { I2CdevWriteByte(deviceAddress, MPU6050_RA_Z_FINE_GAIN, gain); } // XA_OFFS_* registers int getXAccelOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_XA_OFFS_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setXAccelOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_XA_OFFS_H, offset); } // YA_OFFS_* register int getYAccelOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_YA_OFFS_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setYAccelOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_YA_OFFS_H, offset); } // ZA_OFFS_* register int getZAccelOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ZA_OFFS_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setZAccelOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_ZA_OFFS_H, offset); } // XG_OFFS_USR* registers int getXGyroOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_XG_OFFS_USRH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setXGyroOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_XG_OFFS_USRH, offset); } // YG_OFFS_USR* register int getYGyroOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_YG_OFFS_USRH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setYGyroOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_YG_OFFS_USRH, offset); } // ZG_OFFS_USR* register int getZGyroOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ZG_OFFS_USRH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setZGyroOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_ZG_OFFS_USRH, offset); } // INT_ENABLE register (DMP functions) boolean getIntPLLReadyEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, bytebuffer); return bytebuffer != 0; } void setIntPLLReadyEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, enabled); } boolean getIntDMPEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DMP_INT_BIT, bytebuffer); return bytebuffer != 0; } void setIntDMPEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DMP_INT_BIT, enabled); } // DMP_INT_STATUS boolean getDMPInt5Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_5_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt4Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_4_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt3Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_3_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt2Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_2_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt1Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_1_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt0Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_0_BIT, bytebuffer); return bytebuffer != 0; } // INT_STATUS register (DMP functions) boolean getIntPLLReadyStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, bytebuffer); return bytebuffer != 0; } boolean getIntDMPStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_DMP_INT_BIT, bytebuffer); return bytebuffer != 0; } // USER_CTRL register (DMP functions) boolean getDMPEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_EN_BIT, bytebuffer); return bytebuffer != 0; } void setDMPEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_EN_BIT, enabled); } void resetDMP() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_RESET_BIT, true); } // BANK_SEL register void setMemoryBank(int bank, boolean prefetchEnabled, boolean userBank) { bank = bank & 0x1F; if (userBank) bank |= 0x20; if (prefetchEnabled) bank |= 0x40; I2CdevWriteByte(deviceAddress, MPU6050_RA_BANK_SEL, bank); } void setMemoryBank(int bank) { setMemoryBank(bank, false, false); } // MEM_START_ADDR register void setMemoryStartAddress(int address) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MEM_START_ADDR, address); } // MEM_R_W register int readMemoryByte() { I2CdevReadByte(deviceAddress, MPU6050_RA_MEM_R_W, bytebuffer); return bytebuffer; } void writeMemoryByte(int data) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MEM_R_W, data); } void readMemoryBlock(int[] data, int dataSize, int bank, int address) { setMemoryBank(bank); setMemoryStartAddress(address); int chunkSize; for (int i = 0; i < dataSize;) { // determine correct chunk size according to bank position and data size chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; // make sure we don't go past the data size if (i + chunkSize > dataSize) chunkSize = dataSize - i; // make sure this chunk doesn't go past the bank boundary (256 bytes) if (chunkSize > 256 - address) chunkSize = 256 - address; // read the chunk of data as specified I2CdevReadBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, data); // increase byte index by [chunkSize] i += chunkSize; // int automatically wraps to 0 at 256 address += chunkSize; // if we aren't done, update bank (if necessary) and address if (i < dataSize) { if (address == 0) bank++; setMemoryBank(bank); setMemoryStartAddress(address); } } } boolean writeMemoryBlock(int[] data, int dataSize, int bank, int address, boolean verify) { setMemoryBank(bank); setMemoryStartAddress(address); int chunkSize; int[] verifyBuffer; int[] progBuffer; int i; int j; if (verify){ verifyBuffer = new int[MPU6050_DMP_MEMORY_CHUNK_SIZE]; } else { verifyBuffer = new int[0]; } for (i = 0; i < dataSize;) { // determine correct chunk size according to bank position and data size chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; // make sure we don't go past the data size if (i + chunkSize > dataSize) {chunkSize = dataSize - i; } // make sure this chunk doesn't go past the bank boundary (256 bytes) if (chunkSize > 256 - address){ chunkSize = 256 - address; } // write the chunk of data as specified // progBuffer = (int *)data + i; progBuffer = new int[chunkSize]; for (j=0; j< chunkSize; j++){ progBuffer[j] = data[i+j]; } log.info(String.format("writeMemoryBlock: Block start: %s, ChunkSize %s", i, chunkSize)); I2CdevWriteBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, progBuffer); // verify data if needed if (verify && (verifyBuffer.length > 0)) { setMemoryBank(bank); setMemoryStartAddress(address); I2CdevReadBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, verifyBuffer); if (memcmp(progBuffer, verifyBuffer, chunkSize) != 0) { /*Serial.print("Block write verification error, bank "); Serial.print(bank, DEC); Serial.print(", address "); Serial.print(address, DEC); Serial.print("!\nExpected:"); for (j = 0; j < chunkSize; j++) { Serial.print(" 0x"); if (progBuffer[j] < 16) Serial.print("0"); Serial.print(progBuffer[j], HEX); } Serial.print("\nReceived:"); for (int j = 0; j < chunkSize; j++) { Serial.print(" 0x"); if (verifyBuffer[i + j] < 16) Serial.print("0"); Serial.print(verifyBuffer[i + j], HEX); } Serial.print("\n");*/ //* free(verifyBuffer); return false; // uh oh. } } // increase byte index by [chunkSize] i += chunkSize; // int automatically wraps to 0 at 256 address += chunkSize & 0xff; // if we aren't done, update bank (if necessary) and address if (i < dataSize) { if (address == 0) bank++; setMemoryBank(bank); setMemoryStartAddress(address); } } //* if (verify) free(verifyBuffer); return true; } boolean writeProgMemoryBlock(int[] data, int dataSize, int bank, int address, boolean verify) { return writeMemoryBlock(data, dataSize, bank, address, verify); } boolean writeProgMemoryBlock(int[] data, int dataSize) { return writeMemoryBlock(data, dataSize, 0, 0, true); } boolean writeDMPConfigurationSet(int[] data, int dataSize) { int[] progBuffer; int special; boolean success = false; int i; // config set data is a long string of blocks with the following structure: // [bank] [offset] [length] [byte[0], byte[1], ..., byte[length]] int bank, offset, length; for (i = 0; i < dataSize;) { bank = data[i++]; offset = data[i++]; length = data[i++]; // write data or perform special action if (length > 0) { // regular block of data to write /*Serial.print("Writing config block to bank "); Serial.print(bank); Serial.print(", offset "); Serial.print(offset); Serial.print(", length="); Serial.println(length);*/ //progBuffer = (int *)data + i; progBuffer = new int[length]; for (int k=0; k<length;k++){ progBuffer[k] = data[i+k]; } success = writeMemoryBlock(progBuffer, length, bank, offset, true); i += length; } else { // special instruction // NOTE: this kind of behavior (what and when to do certain things) // is totally undocumented. This code is in here based on observed // behavior only, and exactly why (or even whether) it has to be here // is anybody's guess for now. special = data[i++]; /*Serial.print("Special command code "); Serial.print(special, HEX); Serial.println(" found...");*/ if (special == 0x01) { // enable DMP-related interrupts //setIntZeroMotionEnabled(true); //setIntFIFOBufferOverflowEnabled(true); //setIntDMPEnabled(true); I2CdevWriteByte(deviceAddress, MPU6050_RA_INT_ENABLE, 0x32); // single operation success = true; } else { // unknown special command success = false; } } if (!success) { return false; // uh oh } } return true; } boolean writeProgDMPConfigurationSet(int[] data, int dataSize) { return writeDMPConfigurationSet(data, dataSize); } // DMP_CFG_1 register int getDMPConfig1() { I2CdevReadByte(deviceAddress, MPU6050_RA_DMP_CFG_1, bytebuffer); return bytebuffer; } void setDMPConfig1(int config) { I2CdevWriteByte(deviceAddress, MPU6050_RA_DMP_CFG_1, config); } // DMP_CFG_2 register int getDMPConfig2() { I2CdevReadByte(deviceAddress, MPU6050_RA_DMP_CFG_2, bytebuffer); return bytebuffer; } void setDMPConfig2(int config) { I2CdevWriteByte(deviceAddress, MPU6050_RA_DMP_CFG_2, config); } //* Compare the content of two buffers // Returns 0 if the two buffers have the same content otherwise 1 int memcmp(int[] buffer1, int[] buffer2, int length ){ int result = 0; for (int i=0 ; i < length ; i++){ if (buffer1[i] != buffer2[i]){ result = 1; } } return result; } int pgm_read_byte(int a){ return 0; } /* Start of I2CDEV section. Most of this code could be moved to and implemented in * the I2CControl interface. */ /** Read a single bit from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitNum Bit position to read (0-7) * @param data Container for single bit value * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadBit(int devAddr, int regAddr, int bitNum, int data, int timeout) { int bitmask = 1; int bytebuffer = data; int count = I2CdevReadByte(devAddr, regAddr, bytebuffer, timeout); data = bytebuffer & (bitmask << bitNum); return count; } int I2CdevReadBit(int devAddr, int regAddr, int bitNum, int data) { return I2CdevReadBit(devAddr, regAddr, bitNum, data, timeout); } /** Read a single bit from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitNum Bit position to read (0-15) * @param data Container for single bit value * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadBitW(int devAddr, int regAddr, int bitNum, int data, int timeout) { int b = 0; int bitmask = 1; int count = I2CdevReadWord(devAddr, regAddr, b, timeout); data = b & (bitmask << bitNum); return count; } /** Read multiple bits from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitStart First bit position to read (0-7) * @param length Number of bits to read (not more than 8) * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05) * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadBits(int devAddr, int regAddr, int bitStart, int length, int data, int timeout) { // 01101001 read byte // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 010 masked // -> 010 shifted int count, b = 0; if ((count = I2CdevReadByte(devAddr, regAddr, b, timeout)) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); b &= mask; b >>= (bitStart - length + 1); data = b; } return count; } int I2CdevReadBits(int devAddr, int regAddr, int bitStart, int length, int data) { return I2CdevReadBits(devAddr, regAddr, bitStart, length, data, timeout); } /** Read multiple bits from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitStart First bit position to read (0-15) * @param length Number of bits to read (not more than 16) * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05) * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (1 = success, 0 = failure, -1 = timeout) */ int I2CdevReadBitsW(int devAddr, int regAddr, int bitStart, int length, int data, int timeout) { // 1101011001101001 read byte // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 010 masked // -> 010 shifted int count; int w = 0; if ((count = I2CdevReadWord(devAddr, regAddr, w, timeout)) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); w &= mask; w >>= (bitStart - length + 1); data = w; } return count; } /** Read single byte from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param data Container for byte value read from device * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadByte(int devAddr, int regAddr, int data, int timeout) { int bytebuffer[] = {data}; int status = I2CdevReadBytes(devAddr, regAddr, 1, bytebuffer, timeout); data = bytebuffer[0]; return status; } /** Read single word from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param data Container for word value read from device * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadWord(int devAddr, int regAddr, int data, int timeout) { int[] readbuffer = {data}; int status = I2CdevReadWords(devAddr, regAddr, 1, readbuffer, timeout); data = readbuffer[0]; return status; } int I2CdevReadWord(int devAddr, int regAddr, int data) { return I2CdevReadWord(devAddr, regAddr, data, timeout); } /** Read multiple words from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr First register regAddr to read from * @param length Number of words to read * @param data Buffer to store read data in * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Number of words read (-1 indicates failure) */ int I2CdevReadWords(int devAddr, int regAddr, int length, int[] data, int timeout) { byte bytebuffer[] = new byte[length *2]; controller.i2cRead(busAddress, devAddr, bytebuffer, bytebuffer.length); for (int i=0; i < bytebuffer.length ; i++){ data[i] = bytebuffer[i*2] <<8 + bytebuffer[i*2+1] & 0xff; } return length; } int I2CdevReadByte(int devAddr, int regAddr, int data) { int bytebuffer [] = {data}; return I2CdevReadBytes(devAddr, regAddr, 1, bytebuffer, timeout); } /** Read multiple bytes from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr First register regAddr to read from * @param length Number of bytes to read * @param data Buffer to store read data in * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Number of bytes read (-1 indicates failure) */ // TODO Return the correct length int I2CdevReadBytes(int devAddr, int regAddr, int length, int[] data, int timeout) { byte[] writebuffer = new byte[] {(byte)regAddr}; byte[] readbuffer = new byte[length]; controller.i2cWrite(busAddress, deviceAddress, writebuffer, writebuffer.length); controller.i2cRead(busAddress, deviceAddress, readbuffer, length); for (int i=0; i < length ; i++){ data[i] = readbuffer[i] & 0xff; } return length; } int I2CdevReadBytes(int devAddr, int regAddr, int length, int[] data) { return I2CdevReadBytes(devAddr, regAddr, length, data, timeout); } /** Write multiple bits in an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitStart First bit position to write (0-7) * @param length Number of bits to write (not more than 8) * @param data Right-aligned value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBits(int devAddr, int regAddr, int bitStart, int length, int data) { // 010 value to write // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 00011100 mask byte // 10101111 original value (sample) // 10100011 original & ~mask // 10101011 masked | value int b = 0; if (I2CdevReadByte(devAddr, regAddr, b) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data b &= ~(mask); // zero all important bits in existing byte b |= data; // combine data with existing byte return I2CdevWriteByte(devAddr, regAddr, b); } else { return false; } } /** Write multiple bits in a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitStart First bit position to write (0-15) * @param length Number of bits to write (not more than 16) * @param data Right-aligned value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBitsW(int devAddr, int regAddr, int bitStart, int length, int data) { // 010 value to write // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 0001110000000000 mask word // 1010111110010110 original value (sample) // 1010001110010110 original & ~mask // 1010101110010110 masked | value int w = 0; if (I2CdevReadWord(devAddr, regAddr, w) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data w &= ~(mask); // zero all important bits in existing word w |= data; // combine data with existing word return I2CdevWriteWord(devAddr, regAddr, w); } else { return false; } } /** write a single bit in an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitNum Bit position to write (0-7) * @param value New bit value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBit(int devAddr, int regAddr, int bitNum, boolean data) { int b = 0; int newbyte = 0; int bitmask = 1; I2CdevReadByte(devAddr, regAddr, b); // Set the specified bit to 1 if (data){ newbyte = b | (bitmask << bitNum); } // Set the specified bit to 0 else { newbyte = (b & ~(bitmask << bitNum)); } return I2CdevWriteByte(devAddr, regAddr, newbyte); } boolean I2CdevWriteByte(int devAddr, int regAddr, int data) { int[] writebuffer = {data}; return I2CdevWriteBytes(devAddr, regAddr, 1, writebuffer); } boolean I2CdevWriteWord(int devAddr, int regAddr, int data) { int[] writebuffer = {data}; return I2CdevWriteWords(devAddr, regAddr, 1, writebuffer); } /** Write multiple bytes to an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr First register address to write to * @param length Number of bytes to write * @param data Buffer to copy new data from * @return Status of operation (true = success) */ boolean I2CdevWriteBytes(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[length +1]; writebuffer[0] = (byte)(regAddr & 0xff); for (int i=0 ; i<length ; i++){ writebuffer[i+1] = (byte) (data[i] & 0xff); } controller.i2cWrite(busAddress, devAddr, writebuffer, writebuffer.length); return true; } // TODO finish development boolean I2CdevWriteWords(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[length*2 +1]; writebuffer[0] = (byte)(regAddr & 0xff); for (int i=0 ; i<length ; i++){ writebuffer[i*2+1] = (byte) (data[i] <<8); // MSByte writebuffer[i*2+2] = (byte) (data[i] & 0xff); // LSByte } controller.i2cWrite(busAddress, devAddr, writebuffer, writebuffer.length); return true; } /* * End of I2CDEV section. */ /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Mpu6050.class.getCanonicalName()); meta.addDescription("General MPU-6050 acclerometer and gyro"); meta.addCategory("microcontroller", "sensor"); return meta; } }
src/org/myrobotlab/service/Mpu6050.java
package org.myrobotlab.service; import org.myrobotlab.framework.Service; import org.myrobotlab.framework.repo.ServiceType; import org.myrobotlab.logging.LoggerFactory; import org.myrobotlab.logging.Logging; import org.myrobotlab.logging.LoggingFactory; import org.myrobotlab.service.interfaces.I2CControl; import org.slf4j.Logger; /** * * MPU6050 - MPU-6050 sensor contains a MEMS accelerometer and a MEMS gyro in a single chip. * It is very accurate, as it contains 16-bits analog to digital conversion hardware for each channel. * Therefore it captures the x, y, and z channel at the same time. * http://playground.arduino.cc/Main/MPU-6050 * */ public class Mpu6050 extends Service{ private static final long serialVersionUID = 1L; public final static Logger log = LoggerFactory.getLogger(Mpu6050.class); StringBuilder debugRX = new StringBuilder(); transient I2CControl controller; // Default i2cAddress public int busAddress = 1; public int deviceAddress = 0x68; public String type = "MPU-6050"; public static final int MPU6050_ADDRESS_AD0_LOW = 0x68; // address pin low (GND), default for InvenSense evaluation board public static final int MPU6050_ADDRESS_AD0_HIGH = 0x69; // address pin high (VCC) public static final int MPU6050_DEFAULT_ADDRESS = MPU6050_ADDRESS_AD0_LOW; public static final int MPU6050_RA_XG_OFFS_TC = 0x00; //[7] PWR_MODE, [6:1] XG_OFFS_TC, [0] OTP_BNK_VLD public static final int MPU6050_RA_YG_OFFS_TC = 0x01; //[7] PWR_MODE, [6:1] YG_OFFS_TC, [0] OTP_BNK_VLD public static final int MPU6050_RA_ZG_OFFS_TC = 0x02; //[7] PWR_MODE, [6:1] ZG_OFFS_TC, [0] OTP_BNK_VLD public static final int MPU6050_RA_X_FINE_GAIN = 0x03; //[7:0] X_FINE_GAIN public static final int MPU6050_RA_Y_FINE_GAIN = 0x04; //[7:0] Y_FINE_GAIN public static final int MPU6050_RA_Z_FINE_GAIN = 0x05; //[7:0] Z_FINE_GAIN public static final int MPU6050_RA_XA_OFFS_H = 0x06; //[15:0] XA_OFFS public static final int MPU6050_RA_XA_OFFS_L_TC = 0x07; public static final int MPU6050_RA_YA_OFFS_H = 0x08; //[15:0] YA_OFFS public static final int MPU6050_RA_YA_OFFS_L_TC = 0x09; public static final int MPU6050_RA_ZA_OFFS_H = 0x0A; //[15:0] ZA_OFFS public static final int MPU6050_RA_ZA_OFFS_L_TC = 0x0B; public static final int MPU6050_RA_SELF_TEST_X = 0x0D; //[7:5] XA_TEST[4-2], [4:0] XG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_Y = 0x0E; //[7:5] YA_TEST[4-2], [4:0] YG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_Z = 0x0F; //[7:5] ZA_TEST[4-2], [4:0] ZG_TEST[4-0] public static final int MPU6050_RA_SELF_TEST_A = 0x10; //[5:4] XA_TEST[1-0], [3:2] YA_TEST[1-0], [1:0] ZA_TEST[1-0] public static final int MPU6050_RA_XG_OFFS_USRH = 0x13; //[15:0] XG_OFFS_USR public static final int MPU6050_RA_XG_OFFS_USRL = 0x14; public static final int MPU6050_RA_YG_OFFS_USRH = 0x15; //[15:0] YG_OFFS_USR public static final int MPU6050_RA_YG_OFFS_USRL = 0x16; public static final int MPU6050_RA_ZG_OFFS_USRH = 0x17; //[15:0] ZG_OFFS_USR public static final int MPU6050_RA_ZG_OFFS_USRL = 0x18; public static final int MPU6050_RA_SMPLRT_DIV = 0x19; public static final int MPU6050_RA_CONFIG = 0x1A; public static final int MPU6050_RA_GYRO_CONFIG = 0x1B; public static final int MPU6050_RA_ACCEL_CONFIG = 0x1C; public static final int MPU6050_RA_FF_THR = 0x1D; public static final int MPU6050_RA_FF_DUR = 0x1E; public static final int MPU6050_RA_MOT_THR = 0x1F; public static final int MPU6050_RA_MOT_DUR = 0x20; public static final int MPU6050_RA_ZRMOT_THR = 0x21; public static final int MPU6050_RA_ZRMOT_DUR = 0x22; public static final int MPU6050_RA_FIFO_EN = 0x23; public static final int MPU6050_RA_I2C_MST_CTRL = 0x24; public static final int MPU6050_RA_I2C_SLV0_ADDR = 0x25; public static final int MPU6050_RA_I2C_SLV0_REG = 0x26; public static final int MPU6050_RA_I2C_SLV0_CTRL = 0x27; public static final int MPU6050_RA_I2C_SLV1_ADDR = 0x28; public static final int MPU6050_RA_I2C_SLV1_REG = 0x29; public static final int MPU6050_RA_I2C_SLV1_CTRL = 0x2A; public static final int MPU6050_RA_I2C_SLV2_ADDR = 0x2B; public static final int MPU6050_RA_I2C_SLV2_REG = 0x2C; public static final int MPU6050_RA_I2C_SLV2_CTRL = 0x2D; public static final int MPU6050_RA_I2C_SLV3_ADDR = 0x2E; public static final int MPU6050_RA_I2C_SLV3_REG = 0x2F; public static final int MPU6050_RA_I2C_SLV3_CTRL = 0x30; public static final int MPU6050_RA_I2C_SLV4_ADDR = 0x31; public static final int MPU6050_RA_I2C_SLV4_REG = 0x32; public static final int MPU6050_RA_I2C_SLV4_DO = 0x33; public static final int MPU6050_RA_I2C_SLV4_CTRL = 0x34; public static final int MPU6050_RA_I2C_SLV4_DI = 0x35; public static final int MPU6050_RA_I2C_MST_STATUS = 0x36; public static final int MPU6050_RA_INT_PIN_CFG = 0x37; public static final int MPU6050_RA_INT_ENABLE = 0x38; public static final int MPU6050_RA_DMP_INT_STATUS = 0x39; public static final int MPU6050_RA_INT_STATUS = 0x3A; public static final int MPU6050_RA_ACCEL_XOUT_H = 0x3B; public static final int MPU6050_RA_ACCEL_XOUT_L = 0x3C; public static final int MPU6050_RA_ACCEL_YOUT_H = 0x3D; public static final int MPU6050_RA_ACCEL_YOUT_L = 0x3E; public static final int MPU6050_RA_ACCEL_ZOUT_H = 0x3F; public static final int MPU6050_RA_ACCEL_ZOUT_L = 0x40; public static final int MPU6050_RA_TEMP_OUT_H = 0x41; public static final int MPU6050_RA_TEMP_OUT_L = 0x42; public static final int MPU6050_RA_GYRO_XOUT_H = 0x43; public static final int MPU6050_RA_GYRO_XOUT_L = 0x44; public static final int MPU6050_RA_GYRO_YOUT_H = 0x45; public static final int MPU6050_RA_GYRO_YOUT_L = 0x46; public static final int MPU6050_RA_GYRO_ZOUT_H = 0x47; public static final int MPU6050_RA_GYRO_ZOUT_L = 0x48; public static final int MPU6050_RA_EXT_SENS_DATA_00 = 0x49; public static final int MPU6050_RA_EXT_SENS_DATA_01 = 0x4A; public static final int MPU6050_RA_EXT_SENS_DATA_02 = 0x4B; public static final int MPU6050_RA_EXT_SENS_DATA_03 = 0x4C; public static final int MPU6050_RA_EXT_SENS_DATA_04 = 0x4D; public static final int MPU6050_RA_EXT_SENS_DATA_05 = 0x4E; public static final int MPU6050_RA_EXT_SENS_DATA_06 = 0x4F; public static final int MPU6050_RA_EXT_SENS_DATA_07 = 0x50; public static final int MPU6050_RA_EXT_SENS_DATA_08 = 0x51; public static final int MPU6050_RA_EXT_SENS_DATA_09 = 0x52; public static final int MPU6050_RA_EXT_SENS_DATA_10 = 0x53; public static final int MPU6050_RA_EXT_SENS_DATA_11 = 0x54; public static final int MPU6050_RA_EXT_SENS_DATA_12 = 0x55; public static final int MPU6050_RA_EXT_SENS_DATA_13 = 0x56; public static final int MPU6050_RA_EXT_SENS_DATA_14 = 0x57; public static final int MPU6050_RA_EXT_SENS_DATA_15 = 0x58; public static final int MPU6050_RA_EXT_SENS_DATA_16 = 0x59; public static final int MPU6050_RA_EXT_SENS_DATA_17 = 0x5A; public static final int MPU6050_RA_EXT_SENS_DATA_18 = 0x5B; public static final int MPU6050_RA_EXT_SENS_DATA_19 = 0x5C; public static final int MPU6050_RA_EXT_SENS_DATA_20 = 0x5D; public static final int MPU6050_RA_EXT_SENS_DATA_21 = 0x5E; public static final int MPU6050_RA_EXT_SENS_DATA_22 = 0x5F; public static final int MPU6050_RA_EXT_SENS_DATA_23 = 0x60; public static final int MPU6050_RA_MOT_DETECT_STATUS = 0x61; public static final int MPU6050_RA_I2C_SLV0_DO = 0x63; public static final int MPU6050_RA_I2C_SLV1_DO = 0x64; public static final int MPU6050_RA_I2C_SLV2_DO = 0x65; public static final int MPU6050_RA_I2C_SLV3_DO = 0x66; public static final int MPU6050_RA_I2C_MST_DELAY_CTRL = 0x67; public static final int MPU6050_RA_SIGNAL_PATH_RESET = 0x68; public static final int MPU6050_RA_MOT_DETECT_CTRL = 0x69; public static final int MPU6050_RA_USER_CTRL = 0x6A; public static final int MPU6050_RA_PWR_MGMT_1 = 0x6B; public static final int MPU6050_RA_PWR_MGMT_2 = 0x6C; public static final int MPU6050_RA_BANK_SEL = 0x6D; public static final int MPU6050_RA_MEM_START_ADDR = 0x6E; public static final int MPU6050_RA_MEM_R_W = 0x6F; public static final int MPU6050_RA_DMP_CFG_1 = 0x70; public static final int MPU6050_RA_DMP_CFG_2 = 0x71; public static final int MPU6050_RA_FIFO_COUNTH = 0x72; public static final int MPU6050_RA_FIFO_COUNTL = 0x73; public static final int MPU6050_RA_FIFO_R_W = 0x74; public static final int MPU6050_RA_WHO_AM_I = 0x75; public static final int MPU6050_SELF_TEST_XA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_XA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_XA_2_BIT = 0x05; public static final int MPU6050_SELF_TEST_XA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_YA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_YA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_YA_2_BIT = 0x03; public static final int MPU6050_SELF_TEST_YA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_ZA_1_BIT = 0x07; public static final int MPU6050_SELF_TEST_ZA_1_LENGTH = 0x03; public static final int MPU6050_SELF_TEST_ZA_2_BIT = 0x01; public static final int MPU6050_SELF_TEST_ZA_2_LENGTH = 0x02; public static final int MPU6050_SELF_TEST_XG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_XG_1_LENGTH = 0x05; public static final int MPU6050_SELF_TEST_YG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_YG_1_LENGTH = 0x05; public static final int MPU6050_SELF_TEST_ZG_1_BIT = 0x04; public static final int MPU6050_SELF_TEST_ZG_1_LENGTH = 0x05; public static final int MPU6050_TC_PWR_MODE_BIT = 7; public static final int MPU6050_TC_OFFSET_BIT = 6; public static final int MPU6050_TC_OFFSET_LENGTH = 6; public static final int MPU6050_TC_OTP_BNK_VLD_BIT = 0; public static final int MPU6050_VDDIO_LEVEL_VLOGIC = 0; public static final int MPU6050_VDDIO_LEVEL_VDD = 1; public static final int MPU6050_CFG_EXT_SYNC_SET_BIT = 5; public static final int MPU6050_CFG_EXT_SYNC_SET_LENGTH = 3; public static final int MPU6050_CFG_DLPF_CFG_BIT = 2; public static final int MPU6050_CFG_DLPF_CFG_LENGTH = 3; public static final int MPU6050_EXT_SYNC_DISABLED = 0x0; public static final int MPU6050_EXT_SYNC_TEMP_OUT_L = 0x1; public static final int MPU6050_EXT_SYNC_GYRO_XOUT_L = 0x2; public static final int MPU6050_EXT_SYNC_GYRO_YOUT_L = 0x3; public static final int MPU6050_EXT_SYNC_GYRO_ZOUT_L = 0x4; public static final int MPU6050_EXT_SYNC_ACCEL_XOUT_L = 0x5; public static final int MPU6050_EXT_SYNC_ACCEL_YOUT_L = 0x6; public static final int MPU6050_EXT_SYNC_ACCEL_ZOUT_L = 0x7; public static final int MPU6050_DLPF_BW_256 = 0x00; public static final int MPU6050_DLPF_BW_188 = 0x01; public static final int MPU6050_DLPF_BW_98 = 0x02; public static final int MPU6050_DLPF_BW_42 = 0x03; public static final int MPU6050_DLPF_BW_20 = 0x04; public static final int MPU6050_DLPF_BW_10 = 0x05; public static final int MPU6050_DLPF_BW_5 = 0x06; public static final int MPU6050_GCONFIG_FS_SEL_BIT = 4; public static final int MPU6050_GCONFIG_FS_SEL_LENGTH = 2; public static final int MPU6050_GYRO_FS_250 = 0x00; public static final int MPU6050_GYRO_FS_500 = 0x01; public static final int MPU6050_GYRO_FS_1000 = 0x02; public static final int MPU6050_GYRO_FS_2000 = 0x03; public static final int MPU6050_ACONFIG_XA_ST_BIT = 7; public static final int MPU6050_ACONFIG_YA_ST_BIT = 6; public static final int MPU6050_ACONFIG_ZA_ST_BIT = 5; public static final int MPU6050_ACONFIG_AFS_SEL_BIT = 4; public static final int MPU6050_ACONFIG_AFS_SEL_LENGTH = 2; public static final int MPU6050_ACONFIG_ACCEL_HPF_BIT = 2; public static final int MPU6050_ACONFIG_ACCEL_HPF_LENGTH = 3; public static final int MPU6050_ACCEL_FS_2 = 0x00; public static final int MPU6050_ACCEL_FS_4 = 0x01; public static final int MPU6050_ACCEL_FS_8 = 0x02; public static final int MPU6050_ACCEL_FS_16 = 0x03; public static final int MPU6050_DHPF_RESET = 0x00; public static final int MPU6050_DHPF_5 = 0x01; public static final int MPU6050_DHPF_2P5 = 0x02; public static final int MPU6050_DHPF_1P25 = 0x03; public static final int MPU6050_DHPF_0P63 = 0x04; public static final int MPU6050_DHPF_HOLD = 0x07; public static final int MPU6050_TEMP_FIFO_EN_BIT = 7; public static final int MPU6050_XG_FIFO_EN_BIT = 6; public static final int MPU6050_YG_FIFO_EN_BIT = 5; public static final int MPU6050_ZG_FIFO_EN_BIT = 4; public static final int MPU6050_ACCEL_FIFO_EN_BIT = 3; public static final int MPU6050_SLV2_FIFO_EN_BIT = 2; public static final int MPU6050_SLV1_FIFO_EN_BIT = 1; public static final int MPU6050_SLV0_FIFO_EN_BIT = 0; public static final int MPU6050_MULT_MST_EN_BIT = 7; public static final int MPU6050_WAIT_FOR_ES_BIT = 6; public static final int MPU6050_SLV_3_FIFO_EN_BIT = 5; public static final int MPU6050_I2C_MST_P_NSR_BIT = 4; public static final int MPU6050_I2C_MST_CLK_BIT = 3; public static final int MPU6050_I2C_MST_CLK_LENGTH = 4; public static final int MPU6050_CLOCK_DIV_348 = 0x0; public static final int MPU6050_CLOCK_DIV_333 = 0x1; public static final int MPU6050_CLOCK_DIV_320 = 0x2; public static final int MPU6050_CLOCK_DIV_308 = 0x3; public static final int MPU6050_CLOCK_DIV_296 = 0x4; public static final int MPU6050_CLOCK_DIV_286 = 0x5; public static final int MPU6050_CLOCK_DIV_276 = 0x6; public static final int MPU6050_CLOCK_DIV_267 = 0x7; public static final int MPU6050_CLOCK_DIV_258 = 0x8; public static final int MPU6050_CLOCK_DIV_500 = 0x9; public static final int MPU6050_CLOCK_DIV_471 = 0xA; public static final int MPU6050_CLOCK_DIV_444 = 0xB; public static final int MPU6050_CLOCK_DIV_421 = 0xC; public static final int MPU6050_CLOCK_DIV_400 = 0xD; public static final int MPU6050_CLOCK_DIV_381 = 0xE; public static final int MPU6050_CLOCK_DIV_364 = 0xF; public static final int MPU6050_I2C_SLV_RW_BIT = 7; public static final int MPU6050_I2C_SLV_ADDR_BIT = 6; public static final int MPU6050_I2C_SLV_ADDR_LENGTH = 7; public static final int MPU6050_I2C_SLV_EN_BIT = 7; public static final int MPU6050_I2C_SLV_BYTE_SW_BIT = 6; public static final int MPU6050_I2C_SLV_REG_DIS_BIT = 5; public static final int MPU6050_I2C_SLV_GRP_BIT = 4; public static final int MPU6050_I2C_SLV_LEN_BIT = 3; public static final int MPU6050_I2C_SLV_LEN_LENGTH = 4; public static final int MPU6050_I2C_SLV4_RW_BIT = 7; public static final int MPU6050_I2C_SLV4_ADDR_BIT = 6; public static final int MPU6050_I2C_SLV4_ADDR_LENGTH = 7; public static final int MPU6050_I2C_SLV4_EN_BIT = 7; public static final int MPU6050_I2C_SLV4_INT_EN_BIT = 6; public static final int MPU6050_I2C_SLV4_REG_DIS_BIT = 5; public static final int MPU6050_I2C_SLV4_MST_DLY_BIT = 4; public static final int MPU6050_I2C_SLV4_MST_DLY_LENGTH = 5; public static final int MPU6050_MST_PASS_THROUGH_BIT = 7; public static final int MPU6050_MST_I2C_SLV4_DONE_BIT = 6; public static final int MPU6050_MST_I2C_LOST_ARB_BIT = 5; public static final int MPU6050_MST_I2C_SLV4_NACK_BIT = 4; public static final int MPU6050_MST_I2C_SLV3_NACK_BIT = 3; public static final int MPU6050_MST_I2C_SLV2_NACK_BIT = 2; public static final int MPU6050_MST_I2C_SLV1_NACK_BIT = 1; public static final int MPU6050_MST_I2C_SLV0_NACK_BIT = 0; public static final int MPU6050_INTCFG_INT_LEVEL_BIT = 7; public static final int MPU6050_INTCFG_INT_OPEN_BIT = 6; public static final int MPU6050_INTCFG_LATCH_INT_EN_BIT = 5; public static final int MPU6050_INTCFG_INT_RD_CLEAR_BIT = 4; public static final int MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT = 3; public static final int MPU6050_INTCFG_FSYNC_INT_EN_BIT = 2; public static final int MPU6050_INTCFG_I2C_BYPASS_EN_BIT = 1; public static final int MPU6050_INTCFG_CLKOUT_EN_BIT = 0; public static final int MPU6050_INTMODE_ACTIVEHIGH = 0x00; public static final int MPU6050_INTMODE_ACTIVELOW = 0x01; public static final int MPU6050_INTDRV_PUSHPULL = 0x00; public static final int MPU6050_INTDRV_OPENDRAIN = 0x01; public static final int MPU6050_INTLATCH_50USPULSE = 0x00; public static final int MPU6050_INTLATCH_WAITCLEAR = 0x01; public static final int MPU6050_INTCLEAR_STATUSREAD = 0x00; public static final int MPU6050_INTCLEAR_ANYREAD = 0x01; public static final int MPU6050_INTERRUPT_FF_BIT = 7; public static final int MPU6050_INTERRUPT_MOT_BIT = 6; public static final int MPU6050_INTERRUPT_ZMOT_BIT = 5; public static final int MPU6050_INTERRUPT_FIFO_OFLOW_BIT = 4; public static final int MPU6050_INTERRUPT_I2C_MST_INT_BIT = 3; public static final int MPU6050_INTERRUPT_PLL_RDY_INT_BIT = 2; public static final int MPU6050_INTERRUPT_DMP_INT_BIT = 1; public static final int MPU6050_INTERRUPT_DATA_RDY_BIT = 0; // TODO: figure out what these actually do // UMPL source code is not very obivous public static final int MPU6050_DMPINT_5_BIT = 5; public static final int MPU6050_DMPINT_4_BIT = 4; public static final int MPU6050_DMPINT_3_BIT = 3; public static final int MPU6050_DMPINT_2_BIT = 2; public static final int MPU6050_DMPINT_1_BIT = 1; public static final int MPU6050_DMPINT_0_BIT = 0; public static final int MPU6050_MOTION_MOT_XNEG_BIT = 7; public static final int MPU6050_MOTION_MOT_XPOS_BIT = 6; public static final int MPU6050_MOTION_MOT_YNEG_BIT = 5; public static final int MPU6050_MOTION_MOT_YPOS_BIT = 4; public static final int MPU6050_MOTION_MOT_ZNEG_BIT = 3; public static final int MPU6050_MOTION_MOT_ZPOS_BIT = 2; public static final int MPU6050_MOTION_MOT_ZRMOT_BIT = 0; public static final int MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT = 7; public static final int MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT = 4; public static final int MPU6050_DELAYCTRL_I2C_SLV3_DLY_EN_BIT = 3; public static final int MPU6050_DELAYCTRL_I2C_SLV2_DLY_EN_BIT = 2; public static final int MPU6050_DELAYCTRL_I2C_SLV1_DLY_EN_BIT = 1; public static final int MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT = 0; public static final int MPU6050_PATHRESET_GYRO_RESET_BIT = 2; public static final int MPU6050_PATHRESET_ACCEL_RESET_BIT = 1; public static final int MPU6050_PATHRESET_TEMP_RESET_BIT = 0; public static final int MPU6050_DETECT_ACCEL_ON_DELAY_BIT = 5; public static final int MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH = 2; public static final int MPU6050_DETECT_FF_COUNT_BIT = 3; public static final int MPU6050_DETECT_FF_COUNT_LENGTH = 2; public static final int MPU6050_DETECT_MOT_COUNT_BIT = 1; public static final int MPU6050_DETECT_MOT_COUNT_LENGTH = 2; public static final int MPU6050_DETECT_DECREMENT_RESET = 0x0; public static final int MPU6050_DETECT_DECREMENT_1 = 0x1; public static final int MPU6050_DETECT_DECREMENT_2 = 0x2; public static final int MPU6050_DETECT_DECREMENT_4 = 0x3; public static final int MPU6050_USERCTRL_DMP_EN_BIT = 7; public static final int MPU6050_USERCTRL_FIFO_EN_BIT = 6; public static final int MPU6050_USERCTRL_I2C_MST_EN_BIT = 5; public static final int MPU6050_USERCTRL_I2C_IF_DIS_BIT = 4; public static final int MPU6050_USERCTRL_DMP_RESET_BIT = 3; public static final int MPU6050_USERCTRL_FIFO_RESET_BIT = 2; public static final int MPU6050_USERCTRL_I2C_MST_RESET_BIT = 1; public static final int MPU6050_USERCTRL_SIG_COND_RESET_BIT = 0; public static final int MPU6050_PWR1_DEVICE_RESET_BIT = 7; public static final int MPU6050_PWR1_SLEEP_BIT = 6; public static final int MPU6050_PWR1_CYCLE_BIT = 5; public static final int MPU6050_PWR1_TEMP_DIS_BIT = 3; public static final int MPU6050_PWR1_CLKSEL_BIT = 2; public static final int MPU6050_PWR1_CLKSEL_LENGTH = 3; public static final int MPU6050_CLOCK_INTERNAL = 0x00; public static final int MPU6050_CLOCK_PLL_XGYRO = 0x01; public static final int MPU6050_CLOCK_PLL_YGYRO = 0x02; public static final int MPU6050_CLOCK_PLL_ZGYRO = 0x03; public static final int MPU6050_CLOCK_PLL_EXT32K = 0x04; public static final int MPU6050_CLOCK_PLL_EXT19M = 0x05; public static final int MPU6050_CLOCK_KEEP_RESET = 0x07; public static final int MPU6050_PWR2_LP_WAKE_CTRL_BIT = 7; public static final int MPU6050_PWR2_LP_WAKE_CTRL_LENGTH = 2; public static final int MPU6050_PWR2_STBY_XA_BIT = 5; public static final int MPU6050_PWR2_STBY_YA_BIT = 4; public static final int MPU6050_PWR2_STBY_ZA_BIT = 3; public static final int MPU6050_PWR2_STBY_XG_BIT = 2; public static final int MPU6050_PWR2_STBY_YG_BIT = 1; public static final int MPU6050_PWR2_STBY_ZG_BIT = 0; public static final int MPU6050_WAKE_FREQ_1P25 = 0x0; public static final int MPU6050_WAKE_FREQ_2P5 = 0x1; public static final int MPU6050_WAKE_FREQ_5 = 0x2; public static final int MPU6050_WAKE_FREQ_10 = 0x3; public static final int MPU6050_BANKSEL_PRFTCH_EN_BIT = 6; public static final int MPU6050_BANKSEL_CFG_USER_BANK_BIT = 5; public static final int MPU6050_BANKSEL_MEM_SEL_BIT = 4; public static final int MPU6050_BANKSEL_MEM_SEL_LENGTH = 5; public static final int MPU6050_WHO_AM_I_BIT = 6; public static final int MPU6050_WHO_AM_I_LENGTH = 6; public static final int MPU6050_DMP_MEMORY_BANKS = 8; public static final int MPU6050_DMP_MEMORY_BANK_SIZE = 256; public static final int MPU6050_DMP_MEMORY_CHUNK_SIZE = 16; public static final byte ACCEL_XOUT_H = 0x3B; public static int accelX; public static int accelY; public static int accelZ; public static double temperature; public static int gyroX; public static int gyroY; public static int gyroZ; // this block of memory gets written to the MPU on start-up, and it seems // to be volatile memory, so it has to be done each time (it only takes ~1 // second though) public static final int[] dmpMemory = { // bank 0, 256 bytes 0xFB, 0x00, 0x00, 0x3E, 0x00, 0x0B, 0x00, 0x36, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0xFA, 0x80, 0x00, 0x0B, 0x12, 0x82, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x28, 0x00, 0x00, 0xFF, 0xFF, 0x45, 0x81, 0xFF, 0xFF, 0xFA, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xE8, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x7F, 0xFF, 0xFF, 0xFE, 0x80, 0x01, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3E, 0x03, 0x30, 0x40, 0x00, 0x00, 0x00, 0x02, 0xCA, 0xE3, 0x09, 0x3E, 0x80, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x41, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x0B, 0x2A, 0x00, 0x00, 0x16, 0x55, 0x00, 0x00, 0x21, 0x82, 0xFD, 0x87, 0x26, 0x50, 0xFD, 0x80, 0x00, 0x00, 0x00, 0x1F, 0x00, 0x00, 0x00, 0x05, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x6F, 0x00, 0x02, 0x65, 0x32, 0x00, 0x00, 0x5E, 0xC0, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0x8C, 0x6F, 0x5D, 0xFD, 0x5D, 0x08, 0xD9, 0x00, 0x7C, 0x73, 0x3B, 0x00, 0x6C, 0x12, 0xCC, 0x32, 0x00, 0x13, 0x9D, 0x32, 0x00, 0xD0, 0xD6, 0x32, 0x00, 0x08, 0x00, 0x40, 0x00, 0x01, 0xF4, 0xFF, 0xE6, 0x80, 0x79, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xD0, 0xD6, 0x00, 0x00, 0x27, 0x10, // bank 1, 256 bytes 0xFB, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFA, 0x36, 0xFF, 0xBC, 0x30, 0x8E, 0x00, 0x05, 0xFB, 0xF0, 0xFF, 0xD9, 0x5B, 0xC8, 0xFF, 0xD0, 0x9A, 0xBE, 0x00, 0x00, 0x10, 0xA9, 0xFF, 0xF4, 0x1E, 0xB2, 0x00, 0xCE, 0xBB, 0xF7, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x04, 0x00, 0x02, 0x00, 0x02, 0x02, 0x00, 0x00, 0x0C, 0xFF, 0xC2, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0xCF, 0x80, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x3F, 0x68, 0xB6, 0x79, 0x35, 0x28, 0xBC, 0xC6, 0x7E, 0xD1, 0x6C, 0x80, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0xB2, 0x6A, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3F, 0xF0, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x25, 0x4D, 0x00, 0x2F, 0x70, 0x6D, 0x00, 0x00, 0x05, 0xAE, 0x00, 0x0C, 0x02, 0xD0, // bank 2, 256 bytes 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x54, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x44, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x65, 0x00, 0x00, 0x00, 0x54, 0x00, 0x00, 0xFF, 0xEF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x1B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // bank 3, 256 bytes 0xD8, 0xDC, 0xBA, 0xA2, 0xF1, 0xDE, 0xB2, 0xB8, 0xB4, 0xA8, 0x81, 0x91, 0xF7, 0x4A, 0x90, 0x7F, 0x91, 0x6A, 0xF3, 0xF9, 0xDB, 0xA8, 0xF9, 0xB0, 0xBA, 0xA0, 0x80, 0xF2, 0xCE, 0x81, 0xF3, 0xC2, 0xF1, 0xC1, 0xF2, 0xC3, 0xF3, 0xCC, 0xA2, 0xB2, 0x80, 0xF1, 0xC6, 0xD8, 0x80, 0xBA, 0xA7, 0xDF, 0xDF, 0xDF, 0xF2, 0xA7, 0xC3, 0xCB, 0xC5, 0xB6, 0xF0, 0x87, 0xA2, 0x94, 0x24, 0x48, 0x70, 0x3C, 0x95, 0x40, 0x68, 0x34, 0x58, 0x9B, 0x78, 0xA2, 0xF1, 0x83, 0x92, 0x2D, 0x55, 0x7D, 0xD8, 0xB1, 0xB4, 0xB8, 0xA1, 0xD0, 0x91, 0x80, 0xF2, 0x70, 0xF3, 0x70, 0xF2, 0x7C, 0x80, 0xA8, 0xF1, 0x01, 0xB0, 0x98, 0x87, 0xD9, 0x43, 0xD8, 0x86, 0xC9, 0x88, 0xBA, 0xA1, 0xF2, 0x0E, 0xB8, 0x97, 0x80, 0xF1, 0xA9, 0xDF, 0xDF, 0xDF, 0xAA, 0xDF, 0xDF, 0xDF, 0xF2, 0xAA, 0xC5, 0xCD, 0xC7, 0xA9, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, 0x97, 0xF1, 0xA9, 0x89, 0x26, 0x46, 0x66, 0xB0, 0xB4, 0xBA, 0x80, 0xAC, 0xDE, 0xF2, 0xCA, 0xF1, 0xB2, 0x8C, 0x02, 0xA9, 0xB6, 0x98, 0x00, 0x89, 0x0E, 0x16, 0x1E, 0xB8, 0xA9, 0xB4, 0x99, 0x2C, 0x54, 0x7C, 0xB0, 0x8A, 0xA8, 0x96, 0x36, 0x56, 0x76, 0xF1, 0xB9, 0xAF, 0xB4, 0xB0, 0x83, 0xC0, 0xB8, 0xA8, 0x97, 0x11, 0xB1, 0x8F, 0x98, 0xB9, 0xAF, 0xF0, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xF1, 0xA3, 0x29, 0x55, 0x7D, 0xAF, 0x83, 0xB5, 0x93, 0xAF, 0xF0, 0x00, 0x28, 0x50, 0xF1, 0xA3, 0x86, 0x9F, 0x61, 0xA6, 0xDA, 0xDE, 0xDF, 0xD9, 0xFA, 0xA3, 0x86, 0x96, 0xDB, 0x31, 0xA6, 0xD9, 0xF8, 0xDF, 0xBA, 0xA6, 0x8F, 0xC2, 0xC5, 0xC7, 0xB2, 0x8C, 0xC1, 0xB8, 0xA2, 0xDF, 0xDF, 0xDF, 0xA3, 0xDF, 0xDF, 0xDF, 0xD8, 0xD8, 0xF1, 0xB8, 0xA8, 0xB2, 0x86, // bank 4, 256 bytes 0xB4, 0x98, 0x0D, 0x35, 0x5D, 0xB8, 0xAA, 0x98, 0xB0, 0x87, 0x2D, 0x35, 0x3D, 0xB2, 0xB6, 0xBA, 0xAF, 0x8C, 0x96, 0x19, 0x8F, 0x9F, 0xA7, 0x0E, 0x16, 0x1E, 0xB4, 0x9A, 0xB8, 0xAA, 0x87, 0x2C, 0x54, 0x7C, 0xB9, 0xA3, 0xDE, 0xDF, 0xDF, 0xA3, 0xB1, 0x80, 0xF2, 0xC4, 0xCD, 0xC9, 0xF1, 0xB8, 0xA9, 0xB4, 0x99, 0x83, 0x0D, 0x35, 0x5D, 0x89, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0xB5, 0x93, 0xA3, 0x0E, 0x16, 0x1E, 0xA9, 0x2C, 0x54, 0x7C, 0xB8, 0xB4, 0xB0, 0xF1, 0x97, 0x83, 0xA8, 0x11, 0x84, 0xA5, 0x09, 0x98, 0xA3, 0x83, 0xF0, 0xDA, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xD8, 0xF1, 0xA5, 0x29, 0x55, 0x7D, 0xA5, 0x85, 0x95, 0x02, 0x1A, 0x2E, 0x3A, 0x56, 0x5A, 0x40, 0x48, 0xF9, 0xF3, 0xA3, 0xD9, 0xF8, 0xF0, 0x98, 0x83, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0x97, 0x82, 0xA8, 0xF1, 0x11, 0xF0, 0x98, 0xA2, 0x24, 0x08, 0x44, 0x10, 0x64, 0x18, 0xDA, 0xF3, 0xDE, 0xD8, 0x83, 0xA5, 0x94, 0x01, 0xD9, 0xA3, 0x02, 0xF1, 0xA2, 0xC3, 0xC5, 0xC7, 0xD8, 0xF1, 0x84, 0x92, 0xA2, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0x93, 0xA3, 0x4D, 0xDA, 0x2A, 0xD8, 0x48, 0x69, 0xD9, 0x2A, 0xD8, 0x68, 0x55, 0xDA, 0x32, 0xD8, 0x50, 0x71, 0xD9, 0x32, 0xD8, 0x70, 0x5D, 0xDA, 0x3A, 0xD8, 0x58, 0x79, 0xD9, 0x3A, 0xD8, 0x78, 0xA8, 0x8A, 0x9A, 0xF0, 0x28, 0x50, 0x78, 0x9E, 0xF3, 0x88, 0x18, 0xF1, 0x9F, 0x1D, 0x98, 0xA8, 0xD9, 0x08, 0xD8, 0xC8, 0x9F, 0x12, 0x9E, 0xF3, 0x15, 0xA8, 0xDA, 0x12, 0x10, 0xD8, 0xF1, 0xAF, 0xC8, 0x97, 0x87, // bank 5, 256 bytes 0x34, 0xB5, 0xB9, 0x94, 0xA4, 0x21, 0xF3, 0xD9, 0x22, 0xD8, 0xF2, 0x2D, 0xF3, 0xD9, 0x2A, 0xD8, 0xF2, 0x35, 0xF3, 0xD9, 0x32, 0xD8, 0x81, 0xA4, 0x60, 0x60, 0x61, 0xD9, 0x61, 0xD8, 0x6C, 0x68, 0x69, 0xD9, 0x69, 0xD8, 0x74, 0x70, 0x71, 0xD9, 0x71, 0xD8, 0xB1, 0xA3, 0x84, 0x19, 0x3D, 0x5D, 0xA3, 0x83, 0x1A, 0x3E, 0x5E, 0x93, 0x10, 0x30, 0x81, 0x10, 0x11, 0xB8, 0xB0, 0xAF, 0x8F, 0x94, 0xF2, 0xDA, 0x3E, 0xD8, 0xB4, 0x9A, 0xA8, 0x87, 0x29, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x35, 0xDA, 0xF8, 0xD8, 0x87, 0x9A, 0x3D, 0xDA, 0xF8, 0xD8, 0xB1, 0xB9, 0xA4, 0x98, 0x85, 0x02, 0x2E, 0x56, 0xA5, 0x81, 0x00, 0x0C, 0x14, 0xA3, 0x97, 0xB0, 0x8A, 0xF1, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x84, 0x0D, 0xDA, 0x0E, 0xD8, 0xA3, 0x29, 0x83, 0xDA, 0x2C, 0x0E, 0xD8, 0xA3, 0x84, 0x49, 0x83, 0xDA, 0x2C, 0x4C, 0x0E, 0xD8, 0xB8, 0xB0, 0xA8, 0x8A, 0x9A, 0xF5, 0x20, 0xAA, 0xDA, 0xDF, 0xD8, 0xA8, 0x40, 0xAA, 0xD0, 0xDA, 0xDE, 0xD8, 0xA8, 0x60, 0xAA, 0xDA, 0xD0, 0xDF, 0xD8, 0xF1, 0x97, 0x86, 0xA8, 0x31, 0x9B, 0x06, 0x99, 0x07, 0xAB, 0x97, 0x28, 0x88, 0x9B, 0xF0, 0x0C, 0x20, 0x14, 0x40, 0xB8, 0xB0, 0xB4, 0xA8, 0x8C, 0x9C, 0xF0, 0x04, 0x28, 0x51, 0x79, 0x1D, 0x30, 0x14, 0x38, 0xB2, 0x82, 0xAB, 0xD0, 0x98, 0x2C, 0x50, 0x50, 0x78, 0x78, 0x9B, 0xF1, 0x1A, 0xB0, 0xF0, 0x8A, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x8B, 0x29, 0x51, 0x79, 0x8A, 0x24, 0x70, 0x59, 0x8B, 0x20, 0x58, 0x71, 0x8A, 0x44, 0x69, 0x38, 0x8B, 0x39, 0x40, 0x68, 0x8A, 0x64, 0x48, 0x31, 0x8B, 0x30, 0x49, 0x60, 0xA5, 0x88, 0x20, 0x09, 0x71, 0x58, 0x44, 0x68, // bank 6, 256 bytes 0x11, 0x39, 0x64, 0x49, 0x30, 0x19, 0xF1, 0xAC, 0x00, 0x2C, 0x54, 0x7C, 0xF0, 0x8C, 0xA8, 0x04, 0x28, 0x50, 0x78, 0xF1, 0x88, 0x97, 0x26, 0xA8, 0x59, 0x98, 0xAC, 0x8C, 0x02, 0x26, 0x46, 0x66, 0xF0, 0x89, 0x9C, 0xA8, 0x29, 0x51, 0x79, 0x24, 0x70, 0x59, 0x44, 0x69, 0x38, 0x64, 0x48, 0x31, 0xA9, 0x88, 0x09, 0x20, 0x59, 0x70, 0xAB, 0x11, 0x38, 0x40, 0x69, 0xA8, 0x19, 0x31, 0x48, 0x60, 0x8C, 0xA8, 0x3C, 0x41, 0x5C, 0x20, 0x7C, 0x00, 0xF1, 0x87, 0x98, 0x19, 0x86, 0xA8, 0x6E, 0x76, 0x7E, 0xA9, 0x99, 0x88, 0x2D, 0x55, 0x7D, 0x9E, 0xB9, 0xA3, 0x8A, 0x22, 0x8A, 0x6E, 0x8A, 0x56, 0x8A, 0x5E, 0x9F, 0xB1, 0x83, 0x06, 0x26, 0x46, 0x66, 0x0E, 0x2E, 0x4E, 0x6E, 0x9D, 0xB8, 0xAD, 0x00, 0x2C, 0x54, 0x7C, 0xF2, 0xB1, 0x8C, 0xB4, 0x99, 0xB9, 0xA3, 0x2D, 0x55, 0x7D, 0x81, 0x91, 0xAC, 0x38, 0xAD, 0x3A, 0xB5, 0x83, 0x91, 0xAC, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0x8C, 0x9D, 0xAE, 0x29, 0xD9, 0x04, 0xAE, 0xD8, 0x51, 0xD9, 0x04, 0xAE, 0xD8, 0x79, 0xD9, 0x04, 0xD8, 0x81, 0xF3, 0x9D, 0xAD, 0x00, 0x8D, 0xAE, 0x19, 0x81, 0xAD, 0xD9, 0x01, 0xD8, 0xF2, 0xAE, 0xDA, 0x26, 0xD8, 0x8E, 0x91, 0x29, 0x83, 0xA7, 0xD9, 0xAD, 0xAD, 0xAD, 0xAD, 0xF3, 0x2A, 0xD8, 0xD8, 0xF1, 0xB0, 0xAC, 0x89, 0x91, 0x3E, 0x5E, 0x76, 0xF3, 0xAC, 0x2E, 0x2E, 0xF1, 0xB1, 0x8C, 0x5A, 0x9C, 0xAC, 0x2C, 0x28, 0x28, 0x28, 0x9C, 0xAC, 0x30, 0x18, 0xA8, 0x98, 0x81, 0x28, 0x34, 0x3C, 0x97, 0x24, 0xA7, 0x28, 0x34, 0x3C, 0x9C, 0x24, 0xF2, 0xB0, 0x89, 0xAC, 0x91, 0x2C, 0x4C, 0x6C, 0x8A, 0x9B, 0x2D, 0xD9, 0xD8, 0xD8, 0x51, 0xD9, 0xD8, 0xD8, 0x79, // bank 7, 138 bytes (remainder) 0xD9, 0xD8, 0xD8, 0xF1, 0x9E, 0x88, 0xA3, 0x31, 0xDA, 0xD8, 0xD8, 0x91, 0x2D, 0xD9, 0x28, 0xD8, 0x4D, 0xD9, 0x48, 0xD8, 0x6D, 0xD9, 0x68, 0xD8, 0xB1, 0x83, 0x93, 0x35, 0x3D, 0x80, 0x25, 0xDA, 0xD8, 0xD8, 0x85, 0x69, 0xDA, 0xD8, 0xD8, 0xB4, 0x93, 0x81, 0xA3, 0x28, 0x34, 0x3C, 0xF3, 0xAB, 0x8B, 0xF8, 0xA3, 0x91, 0xB6, 0x09, 0xB4, 0xD9, 0xAB, 0xDE, 0xFA, 0xB0, 0x87, 0x9C, 0xB9, 0xA3, 0xDD, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x95, 0xF1, 0xA3, 0xA3, 0xA3, 0x9D, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0xF2, 0xA3, 0xB4, 0x90, 0x80, 0xF2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB2, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xA3, 0xB0, 0x87, 0xB5, 0x99, 0xF1, 0xA3, 0xA3, 0xA3, 0x98, 0xF1, 0xA3, 0xA3, 0xA3, 0xA3, 0x97, 0xA3, 0xA3, 0xA3, 0xA3, 0xF3, 0x9B, 0xA3, 0xA3, 0xDC, 0xB9, 0xA7, 0xF1, 0x26, 0x26, 0x26, 0xD8, 0xD8, 0xFF }; // thanks to Noah Zerkin for piecing this stuff together! public static final int[] dmpConfig = { // BANK OFFSET LENGTH [DATA] 0x03, 0x7B, 0x03, 0x4C, 0xCD, 0x6C, // FCFG_1 inv_set_gyro_calibration 0x03, 0xAB, 0x03, 0x36, 0x56, 0x76, // FCFG_3 inv_set_gyro_calibration 0x00, 0x68, 0x04, 0x02, 0xCB, 0x47, 0xA2, // D_0_104 inv_set_gyro_calibration 0x02, 0x18, 0x04, 0x00, 0x05, 0x8B, 0xC1, // D_0_24 inv_set_gyro_calibration 0x01, 0x0C, 0x04, 0x00, 0x00, 0x00, 0x00, // D_1_152 inv_set_accel_calibration 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_accel_calibration 0x03, 0x89, 0x03, 0x26, 0x46, 0x66, // FCFG_7 inv_set_accel_calibration 0x00, 0x6C, 0x02, 0x20, 0x00, // D_0_108 inv_set_accel_calibration 0x02, 0x40, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_00 inv_set_compass_calibration 0x02, 0x44, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_01 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_02 0x02, 0x4C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_10 0x02, 0x50, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_11 0x02, 0x54, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_12 0x02, 0x58, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_20 0x02, 0x5C, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_21 0x02, 0xBC, 0x04, 0x00, 0x00, 0x00, 0x00, // CPASS_MTX_22 0x01, 0xEC, 0x04, 0x00, 0x00, 0x40, 0x00, // D_1_236 inv_apply_endian_accel 0x03, 0x7F, 0x06, 0x0C, 0xC9, 0x2C, 0x97, 0x97, 0x97, // FCFG_2 inv_set_mpu_sensors 0x04, 0x02, 0x03, 0x0D, 0x35, 0x5D, // CFG_MOTION_BIAS inv_turn_on_bias_from_no_motion 0x04, 0x09, 0x04, 0x87, 0x2D, 0x35, 0x3D, // FCFG_5 inv_set_bias_update 0x00, 0xA3, 0x01, 0x00, // D_0_163 inv_set_dead_zone // SPECIAL 0x01 = enable interrupts 0x00, 0x00, 0x00, 0x01, // SET INT_ENABLE at i=22, SPECIAL INSTRUCTION 0x07, 0x86, 0x01, 0xFE, // CFG_6 inv_set_fifo_interupt 0x07, 0x41, 0x05, 0xF1, 0x20, 0x28, 0x30, 0x38, // CFG_8 inv_send_quaternion 0x07, 0x7E, 0x01, 0x30, // CFG_16 inv_set_footer 0x07, 0x46, 0x01, 0x9A, // CFG_GYRO_SOURCE inv_send_gyro 0x07, 0x47, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_9 inv_send_gyro -> inv_construct3_fifo 0x07, 0x6C, 0x04, 0xF1, 0x28, 0x30, 0x38, // CFG_12 inv_send_accel -> inv_construct3_fifo 0x02, 0x16, 0x02, 0x00, 0x01 // D_0_22 inv_set_fifo_rate // This very last 0x01 WAS a 0x09, which drops the FIFO rate down to 20 Hz. 0x07 is 25 Hz, // 0x01 is 100Hz. Going faster than 100Hz (0x00=200Hz) tends to result in very noisy data. // DMP output frequency is calculated easily using this equation: (200Hz / (1 + value)) // It is important to make sure the host processor can keep up with reading and processing // the FIFO output at the desired rate. Handling FIFO overflow cleanly is also a good idea. }; public static final int[] dmpUpdates = { 0x01, 0xB2, 0x02, 0xFF, 0xFF, 0x01, 0x90, 0x04, 0x09, 0x23, 0xA1, 0x35, 0x01, 0x6A, 0x02, 0x06, 0x00, 0x01, 0x60, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0x04, 0x40, 0x00, 0x00, 0x00, 0x01, 0x62, 0x02, 0x00, 0x00, 0x00, 0x60, 0x04, 0x00, 0x40, 0x00, 0x00 }; private int[] buffer = new int[14]; private int bytebuffer; int timeout = 0; public static void main(String[] args) { LoggingFactory.getInstance().configure(); try { Mpu6050 mpu6050 = (Mpu6050) Runtime.start("mpu6050", "Mpu6050"); Runtime.start("gui", "GUIService"); /* Arduino arduino = (Arduino) Runtime.start("Arduino","Arduino"); arduino.connect("COM4"); mpu6050.setController(arduino); */ RasPi raspi = (RasPi) Runtime.start("RasPi","RasPi"); mpu6050.setController(raspi); mpu6050.dmpInitialize(); } catch (Exception e) { Logging.logError(e); } } public Mpu6050(String n) { super(n); } @Override public void startService() { super.startService(); } public boolean setController(I2CControl controller) { if (controller == null) { error("setting null as controller"); return false; } log.info(String.format("%s setController %s", getName(), controller.getName())); this.controller = controller; controller.createDevice(busAddress, deviceAddress, type); broadcastState(); return true; } /** * This method creates the i2c device */ public boolean setDeviceAddress(int DeviceAddress){ if (controller != null) { if (deviceAddress != DeviceAddress){ controller.releaseDevice(busAddress,deviceAddress); controller.createDevice(busAddress, DeviceAddress, type); } } log.info(String.format("Setting device address to x%02X", deviceAddress)); deviceAddress = DeviceAddress; return true; } /** * This method reads all the 7 raw values in one go * accelX * accelY * accelZ * temperature ( In degrees Celcius ) * gyroX * gyroY * gyroZ * */ public void readRaw(){ // Set the start address to read from byte[] writebuffer = {ACCEL_XOUT_H}; controller.i2cWrite(busAddress, deviceAddress, writebuffer, writebuffer.length); // The Arduino example executes a request_from() // Not sure if this will do the trick // Request 14 bytes from the MPU-6050 byte[] readbuffer = new byte[14]; controller.i2cWrite(busAddress, deviceAddress, readbuffer, readbuffer.length); // Fill the variables with the result from the read operation accelX = readbuffer[0]<<8 + readbuffer[1] & 0xFF; accelY = readbuffer[2]<<8 + readbuffer[3] & 0xFF; accelZ = readbuffer[4]<<8 + readbuffer[5] & 0xFF; int temp = readbuffer[6]<<8 + readbuffer[7] & 0xFF; gyroX = readbuffer[8]<<8 + readbuffer[9] & 0xFF; gyroY = readbuffer[10]<<8 + readbuffer[11] & 0xFF; gyroZ = readbuffer[12]<<8 + readbuffer[13] & 0xFF; // Convert temp to degrees Celcius temperature = temp / 340.0 + 36.53; } public int dmpInitialize(){ // reset device log.info("Resetting MPU6050..."); reset(); delay(30); // wait after reset // disable sleep mode log.info("Disabling sleep mode..."); setSleepEnabled(false); // get MPU hardware revision log.info("Selecting user bank 16..."); setMemoryBank(0x10, true, true); log.info("Selecting memory byte 6..."); setMemoryStartAddress(0x06); log.info("Checking hardware revision..."); log.info(String.format("Revision @ user[16][6] = x%02X", readMemoryByte())); log.info("Resetting memory bank selection to 0..."); setMemoryBank(0, false, false); // check OTP bank valid log.info("Reading OTP bank valid flag..."); log.info(String.format("OTP bank is %b", getOTPBankValid())); // get X/Y/Z gyro offsets log.info("Reading gyro offset TC values..."); int xgOffsetTC = getXGyroOffsetTC(); int ygOffsetTC = getYGyroOffsetTC(); int zgOffsetTC = getZGyroOffsetTC(); log.info(String.format("X gyro offset = %s", xgOffsetTC)); log.info(String.format("Y gyro offset = %s", ygOffsetTC)); log.info(String.format("Z gyro offset = %S", zgOffsetTC)); // setup weird slave stuff (?) log.info("Setting slave 0 address to 0x7F..."); setSlaveAddress(0, 0x7F); log.info("Disabling I2C Master mode..."); setI2CMasterModeEnabled(false); log.info("Setting slave 0 address to 0x68 (self)..."); setSlaveAddress(0, 0x68); log.info("Resetting I2C Master control..."); resetI2CMaster(); delay(20); // load DMP code into memory banks log.info(String.format("Writing DMP code to MPU memory banks (%s) bytes", dmpMemory.length)); if (writeProgMemoryBlock(dmpMemory, dmpMemory.length)) { log.info("Success! DMP code written and verified."); // write DMP configuration log.info(String.format("Writing DMP configuration to MPU memory banks (%s bytes in config def)",dmpConfig.length)); if (writeProgDMPConfigurationSet(dmpConfig, dmpConfig.length)) { log.info("Success! DMP configuration written and verified."); log.info("Setting clock source to Z Gyro..."); setClockSource(MPU6050_CLOCK_PLL_ZGYRO); log.info("Setting DMP and FIFO_OFLOW interrupts enabled..."); setIntEnabled(0x12); log.info("Setting sample rate to 200Hz..."); setRate(4); // 1khz / (1 + 4) = 200 Hz log.info("Setting external frame sync to TEMP_OUT_L[0]..."); setExternalFrameSync(MPU6050_EXT_SYNC_TEMP_OUT_L); log.info("Setting DLPF bandwidth to 42Hz..."); setDLPFMode(MPU6050_DLPF_BW_42); log.info("Setting gyro sensitivity to +/- 2000 deg/sec..."); setFullScaleGyroRange(MPU6050_GYRO_FS_2000); log.info("Setting DMP configuration bytes (function unknown)..."); setDMPConfig1(0x03); setDMPConfig2(0x00); log.info("Clearing OTP Bank flag..."); setOTPBankValid(false); log.info("Setting X/Y/Z gyro offset TCs to previous values..."); setXGyroOffsetTC(xgOffsetTC); setYGyroOffsetTC(ygOffsetTC); setZGyroOffsetTC(zgOffsetTC); //log.info("Setting X/Y/Z gyro user offsets to zero...")); //setXGyroOffset(0); //setYGyroOffset(0); //setZGyroOffset(0); log.info("Writing final memory update 1/7 (function unknown)..."); int[] dmpUpdate = new int[13]; int j; int pos = 0; int bank = 0, address = 0, dataSize = 0; for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Writing final memory update 2/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Resetting FIFO..."); resetFIFO(); log.info("Reading FIFO count..."); int fifoCount = getFIFOCount(); int[] fifoBuffer = new int[128]; log.info(String.format("Current FIFO count=%s",fifoCount)); getFIFOBytes(fifoBuffer, fifoCount); log.info("Setting motion detection threshold to 2..."); setMotionDetectionThreshold(2); log.info("Setting zero-motion detection threshold to 156..."); setZeroMotionDetectionThreshold(156); log.info("Setting motion detection duration to 80..."); setMotionDetectionDuration(80); log.info("Setting zero-motion detection duration to 0..."); setZeroMotionDetectionDuration(0); log.info("Resetting FIFO..."); resetFIFO(); log.info("Enabling FIFO..."); setFIFOEnabled(true); log.info("Enabling DMP..."); setDMPEnabled(true); log.info("Resetting DMP..."); resetDMP(); log.info("Writing final memory update 3/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Writing final memory update 4/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Writing final memory update 5/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Waiting for FIFO count > 2..."); while ((fifoCount = getFIFOCount()) < 3); log.info(String.format("Current FIFO count=%s",fifoCount)); log.info("Reading FIFO data..."); getFIFOBytes(fifoBuffer, fifoCount); log.info("Reading interrupt status..."); log.info(String.format("Current interrupt status=x%02X",getIntStatus())); log.info("Reading final memory update 6/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("Waiting for FIFO count > 2..."); while ((fifoCount = getFIFOCount()) < 3); log.info(String.format("Current FIFO count=%s",fifoCount)); log.info("Reading FIFO data..."); getFIFOBytes(fifoBuffer, fifoCount); log.info("Reading interrupt status..."); log.info(String.format("Current interrupt status=x%02X",getIntStatus())); log.info("Writing final memory update 7/7 (function unknown)..."); for (j = 0; j < 4 || j < dmpUpdate[2] + 3; j++, pos++){ if (j==0){ bank = dmpUpdates[j]; } if (j==1){ address = dmpUpdates[j]; } if (j==2){ dataSize = dmpUpdates[j]; } if (j>2){ dmpUpdate[j-3] = dmpUpdates[pos]; } } writeMemoryBlock(dmpUpdate, dataSize, bank, address,true); log.info("DMP is good to go! Finally."); log.info("Disabling DMP (you turn it on later)..."); setDMPEnabled(false); log.info("Setting up internal 42-byte (default) DMP packet buffer..."); int dmpPacketSize = 42; /*if ((dmpPacketBuffer = (int *)malloc(42)) == 0) { return 3; // TODO: proper error code for no memory }*/ log.info("Resetting FIFO and clearing INT status one last time..."); resetFIFO(); getIntStatus(); } else { log.info("ERROR! DMP configuration verification failed."); return 2; // configuration block loading failed } } else { log.info("ERROR! DMP code verification failed."); return 1; // main binary block loading failed } return 0; } public void delay(int ms){ try { Thread.sleep(ms); } catch (InterruptedException e) { // TODO Auto-generated catch block Logging.logError(e); } // wait after reset } public void initialize() { setClockSource(MPU6050_CLOCK_PLL_XGYRO); setFullScaleGyroRange(MPU6050_GYRO_FS_250); setFullScaleAccelRange(MPU6050_ACCEL_FS_2); setSleepEnabled(false); // thanks to Jack Elston for pointing this one out! } /** Verify the I2C connection. * Make sure the device is connected and responds as expected. * @return True if connection is valid, false otherwise */ public boolean testConnection() { return getDeviceID() == 0x34; } // AUX_VDDIO register (InvenSense demo code calls this RA_*G_OFFS_TC) /** Get the auxiliary I2C supply voltage level. * When set to 1, the auxiliary I2C bus high logic level is VDD. When cleared to * 0, the auxiliary I2C bus high logic level is VLOGIC. This does not apply to * the MPU-6000, which does not have a VLOGIC pin. * @return I2C supply voltage level (0=VLOGIC, 1=VDD) */ public int getAuxVDDIOLevel() { I2CdevReadBit(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_PWR_MODE_BIT, bytebuffer); return bytebuffer; } /** Set the auxiliary I2C supply voltage level. * When set to 1, the auxiliary I2C bus high logic level is VDD. When cleared to * 0, the auxiliary I2C bus high logic level is VLOGIC. This does not apply to * the MPU-6000, which does not have a VLOGIC pin. * @param level I2C supply voltage level (0=VLOGIC, 1=VDD) */ void setAuxVDDIOLevel(int level) { boolean bitbuffer = (level != 0); I2CdevWriteBit(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_PWR_MODE_BIT, bitbuffer); } // SMPLRT_DIV register /** Get gyroscope output rate divider. * The sensor register output, FIFO output, DMP sampling, Motion detection, Zero * Motion detection, and Free Fall detection are all based on the Sample Rate. * The Sample Rate is generated by dividing the gyroscope output rate by * SMPLRT_DIV: * * Sample Rate = Gyroscope Output Rate / (1 + SMPLRT_DIV) * * where Gyroscope Output Rate = 8kHz when the DLPF is disabled (DLPF_CFG = 0 or * 7), and 1kHz when the DLPF is enabled (see Register 26). * * Note: The accelerometer output rate is 1kHz. This means that for a Sample * Rate greater than 1kHz, the same accelerometer sample may be output to the * FIFO, DMP, and sensor registers more than once. * * For a diagram of the gyroscope and accelerometer signal paths, see Section 8 * of the MPU-6000/MPU-6050 Product Specification document. * * @return Current sample rate * @see MPU6050_RA_SMPLRT_DIV */ int getRate() { I2CdevReadByte(deviceAddress, MPU6050_RA_SMPLRT_DIV, bytebuffer); return bytebuffer; } /** Set gyroscope sample rate divider. * @param rate New sample rate divider * @see getRate() * @see MPU6050_RA_SMPLRT_DIV */ void setRate(int rate) { I2CdevWriteByte(deviceAddress, MPU6050_RA_SMPLRT_DIV, rate); } // CONFIG register /** Get external FSYNC configuration. * Configures the external Frame Synchronization (FSYNC) pin sampling. An * external signal connected to the FSYNC pin can be sampled by configuring * EXT_SYNC_SET. Signal changes to the FSYNC pin are latched so that short * strobes may be captured. The latched FSYNC signal will be sampled at the * Sampling Rate, as defined in register 25. After sampling, the latch will * reset to the current FSYNC signal state. * * The sampled value will be reported in place of the least significant bit in * a sensor data register determined by the value of EXT_SYNC_SET according to * the following table. * * <pre> * EXT_SYNC_SET | FSYNC Bit Location * -------------+------------------- * 0 | Input disabled * 1 | TEMP_OUT_L[0] * 2 | GYRO_XOUT_L[0] * 3 | GYRO_YOUT_L[0] * 4 | GYRO_ZOUT_L[0] * 5 | ACCEL_XOUT_L[0] * 6 | ACCEL_YOUT_L[0] * 7 | ACCEL_ZOUT_L[0] * </pre> * * @return FSYNC configuration value */ int getExternalFrameSync() { I2CdevReadBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_EXT_SYNC_SET_BIT, MPU6050_CFG_EXT_SYNC_SET_LENGTH, bytebuffer); return bytebuffer; } /** Set external FSYNC configuration. * @see getExternalFrameSync() * @see MPU6050_RA_CONFIG * @param sync New FSYNC configuration value */ void setExternalFrameSync(int sync) { I2CdevWriteBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_EXT_SYNC_SET_BIT, MPU6050_CFG_EXT_SYNC_SET_LENGTH, sync); } /** Get digital low-pass filter configuration. * The DLPF_CFG parameter sets the digital low pass filter configuration. It * also determines the internal sampling rate used by the device as shown in * the table below. * * Note: The accelerometer output rate is 1kHz. This means that for a Sample * Rate greater than 1kHz, the same accelerometer sample may be output to the * FIFO, DMP, and sensor registers more than once. * * <pre> * | ACCELEROMETER | GYROSCOPE * DLPF_CFG | Bandwidth | Delay | Bandwidth | Delay | Sample Rate * ---------+-----------+--------+-----------+--------+------------- * 0 | 260Hz | 0ms | 256Hz | 0.98ms | 8kHz * 1 | 184Hz | 2.0ms | 188Hz | 1.9ms | 1kHz * 2 | 94Hz | 3.0ms | 98Hz | 2.8ms | 1kHz * 3 | 44Hz | 4.9ms | 42Hz | 4.8ms | 1kHz * 4 | 21Hz | 8.5ms | 20Hz | 8.3ms | 1kHz * 5 | 10Hz | 13.8ms | 10Hz | 13.4ms | 1kHz * 6 | 5Hz | 19.0ms | 5Hz | 18.6ms | 1kHz * 7 | -- Reserved -- | -- Reserved -- | Reserved * </pre> * * @return DLFP configuration * @see MPU6050_RA_CONFIG * @see MPU6050_CFG_DLPF_CFG_BIT * @see MPU6050_CFG_DLPF_CFG_LENGTH */ int getDLPFMode() { I2CdevReadBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_DLPF_CFG_BIT, MPU6050_CFG_DLPF_CFG_LENGTH, bytebuffer); return bytebuffer; } /** Set digital low-pass filter configuration. * @param mode New DLFP configuration setting * @see getDLPFBandwidth() * @see MPU6050_DLPF_BW_256 * @see MPU6050_RA_CONFIG * @see MPU6050_CFG_DLPF_CFG_BIT * @see MPU6050_CFG_DLPF_CFG_LENGTH */ void setDLPFMode(int mode) { I2CdevWriteBits(deviceAddress, MPU6050_RA_CONFIG, MPU6050_CFG_DLPF_CFG_BIT, MPU6050_CFG_DLPF_CFG_LENGTH, mode); } // GYRO_CONFIG register /** Get full-scale gyroscope range. * The FS_SEL parameter allows setting the full-scale range of the gyro sensors, * as described in the table below. * * <pre> * 0 = +/- 250 degrees/sec * 1 = +/- 500 degrees/sec * 2 = +/- 1000 degrees/sec * 3 = +/- 2000 degrees/sec * </pre> * * @return Current full-scale gyroscope range setting * @see MPU6050_GYRO_FS_250 * @see MPU6050_RA_GYRO_CONFIG * @see MPU6050_GCONFIG_FS_SEL_BIT * @see MPU6050_GCONFIG_FS_SEL_LENGTH */ int getFullScaleGyroRange() { I2CdevReadBits(deviceAddress, MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, bytebuffer); return bytebuffer; } /** Set full-scale gyroscope range. * @param range New full-scale gyroscope range value * @see getFullScaleRange() * @see MPU6050_GYRO_FS_250 * @see MPU6050_RA_GYRO_CONFIG * @see MPU6050_GCONFIG_FS_SEL_BIT * @see MPU6050_GCONFIG_FS_SEL_LENGTH */ void setFullScaleGyroRange(int range) { I2CdevWriteBits(deviceAddress, MPU6050_RA_GYRO_CONFIG, MPU6050_GCONFIG_FS_SEL_BIT, MPU6050_GCONFIG_FS_SEL_LENGTH, range); } // SELF TEST FACTORY TRIM VALUES /** Get self-test factory trim value for accelerometer X axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_X */ int getAccelXSelfTestFactoryTrim() { int buffer0 = 0; int buffer1 = 0; I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_X, buffer0); I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_A, buffer1); return (buffer0>>3) | ((buffer1>>4) & 0x03); } /** Get self-test factory trim value for accelerometer Y axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Y */ int getAccelYSelfTestFactoryTrim() { int buffer0 = 0; int buffer1 = 0; I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_Y, buffer0); I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_A, buffer1); return (buffer0>>3) | ((buffer1>>2) & 0x03); } /** Get self-test factory trim value for accelerometer Z axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Z */ int getAccelZSelfTestFactoryTrim() { I2CdevReadBytes(deviceAddress, MPU6050_RA_SELF_TEST_Z, 2, buffer); return (buffer[0]>>3) | (buffer[1] & 0x03); } /** Get self-test factory trim value for gyro X axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_X */ int getGyroXSelfTestFactoryTrim() { I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_X, bytebuffer); return (bytebuffer & 0x1F); } /** Get self-test factory trim value for gyro Y axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Y */ int getGyroYSelfTestFactoryTrim() { I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_Y, bytebuffer); return (bytebuffer & 0x1F); } /** Get self-test factory trim value for gyro Z axis. * @return factory trim value * @see MPU6050_RA_SELF_TEST_Z */ int getGyroZSelfTestFactoryTrim() { I2CdevReadByte(deviceAddress, MPU6050_RA_SELF_TEST_Z, bytebuffer); return (bytebuffer & 0x1F); } // ACCEL_CONFIG register /** Get self-test enabled setting for accelerometer X axis. * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelXSelfTest() { I2CdevReadBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_XA_ST_BIT, bytebuffer); return bytebuffer != 0; } /** Get self-test enabled setting for accelerometer X axis. * @param enabled Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelXSelfTest(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_XA_ST_BIT, enabled); } /** Get self-test enabled value for accelerometer Y axis. * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelYSelfTest() { I2CdevReadBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_YA_ST_BIT, bytebuffer); return bytebuffer != 0; } /** Get self-test enabled value for accelerometer Y axis. * @param enabled Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelYSelfTest(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_YA_ST_BIT, enabled); } /** Get self-test enabled value for accelerometer Z axis. * @return Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ boolean getAccelZSelfTest() { I2CdevReadBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ZA_ST_BIT, bytebuffer); return bytebuffer != 0; } /** Set self-test enabled value for accelerometer Z axis. * @param enabled Self-test enabled value * @see MPU6050_RA_ACCEL_CONFIG */ void setAccelZSelfTest(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ZA_ST_BIT, enabled); } /** Get full-scale accelerometer range. * The FS_SEL parameter allows setting the full-scale range of the accelerometer * sensors, as described in the table below. * * <pre> * 0 = +/- 2g * 1 = +/- 4g * 2 = +/- 8g * 3 = +/- 16g * </pre> * * @return Current full-scale accelerometer range setting * @see MPU6050_ACCEL_FS_2 * @see MPU6050_RA_ACCEL_CONFIG * @see MPU6050_ACONFIG_AFS_SEL_BIT * @see MPU6050_ACONFIG_AFS_SEL_LENGTH */ int getFullScaleAccelRange() { I2CdevReadBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, bytebuffer); return bytebuffer; } /** Set full-scale accelerometer range. * @param range New full-scale accelerometer range setting * @see getFullScaleAccelRange() */ void setFullScaleAccelRange(int range) { I2CdevWriteBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_AFS_SEL_BIT, MPU6050_ACONFIG_AFS_SEL_LENGTH, range); } /** Get the high-pass filter configuration. * The DHPF is a filter module in the path leading to motion detectors (Free * Fall, Motion threshold, and Zero Motion). The high pass filter output is not * available to the data registers (see Figure in Section 8 of the MPU-6000/ * MPU-6050 Product Specification document). * * The high pass filter has three modes: * * <pre> * Reset: The filter output settles to zero within one sample. This * effectively disables the high pass filter. This mode may be toggled * to quickly settle the filter. * * On: The high pass filter will pass signals above the cut off frequency. * * Hold: When triggered, the filter holds the present sample. The filter * output will be the difference between the input sample and the held * sample. * </pre> * * <pre> * ACCEL_HPF | Filter Mode | Cut-off Frequency * ----------+-------------+------------------ * 0 | Reset | None * 1 | On | 5Hz * 2 | On | 2.5Hz * 3 | On | 1.25Hz * 4 | On | 0.63Hz * 7 | Hold | None * </pre> * * @return Current high-pass filter configuration * @see MPU6050_DHPF_RESET * @see MPU6050_RA_ACCEL_CONFIG */ int getDHPFMode() { I2CdevReadBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ACCEL_HPF_BIT, MPU6050_ACONFIG_ACCEL_HPF_LENGTH, bytebuffer); return bytebuffer; } /** Set the high-pass filter configuration. * @param bandwidth New high-pass filter configuration * @see setDHPFMode() * @see MPU6050_DHPF_RESET * @see MPU6050_RA_ACCEL_CONFIG */ void setDHPFMode(int bandwidth) { I2CdevWriteBits(deviceAddress, MPU6050_RA_ACCEL_CONFIG, MPU6050_ACONFIG_ACCEL_HPF_BIT, MPU6050_ACONFIG_ACCEL_HPF_LENGTH, bandwidth); } // FF_THR register /** Get free-fall event acceleration threshold. * This register configures the detection threshold for Free Fall event * detection. The unit of FF_THR is 1LSB = 2mg. Free Fall is detected when the * absolute value of the accelerometer measurements for the three axes are each * less than the detection threshold. This condition increments the Free Fall * duration counter (Register 30). The Free Fall interrupt is triggered when the * Free Fall duration counter reaches the time specified in FF_DUR. * * For more details on the Free Fall detection interrupt, see Section 8.2 of the * MPU-6000/MPU-6050 Product Specification document as well as Registers 56 and * 58 of this document. * * @return Current free-fall acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_FF_THR */ int getFreefallDetectionThreshold() { I2CdevReadByte(deviceAddress, MPU6050_RA_FF_THR, bytebuffer); return bytebuffer; } /** Get free-fall event acceleration threshold. * @param threshold New free-fall acceleration threshold value (LSB = 2mg) * @see getFreefallDetectionThreshold() * @see MPU6050_RA_FF_THR */ void setFreefallDetectionThreshold(int threshold) { I2CdevWriteByte(deviceAddress, MPU6050_RA_FF_THR, threshold); } // FF_DUR register /** Get free-fall event duration threshold. * This register configures the duration counter threshold for Free Fall event * detection. The duration counter ticks at 1kHz, therefore FF_DUR has a unit * of 1 LSB = 1 ms. * * The Free Fall duration counter increments while the absolute value of the * accelerometer measurements are each less than the detection threshold * (Register 29). The Free Fall interrupt is triggered when the Free Fall * duration counter reaches the time specified in this register. * * For more details on the Free Fall detection interrupt, see Section 8.2 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers 56 * and 58 of this document. * * @return Current free-fall duration threshold value (LSB = 1ms) * @see MPU6050_RA_FF_DUR */ int getFreefallDetectionDuration() { I2CdevReadByte(deviceAddress, MPU6050_RA_FF_DUR, bytebuffer); return bytebuffer; } /** Get free-fall event duration threshold. * @param duration New free-fall duration threshold value (LSB = 1ms) * @see getFreefallDetectionDuration() * @see MPU6050_RA_FF_DUR */ void setFreefallDetectionDuration(int duration) { I2CdevWriteByte(deviceAddress, MPU6050_RA_FF_DUR, duration); } // MOT_THR register /** Get motion detection event acceleration threshold. * This register configures the detection threshold for Motion interrupt * generation. The unit of MOT_THR is 1LSB = 2mg. Motion is detected when the * absolute value of any of the accelerometer measurements exceeds this Motion * detection threshold. This condition increments the Motion detection duration * counter (Register 32). The Motion detection interrupt is triggered when the * Motion Detection counter reaches the time count specified in MOT_DUR * (Register 32). * * The Motion interrupt will indicate the axis and polarity of detected motion * in MOT_DETECT_STATUS (Register 97). * * For more details on the Motion detection interrupt, see Section 8.3 of the * MPU-6000/MPU-6050 Product Specification document as well as Registers 56 and * 58 of this document. * * @return Current motion detection acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_MOT_THR */ int getMotionDetectionThreshold() { I2CdevReadByte(deviceAddress, MPU6050_RA_MOT_THR, bytebuffer); return bytebuffer; } /** Set motion detection event acceleration threshold. * @param threshold New motion detection acceleration threshold value (LSB = 2mg) * @see getMotionDetectionThreshold() * @see MPU6050_RA_MOT_THR */ void setMotionDetectionThreshold(int threshold) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MOT_THR, threshold); } // MOT_DUR register /** Get motion detection event duration threshold. * This register configures the duration counter threshold for Motion interrupt * generation. The duration counter ticks at 1 kHz, therefore MOT_DUR has a unit * of 1LSB = 1ms. The Motion detection duration counter increments when the * absolute value of any of the accelerometer measurements exceeds the Motion * detection threshold (Register 31). The Motion detection interrupt is * triggered when the Motion detection counter reaches the time count specified * in this register. * * For more details on the Motion detection interrupt, see Section 8.3 of the * MPU-6000/MPU-6050 Product Specification document. * * @return Current motion detection duration threshold value (LSB = 1ms) * @see MPU6050_RA_MOT_DUR */ int getMotionDetectionDuration() { I2CdevReadByte(deviceAddress, MPU6050_RA_MOT_DUR, bytebuffer); return bytebuffer; } /** Set motion detection event duration threshold. * @param duration New motion detection duration threshold value (LSB = 1ms) * @see getMotionDetectionDuration() * @see MPU6050_RA_MOT_DUR */ void setMotionDetectionDuration(int duration) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MOT_DUR, duration); } // ZRMOT_THR register /** Get zero motion detection event acceleration threshold. * This register configures the detection threshold for Zero Motion interrupt * generation. The unit of ZRMOT_THR is 1LSB = 2mg. Zero Motion is detected when * the absolute value of the accelerometer measurements for the 3 axes are each * less than the detection threshold. This condition increments the Zero Motion * duration counter (Register 34). The Zero Motion interrupt is triggered when * the Zero Motion duration counter reaches the time count specified in * ZRMOT_DUR (Register 34). * * Unlike Free Fall or Motion detection, Zero Motion detection triggers an * interrupt both when Zero Motion is first detected and when Zero Motion is no * longer detected. * * When a zero motion event is detected, a Zero Motion Status will be indicated * in the MOT_DETECT_STATUS register (Register 97). When a motion-to-zero-motion * condition is detected, the status bit is set to 1. When a zero-motion-to- * motion condition is detected, the status bit is set to 0. * * For more details on the Zero Motion detection interrupt, see Section 8.4 of * the MPU-6000/MPU-6050 Product Specification document as well as Registers 56 * and 58 of this document. * * @return Current zero motion detection acceleration threshold value (LSB = 2mg) * @see MPU6050_RA_ZRMOT_THR */ int getZeroMotionDetectionThreshold() { I2CdevReadByte(deviceAddress, MPU6050_RA_ZRMOT_THR, bytebuffer); return bytebuffer; } /** Set zero motion detection event acceleration threshold. * @param threshold New zero motion detection acceleration threshold value (LSB = 2mg) * @see getZeroMotionDetectionThreshold() * @see MPU6050_RA_ZRMOT_THR */ void setZeroMotionDetectionThreshold(int threshold) { I2CdevWriteByte(deviceAddress, MPU6050_RA_ZRMOT_THR, threshold); } // ZRMOT_DUR register /** Get zero motion detection event duration threshold. * This register configures the duration counter threshold for Zero Motion * interrupt generation. The duration counter ticks at 16 Hz, therefore * ZRMOT_DUR has a unit of 1 LSB = 64 ms. The Zero Motion duration counter * increments while the absolute value of the accelerometer measurements are * each less than the detection threshold (Register 33). The Zero Motion * interrupt is triggered when the Zero Motion duration counter reaches the time * count specified in this register. * * For more details on the Zero Motion detection interrupt, see Section 8.4 of * the MPU-6000/MPU-6050 Product Specification document, as well as Registers 56 * and 58 of this document. * * @return Current zero motion detection duration threshold value (LSB = 64ms) * @see MPU6050_RA_ZRMOT_DUR */ int getZeroMotionDetectionDuration() { I2CdevReadByte(deviceAddress, MPU6050_RA_ZRMOT_DUR, bytebuffer); return bytebuffer; } /** Set zero motion detection event duration threshold. * @param duration New zero motion detection duration threshold value (LSB = 1ms) * @see getZeroMotionDetectionDuration() * @see MPU6050_RA_ZRMOT_DUR */ void setZeroMotionDetectionDuration(int duration) { I2CdevWriteByte(deviceAddress, MPU6050_RA_ZRMOT_DUR, duration); } // FIFO_EN register /** Get temperature FIFO enabled value. * When set to 1, this bit enables TEMP_OUT_H and TEMP_OUT_L (Registers 65 and * 66) to be written into the FIFO buffer. * @return Current temperature FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getTempFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_TEMP_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set temperature FIFO enabled value. * @param enabled New temperature FIFO enabled value * @see getTempFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setTempFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_TEMP_FIFO_EN_BIT, enabled); } /** Get gyroscope X-axis FIFO enabled value. * When set to 1, this bit enables GYRO_XOUT_H and GYRO_XOUT_L (Registers 67 and * 68) to be written into the FIFO buffer. * @return Current gyroscope X-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getXGyroFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_XG_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set gyroscope X-axis FIFO enabled value. * @param enabled New gyroscope X-axis FIFO enabled value * @see getXGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setXGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_XG_FIFO_EN_BIT, enabled); } /** Get gyroscope Y-axis FIFO enabled value. * When set to 1, this bit enables GYRO_YOUT_H and GYRO_YOUT_L (Registers 69 and * 70) to be written into the FIFO buffer. * @return Current gyroscope Y-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getYGyroFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_YG_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set gyroscope Y-axis FIFO enabled value. * @param enabled New gyroscope Y-axis FIFO enabled value * @see getYGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setYGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_YG_FIFO_EN_BIT, enabled); } /** Get gyroscope Z-axis FIFO enabled value. * When set to 1, this bit enables GYRO_ZOUT_H and GYRO_ZOUT_L (Registers 71 and * 72) to be written into the FIFO buffer. * @return Current gyroscope Z-axis FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getZGyroFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ZG_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set gyroscope Z-axis FIFO enabled value. * @param enabled New gyroscope Z-axis FIFO enabled value * @see getZGyroFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setZGyroFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ZG_FIFO_EN_BIT, enabled); } /** Get accelerometer FIFO enabled value. * When set to 1, this bit enables ACCEL_XOUT_H, ACCEL_XOUT_L, ACCEL_YOUT_H, * ACCEL_YOUT_L, ACCEL_ZOUT_H, and ACCEL_ZOUT_L (Registers 59 to 64) to be * written into the FIFO buffer. * @return Current accelerometer FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getAccelFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ACCEL_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set accelerometer FIFO enabled value. * @param enabled New accelerometer FIFO enabled value * @see getAccelFIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setAccelFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_ACCEL_FIFO_EN_BIT, enabled); } /** Get Slave 2 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 2 to be written into the FIFO buffer. * @return Current Slave 2 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave2FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV2_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 2 FIFO enabled value. * @param enabled New Slave 2 FIFO enabled value * @see getSlave2FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave2FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV2_FIFO_EN_BIT, enabled); } /** Get Slave 1 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 1 to be written into the FIFO buffer. * @return Current Slave 1 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave1FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV1_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 1 FIFO enabled value. * @param enabled New Slave 1 FIFO enabled value * @see getSlave1FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave1FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV1_FIFO_EN_BIT, enabled); } /** Get Slave 0 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 0 to be written into the FIFO buffer. * @return Current Slave 0 FIFO enabled value * @see MPU6050_RA_FIFO_EN */ boolean getSlave0FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV0_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 0 FIFO enabled value. * @param enabled New Slave 0 FIFO enabled value * @see getSlave0FIFOEnabled() * @see MPU6050_RA_FIFO_EN */ void setSlave0FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_FIFO_EN, MPU6050_SLV0_FIFO_EN_BIT, enabled); } // I2C_MST_CTRL register /** Get multi-master enabled value. * Multi-master capability allows multiple I2C masters to operate on the same * bus. In circuits where multi-master capability is required, set MULT_MST_EN * to 1. This will increase current drawn by approximately 30uA. * * In circuits where multi-master capability is required, the state of the I2C * bus must always be monitored by each separate I2C Master. Before an I2C * Master can assume arbitration of the bus, it must first confirm that no other * I2C Master has arbitration of the bus. When MULT_MST_EN is set to 1, the * MPU-60X0's bus arbitration detection logic is turned on, enabling it to * detect when the bus is available. * * @return Current multi-master enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getMultiMasterEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_MULT_MST_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set multi-master enabled value. * @param enabled New multi-master enabled value * @see getMultiMasterEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setMultiMasterEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_MULT_MST_EN_BIT, enabled); } /** Get wait-for-external-sensor-data enabled value. * When the WAIT_FOR_ES bit is set to 1, the Data Ready interrupt will be * delayed until External Sensor data from the Slave Devices are loaded into the * EXT_SENS_DATA registers. This is used to ensure that both the internal sensor * data (i.e. from gyro and accel) and external sensor data have been loaded to * their respective data registers (i.e. the data is synced) when the Data Ready * interrupt is triggered. * * @return Current wait-for-external-sensor-data enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getWaitForExternalSensorEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_WAIT_FOR_ES_BIT, bytebuffer); return bytebuffer != 0; } /** Set wait-for-external-sensor-data enabled value. * @param enabled New wait-for-external-sensor-data enabled value * @see getWaitForExternalSensorEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setWaitForExternalSensorEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_WAIT_FOR_ES_BIT, enabled); } /** Get Slave 3 FIFO enabled value. * When set to 1, this bit enables EXT_SENS_DATA registers (Registers 73 to 96) * associated with Slave 3 to be written into the FIFO buffer. * @return Current Slave 3 FIFO enabled value * @see MPU6050_RA_MST_CTRL */ boolean getSlave3FIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_SLV_3_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set Slave 3 FIFO enabled value. * @param enabled New Slave 3 FIFO enabled value * @see getSlave3FIFOEnabled() * @see MPU6050_RA_MST_CTRL */ void setSlave3FIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_SLV_3_FIFO_EN_BIT, enabled); } /** Get slave read/write transition enabled value. * The I2C_MST_P_NSR bit configures the I2C Master's transition from one slave * read to the next slave read. If the bit equals 0, there will be a restart * between reads. If the bit equals 1, there will be a stop followed by a start * of the following read. When a write transaction follows a read transaction, * the stop followed by a start of the successive write will be always used. * * @return Current slave read/write transition enabled value * @see MPU6050_RA_I2C_MST_CTRL */ boolean getSlaveReadWriteTransitionEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_P_NSR_BIT, bytebuffer); return bytebuffer != 0; } /** Set slave read/write transition enabled value. * @param enabled New slave read/write transition enabled value * @see getSlaveReadWriteTransitionEnabled() * @see MPU6050_RA_I2C_MST_CTRL */ void setSlaveReadWriteTransitionEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_P_NSR_BIT, enabled); } /** Get I2C master clock speed. * I2C_MST_CLK is a 4 bit unsigned value which configures a divider on the * MPU-60X0 internal 8MHz clock. It sets the I2C master clock speed according to * the following table: * * <pre> * I2C_MST_CLK | I2C Master Clock Speed | 8MHz Clock Divider * ------------+------------------------+------------------- * 0 | 348kHz | 23 * 1 | 333kHz | 24 * 2 | 320kHz | 25 * 3 | 308kHz | 26 * 4 | 296kHz | 27 * 5 | 286kHz | 28 * 6 | 276kHz | 29 * 7 | 267kHz | 30 * 8 | 258kHz | 31 * 9 | 500kHz | 16 * 10 | 471kHz | 17 * 11 | 444kHz | 18 * 12 | 421kHz | 19 * 13 | 400kHz | 20 * 14 | 381kHz | 21 * 15 | 364kHz | 22 * </pre> * * @return Current I2C master clock speed * @see MPU6050_RA_I2C_MST_CTRL */ int getMasterClockSpeed() { I2CdevReadBits(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_CLK_BIT, MPU6050_I2C_MST_CLK_LENGTH, bytebuffer); return bytebuffer; } /** Set I2C master clock speed. * @reparam speed Current I2C master clock speed * @see MPU6050_RA_I2C_MST_CTRL */ void setMasterClockSpeed(int speed) { I2CdevWriteBits(deviceAddress, MPU6050_RA_I2C_MST_CTRL, MPU6050_I2C_MST_CLK_BIT, MPU6050_I2C_MST_CLK_LENGTH, speed); } // I2C_SLV* registers (Slave 0-3) /** Get the I2C address of the specified slave (0-3). * Note that Bit 7 (MSB) controls read/write mode. If Bit 7 is set, it's a read * operation, and if it is cleared, then it's a write operation. The remaining * bits (6-0) are the 7-bit device address of the slave device. * * In read mode, the result of the read is placed in the lowest available * EXT_SENS_DATA register. For further information regarding the allocation of * read results, please refer to the EXT_SENS_DATA register description * (Registers 73 - 96). * * The MPU-6050 supports a total of five slaves, but Slave 4 has unique * characteristics, and so it has its own functions (getSlave4* and setSlave4*). * * I2C data transactions are performed at the Sample Rate, as defined in * Register 25. The user is responsible for ensuring that I2C data transactions * to and from each enabled Slave can be completed within a single period of the * Sample Rate. * * The I2C slave access rate can be reduced relative to the Sample Rate. This * reduced access rate is determined by I2C_MST_DLY (Register 52). Whether a * slave's access rate is reduced relative to the Sample Rate is determined by * I2C_MST_DELAY_CTRL (Register 103). * * The processing order for the slaves is fixed. The sequence followed for * processing the slaves is Slave 0, Slave 1, Slave 2, Slave 3 and Slave 4. If a * particular Slave is disabled it will be skipped. * * Each slave can either be accessed at the sample rate or at a reduced sample * rate. In a case where some slaves are accessed at the Sample Rate and some * slaves are accessed at the reduced rate, the sequence of accessing the slaves * (Slave 0 to Slave 4) is still followed. However, the reduced rate slaves will * be skipped if their access rate dictates that they should not be accessed * during that particular cycle. For further information regarding the reduced * access rate, please refer to Register 52. Whether a slave is accessed at the * Sample Rate or at the reduced rate is determined by the Delay Enable bits in * Register 103. * * @param num Slave number (0-3) * @return Current address for specified slave * @see MPU6050_RA_I2C_SLV0_ADDR */ int getSlaveAddress(int num) { if (num > 3) return 0; I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV0_ADDR + num*3, bytebuffer); return bytebuffer; } /** Set the I2C address of the specified slave (0-3). * @param num Slave number (0-3) * @param address New address for specified slave * @see getSlaveAddress() * @see MPU6050_RA_I2C_SLV0_ADDR */ void setSlaveAddress(int num, int address) { if (num > 3) return; I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV0_ADDR + num*3, address); } /** Get the active internal register for the specified slave (0-3). * Read/write operations for this slave will be done to whatever internal * register address is stored in this MPU register. * * The MPU-6050 supports a total of five slaves, but Slave 4 has unique * characteristics, and so it has its own functions. * * @param num Slave number (0-3) * @return Current active register for specified slave * @see MPU6050_RA_I2C_SLV0_REG */ int getSlaveRegister(int num) { if (num > 3) return 0; I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV0_REG + num*3, bytebuffer); return bytebuffer; } /** Set the active internal register for the specified slave (0-3). * @param num Slave number (0-3) * @param reg New active register for specified slave * @see getSlaveRegister() * @see MPU6050_RA_I2C_SLV0_REG */ void setSlaveRegister(int num, int reg) { if (num > 3) return; I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV0_REG + num*3, reg); } /** Get the enabled value for the specified slave (0-3). * When set to 1, this bit enables Slave 0 for data transfer operations. When * cleared to 0, this bit disables Slave 0 from data transfer operations. * @param num Slave number (0-3) * @return Current enabled value for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveEnabled(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set the enabled value for the specified slave (0-3). * @param num Slave number (0-3) * @param enabled New enabled value for specified slave * @see getSlaveEnabled() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveEnabled(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_EN_BIT, enabled); } /** Get word pair byte-swapping enabled for the specified slave (0-3). * When set to 1, this bit enables byte swapping. When byte swapping is enabled, * the high and low bytes of a word pair are swapped. Please refer to * I2C_SLV0_GRP for the pairing convention of the word pairs. When cleared to 0, * bytes transferred to and from Slave 0 will be written to EXT_SENS_DATA * registers in the order they were transferred. * * @param num Slave number (0-3) * @return Current word pair byte-swapping enabled value for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWordByteSwap(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_BYTE_SW_BIT, bytebuffer); return bytebuffer != 0; } /** Set word pair byte-swapping enabled for the specified slave (0-3). * @param num Slave number (0-3) * @param enabled New word pair byte-swapping enabled value for specified slave * @see getSlaveWordByteSwap() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWordByteSwap(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_BYTE_SW_BIT, enabled); } /** Get write mode for the specified slave (0-3). * When set to 1, the transaction will read or write data only. When cleared to * 0, the transaction will write a register address prior to reading or writing * data. This should equal 0 when specifying the register address within the * Slave device to/from which the ensuing data transaction will take place. * * @param num Slave number (0-3) * @return Current write mode for specified slave (0 = register address + data, 1 = data only) * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWriteMode(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_REG_DIS_BIT, bytebuffer); return bytebuffer != 0; } /** Set write mode for the specified slave (0-3). * @param num Slave number (0-3) * @param mode New write mode for specified slave (0 = register address + data, 1 = data only) * @see getSlaveWriteMode() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWriteMode(int num, boolean mode) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_REG_DIS_BIT, mode); } /** Get word pair grouping order offset for the specified slave (0-3). * This sets specifies the grouping order of word pairs received from registers. * When cleared to 0, bytes from register addresses 0 and 1, 2 and 3, etc (even, * then odd register addresses) are paired to form a word. When set to 1, bytes * from register addresses are paired 1 and 2, 3 and 4, etc. (odd, then even * register addresses) are paired to form a word. * * @param num Slave number (0-3) * @return Current word pair grouping order offset for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ boolean getSlaveWordGroupOffset(int num) { if (num > 3) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_GRP_BIT, bytebuffer); return bytebuffer != 0; } /** Set word pair grouping order offset for the specified slave (0-3). * @param num Slave number (0-3) * @param enabled New word pair grouping order offset for specified slave * @see getSlaveWordGroupOffset() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveWordGroupOffset(int num, boolean enabled) { if (num > 3) return; I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_GRP_BIT, enabled); } /** Get number of bytes to read for the specified slave (0-3). * Specifies the number of bytes transferred to and from Slave 0. Clearing this * bit to 0 is equivalent to disabling the register by writing 0 to I2C_SLV0_EN. * @param num Slave number (0-3) * @return Number of bytes to read for specified slave * @see MPU6050_RA_I2C_SLV0_CTRL */ int getSlaveDataLength(int num) { if (num > 3) return 0; I2CdevReadBits(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_LEN_BIT, MPU6050_I2C_SLV_LEN_LENGTH, bytebuffer); return bytebuffer; } /** Set number of bytes to read for the specified slave (0-3). * @param num Slave number (0-3) * @param length Number of bytes to read for specified slave * @see getSlaveDataLength() * @see MPU6050_RA_I2C_SLV0_CTRL */ void setSlaveDataLength(int num, int length) { if (num > 3) return; I2CdevWriteBits(deviceAddress, MPU6050_RA_I2C_SLV0_CTRL + num*3, MPU6050_I2C_SLV_LEN_BIT, MPU6050_I2C_SLV_LEN_LENGTH, length); } // I2C_SLV* registers (Slave 4) /** Get the I2C address of Slave 4. * Note that Bit 7 (MSB) controls read/write mode. If Bit 7 is set, it's a read * operation, and if it is cleared, then it's a write operation. The remaining * bits (6-0) are the 7-bit device address of the slave device. * * @return Current address for Slave 4 * @see getSlaveAddress() * @see MPU6050_RA_I2C_SLV4_ADDR */ int getSlave4Address() { I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV4_ADDR, bytebuffer); return bytebuffer; } /** Set the I2C address of Slave 4. * @param address New address for Slave 4 * @see getSlave4Address() * @see MPU6050_RA_I2C_SLV4_ADDR */ void setSlave4Address(int address) { I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV4_ADDR, address); } /** Get the active internal register for the Slave 4. * Read/write operations for this slave will be done to whatever internal * register address is stored in this MPU register. * * @return Current active register for Slave 4 * @see MPU6050_RA_I2C_SLV4_REG */ int getSlave4Register() { I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV4_REG, bytebuffer); return bytebuffer; } /** Set the active internal register for Slave 4. * @param reg New active register for Slave 4 * @see getSlave4Register() * @see MPU6050_RA_I2C_SLV4_REG */ void setSlave4Register(int reg) { I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV4_REG, reg); } /** Set new byte to write to Slave 4. * This register stores the data to be written into the Slave 4. If I2C_SLV4_RW * is set 1 (set to read), this register has no effect. * @param data New byte to write to Slave 4 * @see MPU6050_RA_I2C_SLV4_DO */ void setSlave4OutputByte(int data) { I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV4_DO, data); } /** Get the enabled value for the Slave 4. * When set to 1, this bit enables Slave 4 for data transfer operations. When * cleared to 0, this bit disables Slave 4 from data transfer operations. * @return Current enabled value for Slave 4 * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4Enabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set the enabled value for Slave 4. * @param enabled New enabled value for Slave 4 * @see getSlave4Enabled() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4Enabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_EN_BIT, enabled); } /** Get the enabled value for Slave 4 transaction interrupts. * When set to 1, this bit enables the generation of an interrupt signal upon * completion of a Slave 4 transaction. When cleared to 0, this bit disables the * generation of an interrupt signal upon completion of a Slave 4 transaction. * The interrupt status can be observed in Register 54. * * @return Current enabled value for Slave 4 transaction interrupts. * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4InterruptEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_INT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set the enabled value for Slave 4 transaction interrupts. * @param enabled New enabled value for Slave 4 transaction interrupts. * @see getSlave4InterruptEnabled() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4InterruptEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_INT_EN_BIT, enabled); } /** Get write mode for Slave 4. * When set to 1, the transaction will read or write data only. When cleared to * 0, the transaction will write a register address prior to reading or writing * data. This should equal 0 when specifying the register address within the * Slave device to/from which the ensuing data transaction will take place. * * @return Current write mode for Slave 4 (0 = register address + data, 1 = data only) * @see MPU6050_RA_I2C_SLV4_CTRL */ boolean getSlave4WriteMode() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_REG_DIS_BIT, bytebuffer); return bytebuffer != 0; } /** Set write mode for the Slave 4. * @param mode New write mode for Slave 4 (0 = register address + data, 1 = data only) * @see getSlave4WriteMode() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4WriteMode(boolean mode) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_REG_DIS_BIT, mode); } /** Get Slave 4 master delay value. * This configures the reduced access rate of I2C slaves relative to the Sample * Rate. When a slave's access rate is decreased relative to the Sample Rate, * the slave is accessed every: * * 1 / (1 + I2C_MST_DLY) samples * * This base Sample Rate in turn is determined by SMPLRT_DIV (register 25) and * DLPF_CFG (register 26). Whether a slave's access rate is reduced relative to * the Sample Rate is determined by I2C_MST_DELAY_CTRL (register 103). For * further information regarding the Sample Rate, please refer to register 25. * * @return Current Slave 4 master delay value * @see MPU6050_RA_I2C_SLV4_CTRL */ int getSlave4MasterDelay() { I2CdevReadBits(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_MST_DLY_BIT, MPU6050_I2C_SLV4_MST_DLY_LENGTH, bytebuffer); return bytebuffer; } /** Set Slave 4 master delay value. * @param delay New Slave 4 master delay value * @see getSlave4MasterDelay() * @see MPU6050_RA_I2C_SLV4_CTRL */ void setSlave4MasterDelay(int delay) { I2CdevWriteBits(deviceAddress, MPU6050_RA_I2C_SLV4_CTRL, MPU6050_I2C_SLV4_MST_DLY_BIT, MPU6050_I2C_SLV4_MST_DLY_LENGTH, delay); } /** Get last available byte read from Slave 4. * This register stores the data read from Slave 4. This field is populated * after a read transaction. * @return Last available byte read from to Slave 4 * @see MPU6050_RA_I2C_SLV4_DI */ int getSlate4InputByte() { I2CdevReadByte(deviceAddress, MPU6050_RA_I2C_SLV4_DI, bytebuffer); return bytebuffer; } // I2C_MST_STATUS register /** Get FSYNC interrupt status. * This bit reflects the status of the FSYNC interrupt from an external device * into the MPU-60X0. This is used as a way to pass an external interrupt * through the MPU-60X0 to the host application processor. When set to 1, this * bit will cause an interrupt if FSYNC_INT_EN is asserted in INT_PIN_CFG * (Register 55). * @return FSYNC interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getPassthroughStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_PASS_THROUGH_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 4 transaction done status. * Automatically sets to 1 when a Slave 4 transaction has completed. This * triggers an interrupt if the I2C_MST_INT_EN bit in the INT_ENABLE register * (Register 56) is asserted and if the SLV_4_DONE_INT bit is asserted in the * I2C_SLV4_CTRL register (Register 52). * @return Slave 4 transaction done status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave4IsDone() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV4_DONE_BIT, bytebuffer); return bytebuffer != 0; } /** Get master arbitration lost status. * This bit automatically sets to 1 when the I2C Master has lost arbitration of * the auxiliary I2C bus (an error condition). This triggers an interrupt if the * I2C_MST_INT_EN bit in the INT_ENABLE register (Register 56) is asserted. * @return Master arbitration lost status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getLostArbitration() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_LOST_ARB_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 4 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 4. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 4 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave4Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV4_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 3 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 3. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 3 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave3Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV3_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 2 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 2. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 2 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave2Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV2_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 1 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 1. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 1 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave1Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV1_NACK_BIT, bytebuffer); return bytebuffer != 0; } /** Get Slave 0 NACK status. * This bit automatically sets to 1 when the I2C Master receives a NACK in a * transaction with Slave 0. This triggers an interrupt if the I2C_MST_INT_EN * bit in the INT_ENABLE register (Register 56) is asserted. * @return Slave 0 NACK interrupt status * @see MPU6050_RA_I2C_MST_STATUS */ boolean getSlave0Nack() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_STATUS, MPU6050_MST_I2C_SLV0_NACK_BIT, bytebuffer); return bytebuffer != 0; } // INT_PIN_CFG register /** Get interrupt logic level mode. * Will be set 0 for active-high, 1 for active-low. * @return Current interrupt mode (0=active-high, 1=active-low) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_LEVEL_BIT */ boolean getInterruptMode() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_LEVEL_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt logic level mode. * @param mode New interrupt mode (0=active-high, 1=active-low) * @see getInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_LEVEL_BIT */ void setInterruptMode(boolean mode) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_LEVEL_BIT, mode); } /** Get interrupt drive mode. * Will be set 0 for push-pull, 1 for open-drain. * @return Current interrupt drive mode (0=push-pull, 1=open-drain) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_OPEN_BIT */ boolean getInterruptDrive() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_OPEN_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt drive mode. * @param drive New interrupt drive mode (0=push-pull, 1=open-drain) * @see getInterruptDrive() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_OPEN_BIT */ void setInterruptDrive(boolean drive) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_OPEN_BIT, drive); } /** Get interrupt latch mode. * Will be set 0 for 50us-pulse, 1 for latch-until-int-cleared. * @return Current latch mode (0=50us-pulse, 1=latch-until-int-cleared) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_LATCH_INT_EN_BIT */ boolean getInterruptLatch() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_LATCH_INT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt latch mode. * @param latch New latch mode (0=50us-pulse, 1=latch-until-int-cleared) * @see getInterruptLatch() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_LATCH_INT_EN_BIT */ void setInterruptLatch(boolean latch) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_LATCH_INT_EN_BIT, latch); } /** Get interrupt latch clear mode. * Will be set 0 for status-read-only, 1 for any-register-read. * @return Current latch clear mode (0=status-read-only, 1=any-register-read) * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_RD_CLEAR_BIT */ boolean getInterruptLatchClear() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_RD_CLEAR_BIT, bytebuffer); return bytebuffer != 0; } /** Set interrupt latch clear mode. * @param clear New latch clear mode (0=status-read-only, 1=any-register-read) * @see getInterruptLatchClear() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_INT_RD_CLEAR_BIT */ void setInterruptLatchClear(boolean clear) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_INT_RD_CLEAR_BIT, clear); } /** Get FSYNC interrupt logic level mode. * @return Current FSYNC interrupt mode (0=active-high, 1=active-low) * @see getFSyncInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT */ boolean getFSyncInterruptLevel() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT, bytebuffer); return bytebuffer != 0; } /** Set FSYNC interrupt logic level mode. * @param mode New FSYNC interrupt mode (0=active-high, 1=active-low) * @see getFSyncInterruptMode() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT */ void setFSyncInterruptLevel(boolean level) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_LEVEL_BIT, level); } /** Get FSYNC pin interrupt enabled setting. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled setting * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_EN_BIT */ boolean getFSyncInterruptEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set FSYNC pin interrupt enabled setting. * @param enabled New FSYNC pin interrupt enabled setting * @see getFSyncInterruptEnabled() * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_FSYNC_INT_EN_BIT */ void setFSyncInterruptEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_FSYNC_INT_EN_BIT, enabled); } /** Get I2C bypass enabled status. * When this bit is equal to 1 and I2C_MST_EN (Register 106 bit[5]) is equal to * 0, the host application processor will be able to directly access the * auxiliary I2C bus of the MPU-60X0. When this bit is equal to 0, the host * application processor will not be able to directly access the auxiliary I2C * bus of the MPU-60X0 regardless of the state of I2C_MST_EN (Register 106 * bit[5]). * @return Current I2C bypass enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_I2C_BYPASS_EN_BIT */ boolean getI2CBypassEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set I2C bypass enabled status. * When this bit is equal to 1 and I2C_MST_EN (Register 106 bit[5]) is equal to * 0, the host application processor will be able to directly access the * auxiliary I2C bus of the MPU-60X0. When this bit is equal to 0, the host * application processor will not be able to directly access the auxiliary I2C * bus of the MPU-60X0 regardless of the state of I2C_MST_EN (Register 106 * bit[5]). * @param enabled New I2C bypass enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_I2C_BYPASS_EN_BIT */ void setI2CBypassEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_I2C_BYPASS_EN_BIT, enabled); } /** Get reference clock output enabled status. * When this bit is equal to 1, a reference clock output is provided at the * CLKOUT pin. When this bit is equal to 0, the clock output is disabled. For * further information regarding CLKOUT, please refer to the MPU-60X0 Product * Specification document. * @return Current reference clock output enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_CLKOUT_EN_BIT */ boolean getClockOutputEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_CLKOUT_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set reference clock output enabled status. * When this bit is equal to 1, a reference clock output is provided at the * CLKOUT pin. When this bit is equal to 0, the clock output is disabled. For * further information regarding CLKOUT, please refer to the MPU-60X0 Product * Specification document. * @param enabled New reference clock output enabled status * @see MPU6050_RA_INT_PIN_CFG * @see MPU6050_INTCFG_CLKOUT_EN_BIT */ void setClockOutputEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_PIN_CFG, MPU6050_INTCFG_CLKOUT_EN_BIT, enabled); } // INT_ENABLE register /** Get full interrupt enabled status. * Full register byte for all interrupts, for quick reading. Each bit will be * set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ int getIntEnabled() { I2CdevReadByte(deviceAddress, MPU6050_RA_INT_ENABLE, bytebuffer); return bytebuffer; } /** Set full interrupt enabled status. * Full register byte for all interrupts, for quick reading. Each bit should be * set 0 for disabled, 1 for enabled. * @param enabled New interrupt enabled status * @see getIntFreefallEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ void setIntEnabled(int enabled) { I2CdevWriteByte(deviceAddress, MPU6050_RA_INT_ENABLE, enabled); } /** Get Free Fall interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ boolean getIntFreefallEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FF_BIT, bytebuffer); return bytebuffer != 0; } /** Set Free Fall interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntFreefallEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FF_BIT **/ void setIntFreefallEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FF_BIT, enabled); } /** Get Motion Detection interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_MOT_BIT **/ boolean getIntMotionEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_MOT_BIT, bytebuffer); return bytebuffer != 0; } /** Set Motion Detection interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntMotionEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_MOT_BIT **/ void setIntMotionEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_MOT_BIT, enabled); } /** Get Zero Motion Detection interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_ZMOT_BIT **/ boolean getIntZeroMotionEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_ZMOT_BIT, bytebuffer); return bytebuffer != 0; } /** Set Zero Motion Detection interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntZeroMotionEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_ZMOT_BIT **/ void setIntZeroMotionEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_ZMOT_BIT, enabled); } /** Get FIFO Buffer Overflow interrupt enabled status. * Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT **/ boolean getIntFIFOBufferOverflowEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, bytebuffer); return bytebuffer != 0; } /** Set FIFO Buffer Overflow interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntFIFOBufferOverflowEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT **/ void setIntFIFOBufferOverflowEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, enabled); } /** Get I2C Master interrupt enabled status. * This enables any of the I2C Master interrupt sources to generate an * interrupt. Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT **/ boolean getIntI2CMasterEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_I2C_MST_INT_BIT, bytebuffer); return bytebuffer != 0; } /** Set I2C Master interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntI2CMasterEnabled() * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT **/ void setIntI2CMasterEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_I2C_MST_INT_BIT, enabled); } /** Get Data Ready interrupt enabled setting. * This event occurs each time a write operation to all of the sensor registers * has been completed. Will be set 0 for disabled, 1 for enabled. * @return Current interrupt enabled status * @see MPU6050_RA_INT_ENABLE * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ boolean getIntDataReadyEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DATA_RDY_BIT, bytebuffer); return bytebuffer != 0; } /** Set Data Ready interrupt enabled status. * @param enabled New interrupt enabled status * @see getIntDataReadyEnabled() * @see MPU6050_RA_INT_CFG * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ void setIntDataReadyEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DATA_RDY_BIT, enabled); } // INT_STATUS register /** Get full set of interrupt status bits. * These bits clear to 0 after the register has been read. Very useful * for getting multiple INT statuses, since each single bit read clears * all of them because it has to read the whole byte. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS */ int getIntStatus() { I2CdevReadByte(deviceAddress, MPU6050_RA_INT_STATUS, bytebuffer); return bytebuffer; } /** Get Free Fall interrupt status. * This bit automatically sets to 1 when a Free Fall interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_FF_BIT */ boolean getIntFreefallStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_FF_BIT, bytebuffer); return bytebuffer != 0; } /** Get Motion Detection interrupt status. * This bit automatically sets to 1 when a Motion Detection interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_MOT_BIT */ boolean getIntMotionStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_MOT_BIT, bytebuffer); return bytebuffer != 0; } /** Get Zero Motion Detection interrupt status. * This bit automatically sets to 1 when a Zero Motion Detection interrupt has * been generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_ZMOT_BIT */ boolean getIntZeroMotionStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_ZMOT_BIT, bytebuffer); return bytebuffer != 0; } /** Get FIFO Buffer Overflow interrupt status. * This bit automatically sets to 1 when a Free Fall interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_FIFO_OFLOW_BIT */ boolean getIntFIFOBufferOverflowStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_FIFO_OFLOW_BIT, bytebuffer); return bytebuffer != 0; } /** Get I2C Master interrupt status. * This bit automatically sets to 1 when an I2C Master interrupt has been * generated. For a list of I2C Master interrupts, please refer to Register 54. * The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_I2C_MST_INT_BIT */ boolean getIntI2CMasterStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_I2C_MST_INT_BIT, bytebuffer); return bytebuffer != 0; } /** Get Data Ready interrupt status. * This bit automatically sets to 1 when a Data Ready interrupt has been * generated. The bit clears to 0 after the register has been read. * @return Current interrupt status * @see MPU6050_RA_INT_STATUS * @see MPU6050_INTERRUPT_DATA_RDY_BIT */ boolean getIntDataReadyStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_DATA_RDY_BIT, bytebuffer); return bytebuffer != 0; } // ACCEL_*OUT_* registers /** Get raw 9-axis motion sensor readings (accel/gyro/compass). * FUNCTION NOT FULLY IMPLEMENTED YET. * @param ax 16-bit signed integer container for accelerometer X-axis value * @param ay 16-bit signed integer container for accelerometer Y-axis value * @param az 16-bit signed integer container for accelerometer Z-axis value * @param gx 16-bit signed integer container for gyroscope X-axis value * @param gy 16-bit signed integer container for gyroscope Y-axis value * @param gz 16-bit signed integer container for gyroscope Z-axis value * @param mx 16-bit signed integer container for magnetometer X-axis value * @param my 16-bit signed integer container for magnetometer Y-axis value * @param mz 16-bit signed integer container for magnetometer Z-axis value * @see getMotion6() * @see getAcceleration() * @see getRotation() * @see MPU6050_RA_ACCEL_XOUT_H */ void getMotion9(int ax, int ay, int az, int gx, int gy, int gz, int mx, int my, int mz) { getMotion6(ax, ay, az, gx, gy, gz); // TODO: magnetometer integration } /** Get raw 6-axis motion sensor readings (accel/gyro). * Retrieves all currently available motion sensor values. * @param ax 16-bit signed integer container for accelerometer X-axis value * @param ay 16-bit signed integer container for accelerometer Y-axis value * @param az 16-bit signed integer container for accelerometer Z-axis value * @param gx 16-bit signed integer container for gyroscope X-axis value * @param gy 16-bit signed integer container for gyroscope Y-axis value * @param gz 16-bit signed integer container for gyroscope Z-axis value * @see getAcceleration() * @see getRotation() * @see MPU6050_RA_ACCEL_XOUT_H */ void getMotion6(int ax, int ay, int az, int gx, int gy, int gz) { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_XOUT_H, 14, buffer); ax = (((int)buffer[0]) << 8) | buffer[1]; ay = (((int)buffer[2]) << 8) | buffer[3]; az = (((int)buffer[4]) << 8) | buffer[5]; gx = (((int)buffer[8]) << 8) | buffer[9]; gy = (((int)buffer[10]) << 8) | buffer[11]; gz = (((int)buffer[12]) << 8) | buffer[13]; } /** Get 3-axis accelerometer readings. * These registers store the most recent accelerometer measurements. * Accelerometer measurements are written to these registers at the Sample Rate * as defined in Register 25. * * The accelerometer measurement registers, along with the temperature * measurement registers, gyroscope measurement registers, and external sensor * data registers, are composed of two sets of registers: an internal register * set and a user-facing read register set. * * The data within the accelerometer sensors' internal register set is always * updated at the Sample Rate. Meanwhile, the user-facing read register set * duplicates the internal register set's data values whenever the serial * interface is idle. This guarantees that a burst read of sensor registers will * read measurements from the same sampling instant. Note that if burst reads * are not used, the user is responsible for ensuring a set of single byte reads * correspond to a single sampling instant by checking the Data Ready interrupt. * * Each 16-bit accelerometer measurement has a full scale defined in ACCEL_FS * (Register 28). For each full scale setting, the accelerometers' sensitivity * per LSB in ACCEL_xOUT is shown in the table below: * * <pre> * AFS_SEL | Full Scale Range | LSB Sensitivity * --------+------------------+---------------- * 0 | +/- 2g | 8192 LSB/mg * 1 | +/- 4g | 4096 LSB/mg * 2 | +/- 8g | 2048 LSB/mg * 3 | +/- 16g | 1024 LSB/mg * </pre> * * @param x 16-bit signed integer container for X-axis acceleration * @param y 16-bit signed integer container for Y-axis acceleration * @param z 16-bit signed integer container for Z-axis acceleration * @see MPU6050_RA_GYRO_XOUT_H */ void getAcceleration(int x, int y, int z) { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_XOUT_H, 6, buffer); x = (((int)buffer[0]) << 8) | buffer[1]; y = (((int)buffer[2]) << 8) | buffer[3]; z = (((int)buffer[4]) << 8) | buffer[5]; } /** Get X-axis accelerometer reading. * @return X-axis acceleration measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_ACCEL_XOUT_H */ int getAccelerationX() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_XOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Y-axis accelerometer reading. * @return Y-axis acceleration measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_ACCEL_YOUT_H */ int getAccelerationY() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_YOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Z-axis accelerometer reading. * @return Z-axis acceleration measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_ACCEL_ZOUT_H */ int getAccelerationZ() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ACCEL_ZOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // TEMP_OUT_* registers /** Get current internal temperature. * @return Temperature reading in 16-bit 2's complement format * @see MPU6050_RA_TEMP_OUT_H */ int getTemperature() { I2CdevReadBytes(deviceAddress, MPU6050_RA_TEMP_OUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // GYRO_*OUT_* registers /** Get 3-axis gyroscope readings. * These gyroscope measurement registers, along with the accelerometer * measurement registers, temperature measurement registers, and external sensor * data registers, are composed of two sets of registers: an internal register * set and a user-facing read register set. * The data within the gyroscope sensors' internal register set is always * updated at the Sample Rate. Meanwhile, the user-facing read register set * duplicates the internal register set's data values whenever the serial * interface is idle. This guarantees that a burst read of sensor registers will * read measurements from the same sampling instant. Note that if burst reads * are not used, the user is responsible for ensuring a set of single byte reads * correspond to a single sampling instant by checking the Data Ready interrupt. * * Each 16-bit gyroscope measurement has a full scale defined in FS_SEL * (Register 27). For each full scale setting, the gyroscopes' sensitivity per * LSB in GYRO_xOUT is shown in the table below: * * <pre> * FS_SEL | Full Scale Range | LSB Sensitivity * -------+--------------------+---------------- * 0 | +/- 250 degrees/s | 131 LSB/deg/s * 1 | +/- 500 degrees/s | 65.5 LSB/deg/s * 2 | +/- 1000 degrees/s | 32.8 LSB/deg/s * 3 | +/- 2000 degrees/s | 16.4 LSB/deg/s * </pre> * * @param x 16-bit signed integer container for X-axis rotation * @param y 16-bit signed integer container for Y-axis rotation * @param z 16-bit signed integer container for Z-axis rotation * @see getMotion6() * @see MPU6050_RA_GYRO_XOUT_H */ void getRotation(int x, int y, int z) { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_XOUT_H, 6, buffer); x = (((int)buffer[0]) << 8) | buffer[1]; y = (((int)buffer[2]) << 8) | buffer[3]; z = (((int)buffer[4]) << 8) | buffer[5]; } /** Get X-axis gyroscope reading. * @return X-axis rotation measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_GYRO_XOUT_H */ int getRotationX() { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_XOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Y-axis gyroscope reading. * @return Y-axis rotation measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_GYRO_YOUT_H */ int getRotationY() { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_YOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Get Z-axis gyroscope reading. * @return Z-axis rotation measurement in 16-bit 2's complement format * @see getMotion6() * @see MPU6050_RA_GYRO_ZOUT_H */ int getRotationZ() { I2CdevReadBytes(deviceAddress, MPU6050_RA_GYRO_ZOUT_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // EXT_SENS_DATA_* registers /** Read single byte from external sensor data register. * These registers store data read from external sensors by the Slave 0, 1, 2, * and 3 on the auxiliary I2C interface. Data read by Slave 4 is stored in * I2C_SLV4_DI (Register 53). * * External sensor data is written to these registers at the Sample Rate as * defined in Register 25. This access rate can be reduced by using the Slave * Delay Enable registers (Register 103). * * External sensor data registers, along with the gyroscope measurement * registers, accelerometer measurement registers, and temperature measurement * registers, are composed of two sets of registers: an internal register set * and a user-facing read register set. * * The data within the external sensors' internal register set is always updated * at the Sample Rate (or the reduced access rate) whenever the serial interface * is idle. This guarantees that a burst read of sensor registers will read * measurements from the same sampling instant. Note that if burst reads are not * used, the user is responsible for ensuring a set of single byte reads * correspond to a single sampling instant by checking the Data Ready interrupt. * * Data is placed in these external sensor data registers according to * I2C_SLV0_CTRL, I2C_SLV1_CTRL, I2C_SLV2_CTRL, and I2C_SLV3_CTRL (Registers 39, * 42, 45, and 48). When more than zero bytes are read (I2C_SLVx_LEN > 0) from * an enabled slave (I2C_SLVx_EN = 1), the slave is read at the Sample Rate (as * defined in Register 25) or delayed rate (if specified in Register 52 and * 103). During each Sample cycle, slave reads are performed in order of Slave * number. If all slaves are enabled with more than zero bytes to be read, the * order will be Slave 0, followed by Slave 1, Slave 2, and Slave 3. * * Each enabled slave will have EXT_SENS_DATA registers associated with it by * number of bytes read (I2C_SLVx_LEN) in order of slave number, starting from * EXT_SENS_DATA_00. Note that this means enabling or disabling a slave may * change the higher numbered slaves' associated registers. Furthermore, if * fewer total bytes are being read from the external sensors as a result of * such a change, then the data remaining in the registers which no longer have * an associated slave device (i.e. high numbered registers) will remain in * these previously allocated registers unless reset. * * If the sum of the read lengths of all SLVx transactions exceed the number of * available EXT_SENS_DATA registers, the excess bytes will be dropped. There * are 24 EXT_SENS_DATA registers and hence the total read lengths between all * the slaves cannot be greater than 24 or some bytes will be lost. * * Note: Slave 4's behavior is distinct from that of Slaves 0-3. For further * information regarding the characteristics of Slave 4, please refer to * Registers 49 to 53. * * EXAMPLE: * Suppose that Slave 0 is enabled with 4 bytes to be read (I2C_SLV0_EN = 1 and * I2C_SLV0_LEN = 4) while Slave 1 is enabled with 2 bytes to be read so that * I2C_SLV1_EN = 1 and I2C_SLV1_LEN = 2. In such a situation, EXT_SENS_DATA _00 * through _03 will be associated with Slave 0, while EXT_SENS_DATA _04 and 05 * will be associated with Slave 1. If Slave 2 is enabled as well, registers * starting from EXT_SENS_DATA_06 will be allocated to Slave 2. * * If Slave 2 is disabled while Slave 3 is enabled in this same situation, then * registers starting from EXT_SENS_DATA_06 will be allocated to Slave 3 * instead. * * REGISTER ALLOCATION FOR DYNAMIC DISABLE VS. NORMAL DISABLE: * If a slave is disabled at any time, the space initially allocated to the * slave in the EXT_SENS_DATA register, will remain associated with that slave. * This is to avoid dynamic adjustment of the register allocation. * * The allocation of the EXT_SENS_DATA registers is recomputed only when (1) all * slaves are disabled, or (2) the I2C_MST_RST bit is set (Register 106). * * This above is also true if one of the slaves gets NACKed and stops * functioning. * * @param position Starting position (0-23) * @return Byte read from register */ int getExternalSensorByte(int position) { I2CdevReadByte(deviceAddress, MPU6050_RA_EXT_SENS_DATA_00 + position, bytebuffer); return bytebuffer; } /** Read word (2 bytes) from external sensor data registers. * @param position Starting position (0-21) * @return Word read from register * @see getExternalSensorByte() */ int getExternalSensorWord(int position) { I2CdevReadBytes(deviceAddress, MPU6050_RA_EXT_SENS_DATA_00 + position, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } /** Read double word (4 bytes) from external sensor data registers. * @param position Starting position (0-20) * @return Double word read from registers * @see getExternalSensorByte() */ int getExternalSensorDWord(int position) { I2CdevReadBytes(deviceAddress, MPU6050_RA_EXT_SENS_DATA_00 + position, 4, buffer); return (((int)buffer[0]) << 24) | (((int)buffer[1]) << 16) | (((int)buffer[2]) << 8) | buffer[3]; } // MOT_DETECT_STATUS register /** Get full motion detection status register content (all bits). * @return Motion detection status byte * @see MPU6050_RA_MOT_DETECT_STATUS */ int getMotionStatus() { I2CdevReadByte(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, bytebuffer); return bytebuffer; } /** Get X-axis negative motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_XNEG_BIT */ boolean getXNegMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_XNEG_BIT, bytebuffer); return bytebuffer != 0; } /** Get X-axis positive motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_XPOS_BIT */ boolean getXPosMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_XPOS_BIT, bytebuffer); return bytebuffer != 0; } /** Get Y-axis negative motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_YNEG_BIT */ boolean getYNegMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_YNEG_BIT, bytebuffer); return bytebuffer != 0; } /** Get Y-axis positive motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_YPOS_BIT */ boolean getYPosMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_YPOS_BIT, bytebuffer); return bytebuffer != 0; } /** Get Z-axis negative motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZNEG_BIT */ boolean getZNegMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZNEG_BIT, bytebuffer); return bytebuffer != 0; } /** Get Z-axis positive motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZPOS_BIT */ boolean getZPosMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZPOS_BIT, bytebuffer); return bytebuffer != 0; } /** Get zero motion detection interrupt status. * @return Motion detection status * @see MPU6050_RA_MOT_DETECT_STATUS * @see MPU6050_MOTION_MOT_ZRMOT_BIT */ boolean getZeroMotionDetected() { I2CdevReadBit(deviceAddress, MPU6050_RA_MOT_DETECT_STATUS, MPU6050_MOTION_MOT_ZRMOT_BIT, bytebuffer); return bytebuffer != 0; } // I2C_SLV*_DO register /** Write byte to Data Output container for specified slave. * This register holds the output data written into Slave when Slave is set to * write mode. For further information regarding Slave control, please * refer to Registers 37 to 39 and immediately following. * @param num Slave number (0-3) * @param data Byte to write * @see MPU6050_RA_I2C_SLV0_DO */ void setSlaveOutputByte(int num, int data) { if (num > 3) return; I2CdevWriteByte(deviceAddress, MPU6050_RA_I2C_SLV0_DO + num, data); } // I2C_MST_DELAY_CTRL register /** Get external data shadow delay enabled status. * This register is used to specify the timing of external sensor data * shadowing. When DELAY_ES_SHADOW is set to 1, shadowing of external * sensor data is delayed until all data has been received. * @return Current external data shadow delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT */ boolean getExternalShadowDelayEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT, bytebuffer); return bytebuffer != 0; } /** Set external data shadow delay enabled status. * @param enabled New external data shadow delay enabled status. * @see getExternalShadowDelayEnabled() * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT */ void setExternalShadowDelayEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, MPU6050_DELAYCTRL_DELAY_ES_SHADOW_BIT, enabled); } /** Get slave delay enabled status. * When a particular slave delay is enabled, the rate of access for the that * slave device is reduced. When a slave's access rate is decreased relative to * the Sample Rate, the slave is accessed every: * * 1 / (1 + I2C_MST_DLY) Samples * * This base Sample Rate in turn is determined by SMPLRT_DIV (register * 25) * and DLPF_CFG (register 26). * * For further information regarding I2C_MST_DLY, please refer to register 52. * For further information regarding the Sample Rate, please refer to register 25. * * @param num Slave number (0-4) * @return Current slave delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT */ boolean getSlaveDelayEnabled(int num) { // MPU6050_DELAYCTRL_I2C_SLV4_DLY_EN_BIT is 4, SLV3 is 3, etc. if (num > 4) return false; I2CdevReadBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, num, bytebuffer); return bytebuffer != 0; } /** Set slave delay enabled status. * @param num Slave number (0-4) * @param enabled New slave delay enabled status. * @see MPU6050_RA_I2C_MST_DELAY_CTRL * @see MPU6050_DELAYCTRL_I2C_SLV0_DLY_EN_BIT */ void setSlaveDelayEnabled(int num, boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_I2C_MST_DELAY_CTRL, num, enabled); } // SIGNAL_PATH_RESET register /** Reset gyroscope signal path. * The reset will revert the signal path analog to digital converters and * filters to their power up configurations. * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_GYRO_RESET_BIT */ void resetGyroscopePath() { I2CdevWriteBit(deviceAddress, MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_GYRO_RESET_BIT, true); } /** Reset accelerometer signal path. * The reset will revert the signal path analog to digital converters and * filters to their power up configurations. * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_ACCEL_RESET_BIT */ void resetAccelerometerPath() { I2CdevWriteBit(deviceAddress, MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_ACCEL_RESET_BIT, true); } /** Reset temperature sensor signal path. * The reset will revert the signal path analog to digital converters and * filters to their power up configurations. * @see MPU6050_RA_SIGNAL_PATH_RESET * @see MPU6050_PATHRESET_TEMP_RESET_BIT */ void resetTemperaturePath() { I2CdevWriteBit(deviceAddress, MPU6050_RA_SIGNAL_PATH_RESET, MPU6050_PATHRESET_TEMP_RESET_BIT, true); } // MOT_DETECT_CTRL register /** Get accelerometer power-on delay. * The accelerometer data path provides samples to the sensor registers, Motion * detection, Zero Motion detection, and Free Fall detection modules. The * signal path contains filters which must be flushed on wake-up with new * samples before the detection modules begin operations. The default wake-up * delay, of 4ms can be lengthened by up to 3ms. This additional delay is * specified in ACCEL_ON_DELAY in units of 1 LSB = 1 ms. The user may select * any value above zero unless instructed otherwise by InvenSense. Please refer * to Section 8 of the MPU-6000/MPU-6050 Product Specification document for * further information regarding the detection modules. * @return Current accelerometer power-on delay * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_ACCEL_ON_DELAY_BIT */ int getAccelerometerPowerOnDelay() { I2CdevReadBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_ACCEL_ON_DELAY_BIT, MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH, bytebuffer); return bytebuffer; } /** Set accelerometer power-on delay. * @param delay New accelerometer power-on delay (0-3) * @see getAccelerometerPowerOnDelay() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_ACCEL_ON_DELAY_BIT */ void setAccelerometerPowerOnDelay(int delay) { I2CdevWriteBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_ACCEL_ON_DELAY_BIT, MPU6050_DETECT_ACCEL_ON_DELAY_LENGTH, delay); } /** Get Free Fall detection counter decrement configuration. * Detection is registered by the Free Fall detection module after accelerometer * measurements meet their respective threshold conditions over a specified * number of samples. When the threshold conditions are met, the corresponding * detection counter increments by 1. The user may control the rate at which the * detection counter decrements when the threshold condition is not met by * configuring FF_COUNT. The decrement rate can be set according to the * following table: * * <pre> * FF_COUNT | Counter Decrement * ---------+------------------ * 0 | Reset * 1 | 1 * 2 | 2 * 3 | 4 * </pre> * * When FF_COUNT is configured to 0 (reset), any non-qualifying sample will * reset the counter to 0. For further information on Free Fall detection, * please refer to Registers 29 to 32. * * @return Current decrement configuration * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_FF_COUNT_BIT */ int getFreefallDetectionCounterDecrement() { I2CdevReadBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_FF_COUNT_BIT, MPU6050_DETECT_FF_COUNT_LENGTH, bytebuffer); return bytebuffer; } /** Set Free Fall detection counter decrement configuration. * @param decrement New decrement configuration value * @see getFreefallDetectionCounterDecrement() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_FF_COUNT_BIT */ void setFreefallDetectionCounterDecrement(int decrement) { I2CdevWriteBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_FF_COUNT_BIT, MPU6050_DETECT_FF_COUNT_LENGTH, decrement); } /** Get Motion detection counter decrement configuration. * Detection is registered by the Motion detection module after accelerometer * measurements meet their respective threshold conditions over a specified * number of samples. When the threshold conditions are met, the corresponding * detection counter increments by 1. The user may control the rate at which the * detection counter decrements when the threshold condition is not met by * configuring MOT_COUNT. The decrement rate can be set according to the * following table: * * <pre> * MOT_COUNT | Counter Decrement * ----------+------------------ * 0 | Reset * 1 | 1 * 2 | 2 * 3 | 4 * </pre> * * When MOT_COUNT is configured to 0 (reset), any non-qualifying sample will * reset the counter to 0. For further information on Motion detection, * please refer to Registers 29 to 32. * */ int getMotionDetectionCounterDecrement() { I2CdevReadBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_MOT_COUNT_BIT, MPU6050_DETECT_MOT_COUNT_LENGTH, bytebuffer); return bytebuffer; } /** Set Motion detection counter decrement configuration. * @param decrement New decrement configuration value * @see getMotionDetectionCounterDecrement() * @see MPU6050_RA_MOT_DETECT_CTRL * @see MPU6050_DETECT_MOT_COUNT_BIT */ void setMotionDetectionCounterDecrement(int decrement) { I2CdevWriteBits(deviceAddress, MPU6050_RA_MOT_DETECT_CTRL, MPU6050_DETECT_MOT_COUNT_BIT, MPU6050_DETECT_MOT_COUNT_LENGTH, decrement); } // USER_CTRL register /** Get FIFO enabled status. * When this bit is set to 0, the FIFO buffer is disabled. The FIFO buffer * cannot be written to or read from while disabled. The FIFO buffer's state * does not change unless the MPU-60X0 is power cycled. * @return Current FIFO enabled status * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_EN_BIT */ boolean getFIFOEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set FIFO enabled status. * @param enabled New FIFO enabled status * @see getFIFOEnabled() * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_EN_BIT */ void setFIFOEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_EN_BIT, enabled); } /** Get I2C Master Mode enabled status. * When this mode is enabled, the MPU-60X0 acts as the I2C Master to the * external sensor slave devices on the auxiliary I2C bus. When this bit is * cleared to 0, the auxiliary I2C bus lines (AUX_DA and AUX_CL) are logically * driven by the primary I2C bus (SDA and SCL). This is a precondition to * enabling Bypass Mode. For further information regarding Bypass Mode, please * refer to Register 55. * @return Current I2C Master Mode enabled status * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_EN_BIT */ boolean getI2CMasterModeEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT, bytebuffer); return bytebuffer != 0; } /** Set I2C Master Mode enabled status. * @param enabled New I2C Master Mode enabled status * @see getI2CMasterModeEnabled() * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_EN_BIT */ void setI2CMasterModeEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_EN_BIT, enabled); } /** Switch from I2C to SPI mode (MPU-6000 only) * If this is set, the primary SPI interface will be enabled in place of the * disabled primary I2C interface. */ void switchSPIEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_IF_DIS_BIT, enabled); } /** Reset the FIFO. * This bit resets the FIFO buffer when set to 1 while FIFO_EN equals 0. This * bit automatically clears to 0 after the reset has been triggered. * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_FIFO_RESET_BIT */ void resetFIFO() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_FIFO_RESET_BIT, true); } /** Reset the I2C Master. * This bit resets the I2C Master when set to 1 while I2C_MST_EN equals 0. * This bit automatically clears to 0 after the reset has been triggered. * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_I2C_MST_RESET_BIT */ void resetI2CMaster() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_I2C_MST_RESET_BIT, true); } /** Reset all sensor registers and signal paths. * When set to 1, this bit resets the signal paths for all sensors (gyroscopes, * accelerometers, and temperature sensor). This operation will also clear the * sensor registers. This bit automatically clears to 0 after the reset has been * triggered. * * When resetting only the signal path (and not the sensor registers), please * use Register 104, SIGNAL_PATH_RESET. * * @see MPU6050_RA_USER_CTRL * @see MPU6050_USERCTRL_SIG_COND_RESET_BIT */ void resetSensors() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_SIG_COND_RESET_BIT, true); } // PWR_MGMT_1 register /** Trigger a full device reset. * A small delay of ~50ms may be desirable after triggering a reset. * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_DEVICE_RESET_BIT */ void reset() { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_DEVICE_RESET_BIT, true); } /** Get sleep mode status. * Setting the SLEEP bit in the register puts the device into very low power * sleep mode. In this mode, only the serial interface and internal registers * remain active, allowing for a very low standby current. Clearing this bit * puts the device back into normal mode. To save power, the individual standby * selections for each of the gyros should be used if any gyro axis is not used * by the application. * @return Current sleep mode enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_SLEEP_BIT */ boolean getSleepEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, bytebuffer); return bytebuffer != 0; } /** Set sleep mode status. * @param enabled New sleep mode enabled status * @see getSleepEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_SLEEP_BIT */ void setSleepEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_SLEEP_BIT, enabled); } /** Get wake cycle enabled status. * When this bit is set to 1 and SLEEP is disabled, the MPU-60X0 will cycle * between sleep mode and waking up to take a single sample of data from active * sensors at a rate determined by LP_WAKE_CTRL (register 108). * @return Current sleep mode enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CYCLE_BIT */ boolean getWakeCycleEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CYCLE_BIT, bytebuffer); return bytebuffer != 0; } /** Set wake cycle enabled status. * @param enabled New sleep mode enabled status * @see getWakeCycleEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CYCLE_BIT */ void setWakeCycleEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CYCLE_BIT, enabled); } /** Get temperature sensor enabled status. * Control the usage of the internal temperature sensor. * * Note: this register stores the *disabled* value, but for consistency with the * rest of the code, the function is named and used with standard true/false * values to indicate whether the sensor is enabled or disabled, respectively. * * @return Current temperature sensor enabled status * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_TEMP_DIS_BIT */ boolean getTempSensorEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_TEMP_DIS_BIT, bytebuffer); return bytebuffer != 0; // 1 is actually disabled here } /** Set temperature sensor enabled status. * Note: this register stores the *disabled* value, but for consistency with the * rest of the code, the function is named and used with standard true/false * values to indicate whether the sensor is enabled or disabled, respectively. * * @param enabled New temperature sensor enabled status * @see getTempSensorEnabled() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_TEMP_DIS_BIT */ void setTempSensorEnabled(boolean enabled) { // 1 is actually disabled here I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_TEMP_DIS_BIT, !enabled); } /** Get clock source setting. * @return Current clock source setting * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CLKSEL_BIT * @see MPU6050_PWR1_CLKSEL_LENGTH */ int getClockSource() { I2CdevReadBits(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, bytebuffer); return bytebuffer; } /** Set clock source setting. * An internal 8MHz oscillator, gyroscope based clock, or external sources can * be selected as the MPU-60X0 clock source. When the internal 8 MHz oscillator * or an external source is chosen as the clock source, the MPU-60X0 can operate * in low power modes with the gyroscopes disabled. * * Upon power up, the MPU-60X0 clock source defaults to the internal oscillator. * However, it is highly recommended that the device be configured to use one of * the gyroscopes (or an external clock source) as the clock reference for * improved stability. The clock source can be selected according to the following table: * * <pre> * CLK_SEL | Clock Source * --------+-------------------------------------- * 0 | Internal oscillator * 1 | PLL with X Gyro reference * 2 | PLL with Y Gyro reference * 3 | PLL with Z Gyro reference * 4 | PLL with external 32.768kHz reference * 5 | PLL with external 19.2MHz reference * 6 | Reserved * 7 | Stops the clock and keeps the timing generator in reset * </pre> * * @param source New clock source setting * @see getClockSource() * @see MPU6050_RA_PWR_MGMT_1 * @see MPU6050_PWR1_CLKSEL_BIT * @see MPU6050_PWR1_CLKSEL_LENGTH */ void setClockSource(int source) { I2CdevWriteBits(deviceAddress, MPU6050_RA_PWR_MGMT_1, MPU6050_PWR1_CLKSEL_BIT, MPU6050_PWR1_CLKSEL_LENGTH, source); } // PWR_MGMT_2 register /** Get wake frequency in Accel-Only Low Power Mode. * The MPU-60X0 can be put into Accerlerometer Only Low Power Mode by setting * PWRSEL to 1 in the Power Management 1 register (Register 107). In this mode, * the device will power off all devices except for the primary I2C interface, * waking only the accelerometer at fixed intervals to take a single * measurement. The frequency of wake-ups can be configured with LP_WAKE_CTRL * as shown below: * * <pre> * LP_WAKE_CTRL | Wake-up Frequency * -------------+------------------ * 0 | 1.25 Hz * 1 | 2.5 Hz * 2 | 5 Hz * 3 | 10 Hz * </pre> * * For further information regarding the MPU-60X0's power modes, please refer to * Register 107. * * @return Current wake frequency * @see MPU6050_RA_PWR_MGMT_2 */ int getWakeFrequency() { I2CdevReadBits(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_LP_WAKE_CTRL_BIT, MPU6050_PWR2_LP_WAKE_CTRL_LENGTH, bytebuffer); return bytebuffer; } /** Set wake frequency in Accel-Only Low Power Mode. * @param frequency New wake frequency * @see MPU6050_RA_PWR_MGMT_2 */ void setWakeFrequency(int frequency) { I2CdevWriteBits(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_LP_WAKE_CTRL_BIT, MPU6050_PWR2_LP_WAKE_CTRL_LENGTH, frequency); } /** Get X-axis accelerometer standby enabled status. * If enabled, the X-axis will not gather or report data (or use power). * @return Current X-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XA_BIT */ boolean getStandbyXAccelEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XA_BIT, bytebuffer); return bytebuffer != 0; } /** Set X-axis accelerometer standby enabled status. * @param New X-axis standby enabled status * @see getStandbyXAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XA_BIT */ void setStandbyXAccelEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XA_BIT, enabled); } /** Get Y-axis accelerometer standby enabled status. * If enabled, the Y-axis will not gather or report data (or use power). * @return Current Y-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YA_BIT */ boolean getStandbyYAccelEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YA_BIT, bytebuffer); return bytebuffer != 0; } /** Set Y-axis accelerometer standby enabled status. * @param New Y-axis standby enabled status * @see getStandbyYAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YA_BIT */ void setStandbyYAccelEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YA_BIT, enabled); } /** Get Z-axis accelerometer standby enabled status. * If enabled, the Z-axis will not gather or report data (or use power). * @return Current Z-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZA_BIT */ boolean getStandbyZAccelEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZA_BIT, bytebuffer); return bytebuffer != 0; } /** Set Z-axis accelerometer standby enabled status. * @param New Z-axis standby enabled status * @see getStandbyZAccelEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZA_BIT */ void setStandbyZAccelEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZA_BIT, enabled); } /** Get X-axis gyroscope standby enabled status. * If enabled, the X-axis will not gather or report data (or use power). * @return Current X-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XG_BIT */ boolean getStandbyXGyroEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XG_BIT, bytebuffer); return bytebuffer != 0; } /** Set X-axis gyroscope standby enabled status. * @param New X-axis standby enabled status * @see getStandbyXGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_XG_BIT */ void setStandbyXGyroEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_XG_BIT, enabled); } /** Get Y-axis gyroscope standby enabled status. * If enabled, the Y-axis will not gather or report data (or use power). * @return Current Y-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YG_BIT */ boolean getStandbyYGyroEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YG_BIT, bytebuffer); return bytebuffer != 0; } /** Set Y-axis gyroscope standby enabled status. * @param New Y-axis standby enabled status * @see getStandbyYGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_YG_BIT */ void setStandbyYGyroEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_YG_BIT, enabled); } /** Get Z-axis gyroscope standby enabled status. * If enabled, the Z-axis will not gather or report data (or use power). * @return Current Z-axis standby enabled status * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZG_BIT */ boolean getStandbyZGyroEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZG_BIT, bytebuffer); return bytebuffer != 0; } /** Set Z-axis gyroscope standby enabled status. * @param New Z-axis standby enabled status * @see getStandbyZGyroEnabled() * @see MPU6050_RA_PWR_MGMT_2 * @see MPU6050_PWR2_STBY_ZG_BIT */ void setStandbyZGyroEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_PWR_MGMT_2, MPU6050_PWR2_STBY_ZG_BIT, enabled); } // FIFO_COUNT* registers /** Get current FIFO buffer size. * This value indicates the number of bytes stored in the FIFO buffer. This * number is in turn the number of bytes that can be read from the FIFO buffer * and it is directly proportional to the number of samples available given the * set of sensor data bound to be stored in the FIFO (register 35 and 36). * @return Current FIFO buffer size */ int getFIFOCount() { I2CdevReadBytes(deviceAddress, MPU6050_RA_FIFO_COUNTH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } // FIFO_R_W register /** Get byte from FIFO buffer. * This register is used to read and write data from the FIFO buffer. Data is * written to the FIFO in order of register number (from lowest to highest). If * all the FIFO enable flags (see below) are enabled and all External Sensor * Data registers (Registers 73 to 96) are associated with a Slave device, the * contents of registers 59 through 96 will be written in order at the Sample * Rate. * * The contents of the sensor data registers (Registers 59 to 96) are written * into the FIFO buffer when their corresponding FIFO enable flags are set to 1 * in FIFO_EN (Register 35). An additional flag for the sensor data registers * associated with I2C Slave 3 can be found in I2C_MST_CTRL (Register 36). * * If the FIFO buffer has overflowed, the status bit FIFO_OFLOW_INT is * automatically set to 1. This bit is located in INT_STATUS (Register 58). * When the FIFO buffer has overflowed, the oldest data will be lost and new * data will be written to the FIFO. * * If the FIFO buffer is empty, reading this register will return the last byte * that was previously read from the FIFO until new data is available. The user * should check FIFO_COUNT to ensure that the FIFO buffer is not read when * empty. * * @return Byte from FIFO buffer */ int getFIFOByte() { I2CdevReadByte(deviceAddress, MPU6050_RA_FIFO_R_W, bytebuffer); return bytebuffer; } void getFIFOBytes(int[] data, int length) { if(length > 0){ I2CdevReadBytes(deviceAddress, MPU6050_RA_FIFO_R_W, length, data); } else { data = new int[0]; } } /** Write byte to FIFO buffer. * @see getFIFOByte() * @see MPU6050_RA_FIFO_R_W */ void setFIFOByte(int data) { I2CdevWriteByte(deviceAddress, MPU6050_RA_FIFO_R_W, data); } // WHO_AM_I register /** Get Device ID. * This register is used to verify the identity of the device (0b110100, 0x34). * @return Device ID (6 bits only! should be 0x34) * @see MPU6050_RA_WHO_AM_I * @see MPU6050_WHO_AM_I_BIT * @see MPU6050_WHO_AM_I_LENGTH */ int getDeviceID() { I2CdevReadBits(deviceAddress, MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, bytebuffer); return bytebuffer; } /** Set Device ID. * Write a new ID into the WHO_AM_I register (no idea why this should ever be * necessary though). * @param id New device ID to set. * @see getDeviceID() * @see MPU6050_RA_WHO_AM_I * @see MPU6050_WHO_AM_I_BIT * @see MPU6050_WHO_AM_I_LENGTH */ void setDeviceID(int id) { I2CdevWriteBits(deviceAddress, MPU6050_RA_WHO_AM_I, MPU6050_WHO_AM_I_BIT, MPU6050_WHO_AM_I_LENGTH, id); } // ======== UNDOCUMENTED/DMP REGISTERS/METHODS ======== // XG_OFFS_TC register int getOTPBankValid() { I2CdevReadBit(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OTP_BNK_VLD_BIT, bytebuffer); return bytebuffer; } void setOTPBankValid(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OTP_BNK_VLD_BIT, enabled); } int getXGyroOffsetTC() { I2CdevReadBits(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, bytebuffer); return bytebuffer; } void setXGyroOffsetTC(int offset) { I2CdevWriteBits(deviceAddress, MPU6050_RA_XG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // YG_OFFS_TC register int getYGyroOffsetTC() { I2CdevReadBits(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, bytebuffer); return bytebuffer; } void setYGyroOffsetTC(int offset) { I2CdevWriteBits(deviceAddress, MPU6050_RA_YG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // ZG_OFFS_TC register int getZGyroOffsetTC() { I2CdevReadBits(deviceAddress, MPU6050_RA_ZG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, bytebuffer); return bytebuffer; } void setZGyroOffsetTC(int offset) { I2CdevWriteBits(deviceAddress, MPU6050_RA_ZG_OFFS_TC, MPU6050_TC_OFFSET_BIT, MPU6050_TC_OFFSET_LENGTH, offset); } // X_FINE_GAIN register int getXFineGain() { I2CdevReadByte(deviceAddress, MPU6050_RA_X_FINE_GAIN, bytebuffer); return bytebuffer; } void setXFineGain(int gain) { I2CdevWriteByte(deviceAddress, MPU6050_RA_X_FINE_GAIN, gain); } // Y_FINE_GAIN register int getYFineGain() { I2CdevReadByte(deviceAddress, MPU6050_RA_Y_FINE_GAIN, bytebuffer); return bytebuffer; } void setYFineGain(int gain) { I2CdevWriteByte(deviceAddress, MPU6050_RA_Y_FINE_GAIN, gain); } // Z_FINE_GAIN register int getZFineGain() { I2CdevReadByte(deviceAddress, MPU6050_RA_Z_FINE_GAIN, bytebuffer); return bytebuffer; } void setZFineGain(int gain) { I2CdevWriteByte(deviceAddress, MPU6050_RA_Z_FINE_GAIN, gain); } // XA_OFFS_* registers int getXAccelOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_XA_OFFS_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setXAccelOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_XA_OFFS_H, offset); } // YA_OFFS_* register int getYAccelOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_YA_OFFS_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setYAccelOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_YA_OFFS_H, offset); } // ZA_OFFS_* register int getZAccelOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ZA_OFFS_H, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setZAccelOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_ZA_OFFS_H, offset); } // XG_OFFS_USR* registers int getXGyroOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_XG_OFFS_USRH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setXGyroOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_XG_OFFS_USRH, offset); } // YG_OFFS_USR* register int getYGyroOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_YG_OFFS_USRH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setYGyroOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_YG_OFFS_USRH, offset); } // ZG_OFFS_USR* register int getZGyroOffset() { I2CdevReadBytes(deviceAddress, MPU6050_RA_ZG_OFFS_USRH, 2, buffer); return (((int)buffer[0]) << 8) | buffer[1]; } void setZGyroOffset(int offset) { I2CdevWriteWord(deviceAddress, MPU6050_RA_ZG_OFFS_USRH, offset); } // INT_ENABLE register (DMP functions) boolean getIntPLLReadyEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, bytebuffer); return bytebuffer != 0; } void setIntPLLReadyEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, enabled); } boolean getIntDMPEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DMP_INT_BIT, bytebuffer); return bytebuffer != 0; } void setIntDMPEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_INT_ENABLE, MPU6050_INTERRUPT_DMP_INT_BIT, enabled); } // DMP_INT_STATUS boolean getDMPInt5Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_5_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt4Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_4_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt3Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_3_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt2Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_2_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt1Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_1_BIT, bytebuffer); return bytebuffer != 0; } boolean getDMPInt0Status() { I2CdevReadBit(deviceAddress, MPU6050_RA_DMP_INT_STATUS, MPU6050_DMPINT_0_BIT, bytebuffer); return bytebuffer != 0; } // INT_STATUS register (DMP functions) boolean getIntPLLReadyStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_PLL_RDY_INT_BIT, bytebuffer); return bytebuffer != 0; } boolean getIntDMPStatus() { I2CdevReadBit(deviceAddress, MPU6050_RA_INT_STATUS, MPU6050_INTERRUPT_DMP_INT_BIT, bytebuffer); return bytebuffer != 0; } // USER_CTRL register (DMP functions) boolean getDMPEnabled() { I2CdevReadBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_EN_BIT, bytebuffer); return bytebuffer != 0; } void setDMPEnabled(boolean enabled) { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_EN_BIT, enabled); } void resetDMP() { I2CdevWriteBit(deviceAddress, MPU6050_RA_USER_CTRL, MPU6050_USERCTRL_DMP_RESET_BIT, true); } // BANK_SEL register void setMemoryBank(int bank, boolean prefetchEnabled, boolean userBank) { bank = bank & 0x1F; if (userBank) bank |= 0x20; if (prefetchEnabled) bank |= 0x40; I2CdevWriteByte(deviceAddress, MPU6050_RA_BANK_SEL, bank); } void setMemoryBank(int bank) { setMemoryBank(bank, false, false); } // MEM_START_ADDR register void setMemoryStartAddress(int address) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MEM_START_ADDR, address); } // MEM_R_W register int readMemoryByte() { I2CdevReadByte(deviceAddress, MPU6050_RA_MEM_R_W, bytebuffer); return bytebuffer; } void writeMemoryByte(int data) { I2CdevWriteByte(deviceAddress, MPU6050_RA_MEM_R_W, data); } void readMemoryBlock(int[] data, int dataSize, int bank, int address) { setMemoryBank(bank); setMemoryStartAddress(address); int chunkSize; for (int i = 0; i < dataSize;) { // determine correct chunk size according to bank position and data size chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; // make sure we don't go past the data size if (i + chunkSize > dataSize) chunkSize = dataSize - i; // make sure this chunk doesn't go past the bank boundary (256 bytes) if (chunkSize > 256 - address) chunkSize = 256 - address; // read the chunk of data as specified I2CdevReadBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, data); // increase byte index by [chunkSize] i += chunkSize; // int automatically wraps to 0 at 256 address += chunkSize; // if we aren't done, update bank (if necessary) and address if (i < dataSize) { if (address == 0) bank++; setMemoryBank(bank); setMemoryStartAddress(address); } } } boolean writeMemoryBlock(int[] data, int dataSize, int bank, int address, boolean verify) { setMemoryBank(bank); setMemoryStartAddress(address); int chunkSize; int[] verifyBuffer; int[] progBuffer; int i; int j; if (verify){ verifyBuffer = new int[MPU6050_DMP_MEMORY_CHUNK_SIZE]; } else { verifyBuffer = new int[0]; } for (i = 0; i < dataSize;) { // determine correct chunk size according to bank position and data size chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; // make sure we don't go past the data size if (i + chunkSize > dataSize) chunkSize = dataSize - i; // make sure this chunk doesn't go past the bank boundary (256 bytes) if (chunkSize > 256 - address) chunkSize = 256 - address; // write the chunk of data as specified // progBuffer = (int *)data + i; progBuffer = new int[chunkSize]; for (j=0; j< chunkSize; j++){ progBuffer[j] = data[i+j]; } log.info(String.format("writeMemoryBlock: Block start: %s, ChunkSize %s", chunkSize, i)); I2CdevWriteBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, progBuffer); // verify data if needed if (verify && (verifyBuffer.length > 0)) { setMemoryBank(bank); setMemoryStartAddress(address); I2CdevReadBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, verifyBuffer); if (memcmp(progBuffer, verifyBuffer, chunkSize) != 0) { /*Serial.print("Block write verification error, bank "); Serial.print(bank, DEC); Serial.print(", address "); Serial.print(address, DEC); Serial.print("!\nExpected:"); for (j = 0; j < chunkSize; j++) { Serial.print(" 0x"); if (progBuffer[j] < 16) Serial.print("0"); Serial.print(progBuffer[j], HEX); } Serial.print("\nReceived:"); for (int j = 0; j < chunkSize; j++) { Serial.print(" 0x"); if (verifyBuffer[i + j] < 16) Serial.print("0"); Serial.print(verifyBuffer[i + j], HEX); } Serial.print("\n");*/ //* free(verifyBuffer); return false; // uh oh. } } // increase byte index by [chunkSize] i += chunkSize; // int automatically wraps to 0 at 256 address += chunkSize; // if we aren't done, update bank (if necessary) and address if (i < dataSize) { if (address == 0) bank++; setMemoryBank(bank); setMemoryStartAddress(address); } } //* if (verify) free(verifyBuffer); return true; } boolean writeProgMemoryBlock(int[] data, int dataSize, int bank, int address, boolean verify) { return writeMemoryBlock(data, dataSize, bank, address, verify); } boolean writeProgMemoryBlock(int[] data, int dataSize) { return writeMemoryBlock(data, dataSize, 0, 0, true); } boolean writeDMPConfigurationSet(int[] data, int dataSize) { int[] progBuffer; int special; boolean success = false; int i; // config set data is a long string of blocks with the following structure: // [bank] [offset] [length] [byte[0], byte[1], ..., byte[length]] int bank, offset, length; for (i = 0; i < dataSize;) { bank = data[i++]; offset = data[i++]; length = data[i++]; // write data or perform special action if (length > 0) { // regular block of data to write /*Serial.print("Writing config block to bank "); Serial.print(bank); Serial.print(", offset "); Serial.print(offset); Serial.print(", length="); Serial.println(length);*/ //progBuffer = (int *)data + i; progBuffer = new int[length]; for (int k=0; k<length;k++){ progBuffer[k] = data[i+k]; } success = writeMemoryBlock(progBuffer, length, bank, offset, true); i += length; } else { // special instruction // NOTE: this kind of behavior (what and when to do certain things) // is totally undocumented. This code is in here based on observed // behavior only, and exactly why (or even whether) it has to be here // is anybody's guess for now. special = data[i++]; /*Serial.print("Special command code "); Serial.print(special, HEX); Serial.println(" found...");*/ if (special == 0x01) { // enable DMP-related interrupts //setIntZeroMotionEnabled(true); //setIntFIFOBufferOverflowEnabled(true); //setIntDMPEnabled(true); I2CdevWriteByte(deviceAddress, MPU6050_RA_INT_ENABLE, 0x32); // single operation success = true; } else { // unknown special command success = false; } } if (!success) { return false; // uh oh } } return true; } boolean writeProgDMPConfigurationSet(int[] data, int dataSize) { return writeDMPConfigurationSet(data, dataSize); } // DMP_CFG_1 register int getDMPConfig1() { I2CdevReadByte(deviceAddress, MPU6050_RA_DMP_CFG_1, bytebuffer); return bytebuffer; } void setDMPConfig1(int config) { I2CdevWriteByte(deviceAddress, MPU6050_RA_DMP_CFG_1, config); } // DMP_CFG_2 register int getDMPConfig2() { I2CdevReadByte(deviceAddress, MPU6050_RA_DMP_CFG_2, bytebuffer); return bytebuffer; } void setDMPConfig2(int config) { I2CdevWriteByte(deviceAddress, MPU6050_RA_DMP_CFG_2, config); } //* Compare the content of two buffers // Returns 0 if the two buffers have the same content otherwise 1 int memcmp(int[] buffer1, int[] buffer2, int length ){ int result = 0; for (int i=0 ; i < length ; i++){ if (buffer1[i] != buffer2[i]){ result = 1; } } return result; } int pgm_read_byte(int a){ return 0; } /* Start of I2CDEV section. Most of this code could be moved to and implemented in * the I2CControl interface. */ /** Read a single bit from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitNum Bit position to read (0-7) * @param data Container for single bit value * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadBit(int devAddr, int regAddr, int bitNum, int data, int timeout) { int bitmask = 1; int bytebuffer = data; int count = I2CdevReadByte(devAddr, regAddr, bytebuffer, timeout); data = bytebuffer & (bitmask << bitNum); return count; } int I2CdevReadBit(int devAddr, int regAddr, int bitNum, int data) { return I2CdevReadBit(devAddr, regAddr, bitNum, data, timeout); } /** Read a single bit from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitNum Bit position to read (0-15) * @param data Container for single bit value * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadBitW(int devAddr, int regAddr, int bitNum, int data, int timeout) { int b = 0; int bitmask = 1; int count = I2CdevReadWord(devAddr, regAddr, b, timeout); data = b & (bitmask << bitNum); return count; } /** Read multiple bits from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitStart First bit position to read (0-7) * @param length Number of bits to read (not more than 8) * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05) * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadBits(int devAddr, int regAddr, int bitStart, int length, int data, int timeout) { // 01101001 read byte // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 010 masked // -> 010 shifted int count, b = 0; if ((count = I2CdevReadByte(devAddr, regAddr, b, timeout)) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); b &= mask; b >>= (bitStart - length + 1); data = b; } return count; } int I2CdevReadBits(int devAddr, int regAddr, int bitStart, int length, int data) { return I2CdevReadBits(devAddr, regAddr, bitStart, length, data, timeout); } /** Read multiple bits from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param bitStart First bit position to read (0-15) * @param length Number of bits to read (not more than 16) * @param data Container for right-aligned value (i.e. '101' read from any bitStart position will equal 0x05) * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (1 = success, 0 = failure, -1 = timeout) */ int I2CdevReadBitsW(int devAddr, int regAddr, int bitStart, int length, int data, int timeout) { // 1101011001101001 read byte // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 010 masked // -> 010 shifted int count; int w = 0; if ((count = I2CdevReadWord(devAddr, regAddr, w, timeout)) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); w &= mask; w >>= (bitStart - length + 1); data = w; } return count; } /** Read single byte from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param data Container for byte value read from device * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadByte(int devAddr, int regAddr, int data, int timeout) { int bytebuffer[] = {data}; int status = I2CdevReadBytes(devAddr, regAddr, 1, bytebuffer, timeout); data = bytebuffer[0]; return status; } /** Read single word from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to read from * @param data Container for word value read from device * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Status of read operation (true = success) */ int I2CdevReadWord(int devAddr, int regAddr, int data, int timeout) { int[] readbuffer = {data}; int status = I2CdevReadWords(devAddr, regAddr, 1, readbuffer, timeout); data = readbuffer[0]; return status; } int I2CdevReadWord(int devAddr, int regAddr, int data) { return I2CdevReadWord(devAddr, regAddr, data, timeout); } /** Read multiple words from a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr First register regAddr to read from * @param length Number of words to read * @param data Buffer to store read data in * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Number of words read (-1 indicates failure) */ int I2CdevReadWords(int devAddr, int regAddr, int length, int[] data, int timeout) { byte bytebuffer[] = new byte[length *2]; controller.i2cRead(busAddress, devAddr, bytebuffer, bytebuffer.length); for (int i=0; i < bytebuffer.length ; i++){ data[i] = bytebuffer[i*2] <<8 + bytebuffer[i*2+1] & 0xff; } return length; } int I2CdevReadByte(int devAddr, int regAddr, int data) { int bytebuffer [] = {data}; return I2CdevReadBytes(devAddr, regAddr, 1, bytebuffer, timeout); } /** Read multiple bytes from an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr First register regAddr to read from * @param length Number of bytes to read * @param data Buffer to store read data in * @param timeout Optional read timeout in milliseconds (0 to disable, leave off to use default class value in I2Cdev::readTimeout) * @return Number of bytes read (-1 indicates failure) */ // TODO Return the correct length int I2CdevReadBytes(int devAddr, int regAddr, int length, int[] data, int timeout) { byte[] writebuffer = new byte[] {(byte)regAddr}; byte[] readbuffer = new byte[length]; controller.i2cWrite(busAddress, deviceAddress, writebuffer, writebuffer.length); controller.i2cRead(busAddress, deviceAddress, readbuffer, length); for (int i=0; i < length ; i++){ data[i] = readbuffer[i] & 0xff; } return length; } int I2CdevReadBytes(int devAddr, int regAddr, int length, int[] data) { return I2CdevReadBytes(devAddr, regAddr, length, data, timeout); } /** Write multiple bits in an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitStart First bit position to write (0-7) * @param length Number of bits to write (not more than 8) * @param data Right-aligned value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBits(int devAddr, int regAddr, int bitStart, int length, int data) { // 010 value to write // 76543210 bit numbers // xxx args: bitStart=4, length=3 // 00011100 mask byte // 10101111 original value (sample) // 10100011 original & ~mask // 10101011 masked | value int b = 0; if (I2CdevReadByte(devAddr, regAddr, b) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data b &= ~(mask); // zero all important bits in existing byte b |= data; // combine data with existing byte return I2CdevWriteByte(devAddr, regAddr, b); } else { return false; } } /** Write multiple bits in a 16-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitStart First bit position to write (0-15) * @param length Number of bits to write (not more than 16) * @param data Right-aligned value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBitsW(int devAddr, int regAddr, int bitStart, int length, int data) { // 010 value to write // fedcba9876543210 bit numbers // xxx args: bitStart=12, length=3 // 0001110000000000 mask word // 1010111110010110 original value (sample) // 1010001110010110 original & ~mask // 1010101110010110 masked | value int w = 0; if (I2CdevReadWord(devAddr, regAddr, w) != 0) { int mask = ((1 << length) - 1) << (bitStart - length + 1); data <<= (bitStart - length + 1); // shift data into correct position data &= mask; // zero all non-important bits in data w &= ~(mask); // zero all important bits in existing word w |= data; // combine data with existing word return I2CdevWriteWord(devAddr, regAddr, w); } else { return false; } } /** write a single bit in an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr Register regAddr to write to * @param bitNum Bit position to write (0-7) * @param value New bit value to write * @return Status of operation (true = success) */ boolean I2CdevWriteBit(int devAddr, int regAddr, int bitNum, boolean data) { int b = 0; int newbyte = 0; int bitmask = 1; I2CdevReadByte(devAddr, regAddr, b); // Set the specified bit to 1 if (data){ newbyte = b | (bitmask << bitNum); } // Set the specified bit to 0 else { newbyte = (b & ~(bitmask << bitNum)); } return I2CdevWriteByte(devAddr, regAddr, newbyte); } boolean I2CdevWriteByte(int devAddr, int regAddr, int data) { int[] writebuffer = {data}; return I2CdevWriteBytes(devAddr, regAddr, 1, writebuffer); } boolean I2CdevWriteWord(int devAddr, int regAddr, int data) { int[] writebuffer = {data}; return I2CdevWriteWords(devAddr, regAddr, 1, writebuffer); } /** Write multiple bytes to an 8-bit device register. * @param devAddr I2C slave device address * @param regAddr First register address to write to * @param length Number of bytes to write * @param data Buffer to copy new data from * @return Status of operation (true = success) */ boolean I2CdevWriteBytes(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[length +1]; writebuffer[0] = (byte)(regAddr & 0xff); for (int i=0 ; i<length ; i++){ writebuffer[i+1] = (byte) (data[i] & 0xff); } controller.i2cWrite(busAddress, devAddr, writebuffer, writebuffer.length); return true; } // TODO finish development boolean I2CdevWriteWords(int devAddr, int regAddr, int length, int[] data) { byte[] writebuffer = new byte[length*2 +1]; writebuffer[0] = (byte)(regAddr & 0xff); for (int i=0 ; i<length ; i++){ writebuffer[i*2+1] = (byte) (data[i] <<8); // MSByte writebuffer[i*2+2] = (byte) (data[i] & 0xff); // LSByte } controller.i2cWrite(busAddress, devAddr, writebuffer, writebuffer.length); return true; } /* * End of I2CDEV section. */ /** * This static method returns all the details of the class without it having * to be constructed. It has description, categories, dependencies, and peer * definitions. * * @return ServiceType - returns all the data * */ static public ServiceType getMetaData() { ServiceType meta = new ServiceType(Mpu6050.class.getCanonicalName()); meta.addDescription("General MPU-6050 acclerometer and gyro"); meta.addCategory("microcontroller", "sensor"); return meta; } }
Corrected infinite loop problem.
src/org/myrobotlab/service/Mpu6050.java
Corrected infinite loop problem.
<ide><path>rc/org/myrobotlab/service/Mpu6050.java <ide> chunkSize = MPU6050_DMP_MEMORY_CHUNK_SIZE; <ide> <ide> // make sure we don't go past the data size <del> if (i + chunkSize > dataSize) chunkSize = dataSize - i; <add> if (i + chunkSize > dataSize) <add> {chunkSize = dataSize - i; <add> } <ide> <ide> // make sure this chunk doesn't go past the bank boundary (256 bytes) <del> if (chunkSize > 256 - address) chunkSize = 256 - address; <add> if (chunkSize > 256 - address){ <add> chunkSize = 256 - address; <add> } <ide> <ide> // write the chunk of data as specified <ide> // progBuffer = (int *)data + i; <ide> progBuffer[j] = data[i+j]; <ide> } <ide> <del> log.info(String.format("writeMemoryBlock: Block start: %s, ChunkSize %s", chunkSize, i)); <add> log.info(String.format("writeMemoryBlock: Block start: %s, ChunkSize %s", i, chunkSize)); <ide> I2CdevWriteBytes(deviceAddress, MPU6050_RA_MEM_R_W, chunkSize, progBuffer); <ide> <ide> // verify data if needed <ide> i += chunkSize; <ide> <ide> // int automatically wraps to 0 at 256 <del> address += chunkSize; <add> address += chunkSize & 0xff; <ide> <ide> // if we aren't done, update bank (if necessary) and address <ide> if (i < dataSize) {
Java
epl-1.0
a3310118044c5b8f4cd05d02ac5b09d5f81413ff
0
ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio
/* * Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.archive.common.service.mysqlimpl.persistengine; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.List; import java.util.Queue; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.csstudio.archive.common.service.ArchiveConnectionException; import org.csstudio.archive.common.service.mysqlimpl.batch.BatchQueueHandlerSupport; import org.csstudio.archive.common.service.mysqlimpl.batch.IBatchQueueHandlerProvider; import org.csstudio.archive.common.service.mysqlimpl.dao.ArchiveConnectionHandler; import org.csstudio.archive.common.service.mysqlimpl.dao.ArchiveDaoException; import org.csstudio.archive.common.service.mysqlimpl.notification.ArchiveNotifications; import org.csstudio.domain.desy.task.AbstractTimeMeasuredRunnable; import org.csstudio.domain.desy.time.StopWatch; import org.csstudio.domain.desy.time.StopWatch.RunningStopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * Persistence layer worker for batched statements. * Intended to be scheduled periodically and if necessary on demand * (when the queue is getting big or the contained statements reach the max allowed packet size). * * Gets a connection and does not close it! As this worker is expected to use it very very often. * * @author bknerr * @since 08.02.2011 */ public class PersistDataWorker extends AbstractTimeMeasuredRunnable { private static final Logger RESCUE_LOG = LoggerFactory.getLogger("StatementRescueLogger"); private static final Logger LOG = LoggerFactory.getLogger(PersistDataWorker.class); /** * See configuration of this logger - if log4j is used - see log4j.properties */ private static final Logger EMAIL_LOG = LoggerFactory.getLogger("ErrorPerEmailLogger"); private final ArchiveConnectionHandler _connectionHandler; private final String _name; private final long _periodInMS; private final IBatchQueueHandlerProvider _handlerProvider; private final List<Object> _rescueDataList = Lists.newLinkedList(); /** * Constructor. */ public PersistDataWorker(@Nonnull final ArchiveConnectionHandler connectionHandler, @Nonnull final String name, @Nonnull final long periodInMS, @Nonnull final IBatchQueueHandlerProvider provider) { _connectionHandler = connectionHandler; _name = name; _periodInMS = periodInMS; _handlerProvider = provider; } /** * {@inheritDoc} */ @Override public void measuredRun() { try { final Connection connection = _connectionHandler.getThreadLocalConnection(); processBatchHandlerMap(connection, _handlerProvider, _rescueDataList); } catch (final ArchiveConnectionException e) { LOG.error("Connection to archive failed", e); // FIXME (bknerr) : strategy for queues getting full, when to rescue data? How to check for failover? } catch (final Throwable t) { LOG.error("Unknown throwable in thread {}.", _name); t.printStackTrace(); EMAIL_LOG.info("Unknown throwable in thread {}. See event.log for more info.", _name); } } @SuppressWarnings("unchecked") private <T> void processBatchHandlerMap(@Nonnull final Connection connection, @Nonnull final IBatchQueueHandlerProvider handlerProvider, @Nonnull final List<T> rescueDataList) { for (final BatchQueueHandlerSupport<?> handler : handlerProvider.getHandlers()) { PreparedStatement stmt = null; try { if (!handler.getQueue().isEmpty()) { LOG.debug("Start for {} in {}", handler.getHandlerType().getSimpleName(), _name); stmt = handler.createNewStatement(connection); processBatchForStatement((BatchQueueHandlerSupport<T>) handler, stmt, rescueDataList); LOG.debug("End for {}", handler.getHandlerType().getSimpleName()); } } catch (final SQLException e) { LOG.error("Creation of batch statement failed for strategy " + handler.getClass().getSimpleName(), e); // FIXME (bknerr) : strategy for queues getting full, when to rescue data? } finally { closeStatement(stmt); } } } private <T> void processBatchForStatement(@Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final PreparedStatement stmt, @Nonnull final List<T> rescueDataList) { final Queue<T> queue = handler.getQueue(); T element; try { while (true) { element = queue.poll(); if (element != null) { addElementToBatchAndRescueList(handler, stmt, element, rescueDataList); executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1000); } else { executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1); break; } } } catch (final Throwable t) { handleThrowable(t, handler, rescueDataList); } } private <T> void addElementToBatchAndRescueList(@Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final PreparedStatement stmt, @Nonnull final T element, @Nonnull final List<T> rescueDataList) throws ArchiveDaoException { rescueDataList.add(element); handler.applyBatch(stmt, element); } @Nonnull private <T> boolean executeBatchAndClearListOnCondition(@Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final PreparedStatement stmt, @Nonnull final List<T> rescueDataList, final int minBatchSize) throws SQLException { final int size = rescueDataList.size(); if (size >= minBatchSize) { LOG.info("{} for {}", new Object[]{size, handler.getHandlerType().getSimpleName()}); try { final RunningStopWatch start = StopWatch.start(); stmt.executeBatch(); LOG.info("took for {}: {}ms", size, start.getElapsedTimeInMillis()); } finally { rescueDataList.clear(); } return true; } return false; } private <T> void handleThrowable(@Nonnull final Throwable t, @Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final List<T> rescueDataList) { final Collection<String> statements = handler.convertToStatementString(rescueDataList); try { throw t; } catch (final ArchiveConnectionException se) { LOG.error("Archive Connection failed. No batch update. Drain unpersisted statements to file system.", se); rescueDataToFileSystem(statements); } catch (final BatchUpdateException be) { LOG.error("Batched update failed. Drain unpersisted statements to file system.", be); processFailedBatch(statements, be); } catch (final SQLException se) { LOG.error("Batched update failed. Batched statement could not be composed.", se); rescueDataToFileSystem(statements); } catch (final Throwable tt) { LOG.error("Unknown throwable. Thread " + _name + " is terminated", tt); rescueDataToFileSystem(statements); } finally { rescueDataList.clear(); } } private <T> void processFailedBatch(@Nonnull final Collection<String> batchedStatements, @Nonnull final BatchUpdateException be) { // NOT all statements have been successfully executed! (Depends on RDBM) final int[] updateCounts = be.getUpdateCounts(); if (updateCounts.length == batchedStatements.size()) { // All statements have been tried to be executed, look for the failed ones final List<String> failedStmts = findFailedStatements(updateCounts, batchedStatements); rescueDataToFileSystem(failedStmts); } else { // Not all statements have been tried to be executed - safe only the failed ones rescueDataToFileSystem(Iterables.skip(batchedStatements, updateCounts.length)); } } private static void closeStatement(@CheckForNull final Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (final SQLException e) { LOG.warn("Closing of statement failed: " + stmt); } } } @Nonnull private static List<String> findFailedStatements(@Nonnull final int[] updateCounts, @Nonnull final Collection<String> allStmts) { final List<String> failedStmts = Lists.newLinkedList(); int i = 0; for (final String stmt : allStmts) { if (i < updateCounts.length && updateCounts[i] == Statement.EXECUTE_FAILED) { failedStmts.add(stmt); } i++; } return failedStmts; } @Nonnull public String getName() { return _name; } public long getPeriodInMS() { return _periodInMS; } void rescueDataToFileSystem(@Nonnull final Iterable<String> statements) { final int noOfRescuedStmts = Iterables.size(statements); LOG.warn("Rescue statements: " + noOfRescuedStmts); int no = 0; for (final String stmt : statements) { RESCUE_LOG.info(stmt); no++; } ArchiveNotifications.notify(NotificationType.PERSIST_DATA_FAILED, "#Rescued: " + no); } }
applications/plugins/org.csstudio.archive.common.service.mysqlimpl/src/java/org/csstudio/archive/common/service/mysqlimpl/persistengine/PersistDataWorker.java
/* * Copyright (c) 2010 Stiftung Deutsches Elektronen-Synchrotron, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.archive.common.service.mysqlimpl.persistengine; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.Statement; import java.util.Collection; import java.util.List; import java.util.Queue; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import org.csstudio.archive.common.service.ArchiveConnectionException; import org.csstudio.archive.common.service.mysqlimpl.batch.BatchQueueHandlerSupport; import org.csstudio.archive.common.service.mysqlimpl.batch.IBatchQueueHandlerProvider; import org.csstudio.archive.common.service.mysqlimpl.dao.ArchiveConnectionHandler; import org.csstudio.archive.common.service.mysqlimpl.dao.ArchiveDaoException; import org.csstudio.archive.common.service.mysqlimpl.notification.ArchiveNotifications; import org.csstudio.domain.desy.task.AbstractTimeMeasuredRunnable; import org.csstudio.domain.desy.time.StopWatch; import org.csstudio.domain.desy.time.StopWatch.RunningStopWatch; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; /** * Persistence layer worker for batched statements. * Intended to be scheduled periodically and if necessary on demand * (when the queue is getting big or the contained statements reach the max allowed packet size). * * Gets a connection and does not close it! As this worker is expected to use it very very often. * * @author bknerr * @since 08.02.2011 */ public class PersistDataWorker extends AbstractTimeMeasuredRunnable { private static final Logger RESCUE_LOG = LoggerFactory.getLogger("StatementRescueLogger"); private static final Logger LOG = LoggerFactory.getLogger(PersistDataWorker.class); /** * See configuration of this logger - if log4j is used - see log4j.properties */ private static final Logger EMAIL_LOG = LoggerFactory.getLogger("ErrorPerEmailLogger"); private final ArchiveConnectionHandler _connectionHandler; private final String _name; private final long _periodInMS; private final IBatchQueueHandlerProvider _handlerProvider; private final List<Object> _rescueDataList = Lists.newLinkedList(); /** * Constructor. */ public PersistDataWorker(@Nonnull final ArchiveConnectionHandler connectionHandler, @Nonnull final String name, @Nonnull final long periodInMS, @Nonnull final IBatchQueueHandlerProvider provider) { _connectionHandler = connectionHandler; _name = name; _periodInMS = periodInMS; _handlerProvider = provider; } /** * {@inheritDoc} */ @Override public void measuredRun() { try { final Connection connection = _connectionHandler.getThreadLocalConnection(); processBatchHandlerMap(connection, _handlerProvider, _rescueDataList); } catch (final ArchiveConnectionException e) { LOG.error("Connection to archive failed", e); // FIXME (bknerr) : strategy for queues getting full, when to rescue data? How to check for failover? } catch (final Throwable t) { LOG.error("Unknown throwable in thread {}.", _name); t.printStackTrace(); EMAIL_LOG.info("Unknown throwable in thread {}. See event.log for more info.", _name); } } @SuppressWarnings("unchecked") private <T> void processBatchHandlerMap(@Nonnull final Connection connection, @Nonnull final IBatchQueueHandlerProvider handlerProvider, @Nonnull final List<T> rescueDataList) { for (final BatchQueueHandlerSupport<?> handler : handlerProvider.getHandlers()) { PreparedStatement stmt = null; try { if (!handler.getQueue().isEmpty()) { LOG.debug("Start for {} in {}", handler.getHandlerType().getSimpleName(), _name); stmt = handler.createNewStatement(connection); processBatchForStatement((BatchQueueHandlerSupport<T>) handler, stmt, rescueDataList); LOG.debug("End for {}", handler.getHandlerType().getSimpleName()); } } catch (final SQLException e) { LOG.error("Creation of batch statement failed for strategy " + handler.getClass().getSimpleName(), e); // FIXME (bknerr) : strategy for queues getting full, when to rescue data? } finally { closeStatement(stmt); } } } private <T> void processBatchForStatement(@Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final PreparedStatement stmt, @Nonnull final List<T> rescueDataList) { final Queue<T> queue = handler.getQueue(); T element; while (true) { element = queue.poll(); if (element != null) { addElementToBatchAndRescueList(handler, stmt, element, rescueDataList); executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1000); } else { executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1); break; } } } private <T> void addElementToBatchAndRescueList(@Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final PreparedStatement stmt, @Nonnull final T element, @Nonnull final List<T> rescueDataList) { try { rescueDataList.add(element); handler.applyBatch(stmt, element); } catch (final ArchiveDaoException t) { handleThrowable(t, handler, rescueDataList); } } @Nonnull private <T> boolean executeBatchAndClearListOnCondition(@Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final PreparedStatement stmt, @Nonnull final List<T> rescueDataList, final int minBatchSize) { final int size = rescueDataList.size(); if (size >= minBatchSize) { LOG.info("{} for {}", new Object[]{size, handler.getHandlerType().getSimpleName()}); try { final RunningStopWatch start = StopWatch.start(); stmt.executeBatch(); LOG.info("took for {}: {}ms", size, start.getElapsedTimeInMillis()); } catch (final Throwable t) { handleThrowable(t, handler, rescueDataList); } finally { rescueDataList.clear(); } return true; } return false; } private <T> void handleThrowable(@Nonnull final Throwable t, @Nonnull final BatchQueueHandlerSupport<T> handler, @Nonnull final List<T> rescueDataList) { final Collection<String> statements = handler.convertToStatementString(rescueDataList); try { throw t; } catch (final ArchiveConnectionException se) { LOG.error("Archive Connection failed. No batch update. Drain unpersisted statements to file system.", se); rescueDataToFileSystem(statements); } catch (final BatchUpdateException be) { LOG.error("Batched update failed. Drain unpersisted statements to file system.", be); processFailedBatch(statements, be); } catch (final SQLException se) { LOG.error("Batched update failed. Batched statement could not be composed.", se); rescueDataToFileSystem(statements); } catch (final Throwable tt) { LOG.error("Unknown throwable. Thread " + _name + " is terminated", tt); rescueDataToFileSystem(statements); } finally { rescueDataList.clear(); } } private <T> void processFailedBatch(@Nonnull final Collection<String> batchedStatements, @Nonnull final BatchUpdateException be) { // NOT all statements have been successfully executed! (Depends on RDBM) final int[] updateCounts = be.getUpdateCounts(); if (updateCounts.length == batchedStatements.size()) { // All statements have been tried to be executed, look for the failed ones final List<String> failedStmts = findFailedStatements(updateCounts, batchedStatements); rescueDataToFileSystem(failedStmts); } else { // Not all statements have been tried to be executed - safe only the failed ones rescueDataToFileSystem(Iterables.skip(batchedStatements, updateCounts.length)); } } private static void closeStatement(@CheckForNull final Statement stmt) { if (stmt != null) { try { stmt.close(); } catch (final SQLException e) { LOG.warn("Closing of statement failed: " + stmt); } } } @Nonnull private static List<String> findFailedStatements(@Nonnull final int[] updateCounts, @Nonnull final Collection<String> allStmts) { final List<String> failedStmts = Lists.newLinkedList(); int i = 0; for (final String stmt : allStmts) { if (i < updateCounts.length && updateCounts[i] == Statement.EXECUTE_FAILED) { failedStmts.add(stmt); } i++; } return failedStmts; } @Nonnull public String getName() { return _name; } public long getPeriodInMS() { return _periodInMS; } void rescueDataToFileSystem(@Nonnull final Iterable<String> statements) { final int noOfRescuedStmts = Iterables.size(statements); LOG.warn("Rescue statements: " + noOfRescuedStmts); int no = 0; for (final String stmt : statements) { RESCUE_LOG.info(stmt); no++; } ArchiveNotifications.notify(NotificationType.PERSIST_DATA_FAILED, "#Rescued: " + no); } }
o.c.archive.common.service.mysqlimpl: debugged double creation of rescue statements
applications/plugins/org.csstudio.archive.common.service.mysqlimpl/src/java/org/csstudio/archive/common/service/mysqlimpl/persistengine/PersistDataWorker.java
o.c.archive.common.service.mysqlimpl: debugged double creation of rescue statements
<ide><path>pplications/plugins/org.csstudio.archive.common.service.mysqlimpl/src/java/org/csstudio/archive/common/service/mysqlimpl/persistengine/PersistDataWorker.java <ide> @Nonnull final List<T> rescueDataList) { <ide> final Queue<T> queue = handler.getQueue(); <ide> T element; <del> while (true) { <del> element = queue.poll(); <del> if (element != null) { <del> addElementToBatchAndRescueList(handler, stmt, element, rescueDataList); <del> executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1000); <del> } else { <del> executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1); <del> break; <del> } <add> try { <add> while (true) { <add> element = queue.poll(); <add> if (element != null) { <add> addElementToBatchAndRescueList(handler, stmt, element, rescueDataList); <add> executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1000); <add> } else { <add> executeBatchAndClearListOnCondition(handler, stmt, rescueDataList, 1); <add> break; <add> } <add> } <add> } catch (final Throwable t) { <add> handleThrowable(t, handler, rescueDataList); <ide> } <ide> } <ide> <ide> private <T> void addElementToBatchAndRescueList(@Nonnull final BatchQueueHandlerSupport<T> handler, <ide> @Nonnull final PreparedStatement stmt, <ide> @Nonnull final T element, <del> @Nonnull final List<T> rescueDataList) { <del> try { <add> @Nonnull final List<T> rescueDataList) throws ArchiveDaoException { <ide> rescueDataList.add(element); <ide> handler.applyBatch(stmt, element); <del> } catch (final ArchiveDaoException t) { <del> handleThrowable(t, handler, rescueDataList); <del> } <ide> } <ide> <ide> @Nonnull <ide> private <T> boolean executeBatchAndClearListOnCondition(@Nonnull final BatchQueueHandlerSupport<T> handler, <ide> @Nonnull final PreparedStatement stmt, <ide> @Nonnull final List<T> rescueDataList, <del> final int minBatchSize) { <add> final int minBatchSize) throws SQLException { <ide> final int size = rescueDataList.size(); <ide> if (size >= minBatchSize) { <ide> LOG.info("{} for {}", new Object[]{size, handler.getHandlerType().getSimpleName()}); <ide> stmt.executeBatch(); <ide> LOG.info("took for {}: {}ms", size, start.getElapsedTimeInMillis()); <ide> <del> } catch (final Throwable t) { <del> handleThrowable(t, handler, rescueDataList); <ide> } finally { <ide> rescueDataList.clear(); <ide> }
Java
epl-1.0
3145d0256518bddec38fe2d141029e034706c266
0
fappel/xiliary,fappel/xiliary,fappel/xiliary,fappel/xiliary
/** * Copyright (c) 2014 - 2017 Frank Appel * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Frank Appel - initial API and implementation */ package com.codeaffine.eclipse.swt.util; import static com.codeaffine.test.util.lang.ThrowableCaptor.thrownBy; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.eclipse.swt.widgets.Shell; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.codeaffine.eclipse.swt.test.util.DisplayHelper; import com.codeaffine.eclipse.swt.test.util.SWTIgnoreConditions.CocoaPlatform; import com.codeaffine.eclipse.swt.util.ReadAndDispatch.ProblemHandler; import com.codeaffine.test.util.junit.ConditionalIgnoreRule; import com.codeaffine.test.util.junit.ConditionalIgnoreRule.ConditionalIgnore; public class ReadAndDispatchTest { private static final int DURATION = 50; private static final int SCHEDULE = 50; @Rule public final DisplayHelper displayHelper = new DisplayHelper(); @Rule public final ConditionalIgnoreRule conditionalIgnore = new ConditionalIgnoreRule(); private Shell shell; @Before public void setUp() { shell = openShell(); } @Test public void spinLoop() { ReadAndDispatch readAndDispatch = new ReadAndDispatch(); displayHelper.getDisplay().timerExec( SCHEDULE, () -> shell.dispose() ); readAndDispatch.spinLoop( shell ); assertThat( shell.isDisposed() ).isTrue(); } @Test public void spinLoopWithDuration() { ReadAndDispatch readAndDispatch = new ReadAndDispatch(); long start = System.currentTimeMillis(); readAndDispatch.spinLoop( shell, DURATION ); long actual = System.currentTimeMillis() - start; assertThat( actual ).isGreaterThanOrEqualTo( DURATION ); } @Test public void spinLoopWithProblem() { ReadAndDispatch readAndDispatch = new ReadAndDispatch(); RuntimeException expected = new RuntimeException(); displayHelper.getDisplay().timerExec( SCHEDULE, () -> { throw expected; } ); Throwable actual = thrownBy( () -> readAndDispatch.spinLoop( shell ) ); assertThat( actual ).isSameAs( expected ); } @Test public void spinLoopWithProblemHandler() { ProblemHandler problemHandler = mock( ProblemHandler.class ); RuntimeException expected = new RuntimeException(); ReadAndDispatch readAndDispatch = new ReadAndDispatch( problemHandler ); displayHelper.getDisplay().timerExec( SCHEDULE, () -> { throw expected; } ); readAndDispatch.spinLoop( shell, SCHEDULE * 2 ); verify( problemHandler ).handle( shell, expected ); } @Test @ConditionalIgnore(condition = CocoaPlatform.class) public void openErrorDialog() { Shell problemShell = displayHelper.createShell(); boolean[] wasOpened = new boolean[ 1 ]; displayHelper.getDisplay().timerExec( SCHEDULE, () -> captureOpenStateAndClose( problemShell, wasOpened ) ); ReadAndDispatch.openErrorDialog( problemShell, new RuntimeException() ); assertThat( wasOpened[ 0 ] ).isTrue(); assertThat( problemShell.isDisposed() ).isTrue(); } @Test( expected = IllegalArgumentException.class ) public void constructorWithNullAsProblemHandler() { new ReadAndDispatch( null ); } @Test( expected = IllegalArgumentException.class ) public void openErrorDialogWithNullAsShell() { ReadAndDispatch.openErrorDialog( null, new RuntimeException() ); } @Test( expected = IllegalArgumentException.class ) public void openErrorDialogWithNullAsProblem() { ReadAndDispatch.openErrorDialog( shell, null ); } private Shell openShell() { Shell result = displayHelper.createShell(); result.open(); return result; } private static void captureOpenStateAndClose( Shell problemShell, boolean[] problemShellOpened ) { captureDisposeState( problemShell, problemShellOpened ); problemShell.close(); } private static boolean captureDisposeState( Shell shell, boolean[] isOpen ) { return isOpen[ 0 ] = !shell.isDisposed(); } }
com.codeaffine.eclipse.swt.test/src/com/codeaffine/eclipse/swt/util/ReadAndDispatchTest.java
/** * Copyright (c) 2014 - 2017 Frank Appel * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Frank Appel - initial API and implementation */ package com.codeaffine.eclipse.swt.util; import static com.codeaffine.test.util.lang.ThrowableCaptor.thrownBy; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import org.eclipse.swt.widgets.Shell; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import com.codeaffine.eclipse.swt.test.util.DisplayHelper; import com.codeaffine.eclipse.swt.test.util.SWTIgnoreConditions.CocoaPlatform; import com.codeaffine.eclipse.swt.util.ReadAndDispatch.ProblemHandler; import com.codeaffine.test.util.junit.ConditionalIgnoreRule; import com.codeaffine.test.util.junit.ConditionalIgnoreRule.ConditionalIgnore; public class ReadAndDispatchTest { private static final int DURATION = 10; private static final int SCHEDULE = 10; @Rule public final DisplayHelper displayHelper = new DisplayHelper(); @Rule public final ConditionalIgnoreRule conditionalIgnore = new ConditionalIgnoreRule(); private Shell shell; @Before public void setUp() { shell = openShell(); } @Test public void spinLoop() { ReadAndDispatch readAndDispatch = new ReadAndDispatch(); displayHelper.getDisplay().timerExec( SCHEDULE, () -> shell.dispose() ); readAndDispatch.spinLoop( shell ); assertThat( shell.isDisposed() ).isTrue(); } @Test public void spinLoopWithDuration() { ReadAndDispatch readAndDispatch = new ReadAndDispatch(); long start = System.currentTimeMillis(); readAndDispatch.spinLoop( shell, DURATION ); long actual = System.currentTimeMillis() - start; assertThat( actual ).isGreaterThanOrEqualTo( DURATION ); } @Test public void spinLoopWithProblem() { ReadAndDispatch readAndDispatch = new ReadAndDispatch(); RuntimeException expected = new RuntimeException(); displayHelper.getDisplay().timerExec( SCHEDULE, () -> { throw expected; } ); Throwable actual = thrownBy( () -> readAndDispatch.spinLoop( shell ) ); assertThat( actual ).isSameAs( expected ); } @Test public void spinLoopWithProblemHandler() { ProblemHandler problemHandler = mock( ProblemHandler.class ); RuntimeException expected = new RuntimeException(); ReadAndDispatch readAndDispatch = new ReadAndDispatch( problemHandler ); displayHelper.getDisplay().timerExec( SCHEDULE, () -> { throw expected; } ); readAndDispatch.spinLoop( shell, SCHEDULE * 2 ); verify( problemHandler ).handle( shell, expected ); } @Test @ConditionalIgnore(condition = CocoaPlatform.class) public void openErrorDialog() { Shell problemShell = displayHelper.createShell(); boolean[] wasOpened = new boolean[ 1 ]; displayHelper.getDisplay().timerExec( SCHEDULE, () -> captureOpenStateAndClose( problemShell, wasOpened ) ); ReadAndDispatch.openErrorDialog( problemShell, new RuntimeException() ); assertThat( wasOpened[ 0 ] ).isTrue(); assertThat( problemShell.isDisposed() ).isTrue(); } @Test( expected = IllegalArgumentException.class ) public void constructorWithNullAsProblemHandler() { new ReadAndDispatch( null ); } @Test( expected = IllegalArgumentException.class ) public void openErrorDialogWithNullAsShell() { ReadAndDispatch.openErrorDialog( null, new RuntimeException() ); } @Test( expected = IllegalArgumentException.class ) public void openErrorDialogWithNullAsProblem() { ReadAndDispatch.openErrorDialog( shell, null ); } private Shell openShell() { Shell result = displayHelper.createShell(); result.open(); return result; } private static void captureOpenStateAndClose( Shell problemShell, boolean[] problemShellOpened ) { captureDisposeState( problemShell, problemShellOpened ); problemShell.close(); } private static boolean captureDisposeState( Shell shell, boolean[] isOpen ) { return isOpen[ 0 ] = !shell.isDisposed(); } }
Try to fix build problem on Mac of ReadAndDispatchTest
com.codeaffine.eclipse.swt.test/src/com/codeaffine/eclipse/swt/util/ReadAndDispatchTest.java
Try to fix build problem on Mac of ReadAndDispatchTest
<ide><path>om.codeaffine.eclipse.swt.test/src/com/codeaffine/eclipse/swt/util/ReadAndDispatchTest.java <ide> <ide> public class ReadAndDispatchTest { <ide> <del> private static final int DURATION = 10; <del> private static final int SCHEDULE = 10; <add> private static final int DURATION = 50; <add> private static final int SCHEDULE = 50; <ide> <ide> @Rule <ide> public final DisplayHelper displayHelper = new DisplayHelper();
Java
mit
e91845db24d78855f9279c4eae824df88b34fc05
0
PrinceOfAmber/CyclicMagic
/******************************************************************************* * The MIT License (MIT) * * Copyright (C) 2014-2018 Sam Bassett (aka Lothrazar) * * 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. ******************************************************************************/ package com.lothrazar.cyclic.block.crafter; import com.lothrazar.cyclic.ModCyclic; import com.lothrazar.cyclic.base.TileEntityBase; import com.lothrazar.cyclic.capability.CustomEnergyStorage; import com.lothrazar.cyclic.capability.ItemStackHandlerWrapper; import com.lothrazar.cyclic.registry.TileRegistry; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.CraftingInventory; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.Ingredient; import net.minecraft.item.crafting.ShapedRecipe; import net.minecraft.item.crafting.ShapelessRecipe; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.util.Direction; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.common.ForgeConfigSpec.IntValue; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.energy.CapabilityEnergy; import net.minecraftforge.energy.IEnergyStorage; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; @SuppressWarnings("unchecked") public class TileCrafter extends TileEntityBase implements INamedContainerProvider, ITickableTileEntity { static final int MAX = 64000; public static final int TIMER_FULL = 40; public static IntValue POWERCONF; private CustomEnergyStorage energy = new CustomEnergyStorage(MAX, MAX); private final LazyOptional<IEnergyStorage> energyCap = LazyOptional.of(() -> energy); ItemStackHandler inputHandler = new ItemStackHandler(IO_SIZE); ItemStackHandler outHandler = new ItemStackHandler(IO_SIZE); private final LazyOptional<IItemHandler> input = LazyOptional.of(() -> inputHandler); private final LazyOptional<IItemHandler> output = LazyOptional.of(() -> outHandler); private final LazyOptional<IItemHandler> gridCap = LazyOptional.of(() -> new ItemStackHandler(GRID_SIZE)); private final LazyOptional<IItemHandler> preview = LazyOptional.of(() -> new ItemStackHandler(1)); private ItemStackHandlerWrapper inventoryWrapper = new ItemStackHandlerWrapper(inputHandler, outHandler); private final LazyOptional<IItemHandler> inventoryCap = LazyOptional.of(() -> inventoryWrapper); // public static final int IO_NUM_ROWS = 5; public static final int IO_NUM_COLS = 2; public static final int GRID_NUM_ROWS = 3; public static final int GRID_NUM_COLS = 3; public static final int IO_SIZE = IO_NUM_ROWS * IO_NUM_COLS; public static final int GRID_SIZE = GRID_NUM_ROWS * GRID_NUM_COLS; public static final int PREVIEW_SLOT = IO_SIZE * 2 + GRID_SIZE; public static final int OUTPUT_SLOT_START = IO_SIZE + GRID_SIZE; public static final int OUTPUT_SLOT_STOP = OUTPUT_SLOT_START + IO_SIZE - 1; public static final int GRID_SLOT_START = IO_SIZE; public static final int GRID_SLOT_STOP = GRID_SLOT_START + GRID_SIZE - 1; private boolean hasValidRecipe = false; public boolean shouldSearch = true; private ArrayList<ItemStack> lastRecipeGrid = null; private IRecipe<?> lastValidRecipe = null; private ItemStack recipeOutput = ItemStack.EMPTY; public enum ItemHandlers { INPUT, OUTPUT, GRID, PREVIEW }; public enum Fields { TIMER, REDSTONE, RENDER; } public TileCrafter() { super(TileRegistry.crafter); } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { if (index != PREVIEW_SLOT && (index < OUTPUT_SLOT_START || index > OUTPUT_SLOT_STOP)) { super.isItemValidForSlot(index, stack); } return false; } @Override public void tick() { this.syncEnergy(); if (world == null || world.getServer() == null) { return; } if (world.isRemote) { return; } IItemHandler previewHandler = this.preview.orElse(null); ArrayList<ItemStack> itemStacksInGrid = getItemsInCraftingGrid(); if (lastRecipeGrid == null) { lastRecipeGrid = itemStacksInGrid; } if (itemStacksInGrid == null || countNonEmptyStacks(itemStacksInGrid) == 0) { //Nothing in Crafting grid, so don't do anything setPreviewSlot(previewHandler, ItemStack.EMPTY); return; } else if (!itemStacksInGrid.equals(lastRecipeGrid)) { //Crafting grid is updated, search for new recipe reset(); lastRecipeGrid = itemStacksInGrid; shouldSearch = true; } if (!hasValidRecipe && shouldSearch) { IRecipe<?> recipe = tryRecipes(itemStacksInGrid); if (recipe != null) { hasValidRecipe = true; lastValidRecipe = recipe; lastRecipeGrid = itemStacksInGrid; recipeOutput = lastValidRecipe.getRecipeOutput(); shouldSearch = false; setPreviewSlot(previewHandler, lastValidRecipe.getRecipeOutput()); } else { reset(); shouldSearch = false; //Went through all recipes, didn't find match. Don't search again (until crafting grid changes) } } if (this.requiresRedstone() && !this.isPowered()) { setLitProperty(false); return; } setLitProperty(true); IEnergyStorage cap = this.energyCap.orElse(null); if (cap == null) { return; } final int cost = POWERCONF.get(); if (cap.getEnergyStored() < cost && cost > 0) { return; } if (hasValidRecipe) { timer--; if (timer > 0) { return; } timer = TIMER_FULL; // ModCyclic.LOGGER.info("tick down valid recipe output " + recipeOutput + " readyToCraft = " + readyToCraft); if (doCraft(inputHandler, true)) { // docraft in simulate mode ItemStack output = recipeOutput.copy(); if (hasFreeSpace(outHandler, recipeOutput) && doCraft(inputHandler, false)) { if (lastValidRecipe != null && lastValidRecipe instanceof ShapedRecipe) { ShapedRecipe r = (ShapedRecipe) lastValidRecipe; r.getRemainingItems(craftMatrix); ModCyclic.LOGGER.info("getRemaining done"); } //docraft simulate false is done, and we have space for output energy.extractEnergy(cost, false); //compare to what it was ArrayList<ItemStack> itemStacksInGridBackup = getItemsInCraftingGrid(); for (int i = 0; i < this.craftMatrix.getSizeInventory(); i++) { ItemStack recipeLeftover = this.craftMatrix.getStackInSlot(i); if (!recipeLeftover.isEmpty()) { ModCyclic.LOGGER.info(i + " recipe leftovers " + recipeLeftover + " ||| itemStacksInGridBackup " + itemStacksInGridBackup.get(i)); if (recipeLeftover.getContainerItem().isEmpty() == false) { // ModCyclic.LOGGER.info(i + "getContainerItem " + recipeLeftover.getContainerItem()); //not just 1 ItemStack result = recipeLeftover.getContainerItem().copy(); for (int j = 0; j < outHandler.getSlots(); j++) { //test it result = this.outHandler.insertItem(j, result, false); if (result.isEmpty()) { break; } } } //its not empty ItemStack actualLeftovers = itemStacksInGridBackup.get(i); if (!recipeLeftover.equals(actualLeftovers, true)) { ModCyclic.LOGGER.info("mismatch post craft:" + " recipeLeftover = " + recipeLeftover + " " + recipeLeftover.getTag() + " ; itemStacksInGridBackup.get(i) = " + actualLeftovers + " " + actualLeftovers.getTag()); } } } for (int slotId = 0; slotId < IO_SIZE; slotId++) { output = outHandler.insertItem(slotId, output, false); if (output == ItemStack.EMPTY || output.getCount() == 0) { break; } } } } } } private ArrayList<ItemStack> getItemsInCraftingGrid() { ArrayList<ItemStack> itemStacks = new ArrayList<>(); IItemHandler gridHandler = this.gridCap.orElse(null); if (gridHandler == null) { return null; } for (int i = 0; i < GRID_SIZE; i++) { itemStacks.add(gridHandler.getStackInSlot(i)); } return itemStacks; } private void setPreviewSlot(IItemHandler previewHandler, ItemStack itemStack) { previewHandler.extractItem(0, 64, false); previewHandler.insertItem(0, itemStack, false); } private boolean hasFreeSpace(IItemHandler inv, ItemStack output) { for (int slotId = 0; slotId < IO_SIZE; slotId++) { if (inv.getStackInSlot(slotId) == ItemStack.EMPTY || (inv.getStackInSlot(slotId).isItemEqual(output) && inv.getStackInSlot(slotId).getCount() + output.getCount() <= output.getMaxStackSize())) { return true; } if (output == ItemStack.EMPTY || output.getCount() == 0) { return true; } } return false; } private boolean doCraft(IItemHandler input, boolean simulate) { HashMap<Integer, List<ItemStack>> putbackStacks = new HashMap<>(); for (Ingredient ingredient : lastValidRecipe.getIngredients()) { if (ingredient == Ingredient.EMPTY) { continue; } boolean matched = false; for (int index = 0; index < input.getSlots(); index++) { ItemStack itemStack = input.getStackInSlot(index); if (ingredient.test(itemStack)) { if (putbackStacks.containsKey(index)) { putbackStacks.get(index).add(new ItemStack(input.getStackInSlot(index).getItem(), 1)); } else { List<ItemStack> list = new ArrayList<>(); list.add(new ItemStack(input.getStackInSlot(index).getItem(), 1)); putbackStacks.put(index, list); } matched = true; input.extractItem(index, 1, false); break; } } if (!matched) { putbackStacks(putbackStacks, input); return false; } } if (simulate) { putbackStacks(putbackStacks, input); } return true; } private void putbackStacks(HashMap<Integer, List<ItemStack>> putbackStacks, IItemHandler itemHandler) { for (HashMap.Entry<Integer, List<ItemStack>> entry : putbackStacks.entrySet()) { for (ItemStack stack : entry.getValue()) { itemHandler.insertItem(entry.getKey(), stack, false); } } } private IRecipe<?> tryRecipes(ArrayList<ItemStack> itemStacksInGrid) { if (world == null || world.getServer() == null) { return null; } Collection<IRecipe<?>> recipes = world.getServer().getRecipeManager().getRecipes(); for (IRecipe<?> recipe : recipes) { if (recipe instanceof ShapelessRecipe) { ShapelessRecipe shapelessRecipe = (ShapelessRecipe) recipe; if (tryMatchShapelessRecipe(itemStacksInGrid, shapelessRecipe)) { return shapelessRecipe; } } else if (recipe instanceof ShapedRecipe) { ShapedRecipe shapedRecipe = (ShapedRecipe) recipe; if (!doSizesMatch(shapedRecipe, itemStacksInGrid)) { continue; } if (tryMatchShapedRecipe(itemStacksInGrid, shapedRecipe)) { return shapedRecipe; } } } return null; } private boolean tryMatchShapedRecipe(ArrayList<ItemStack> itemStacks, ShapedRecipe recipe) { for (int i = 0; i <= 3 - recipe.getWidth(); ++i) { for (int j = 0; j <= 3 - recipe.getHeight(); ++j) { if (this.tryMatchShapedRecipeRegion(itemStacks, recipe, i, j)) { return true; } } } return false; } private boolean tryMatchShapelessRecipe(ArrayList<ItemStack> itemStacks, ShapelessRecipe recipe) { ArrayList<ItemStack> itemStacksCopy = (ArrayList<ItemStack>) itemStacks.clone(); for (Ingredient ingredient : recipe.getIngredients()) { Iterator<ItemStack> iter = itemStacksCopy.iterator(); boolean matched = false; while (iter.hasNext()) { ItemStack itemStack = iter.next(); if (ingredient.test(itemStack)) { iter.remove(); matched = true; break; } } if (!matched) { return false; } } return countNonEmptyStacks(itemStacksCopy) == 0; } public static class FakeContainer extends Container { protected FakeContainer(ContainerType<?> type, int id) { super(type, id); } @Override public boolean canInteractWith(PlayerEntity playerIn) { return true; } } //TODO: future private final CraftingInventory craftMatrix = new CraftingInventory(new FakeContainer(ContainerType.CRAFTING, 18291238), 3, 3); private boolean tryMatchShapedRecipeRegion(ArrayList<ItemStack> itemStacks, ShapedRecipe recipe, int offsetX, int offsetY) { for (int i = 0; i < recipe.getWidth(); i++) { for (int j = 0; j < recipe.getHeight(); j++) { try { int indexInArray = i + j * 3; ItemStack itemStack = itemStacks.get(indexInArray); // ModCyclic.LOGGER.info(pos + " craftMatrix i=" + i + " j=" + j + " " + itemStack); craftMatrix.setInventorySlotContents(indexInArray, itemStack.copy()); } catch (Exception e) { //breakpoint return false; } } } boolean matched = recipe.matches(craftMatrix, world); // ModCyclic.LOGGER.info(recipe.getRecipeOutput() + " -0 matched recipe and getRemainingItems " + matched); return matched; // return false; // int recipeSize = recipe.getWidth() * recipe.getHeight(); // // int itemStacksSize = itemStacks.size(); // Ingredient ingredient; // if (itemStacksSize < recipeSize || offsetX + recipe.getWidth() > 3 || offsetY + recipe.getHeight() > 3) { // return false; // } // int indexInRecipe = 0; // for (int i = 0; i < recipe.getWidth(); i++) { // for (int j = 0; j < recipe.getHeight(); j++) { // int indexInArray = i + j * 3; // ItemStack itemStack = itemStacks.get(indexInArray); // ingredient = recipe.getIngredients().get(indexInRecipe); // if (!ingredient.test(itemStack)) { // if (ingredient.getMatchingStacks().length > 0) { // ModCyclic.LOGGER.info(indexInArray + "=indexInArray; " + itemStack + " does not match-> " + ingredient.getMatchingStacks()[0]); // } // return false; // } // indexInRecipe++; // } // } // return true; } public void reset() { this.hasValidRecipe = false; this.lastRecipeGrid = null; this.lastValidRecipe = null; this.shouldSearch = true; this.timer = 0; IItemHandler previewHandler = this.preview.orElse(null); if (previewHandler != null) { setPreviewSlot(previewHandler, ItemStack.EMPTY); } } private int countNonEmptyStacks(ArrayList<ItemStack> itemStacks) { int count = 0; for (ItemStack itemStack : itemStacks) { if (itemStack != ItemStack.EMPTY) { count++; } } return count; } private boolean doSizesMatch(ShapedRecipe recipe, ArrayList<ItemStack> itemStacks) { int ingredientCount = 0; int itemStackCount = 0; for (Ingredient ingredient : recipe.getIngredients()) { if (!ingredient.test(ItemStack.EMPTY)) { ingredientCount++; } } for (ItemStack itemStack : itemStacks) { if (itemStack != ItemStack.EMPTY) { itemStackCount++; } } return ingredientCount == itemStackCount; } @Override public ITextComponent getDisplayName() { return new StringTextComponent(getType().getRegistryName().getPath()); } @Override public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) { return new ContainerCrafter(i, world, pos, playerInventory, playerEntity); } @Override public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) { if (cap == CapabilityEnergy.ENERGY && POWERCONF.get() > 0) { return energyCap.cast(); } if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return inventoryCap.cast(); } return super.getCapability(cap, side); } public <T> LazyOptional<T> getCapability(Capability<T> cap, ItemHandlers type) { if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { switch (type) { case INPUT: return input.cast(); case OUTPUT: return output.cast(); case GRID: return gridCap.cast(); case PREVIEW: return preview.cast(); } } return null; } @Override public void read(BlockState bs, CompoundNBT tag) { energyCap.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("energy"))); input.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("input"))); output.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("output"))); gridCap.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("grid"))); preview.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("preview"))); super.read(bs, tag); } @Override public CompoundNBT write(CompoundNBT tag) { energyCap.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("energy", compound); }); input.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("input", compound); }); output.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("output", compound); }); gridCap.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("grid", compound); }); preview.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("preview", compound); }); return super.write(tag); } @Override public int getField(int id) { switch (TileCrafter.Fields.values()[id]) { case TIMER: return timer; case REDSTONE: return this.needsRedstone; case RENDER: return render; } return -1; } @Override public void setField(int id, int value) { switch (TileCrafter.Fields.values()[id]) { case TIMER: this.timer = value; break; case REDSTONE: this.needsRedstone = value % 2; break; case RENDER: this.render = value % 2; break; } } }
src/main/java/com/lothrazar/cyclic/block/crafter/TileCrafter.java
/******************************************************************************* * The MIT License (MIT) * * Copyright (C) 2014-2018 Sam Bassett (aka Lothrazar) * * 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. ******************************************************************************/ package com.lothrazar.cyclic.block.crafter; import com.lothrazar.cyclic.ModCyclic; import com.lothrazar.cyclic.base.TileEntityBase; import com.lothrazar.cyclic.capability.CustomEnergyStorage; import com.lothrazar.cyclic.capability.ItemStackHandlerWrapper; import com.lothrazar.cyclic.registry.TileRegistry; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import net.minecraft.block.BlockState; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.entity.player.PlayerInventory; import net.minecraft.inventory.CraftingInventory; import net.minecraft.inventory.container.Container; import net.minecraft.inventory.container.ContainerType; import net.minecraft.inventory.container.INamedContainerProvider; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.item.crafting.Ingredient; import net.minecraft.item.crafting.ShapedRecipe; import net.minecraft.item.crafting.ShapelessRecipe; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.ITickableTileEntity; import net.minecraft.util.Direction; import net.minecraft.util.text.ITextComponent; import net.minecraft.util.text.StringTextComponent; import net.minecraftforge.common.ForgeConfigSpec.IntValue; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.util.INBTSerializable; import net.minecraftforge.common.util.LazyOptional; import net.minecraftforge.energy.CapabilityEnergy; import net.minecraftforge.energy.IEnergyStorage; import net.minecraftforge.items.CapabilityItemHandler; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.ItemStackHandler; @SuppressWarnings("unchecked") public class TileCrafter extends TileEntityBase implements INamedContainerProvider, ITickableTileEntity { static final int MAX = 64000; public static final int TIMER_FULL = 40; public static IntValue POWERCONF; private CustomEnergyStorage energy = new CustomEnergyStorage(MAX, MAX); private final LazyOptional<IEnergyStorage> energyCap = LazyOptional.of(() -> energy); ItemStackHandler inputHandler = new ItemStackHandler(IO_SIZE); ItemStackHandler outHandler = new ItemStackHandler(IO_SIZE); private final LazyOptional<IItemHandler> input = LazyOptional.of(() -> inputHandler); private final LazyOptional<IItemHandler> output = LazyOptional.of(() -> outHandler); private final LazyOptional<IItemHandler> gridCap = LazyOptional.of(() -> new ItemStackHandler(GRID_SIZE)); private final LazyOptional<IItemHandler> preview = LazyOptional.of(() -> new ItemStackHandler(1)); private ItemStackHandlerWrapper inventoryWrapper = new ItemStackHandlerWrapper(inputHandler, outHandler); private final LazyOptional<IItemHandler> inventoryCap = LazyOptional.of(() -> inventoryWrapper); // public static final int IO_NUM_ROWS = 5; public static final int IO_NUM_COLS = 2; public static final int GRID_NUM_ROWS = 3; public static final int GRID_NUM_COLS = 3; public static final int IO_SIZE = IO_NUM_ROWS * IO_NUM_COLS; public static final int GRID_SIZE = GRID_NUM_ROWS * GRID_NUM_COLS; public static final int PREVIEW_SLOT = IO_SIZE * 2 + GRID_SIZE; public static final int OUTPUT_SLOT_START = IO_SIZE + GRID_SIZE; public static final int OUTPUT_SLOT_STOP = OUTPUT_SLOT_START + IO_SIZE - 1; public static final int GRID_SLOT_START = IO_SIZE; public static final int GRID_SLOT_STOP = GRID_SLOT_START + GRID_SIZE - 1; private boolean hasValidRecipe = false; public boolean shouldSearch = true; private ArrayList<ItemStack> lastRecipeGrid = null; private IRecipe<?> lastValidRecipe = null; private ItemStack recipeOutput = ItemStack.EMPTY; public enum ItemHandlers { INPUT, OUTPUT, GRID, PREVIEW }; public enum Fields { TIMER, REDSTONE, RENDER; } public TileCrafter() { super(TileRegistry.crafter); } @Override public boolean isItemValidForSlot(int index, ItemStack stack) { if (index != PREVIEW_SLOT && (index < OUTPUT_SLOT_START || index > OUTPUT_SLOT_STOP)) { super.isItemValidForSlot(index, stack); } return false; } @Override public void tick() { this.syncEnergy(); if (world == null || world.getServer() == null) { return; } if (world.isRemote) { return; } IItemHandler previewHandler = this.preview.orElse(null); ArrayList<ItemStack> itemStacksInGrid = getItemsInCraftingGrid(); if (lastRecipeGrid == null) { lastRecipeGrid = itemStacksInGrid; } if (itemStacksInGrid == null || countNonEmptyStacks(itemStacksInGrid) == 0) { //Nothing in Crafting grid, so don't do anything setPreviewSlot(previewHandler, ItemStack.EMPTY); return; } else if (!itemStacksInGrid.equals(lastRecipeGrid)) { //Crafting grid is updated, search for new recipe reset(); lastRecipeGrid = itemStacksInGrid; shouldSearch = true; } if (!hasValidRecipe && shouldSearch) { IRecipe<?> recipe = tryRecipes(itemStacksInGrid); if (recipe != null) { hasValidRecipe = true; lastValidRecipe = recipe; lastRecipeGrid = itemStacksInGrid; recipeOutput = lastValidRecipe.getRecipeOutput(); shouldSearch = false; setPreviewSlot(previewHandler, lastValidRecipe.getRecipeOutput()); } else { reset(); shouldSearch = false; //Went through all recipes, didn't find match. Don't search again (until crafting grid changes) } } if (this.requiresRedstone() && !this.isPowered()) { setLitProperty(false); return; } setLitProperty(true); IEnergyStorage cap = this.energyCap.orElse(null); if (cap == null) { return; } final int cost = POWERCONF.get(); if (cap.getEnergyStored() < cost && cost > 0) { return; } if (hasValidRecipe) { timer--; if (timer > 0) { return; } timer = TIMER_FULL; // ModCyclic.LOGGER.info("tick down valid recipe output " + recipeOutput + " readyToCraft = " + readyToCraft); if (doCraft(inputHandler, true)) { // docraft in simulate mode ItemStack output = recipeOutput.copy(); if (hasFreeSpace(outHandler, recipeOutput) && doCraft(inputHandler, false)) { if (lastValidRecipe != null && lastValidRecipe instanceof ShapedRecipe) { ShapedRecipe r = (ShapedRecipe) lastValidRecipe; r.getRemainingItems(craftMatrix); ModCyclic.LOGGER.info("getRemaining done"); } //docraft simulate false is done, and we have space for output energy.extractEnergy(cost, false); //compare to what it was ArrayList<ItemStack> itemStacksInGridBackup = getItemsInCraftingGrid(); for (int i = 0; i < this.craftMatrix.getSizeInventory(); i++) { ItemStack recipeLeftover = this.craftMatrix.getStackInSlot(i); if (!recipeLeftover.isEmpty()) { ModCyclic.LOGGER.info(i + " recipe leftovers " + recipeLeftover + " ||| itemStacksInGridBackup " + itemStacksInGridBackup.get(i)); if (recipeLeftover.getContainerItem().isEmpty() == false) { // ModCyclic.LOGGER.info(i + "getContainerItem " + recipeLeftover.getContainerItem()); //not just 1 ItemStack result = recipeLeftover.getContainerItem().copy(); for (int j = 0; j < inputHandler.getSlots(); j++) { //test it result = this.inputHandler.insertItem(j, result, false); if (result.isEmpty()) { break; } } } //its not empty ItemStack actualLeftovers = itemStacksInGridBackup.get(i); if (!recipeLeftover.equals(actualLeftovers, true)) { ModCyclic.LOGGER.info("mismatch post craft:" + " recipeLeftover = " + recipeLeftover + " " + recipeLeftover.getTag() + " ; itemStacksInGridBackup.get(i) = " + actualLeftovers + " " + actualLeftovers.getTag()); } } } for (int slotId = 0; slotId < IO_SIZE; slotId++) { output = outHandler.insertItem(slotId, output, false); if (output == ItemStack.EMPTY || output.getCount() == 0) { break; } } } } } } private ArrayList<ItemStack> getItemsInCraftingGrid() { ArrayList<ItemStack> itemStacks = new ArrayList<>(); IItemHandler gridHandler = this.gridCap.orElse(null); if (gridHandler == null) { return null; } for (int i = 0; i < GRID_SIZE; i++) { itemStacks.add(gridHandler.getStackInSlot(i)); } return itemStacks; } private void setPreviewSlot(IItemHandler previewHandler, ItemStack itemStack) { previewHandler.extractItem(0, 64, false); previewHandler.insertItem(0, itemStack, false); } private boolean hasFreeSpace(IItemHandler inv, ItemStack output) { for (int slotId = 0; slotId < IO_SIZE; slotId++) { if (inv.getStackInSlot(slotId) == ItemStack.EMPTY || (inv.getStackInSlot(slotId).isItemEqual(output) && inv.getStackInSlot(slotId).getCount() + output.getCount() <= output.getMaxStackSize())) { return true; } if (output == ItemStack.EMPTY || output.getCount() == 0) { return true; } } return false; } private boolean doCraft(IItemHandler input, boolean simulate) { HashMap<Integer, List<ItemStack>> putbackStacks = new HashMap<>(); for (Ingredient ingredient : lastValidRecipe.getIngredients()) { if (ingredient == Ingredient.EMPTY) { continue; } boolean matched = false; for (int index = 0; index < input.getSlots(); index++) { ItemStack itemStack = input.getStackInSlot(index); if (ingredient.test(itemStack)) { if (putbackStacks.containsKey(index)) { putbackStacks.get(index).add(new ItemStack(input.getStackInSlot(index).getItem(), 1)); } else { List<ItemStack> list = new ArrayList<>(); list.add(new ItemStack(input.getStackInSlot(index).getItem(), 1)); putbackStacks.put(index, list); } matched = true; input.extractItem(index, 1, false); break; } } if (!matched) { putbackStacks(putbackStacks, input); return false; } } if (simulate) { putbackStacks(putbackStacks, input); } return true; } private void putbackStacks(HashMap<Integer, List<ItemStack>> putbackStacks, IItemHandler itemHandler) { for (HashMap.Entry<Integer, List<ItemStack>> entry : putbackStacks.entrySet()) { for (ItemStack stack : entry.getValue()) { itemHandler.insertItem(entry.getKey(), stack, false); } } } private IRecipe<?> tryRecipes(ArrayList<ItemStack> itemStacksInGrid) { if (world == null || world.getServer() == null) { return null; } Collection<IRecipe<?>> recipes = world.getServer().getRecipeManager().getRecipes(); for (IRecipe<?> recipe : recipes) { if (recipe instanceof ShapelessRecipe) { ShapelessRecipe shapelessRecipe = (ShapelessRecipe) recipe; if (tryMatchShapelessRecipe(itemStacksInGrid, shapelessRecipe)) { return shapelessRecipe; } } else if (recipe instanceof ShapedRecipe) { ShapedRecipe shapedRecipe = (ShapedRecipe) recipe; if (!doSizesMatch(shapedRecipe, itemStacksInGrid)) { continue; } if (tryMatchShapedRecipe(itemStacksInGrid, shapedRecipe)) { return shapedRecipe; } } } return null; } private boolean tryMatchShapedRecipe(ArrayList<ItemStack> itemStacks, ShapedRecipe recipe) { for (int i = 0; i <= 3 - recipe.getWidth(); ++i) { for (int j = 0; j <= 3 - recipe.getHeight(); ++j) { if (this.tryMatchShapedRecipeRegion(itemStacks, recipe, i, j)) { return true; } } } return false; } private boolean tryMatchShapelessRecipe(ArrayList<ItemStack> itemStacks, ShapelessRecipe recipe) { ArrayList<ItemStack> itemStacksCopy = (ArrayList<ItemStack>) itemStacks.clone(); for (Ingredient ingredient : recipe.getIngredients()) { Iterator<ItemStack> iter = itemStacksCopy.iterator(); boolean matched = false; while (iter.hasNext()) { ItemStack itemStack = iter.next(); if (ingredient.test(itemStack)) { iter.remove(); matched = true; break; } } if (!matched) { return false; } } return countNonEmptyStacks(itemStacksCopy) == 0; } public static class FakeContainer extends Container { protected FakeContainer(ContainerType<?> type, int id) { super(type, id); } @Override public boolean canInteractWith(PlayerEntity playerIn) { return true; } } //TODO: future private final CraftingInventory craftMatrix = new CraftingInventory(new FakeContainer(ContainerType.CRAFTING, 18291238), 3, 3); private boolean tryMatchShapedRecipeRegion(ArrayList<ItemStack> itemStacks, ShapedRecipe recipe, int offsetX, int offsetY) { for (int i = 0; i < recipe.getWidth(); i++) { for (int j = 0; j < recipe.getHeight(); j++) { try { int indexInArray = i + j * 3; ItemStack itemStack = itemStacks.get(indexInArray); // ModCyclic.LOGGER.info(pos + " craftMatrix i=" + i + " j=" + j + " " + itemStack); craftMatrix.setInventorySlotContents(indexInArray, itemStack.copy()); } catch (Exception e) { //breakpoint return false; } } } boolean matched = recipe.matches(craftMatrix, world); // ModCyclic.LOGGER.info(recipe.getRecipeOutput() + " -0 matched recipe and getRemainingItems " + matched); return matched; // return false; // int recipeSize = recipe.getWidth() * recipe.getHeight(); // // int itemStacksSize = itemStacks.size(); // Ingredient ingredient; // if (itemStacksSize < recipeSize || offsetX + recipe.getWidth() > 3 || offsetY + recipe.getHeight() > 3) { // return false; // } // int indexInRecipe = 0; // for (int i = 0; i < recipe.getWidth(); i++) { // for (int j = 0; j < recipe.getHeight(); j++) { // int indexInArray = i + j * 3; // ItemStack itemStack = itemStacks.get(indexInArray); // ingredient = recipe.getIngredients().get(indexInRecipe); // if (!ingredient.test(itemStack)) { // if (ingredient.getMatchingStacks().length > 0) { // ModCyclic.LOGGER.info(indexInArray + "=indexInArray; " + itemStack + " does not match-> " + ingredient.getMatchingStacks()[0]); // } // return false; // } // indexInRecipe++; // } // } // return true; } public void reset() { this.hasValidRecipe = false; this.lastRecipeGrid = null; this.lastValidRecipe = null; this.shouldSearch = true; this.timer = 0; IItemHandler previewHandler = this.preview.orElse(null); if (previewHandler != null) { setPreviewSlot(previewHandler, ItemStack.EMPTY); } } private int countNonEmptyStacks(ArrayList<ItemStack> itemStacks) { int count = 0; for (ItemStack itemStack : itemStacks) { if (itemStack != ItemStack.EMPTY) { count++; } } return count; } private boolean doSizesMatch(ShapedRecipe recipe, ArrayList<ItemStack> itemStacks) { int ingredientCount = 0; int itemStackCount = 0; for (Ingredient ingredient : recipe.getIngredients()) { if (!ingredient.test(ItemStack.EMPTY)) { ingredientCount++; } } for (ItemStack itemStack : itemStacks) { if (itemStack != ItemStack.EMPTY) { itemStackCount++; } } return ingredientCount == itemStackCount; } @Override public ITextComponent getDisplayName() { return new StringTextComponent(getType().getRegistryName().getPath()); } @Override public Container createMenu(int i, PlayerInventory playerInventory, PlayerEntity playerEntity) { return new ContainerCrafter(i, world, pos, playerInventory, playerEntity); } @Override public <T> LazyOptional<T> getCapability(Capability<T> cap, Direction side) { if (cap == CapabilityEnergy.ENERGY && POWERCONF.get() > 0) { return energyCap.cast(); } if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { return inventoryCap.cast(); } return super.getCapability(cap, side); } public <T> LazyOptional<T> getCapability(Capability<T> cap, ItemHandlers type) { if (cap == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY) { switch (type) { case INPUT: return input.cast(); case OUTPUT: return output.cast(); case GRID: return gridCap.cast(); case PREVIEW: return preview.cast(); } } return null; } @Override public void read(BlockState bs, CompoundNBT tag) { energyCap.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("energy"))); input.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("input"))); output.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("output"))); gridCap.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("grid"))); preview.ifPresent(h -> ((INBTSerializable<CompoundNBT>) h).deserializeNBT(tag.getCompound("preview"))); super.read(bs, tag); } @Override public CompoundNBT write(CompoundNBT tag) { energyCap.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("energy", compound); }); input.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("input", compound); }); output.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("output", compound); }); gridCap.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("grid", compound); }); preview.ifPresent(h -> { CompoundNBT compound = ((INBTSerializable<CompoundNBT>) h).serializeNBT(); tag.put("preview", compound); }); return super.write(tag); } @Override public int getField(int id) { switch (TileCrafter.Fields.values()[id]) { case TIMER: return timer; case REDSTONE: return this.needsRedstone; case RENDER: return render; } return -1; } @Override public void setField(int id, int value) { switch (TileCrafter.Fields.values()[id]) { case TIMER: this.timer = value; break; case REDSTONE: this.needsRedstone = value % 2; break; case RENDER: this.render = value % 2; break; } } }
getContainerItem to output fix
src/main/java/com/lothrazar/cyclic/block/crafter/TileCrafter.java
getContainerItem to output fix
<ide><path>rc/main/java/com/lothrazar/cyclic/block/crafter/TileCrafter.java <ide> ModCyclic.LOGGER.info(i + "getContainerItem " + recipeLeftover.getContainerItem()); <ide> //not just 1 <ide> ItemStack result = recipeLeftover.getContainerItem().copy(); <del> for (int j = 0; j < inputHandler.getSlots(); j++) { <add> for (int j = 0; j < outHandler.getSlots(); j++) { <ide> //test it <del> result = this.inputHandler.insertItem(j, result, false); <add> result = this.outHandler.insertItem(j, result, false); <ide> if (result.isEmpty()) { <ide> break; <ide> }
JavaScript
mit
4e33fb760670a2af7dc0d00ebe64eec8ed71ab77
0
Noojuno/ludumdare,sgstair/ludumdare,local-minimum/ludumdare,Noojuno/ludumdare,povrazor/ludumdare,Noojuno/ludumdare,ludumdare/ludumdare,zwrawr/ludumdare,sgstair/ludumdare,Noojuno/ludumdare,povrazor/ludumdare,local-minimum/ludumdare,zwrawr/ludumdare,ludumdare/ludumdare,local-minimum/ludumdare,ludumdare/ludumdare,zwrawr/ludumdare,sgstair/ludumdare,povrazor/ludumdare,local-minimum/ludumdare,povrazor/ludumdare,ludumdare/ludumdare,sgstair/ludumdare,zwrawr/ludumdare
import {h, Component} from 'preact/preact'; import SVGIcon from 'com/svg-icon/icon'; export default class YoutubeEmbed extends Component { constructor(props) { super(props); this.state = { 'iframe': false }; this.onClick = this.onClick.bind(this); } onClick(e) { this.setState({'iframe': true}); } render(props, state) { var yt_thumbnail_prefix = "https://i.ytimg.com/vi/"; var yt_thumbnail_suffix = "/mqdefault.jpg"; var url = extractFromURL(props.href); var video_id = url.args.v; var args = ['autoplay=1']; if (url.args.t) { args.push('start=' + parseInt(url.args.t)); } if (state.iframe) { return ( <div class="embed-video"> <div class="-video"> <iframe src={'https://www.youtube.com/embed/' + video_id + '?' + args.join('&')} frameborder="0" allowfullscreen></iframe> </div> </div> ); } return ( <div class="embed-video"> <div class="-thumbnail"> <div class="-overlay" onclick={this.onClick} href={props.href}> <div class="-play"> <SVGIcon middle>play</SVGIcon> </div> <div class="-external"> <a href={props.href} target="_blank" onclick={(e) => {e.stopPropagation();}}> <SVGIcon middle block>youtube</SVGIcon> </a> </div> </div> <img src={yt_thumbnail_prefix + video_id + yt_thumbnail_suffix}/> </div> </div> ); } }
src/com/autoembed/youtube.js
import {h, Component} from 'preact/preact'; import SVGIcon from 'com/svg-icon/icon'; export default class YoutubeEmbed extends Component { constructor(props) { super(props); this.state = { 'iframe': false }; this.onClick = this.onClick.bind(this); } onClick(e) { this.setState({'iframe': true}); } render(props, state) { var yt_thumbnail_prefix = "https://i.ytimg.com/vi/"; var yt_thumbnail_suffix = "/mqdefault.jpg"; var url = extractFromURL(props.href); var video_id = url.args.v; var args = ['autoplay=1']; if (url.args.t) { args.push('start=' + parseInt(url.args.t)); } if (state.iframe) { return ( <div class="embed-video"> <div class="-video"> <iframe src={'https://www.youtube.com/embed/' + video_id + '?' + args.join('&')} frameborder="0" allowfullscreen></iframe> </div> </div> ); } return ( <div class="embed-video"> <div class="-thumbnail"> <div class="-overlay" onclick={this.onClick} href={props.href}> <div class="-play"> <SVGIcon middle>play</SVGIcon> </div> <div class="-external"> <a href={props.href} target="_blank"> <SVGIcon middle block>youtube</SVGIcon> </a> </div> </div> <img src={yt_thumbnail_prefix + video_id + yt_thumbnail_suffix}/> </div> </div> ); } }
Fixed youtube autoembed
src/com/autoembed/youtube.js
Fixed youtube autoembed
<ide><path>rc/com/autoembed/youtube.js <ide> <SVGIcon middle>play</SVGIcon> <ide> </div> <ide> <div class="-external"> <del> <a href={props.href} target="_blank"> <add> <a href={props.href} target="_blank" onclick={(e) => {e.stopPropagation();}}> <ide> <SVGIcon middle block>youtube</SVGIcon> <ide> </a> <ide> </div>
JavaScript
mit
893443b0b26fb313d7900005601e839050465d2f
0
KleeGroup/focus-core
//Dependencies. import CoreStore from '../CoreStore'; import getDefinition from './definition'; import Immutable from 'immutable'; /** * Class standing for the cartridge store. */ class ApplicationStore extends CoreStore { constructor(conf) { conf = conf || {}; conf.definition = conf.definition || getDefinition(); super(conf); } /** * Update the mode value. * @param {object} dataNode - The value of the data. */ updateMode(dataNode) { const modeData = (this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({})) .set(dataNode.newMode, 1) .set(dataNode.previousMode, 0); this.data = this.data.set('mode', modeData); this.willEmit('mode:change'); } } export default ApplicationStore;
src/store/application/store.js
//Dependencies. import CoreStore from '../CoreStore'; import getDefinition from './definition'; import Immutable from 'immutable'; /** * Class standing for the cartridge store. */ class ApplicationStore extends CoreStore { constructor(conf) { conf = conf || {}; conf.definition = conf.definition || getDefinition(); super(conf); } /** * Update the mode value. * @param {object} dataNode - The value of the data. */ updateMode(dataNode) { let modeData = this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({}); let newModeValue = modeData.has(dataNode.newMode) ? (modeData.get(dataNode.newMode) + 1) : 1; //Add a check to not have a negative mode, but it should not happen. let previousModeValue = modeData.has(dataNode.previousMode) ? (modeData.get(dataNode.previousMode) - 1) : 0; this.data = this.data.set('mode', modeData.set(dataNode.newMode, newModeValue).set(dataNode.previousMode, previousModeValue) ); this.willEmit('mode:change'); } } export default ApplicationStore;
Application Store : mode should be only 0 or 1 (not 2, -1, ...)
src/store/application/store.js
Application Store : mode should be only 0 or 1 (not 2, -1, ...)
<ide><path>rc/store/application/store.js <ide> super(conf); <ide> } <ide> /** <del> * Update the mode value. <del> * @param {object} dataNode - The value of the data. <del> */ <add> * Update the mode value. <add> * @param {object} dataNode - The value of the data. <add> */ <ide> updateMode(dataNode) { <del> let modeData = this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({}); <del> let newModeValue = modeData.has(dataNode.newMode) ? (modeData.get(dataNode.newMode) + 1) : 1; <del> //Add a check to not have a negative mode, but it should not happen. <del> let previousModeValue = modeData.has(dataNode.previousMode) ? (modeData.get(dataNode.previousMode) - 1) : 0; <del> this.data = this.data.set('mode', <del> modeData.set(dataNode.newMode, newModeValue).set(dataNode.previousMode, previousModeValue) <del> ); <add> const modeData = (this.data.has('mode') ? this.data.get('mode') : Immutable.fromJS({})) <add> .set(dataNode.newMode, 1) <add> .set(dataNode.previousMode, 0); <add> this.data = this.data.set('mode', modeData); <ide> this.willEmit('mode:change'); <ide> } <ide> }
Java
apache-2.0
f3a33673fcc39e3673a1b1e712fb44fcf781d8f5
0
apache/kylin,apache/kylin,apache/kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin,apache/kylin,apache/incubator-kylin
/* * 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.kylin.gridtable; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.debug.BackdoorToggles; import org.apache.kylin.common.util.ByteArray; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.ImmutableBitSet; import org.apache.kylin.common.util.Pair; import org.apache.kylin.cube.CubeSegment; import org.apache.kylin.cube.common.FuzzyValueCombination; import org.apache.kylin.cube.cuboid.Cuboid; import org.apache.kylin.cube.gridtable.CubeGridTable; import org.apache.kylin.cube.gridtable.CuboidToGridTableMapping; import org.apache.kylin.cube.model.CubeDesc; import org.apache.kylin.metadata.datatype.DataType; import org.apache.kylin.metadata.filter.CompareTupleFilter; import org.apache.kylin.metadata.filter.ConstantTupleFilter; import org.apache.kylin.metadata.filter.LogicalTupleFilter; import org.apache.kylin.metadata.filter.TupleFilter; import org.apache.kylin.metadata.filter.TupleFilter.FilterOperatorEnum; import org.apache.kylin.metadata.model.FunctionDesc; import org.apache.kylin.metadata.model.TblColRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class GTScanRangePlanner { private static final Logger logger = LoggerFactory.getLogger(GTScanRangePlanner.class); protected int maxScanRanges; protected int maxFuzzyKeys; //non-GT protected CubeSegment cubeSegment; protected CubeDesc cubeDesc; protected Cuboid cuboid; protected TupleFilter filter; protected Set<TblColRef> dimensions; protected Set<TblColRef> groupbyDims; protected Set<TblColRef> filterDims; protected Collection<FunctionDesc> metrics; //GT protected TupleFilter gtFilter; protected GTInfo gtInfo; protected Pair<ByteArray, ByteArray> gtStartAndEnd; protected TblColRef gtPartitionCol; protected ImmutableBitSet gtDimensions; protected ImmutableBitSet gtAggrGroups; protected ImmutableBitSet gtAggrMetrics; protected String[] gtAggrFuncs; final protected RecordComparator rangeStartComparator; final protected RecordComparator rangeEndComparator; final protected RecordComparator rangeStartEndComparator; public GTScanRangePlanner(CubeSegment cubeSegment, Cuboid cuboid, TupleFilter filter, Set<TblColRef> dimensions, Set<TblColRef> groupbyDims, // Collection<FunctionDesc> metrics) { this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryStorageVisitScanRangeMax(); this.maxFuzzyKeys = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); this.cubeSegment = cubeSegment; this.cubeDesc = cubeSegment.getCubeDesc(); this.cuboid = cuboid; this.dimensions = dimensions; this.groupbyDims = groupbyDims; this.filter = filter; this.metrics = metrics; this.filterDims = Sets.newHashSet(); TupleFilter.collectColumns(filter, this.filterDims); this.gtInfo = CubeGridTable.newGTInfo(cubeSegment, cuboid.getId()); CuboidToGridTableMapping mapping = cuboid.getCuboidToGridTableMapping(); IGTComparator comp = gtInfo.codeSystem.getComparator(); //start key GTRecord compare to start key GTRecord this.rangeStartComparator = getRangeStartComparator(comp); //stop key GTRecord compare to stop key GTRecord this.rangeEndComparator = getRangeEndComparator(comp); //start key GTRecord compare to stop key GTRecord this.rangeStartEndComparator = getRangeStartEndComparator(comp); //replace the constant values in filter to dictionary codes this.gtFilter = GTUtil.convertFilterColumnsAndConstants(filter, gtInfo, mapping.getCuboidDimensionsInGTOrder(), this.groupbyDims); this.gtDimensions = makeGridTableColumns(mapping, dimensions); this.gtAggrGroups = makeGridTableColumns(mapping, replaceDerivedColumns(groupbyDims, cubeSegment.getCubeDesc())); this.gtAggrMetrics = makeGridTableColumns(mapping, metrics); this.gtAggrFuncs = makeAggrFuncs(mapping, metrics); if (cubeSegment.getCubeDesc().getModel().getPartitionDesc().isPartitioned()) { int index = mapping.getIndexOf(cubeSegment.getCubeDesc().getModel().getPartitionDesc().getPartitionDateColumnRef()); if (index >= 0) { this.gtStartAndEnd = getSegmentStartAndEnd(index); this.gtPartitionCol = gtInfo.colRef(index); } } } /** * constrcut GTScanRangePlanner with incomplete information. only be used for UT * @param info * @param gtStartAndEnd * @param gtPartitionCol * @param gtFilter */ public GTScanRangePlanner(GTInfo info, Pair<ByteArray, ByteArray> gtStartAndEnd, TblColRef gtPartitionCol, TupleFilter gtFilter) { this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryStorageVisitScanRangeMax(); this.maxFuzzyKeys = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); this.gtInfo = info; IGTComparator comp = gtInfo.codeSystem.getComparator(); //start key GTRecord compare to start key GTRecord this.rangeStartComparator = getRangeStartComparator(comp); //stop key GTRecord compare to stop key GTRecord this.rangeEndComparator = getRangeEndComparator(comp); //start key GTRecord compare to stop key GTRecord this.rangeStartEndComparator = getRangeStartEndComparator(comp); this.gtFilter = gtFilter; this.gtStartAndEnd = gtStartAndEnd; this.gtPartitionCol = gtPartitionCol; } public GTScanRequest planScanRequest(boolean allowPreAggregate) { GTScanRequest scanRequest; List<GTScanRange> scanRanges = this.planScanRanges(); if (scanRanges != null && scanRanges.size() != 0) { scanRequest = new GTScanRequest(gtInfo, scanRanges, gtDimensions, gtAggrGroups, gtAggrMetrics, gtAggrFuncs, gtFilter, allowPreAggregate, cubeSegment.getCubeInstance().getConfig().getQueryCoprocessorMemGB()); } else { scanRequest = null; } return scanRequest; } /** * Overwrite this method to provide smarter storage visit plans * @return */ public List<GTScanRange> planScanRanges() { TupleFilter flatFilter = flattenToOrAndFilter(gtFilter); List<Collection<ColumnRange>> orAndDimRanges = translateToOrAndDimRanges(flatFilter); List<GTScanRange> scanRanges = Lists.newArrayListWithCapacity(orAndDimRanges.size()); for (Collection<ColumnRange> andDimRanges : orAndDimRanges) { GTScanRange scanRange = newScanRange(andDimRanges); if (scanRange != null) scanRanges.add(scanRange); } List<GTScanRange> mergedRanges = mergeOverlapRanges(scanRanges); mergedRanges = mergeTooManyRanges(mergedRanges, maxScanRanges); return mergedRanges; } private Pair<ByteArray, ByteArray> getSegmentStartAndEnd(int index) { ByteArray start; if (cubeSegment.getDateRangeStart() != Long.MIN_VALUE) { start = encodeTime(cubeSegment.getDateRangeStart(), index, 1); } else { start = new ByteArray(); } ByteArray end; if (cubeSegment.getDateRangeEnd() != Long.MAX_VALUE) { end = encodeTime(cubeSegment.getDateRangeEnd(), index, -1); } else { end = new ByteArray(); } return Pair.newPair(start, end); } private ByteArray encodeTime(long ts, int index, int roundingFlag) { String value; DataType partitionColType = gtInfo.getColumnType(index); if (partitionColType.isDate()) { value = DateFormat.formatToDateStr(ts); } else if (partitionColType.isDatetime() || partitionColType.isTimestamp()) { value = DateFormat.formatToTimeWithoutMilliStr(ts); } else if (partitionColType.isStringFamily()) { String partitionDateFormat = cubeSegment.getCubeDesc().getModel().getPartitionDesc().getPartitionDateFormat(); if (StringUtils.isEmpty(partitionDateFormat)) partitionDateFormat = DateFormat.DEFAULT_DATE_PATTERN; value = DateFormat.formatToDateStr(ts, partitionDateFormat); } else { throw new RuntimeException("Type " + partitionColType + " is not valid partition column type"); } ByteBuffer buffer = ByteBuffer.allocate(gtInfo.getMaxColumnLength()); gtInfo.getCodeSystem().encodeColumnValue(index, value, roundingFlag, buffer); return ByteArray.copyOf(buffer.array(), 0, buffer.position()); } private Set<TblColRef> replaceDerivedColumns(Set<TblColRef> input, CubeDesc cubeDesc) { Set<TblColRef> ret = Sets.newHashSet(); for (TblColRef col : input) { if (cubeDesc.hasHostColumn(col)) { for (TblColRef host : cubeDesc.getHostInfo(col).columns) { ret.add(host); } } else { ret.add(col); } } return ret; } private ImmutableBitSet makeGridTableColumns(CuboidToGridTableMapping mapping, Set<TblColRef> dimensions) { BitSet result = new BitSet(); for (TblColRef dim : dimensions) { int idx = mapping.getIndexOf(dim); if (idx >= 0) result.set(idx); } return new ImmutableBitSet(result); } private ImmutableBitSet makeGridTableColumns(CuboidToGridTableMapping mapping, Collection<FunctionDesc> metrics) { BitSet result = new BitSet(); for (FunctionDesc metric : metrics) { int idx = mapping.getIndexOf(metric); if (idx < 0) throw new IllegalStateException(metric + " not found in " + mapping); result.set(idx); } return new ImmutableBitSet(result); } private String[] makeAggrFuncs(final CuboidToGridTableMapping mapping, Collection<FunctionDesc> metrics) { //metrics are represented in ImmutableBitSet, which loses order information //sort the aggrFuns to align with metrics natural order List<FunctionDesc> metricList = Lists.newArrayList(metrics); Collections.sort(metricList, new Comparator<FunctionDesc>() { @Override public int compare(FunctionDesc o1, FunctionDesc o2) { int a = mapping.getIndexOf(o1); int b = mapping.getIndexOf(o2); return a - b; } }); String[] result = new String[metricList.size()]; int i = 0; for (FunctionDesc metric : metricList) { result[i++] = metric.getExpression(); } return result; } private String makeReadable(ByteArray byteArray) { if (byteArray == null) { return null; } else { return byteArray.toReadableText(); } } protected GTScanRange newScanRange(Collection<ColumnRange> andDimRanges) { GTRecord pkStart = new GTRecord(gtInfo); GTRecord pkEnd = new GTRecord(gtInfo); Map<Integer, Set<ByteArray>> fuzzyValues = Maps.newHashMap(); List<GTRecord> fuzzyKeys; for (ColumnRange range : andDimRanges) { if (gtPartitionCol != null && range.column.equals(gtPartitionCol)) { if (rangeStartEndComparator.comparator.compare(gtStartAndEnd.getFirst(), range.end) <= 0 // && (rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) < 0 // || rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) == 0 // && (range.op == FilterOperatorEnum.EQ || range.op == FilterOperatorEnum.LTE || range.op == FilterOperatorEnum.GTE || range.op == FilterOperatorEnum.IN))) { //segment range is [Closed,Open), but segmentStartAndEnd.getSecond() might be rounded, so use <= when has equals in condition. } else { logger.debug("Pre-check partition col filter failed, partitionColRef {}, segment start {}, segment end {}, range begin {}, range end {}", // new Object[] { gtPartitionCol, makeReadable(gtStartAndEnd.getFirst()), makeReadable(gtStartAndEnd.getSecond()), makeReadable(range.begin), makeReadable(range.end) }); return null; } } int col = range.column.getColumnDesc().getZeroBasedIndex(); if (!gtInfo.primaryKey.get(col)) continue; pkStart.set(col, range.begin); pkEnd.set(col, range.end); if (range.valueSet != null && !range.valueSet.isEmpty()) { fuzzyValues.put(col, range.valueSet); } } fuzzyKeys = buildFuzzyKeys(fuzzyValues); return new GTScanRange(pkStart, pkEnd, fuzzyKeys); } private List<GTRecord> buildFuzzyKeys(Map<Integer, Set<ByteArray>> fuzzyValueSet) { ArrayList<GTRecord> result = Lists.newArrayList(); if (fuzzyValueSet.isEmpty()) return result; // debug/profiling purpose if (BackdoorToggles.getDisableFuzzyKey()) { logger.info("The execution of this query will not use fuzzy key"); return result; } List<Map<Integer, ByteArray>> fuzzyValueCombinations = FuzzyValueCombination.calculate(fuzzyValueSet, maxFuzzyKeys); for (Map<Integer, ByteArray> fuzzyValue : fuzzyValueCombinations) { BitSet bitSet = new BitSet(gtInfo.getColumnCount()); for (Map.Entry<Integer, ByteArray> entry : fuzzyValue.entrySet()) { bitSet.set(entry.getKey()); } GTRecord fuzzy = new GTRecord(gtInfo, new ImmutableBitSet(bitSet)); for (Map.Entry<Integer, ByteArray> entry : fuzzyValue.entrySet()) { fuzzy.set(entry.getKey(), entry.getValue()); } result.add(fuzzy); } return result; } protected TupleFilter flattenToOrAndFilter(TupleFilter filter) { if (filter == null) return null; TupleFilter flatFilter = filter.flatFilter(); // normalize to OR-AND filter if (flatFilter.getOperator() == FilterOperatorEnum.AND) { LogicalTupleFilter f = new LogicalTupleFilter(FilterOperatorEnum.OR); f.addChild(flatFilter); flatFilter = f; } if (flatFilter.getOperator() != FilterOperatorEnum.OR) throw new IllegalStateException(); return flatFilter; } protected List<Collection<ColumnRange>> translateToOrAndDimRanges(TupleFilter flatFilter) { List<Collection<ColumnRange>> result = Lists.newArrayList(); if (flatFilter == null) { result.add(Collections.<ColumnRange> emptyList()); return result; } for (TupleFilter andFilter : flatFilter.getChildren()) { if (andFilter.getOperator() != FilterOperatorEnum.AND) throw new IllegalStateException("Filter should be AND instead of " + andFilter); Collection<ColumnRange> andRanges = translateToAndDimRanges(andFilter.getChildren()); if (andRanges != null) { result.add(andRanges); } } return preEvaluateConstantConditions(result); } private Collection<ColumnRange> translateToAndDimRanges(List<? extends TupleFilter> andFilters) { Map<TblColRef, ColumnRange> rangeMap = new HashMap<TblColRef, ColumnRange>(); for (TupleFilter filter : andFilters) { if ((filter instanceof CompareTupleFilter) == false) { if (filter instanceof ConstantTupleFilter && !filter.evaluate(null, null)) { return null; } else { continue; } } CompareTupleFilter comp = (CompareTupleFilter) filter; if (comp.getColumn() == null) { continue; } @SuppressWarnings("unchecked") ColumnRange newRange = new ColumnRange(comp.getColumn(), (Set<ByteArray>) comp.getValues(), comp.getOperator()); ColumnRange existing = rangeMap.get(newRange.column); if (existing == null) { rangeMap.put(newRange.column, newRange); } else { existing.andMerge(newRange); } } return rangeMap.values(); } private List<Collection<ColumnRange>> preEvaluateConstantConditions(List<Collection<ColumnRange>> orAndRanges) { boolean globalAlwaysTrue = false; Iterator<Collection<ColumnRange>> iterator = orAndRanges.iterator(); while (iterator.hasNext()) { Collection<ColumnRange> andRanges = iterator.next(); Iterator<ColumnRange> iterator2 = andRanges.iterator(); boolean hasAlwaysFalse = false; while (iterator2.hasNext()) { ColumnRange range = iterator2.next(); if (range.satisfyAll()) iterator2.remove(); else if (range.satisfyNone()) hasAlwaysFalse = true; } if (hasAlwaysFalse) { iterator.remove(); } else if (andRanges.isEmpty()) { globalAlwaysTrue = true; break; } } // return empty OR list means global false // return an empty AND collection inside OR list means global true if (globalAlwaysTrue) { orAndRanges.clear(); orAndRanges.add(Collections.<ColumnRange> emptyList()); } return orAndRanges; } protected List<GTScanRange> mergeOverlapRanges(List<GTScanRange> ranges) { if (ranges.size() <= 1) { return ranges; } // sort ranges by start key Collections.sort(ranges, new Comparator<GTScanRange>() { @Override public int compare(GTScanRange a, GTScanRange b) { return rangeStartComparator.compare(a.pkStart, b.pkStart); } }); // merge the overlap range List<GTScanRange> mergedRanges = new ArrayList<GTScanRange>(); int mergeBeginIndex = 0; GTRecord mergeEnd = ranges.get(0).pkEnd; for (int index = 1; index < ranges.size(); index++) { GTScanRange range = ranges.get(index); // if overlap, swallow it if (rangeStartEndComparator.compare(range.pkStart, mergeEnd) <= 0) { mergeEnd = rangeEndComparator.max(mergeEnd, range.pkEnd); continue; } // not overlap, split here GTScanRange mergedRange = mergeKeyRange(ranges.subList(mergeBeginIndex, index)); mergedRanges.add(mergedRange); // start new split mergeBeginIndex = index; mergeEnd = range.pkEnd; } // don't miss the last range GTScanRange mergedRange = mergeKeyRange(ranges.subList(mergeBeginIndex, ranges.size())); mergedRanges.add(mergedRange); return mergedRanges; } private GTScanRange mergeKeyRange(List<GTScanRange> ranges) { GTScanRange first = ranges.get(0); if (ranges.size() == 1) return first; GTRecord start = first.pkStart; GTRecord end = first.pkEnd; List<GTRecord> newFuzzyKeys = new ArrayList<GTRecord>(); boolean hasNonFuzzyRange = false; for (GTScanRange range : ranges) { hasNonFuzzyRange = hasNonFuzzyRange || range.fuzzyKeys.isEmpty(); newFuzzyKeys.addAll(range.fuzzyKeys); end = rangeEndComparator.max(end, range.pkEnd); } // if any range is non-fuzzy, then all fuzzy keys must be cleared // also too many fuzzy keys will slow down HBase scan if (hasNonFuzzyRange || newFuzzyKeys.size() > maxFuzzyKeys) { newFuzzyKeys.clear(); } return new GTScanRange(start, end, newFuzzyKeys); } protected List<GTScanRange> mergeTooManyRanges(List<GTScanRange> ranges, int maxRanges) { if (ranges.size() <= maxRanges) { return ranges; } // TODO: check the distance between range and merge the large distance range List<GTScanRange> result = new ArrayList<GTScanRange>(1); GTScanRange mergedRange = mergeKeyRange(ranges); result.add(mergedRange); return result; } public int getMaxScanRanges() { return maxScanRanges; } public void setMaxScanRanges(int maxScanRanges) { this.maxScanRanges = maxScanRanges; } protected class ColumnRange { private TblColRef column; private ByteArray begin = ByteArray.EMPTY; private ByteArray end = ByteArray.EMPTY; private Set<ByteArray> valueSet; private FilterOperatorEnum op; public ColumnRange(TblColRef column, Set<ByteArray> values, FilterOperatorEnum op) { this.column = column; this.op = op; switch (op) { case EQ: case IN: valueSet = new HashSet<ByteArray>(values); refreshBeginEndFromEquals(); break; case LT: case LTE: end = rangeEndComparator.comparator.max(values); break; case GT: case GTE: begin = rangeStartComparator.comparator.min(values); break; case NEQ: case NOTIN: case ISNULL: case ISNOTNULL: // let Optiq filter it! break; default: throw new UnsupportedOperationException(op.name()); } } void copy(TblColRef column, ByteArray beginValue, ByteArray endValue, Set<ByteArray> equalValues) { this.column = column; this.begin = beginValue; this.end = endValue; this.valueSet = equalValues; } private void refreshBeginEndFromEquals() { if (valueSet.isEmpty()) { begin = ByteArray.EMPTY; end = ByteArray.EMPTY; } else { begin = rangeStartComparator.comparator.min(valueSet); end = rangeEndComparator.comparator.max(valueSet); } } public boolean satisfyAll() { return begin.array() == null && end.array() == null; // the NEQ case } public boolean satisfyNone() { if (valueSet != null) { return valueSet.isEmpty(); } else if (begin.array() != null && end.array() != null) { return gtInfo.codeSystem.getComparator().compare(begin, end) > 0; } else { return false; } } public void andMerge(ColumnRange another) { assert this.column.equals(another.column); if (another.satisfyAll()) { return; } if (this.satisfyAll()) { copy(another.column, another.begin, another.end, another.valueSet); return; } if (this.valueSet != null && another.valueSet != null) { this.valueSet.retainAll(another.valueSet); refreshBeginEndFromEquals(); return; } if (this.valueSet != null) { this.valueSet = filter(this.valueSet, another.begin, another.end); refreshBeginEndFromEquals(); return; } if (another.valueSet != null) { this.valueSet = filter(another.valueSet, this.begin, this.end); refreshBeginEndFromEquals(); return; } this.begin = rangeStartComparator.comparator.max(this.begin, another.begin); this.end = rangeEndComparator.comparator.min(this.end, another.end); } private Set<ByteArray> filter(Set<ByteArray> equalValues, ByteArray beginValue, ByteArray endValue) { Set<ByteArray> result = Sets.newHashSetWithExpectedSize(equalValues.size()); for (ByteArray v : equalValues) { if (rangeStartEndComparator.comparator.compare(beginValue, v) <= 0 && rangeStartEndComparator.comparator.compare(v, endValue) <= 0) { result.add(v); } } return equalValues; } public String toString() { if (valueSet == null) { return column.getName() + " between " + begin + " and " + end; } else { return column.getName() + " in " + valueSet; } } } public static abstract class ComparatorEx<T> implements Comparator<T> { public T min(Collection<T> v) { if (v.size() <= 0) { return null; } Iterator<T> iterator = v.iterator(); T min = iterator.next(); while (iterator.hasNext()) { min = min(min, iterator.next()); } return min; } public T max(Collection<T> v) { if (v.size() <= 0) { return null; } Iterator<T> iterator = v.iterator(); T max = iterator.next(); while (iterator.hasNext()) { max = max(max, iterator.next()); } return max; } public T min(T a, T b) { return compare(a, b) <= 0 ? a : b; } public T max(T a, T b) { return compare(a, b) >= 0 ? a : b; } public boolean between(T v, T start, T end) { return compare(start, v) <= 0 && compare(v, end) <= 0; } } public static RecordComparator getRangeStartComparator(final IGTComparator comp) { return new RecordComparator(new ComparatorEx<ByteArray>() { @Override public int compare(ByteArray a, ByteArray b) { if (a.array() == null) { if (b.array() == null) { return 0; } else { return -1; } } else if (b.array() == null) { return 1; } else { return comp.compare(a, b); } } }); } public static RecordComparator getRangeEndComparator(final IGTComparator comp) { return new RecordComparator(new ComparatorEx<ByteArray>() { @Override public int compare(ByteArray a, ByteArray b) { if (a.array() == null) { if (b.array() == null) { return 0; } else { return 1; } } else if (b.array() == null) { return -1; } else { return comp.compare(a, b); } } }); } public static RecordComparator getRangeStartEndComparator(final IGTComparator comp) { return new AsymmetricRecordComparator(new ComparatorEx<ByteArray>() { @Override public int compare(ByteArray a, ByteArray b) { if (a.array() == null || b.array() == null) { return -1; } else { return comp.compare(a, b); } } }); } private static class RecordComparator extends ComparatorEx<GTRecord> { final ComparatorEx<ByteArray> comparator; RecordComparator(ComparatorEx<ByteArray> byteComparator) { this.comparator = byteComparator; } @Override public int compare(GTRecord a, GTRecord b) { assert a.info == b.info; assert a.maskForEqualHashComp() == b.maskForEqualHashComp(); ImmutableBitSet mask = a.maskForEqualHashComp(); int comp; for (int i = 0; i < mask.trueBitCount(); i++) { int c = mask.trueBitAt(i); comp = comparator.compare(a.cols[c], b.cols[c]); if (comp != 0) return comp; } return 0; // equals } } /** * asymmetric means compare(a,b) > 0 does not cause compare(b,a) < 0 * so min max functions will not be supported */ private static class AsymmetricRecordComparator extends RecordComparator { AsymmetricRecordComparator(ComparatorEx<ByteArray> byteComparator) { super(byteComparator); } public GTRecord min(Collection<GTRecord> v) { throw new UnsupportedOperationException(); } public GTRecord max(Collection<GTRecord> v) { throw new UnsupportedOperationException(); } public GTRecord min(GTRecord a, GTRecord b) { throw new UnsupportedOperationException(); } public GTRecord max(GTRecord a, GTRecord b) { throw new UnsupportedOperationException(); } public boolean between(GTRecord v, GTRecord start, GTRecord end) { throw new UnsupportedOperationException(); } } }
core-cube/src/main/java/org/apache/kylin/gridtable/GTScanRangePlanner.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.kylin.gridtable; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.apache.kylin.common.KylinConfig; import org.apache.kylin.common.debug.BackdoorToggles; import org.apache.kylin.common.util.ByteArray; import org.apache.kylin.common.util.DateFormat; import org.apache.kylin.common.util.ImmutableBitSet; import org.apache.kylin.common.util.Pair; import org.apache.kylin.cube.CubeSegment; import org.apache.kylin.cube.common.FuzzyValueCombination; import org.apache.kylin.cube.cuboid.Cuboid; import org.apache.kylin.cube.gridtable.CubeGridTable; import org.apache.kylin.cube.gridtable.CuboidToGridTableMapping; import org.apache.kylin.cube.model.CubeDesc; import org.apache.kylin.metadata.datatype.DataType; import org.apache.kylin.metadata.filter.CompareTupleFilter; import org.apache.kylin.metadata.filter.ConstantTupleFilter; import org.apache.kylin.metadata.filter.LogicalTupleFilter; import org.apache.kylin.metadata.filter.TupleFilter; import org.apache.kylin.metadata.filter.TupleFilter.FilterOperatorEnum; import org.apache.kylin.metadata.model.FunctionDesc; import org.apache.kylin.metadata.model.TblColRef; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; public class GTScanRangePlanner { private static final Logger logger = LoggerFactory.getLogger(GTScanRangePlanner.class); private static final int MAX_HBASE_FUZZY_KEYS = 100; protected int maxScanRanges; //non-GT protected CubeSegment cubeSegment; protected CubeDesc cubeDesc; protected Cuboid cuboid; protected TupleFilter filter; protected Set<TblColRef> dimensions; protected Set<TblColRef> groupbyDims; protected Set<TblColRef> filterDims; protected Collection<FunctionDesc> metrics; //GT protected TupleFilter gtFilter; protected GTInfo gtInfo; protected Pair<ByteArray, ByteArray> gtStartAndEnd; protected TblColRef gtPartitionCol; protected ImmutableBitSet gtDimensions; protected ImmutableBitSet gtAggrGroups; protected ImmutableBitSet gtAggrMetrics; protected String[] gtAggrFuncs; final protected RecordComparator rangeStartComparator; final protected RecordComparator rangeEndComparator; final protected RecordComparator rangeStartEndComparator; public GTScanRangePlanner(CubeSegment cubeSegment, Cuboid cuboid, TupleFilter filter, Set<TblColRef> dimensions, Set<TblColRef> groupbyDims, // Collection<FunctionDesc> metrics) { this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); this.cubeSegment = cubeSegment; this.cubeDesc = cubeSegment.getCubeDesc(); this.cuboid = cuboid; this.dimensions = dimensions; this.groupbyDims = groupbyDims; this.filter = filter; this.metrics = metrics; this.filterDims = Sets.newHashSet(); TupleFilter.collectColumns(filter, this.filterDims); this.gtInfo = CubeGridTable.newGTInfo(cubeSegment, cuboid.getId()); CuboidToGridTableMapping mapping = cuboid.getCuboidToGridTableMapping(); IGTComparator comp = gtInfo.codeSystem.getComparator(); //start key GTRecord compare to start key GTRecord this.rangeStartComparator = getRangeStartComparator(comp); //stop key GTRecord compare to stop key GTRecord this.rangeEndComparator = getRangeEndComparator(comp); //start key GTRecord compare to stop key GTRecord this.rangeStartEndComparator = getRangeStartEndComparator(comp); //replace the constant values in filter to dictionary codes this.gtFilter = GTUtil.convertFilterColumnsAndConstants(filter, gtInfo, mapping.getCuboidDimensionsInGTOrder(), this.groupbyDims); this.gtDimensions = makeGridTableColumns(mapping, dimensions); this.gtAggrGroups = makeGridTableColumns(mapping, replaceDerivedColumns(groupbyDims, cubeSegment.getCubeDesc())); this.gtAggrMetrics = makeGridTableColumns(mapping, metrics); this.gtAggrFuncs = makeAggrFuncs(mapping, metrics); if (cubeSegment.getCubeDesc().getModel().getPartitionDesc().isPartitioned()) { int index = mapping.getIndexOf(cubeSegment.getCubeDesc().getModel().getPartitionDesc().getPartitionDateColumnRef()); if (index >= 0) { this.gtStartAndEnd = getSegmentStartAndEnd(index); this.gtPartitionCol = gtInfo.colRef(index); } } } /** * constrcut GTScanRangePlanner with incomplete information. only be used for UT * @param info * @param gtStartAndEnd * @param gtPartitionCol * @param gtFilter */ public GTScanRangePlanner(GTInfo info, Pair<ByteArray, ByteArray> gtStartAndEnd, TblColRef gtPartitionCol, TupleFilter gtFilter) { this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); this.gtInfo = info; IGTComparator comp = gtInfo.codeSystem.getComparator(); //start key GTRecord compare to start key GTRecord this.rangeStartComparator = getRangeStartComparator(comp); //stop key GTRecord compare to stop key GTRecord this.rangeEndComparator = getRangeEndComparator(comp); //start key GTRecord compare to stop key GTRecord this.rangeStartEndComparator = getRangeStartEndComparator(comp); this.gtFilter = gtFilter; this.gtStartAndEnd = gtStartAndEnd; this.gtPartitionCol = gtPartitionCol; } public GTScanRequest planScanRequest(boolean allowPreAggregate) { GTScanRequest scanRequest; List<GTScanRange> scanRanges = this.planScanRanges(); if (scanRanges != null && scanRanges.size() != 0) { scanRequest = new GTScanRequest(gtInfo, scanRanges, gtDimensions, gtAggrGroups, gtAggrMetrics, gtAggrFuncs, gtFilter, allowPreAggregate, cubeSegment.getCubeInstance().getConfig().getQueryCoprocessorMemGB()); } else { scanRequest = null; } return scanRequest; } /** * Overwrite this method to provide smarter storage visit plans * @return */ public List<GTScanRange> planScanRanges() { TupleFilter flatFilter = flattenToOrAndFilter(gtFilter); List<Collection<ColumnRange>> orAndDimRanges = translateToOrAndDimRanges(flatFilter); List<GTScanRange> scanRanges = Lists.newArrayListWithCapacity(orAndDimRanges.size()); for (Collection<ColumnRange> andDimRanges : orAndDimRanges) { GTScanRange scanRange = newScanRange(andDimRanges); if (scanRange != null) scanRanges.add(scanRange); } List<GTScanRange> mergedRanges = mergeOverlapRanges(scanRanges); mergedRanges = mergeTooManyRanges(mergedRanges, maxScanRanges); return mergedRanges; } private Pair<ByteArray, ByteArray> getSegmentStartAndEnd(int index) { ByteArray start; if (cubeSegment.getDateRangeStart() != Long.MIN_VALUE) { start = encodeTime(cubeSegment.getDateRangeStart(), index, 1); } else { start = new ByteArray(); } ByteArray end; if (cubeSegment.getDateRangeEnd() != Long.MAX_VALUE) { end = encodeTime(cubeSegment.getDateRangeEnd(), index, -1); } else { end = new ByteArray(); } return Pair.newPair(start, end); } private ByteArray encodeTime(long ts, int index, int roundingFlag) { String value; DataType partitionColType = gtInfo.getColumnType(index); if (partitionColType.isDate()) { value = DateFormat.formatToDateStr(ts); } else if (partitionColType.isDatetime() || partitionColType.isTimestamp()) { value = DateFormat.formatToTimeWithoutMilliStr(ts); } else if (partitionColType.isStringFamily()) { String partitionDateFormat = cubeSegment.getCubeDesc().getModel().getPartitionDesc().getPartitionDateFormat(); if (StringUtils.isEmpty(partitionDateFormat)) partitionDateFormat = DateFormat.DEFAULT_DATE_PATTERN; value = DateFormat.formatToDateStr(ts, partitionDateFormat); } else { throw new RuntimeException("Type " + partitionColType + " is not valid partition column type"); } ByteBuffer buffer = ByteBuffer.allocate(gtInfo.getMaxColumnLength()); gtInfo.getCodeSystem().encodeColumnValue(index, value, roundingFlag, buffer); return ByteArray.copyOf(buffer.array(), 0, buffer.position()); } private Set<TblColRef> replaceDerivedColumns(Set<TblColRef> input, CubeDesc cubeDesc) { Set<TblColRef> ret = Sets.newHashSet(); for (TblColRef col : input) { if (cubeDesc.hasHostColumn(col)) { for (TblColRef host : cubeDesc.getHostInfo(col).columns) { ret.add(host); } } else { ret.add(col); } } return ret; } private ImmutableBitSet makeGridTableColumns(CuboidToGridTableMapping mapping, Set<TblColRef> dimensions) { BitSet result = new BitSet(); for (TblColRef dim : dimensions) { int idx = mapping.getIndexOf(dim); if (idx >= 0) result.set(idx); } return new ImmutableBitSet(result); } private ImmutableBitSet makeGridTableColumns(CuboidToGridTableMapping mapping, Collection<FunctionDesc> metrics) { BitSet result = new BitSet(); for (FunctionDesc metric : metrics) { int idx = mapping.getIndexOf(metric); if (idx < 0) throw new IllegalStateException(metric + " not found in " + mapping); result.set(idx); } return new ImmutableBitSet(result); } private String[] makeAggrFuncs(final CuboidToGridTableMapping mapping, Collection<FunctionDesc> metrics) { //metrics are represented in ImmutableBitSet, which loses order information //sort the aggrFuns to align with metrics natural order List<FunctionDesc> metricList = Lists.newArrayList(metrics); Collections.sort(metricList, new Comparator<FunctionDesc>() { @Override public int compare(FunctionDesc o1, FunctionDesc o2) { int a = mapping.getIndexOf(o1); int b = mapping.getIndexOf(o2); return a - b; } }); String[] result = new String[metricList.size()]; int i = 0; for (FunctionDesc metric : metricList) { result[i++] = metric.getExpression(); } return result; } private String makeReadable(ByteArray byteArray) { if (byteArray == null) { return null; } else { return byteArray.toReadableText(); } } protected GTScanRange newScanRange(Collection<ColumnRange> andDimRanges) { GTRecord pkStart = new GTRecord(gtInfo); GTRecord pkEnd = new GTRecord(gtInfo); Map<Integer, Set<ByteArray>> fuzzyValues = Maps.newHashMap(); List<GTRecord> fuzzyKeys; for (ColumnRange range : andDimRanges) { if (gtPartitionCol != null && range.column.equals(gtPartitionCol)) { if (rangeStartEndComparator.comparator.compare(gtStartAndEnd.getFirst(), range.end) <= 0 // && (rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) < 0 // || rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) == 0 // && (range.op == FilterOperatorEnum.EQ || range.op == FilterOperatorEnum.LTE || range.op == FilterOperatorEnum.GTE || range.op == FilterOperatorEnum.IN))) { //segment range is [Closed,Open), but segmentStartAndEnd.getSecond() might be rounded, so use <= when has equals in condition. } else { logger.debug("Pre-check partition col filter failed, partitionColRef {}, segment start {}, segment end {}, range begin {}, range end {}", // new Object[] { gtPartitionCol, makeReadable(gtStartAndEnd.getFirst()), makeReadable(gtStartAndEnd.getSecond()), makeReadable(range.begin), makeReadable(range.end) }); return null; } } int col = range.column.getColumnDesc().getZeroBasedIndex(); if (!gtInfo.primaryKey.get(col)) continue; pkStart.set(col, range.begin); pkEnd.set(col, range.end); if (range.valueSet != null && !range.valueSet.isEmpty()) { fuzzyValues.put(col, range.valueSet); } } fuzzyKeys = buildFuzzyKeys(fuzzyValues); return new GTScanRange(pkStart, pkEnd, fuzzyKeys); } private List<GTRecord> buildFuzzyKeys(Map<Integer, Set<ByteArray>> fuzzyValueSet) { ArrayList<GTRecord> result = Lists.newArrayList(); if (fuzzyValueSet.isEmpty()) return result; // debug/profiling purpose if (BackdoorToggles.getDisableFuzzyKey()) { logger.info("The execution of this query will not use fuzzy key"); return result; } List<Map<Integer, ByteArray>> fuzzyValueCombinations = FuzzyValueCombination.calculate(fuzzyValueSet, MAX_HBASE_FUZZY_KEYS); for (Map<Integer, ByteArray> fuzzyValue : fuzzyValueCombinations) { BitSet bitSet = new BitSet(gtInfo.getColumnCount()); for (Map.Entry<Integer, ByteArray> entry : fuzzyValue.entrySet()) { bitSet.set(entry.getKey()); } GTRecord fuzzy = new GTRecord(gtInfo, new ImmutableBitSet(bitSet)); for (Map.Entry<Integer, ByteArray> entry : fuzzyValue.entrySet()) { fuzzy.set(entry.getKey(), entry.getValue()); } result.add(fuzzy); } return result; } protected TupleFilter flattenToOrAndFilter(TupleFilter filter) { if (filter == null) return null; TupleFilter flatFilter = filter.flatFilter(); // normalize to OR-AND filter if (flatFilter.getOperator() == FilterOperatorEnum.AND) { LogicalTupleFilter f = new LogicalTupleFilter(FilterOperatorEnum.OR); f.addChild(flatFilter); flatFilter = f; } if (flatFilter.getOperator() != FilterOperatorEnum.OR) throw new IllegalStateException(); return flatFilter; } protected List<Collection<ColumnRange>> translateToOrAndDimRanges(TupleFilter flatFilter) { List<Collection<ColumnRange>> result = Lists.newArrayList(); if (flatFilter == null) { result.add(Collections.<ColumnRange> emptyList()); return result; } for (TupleFilter andFilter : flatFilter.getChildren()) { if (andFilter.getOperator() != FilterOperatorEnum.AND) throw new IllegalStateException("Filter should be AND instead of " + andFilter); Collection<ColumnRange> andRanges = translateToAndDimRanges(andFilter.getChildren()); if (andRanges != null) { result.add(andRanges); } } return preEvaluateConstantConditions(result); } private Collection<ColumnRange> translateToAndDimRanges(List<? extends TupleFilter> andFilters) { Map<TblColRef, ColumnRange> rangeMap = new HashMap<TblColRef, ColumnRange>(); for (TupleFilter filter : andFilters) { if ((filter instanceof CompareTupleFilter) == false) { if (filter instanceof ConstantTupleFilter && !filter.evaluate(null, null)) { return null; } else { continue; } } CompareTupleFilter comp = (CompareTupleFilter) filter; if (comp.getColumn() == null) { continue; } @SuppressWarnings("unchecked") ColumnRange newRange = new ColumnRange(comp.getColumn(), (Set<ByteArray>) comp.getValues(), comp.getOperator()); ColumnRange existing = rangeMap.get(newRange.column); if (existing == null) { rangeMap.put(newRange.column, newRange); } else { existing.andMerge(newRange); } } return rangeMap.values(); } private List<Collection<ColumnRange>> preEvaluateConstantConditions(List<Collection<ColumnRange>> orAndRanges) { boolean globalAlwaysTrue = false; Iterator<Collection<ColumnRange>> iterator = orAndRanges.iterator(); while (iterator.hasNext()) { Collection<ColumnRange> andRanges = iterator.next(); Iterator<ColumnRange> iterator2 = andRanges.iterator(); boolean hasAlwaysFalse = false; while (iterator2.hasNext()) { ColumnRange range = iterator2.next(); if (range.satisfyAll()) iterator2.remove(); else if (range.satisfyNone()) hasAlwaysFalse = true; } if (hasAlwaysFalse) { iterator.remove(); } else if (andRanges.isEmpty()) { globalAlwaysTrue = true; break; } } // return empty OR list means global false // return an empty AND collection inside OR list means global true if (globalAlwaysTrue) { orAndRanges.clear(); orAndRanges.add(Collections.<ColumnRange> emptyList()); } return orAndRanges; } protected List<GTScanRange> mergeOverlapRanges(List<GTScanRange> ranges) { if (ranges.size() <= 1) { return ranges; } // sort ranges by start key Collections.sort(ranges, new Comparator<GTScanRange>() { @Override public int compare(GTScanRange a, GTScanRange b) { return rangeStartComparator.compare(a.pkStart, b.pkStart); } }); // merge the overlap range List<GTScanRange> mergedRanges = new ArrayList<GTScanRange>(); int mergeBeginIndex = 0; GTRecord mergeEnd = ranges.get(0).pkEnd; for (int index = 1; index < ranges.size(); index++) { GTScanRange range = ranges.get(index); // if overlap, swallow it if (rangeStartEndComparator.compare(range.pkStart, mergeEnd) <= 0) { mergeEnd = rangeEndComparator.max(mergeEnd, range.pkEnd); continue; } // not overlap, split here GTScanRange mergedRange = mergeKeyRange(ranges.subList(mergeBeginIndex, index)); mergedRanges.add(mergedRange); // start new split mergeBeginIndex = index; mergeEnd = range.pkEnd; } // don't miss the last range GTScanRange mergedRange = mergeKeyRange(ranges.subList(mergeBeginIndex, ranges.size())); mergedRanges.add(mergedRange); return mergedRanges; } private GTScanRange mergeKeyRange(List<GTScanRange> ranges) { GTScanRange first = ranges.get(0); if (ranges.size() == 1) return first; GTRecord start = first.pkStart; GTRecord end = first.pkEnd; List<GTRecord> newFuzzyKeys = new ArrayList<GTRecord>(); boolean hasNonFuzzyRange = false; for (GTScanRange range : ranges) { hasNonFuzzyRange = hasNonFuzzyRange || range.fuzzyKeys.isEmpty(); newFuzzyKeys.addAll(range.fuzzyKeys); end = rangeEndComparator.max(end, range.pkEnd); } // if any range is non-fuzzy, then all fuzzy keys must be cleared // also too many fuzzy keys will slow down HBase scan if (hasNonFuzzyRange || newFuzzyKeys.size() > MAX_HBASE_FUZZY_KEYS) { newFuzzyKeys.clear(); } return new GTScanRange(start, end, newFuzzyKeys); } protected List<GTScanRange> mergeTooManyRanges(List<GTScanRange> ranges, int maxRanges) { if (ranges.size() <= maxRanges) { return ranges; } // TODO: check the distance between range and merge the large distance range List<GTScanRange> result = new ArrayList<GTScanRange>(1); GTScanRange mergedRange = mergeKeyRange(ranges); result.add(mergedRange); return result; } public int getMaxScanRanges() { return maxScanRanges; } public void setMaxScanRanges(int maxScanRanges) { this.maxScanRanges = maxScanRanges; } protected class ColumnRange { private TblColRef column; private ByteArray begin = ByteArray.EMPTY; private ByteArray end = ByteArray.EMPTY; private Set<ByteArray> valueSet; private FilterOperatorEnum op; public ColumnRange(TblColRef column, Set<ByteArray> values, FilterOperatorEnum op) { this.column = column; this.op = op; switch (op) { case EQ: case IN: valueSet = new HashSet<ByteArray>(values); refreshBeginEndFromEquals(); break; case LT: case LTE: end = rangeEndComparator.comparator.max(values); break; case GT: case GTE: begin = rangeStartComparator.comparator.min(values); break; case NEQ: case NOTIN: case ISNULL: case ISNOTNULL: // let Optiq filter it! break; default: throw new UnsupportedOperationException(op.name()); } } void copy(TblColRef column, ByteArray beginValue, ByteArray endValue, Set<ByteArray> equalValues) { this.column = column; this.begin = beginValue; this.end = endValue; this.valueSet = equalValues; } private void refreshBeginEndFromEquals() { if (valueSet.isEmpty()) { begin = ByteArray.EMPTY; end = ByteArray.EMPTY; } else { begin = rangeStartComparator.comparator.min(valueSet); end = rangeEndComparator.comparator.max(valueSet); } } public boolean satisfyAll() { return begin.array() == null && end.array() == null; // the NEQ case } public boolean satisfyNone() { if (valueSet != null) { return valueSet.isEmpty(); } else if (begin.array() != null && end.array() != null) { return gtInfo.codeSystem.getComparator().compare(begin, end) > 0; } else { return false; } } public void andMerge(ColumnRange another) { assert this.column.equals(another.column); if (another.satisfyAll()) { return; } if (this.satisfyAll()) { copy(another.column, another.begin, another.end, another.valueSet); return; } if (this.valueSet != null && another.valueSet != null) { this.valueSet.retainAll(another.valueSet); refreshBeginEndFromEquals(); return; } if (this.valueSet != null) { this.valueSet = filter(this.valueSet, another.begin, another.end); refreshBeginEndFromEquals(); return; } if (another.valueSet != null) { this.valueSet = filter(another.valueSet, this.begin, this.end); refreshBeginEndFromEquals(); return; } this.begin = rangeStartComparator.comparator.max(this.begin, another.begin); this.end = rangeEndComparator.comparator.min(this.end, another.end); } private Set<ByteArray> filter(Set<ByteArray> equalValues, ByteArray beginValue, ByteArray endValue) { Set<ByteArray> result = Sets.newHashSetWithExpectedSize(equalValues.size()); for (ByteArray v : equalValues) { if (rangeStartEndComparator.comparator.compare(beginValue, v) <= 0 && rangeStartEndComparator.comparator.compare(v, endValue) <= 0) { result.add(v); } } return equalValues; } public String toString() { if (valueSet == null) { return column.getName() + " between " + begin + " and " + end; } else { return column.getName() + " in " + valueSet; } } } public static abstract class ComparatorEx<T> implements Comparator<T> { public T min(Collection<T> v) { if (v.size() <= 0) { return null; } Iterator<T> iterator = v.iterator(); T min = iterator.next(); while (iterator.hasNext()) { min = min(min, iterator.next()); } return min; } public T max(Collection<T> v) { if (v.size() <= 0) { return null; } Iterator<T> iterator = v.iterator(); T max = iterator.next(); while (iterator.hasNext()) { max = max(max, iterator.next()); } return max; } public T min(T a, T b) { return compare(a, b) <= 0 ? a : b; } public T max(T a, T b) { return compare(a, b) >= 0 ? a : b; } public boolean between(T v, T start, T end) { return compare(start, v) <= 0 && compare(v, end) <= 0; } } public static RecordComparator getRangeStartComparator(final IGTComparator comp) { return new RecordComparator(new ComparatorEx<ByteArray>() { @Override public int compare(ByteArray a, ByteArray b) { if (a.array() == null) { if (b.array() == null) { return 0; } else { return -1; } } else if (b.array() == null) { return 1; } else { return comp.compare(a, b); } } }); } public static RecordComparator getRangeEndComparator(final IGTComparator comp) { return new RecordComparator(new ComparatorEx<ByteArray>() { @Override public int compare(ByteArray a, ByteArray b) { if (a.array() == null) { if (b.array() == null) { return 0; } else { return 1; } } else if (b.array() == null) { return -1; } else { return comp.compare(a, b); } } }); } public static RecordComparator getRangeStartEndComparator(final IGTComparator comp) { return new AsymmetricRecordComparator(new ComparatorEx<ByteArray>() { @Override public int compare(ByteArray a, ByteArray b) { if (a.array() == null || b.array() == null) { return -1; } else { return comp.compare(a, b); } } }); } private static class RecordComparator extends ComparatorEx<GTRecord> { final ComparatorEx<ByteArray> comparator; RecordComparator(ComparatorEx<ByteArray> byteComparator) { this.comparator = byteComparator; } @Override public int compare(GTRecord a, GTRecord b) { assert a.info == b.info; assert a.maskForEqualHashComp() == b.maskForEqualHashComp(); ImmutableBitSet mask = a.maskForEqualHashComp(); int comp; for (int i = 0; i < mask.trueBitCount(); i++) { int c = mask.trueBitAt(i); comp = comparator.compare(a.cols[c], b.cols[c]); if (comp != 0) return comp; } return 0; // equals } } /** * asymmetric means compare(a,b) > 0 does not cause compare(b,a) < 0 * so min max functions will not be supported */ private static class AsymmetricRecordComparator extends RecordComparator { AsymmetricRecordComparator(ComparatorEx<ByteArray> byteComparator) { super(byteComparator); } public GTRecord min(Collection<GTRecord> v) { throw new UnsupportedOperationException(); } public GTRecord max(Collection<GTRecord> v) { throw new UnsupportedOperationException(); } public GTRecord min(GTRecord a, GTRecord b) { throw new UnsupportedOperationException(); } public GTRecord max(GTRecord a, GTRecord b) { throw new UnsupportedOperationException(); } public boolean between(GTRecord v, GTRecord start, GTRecord end) { throw new UnsupportedOperationException(); } } }
KYLIN-1585 make MAX_HBASE_FUZZY_KEYS in GTScanRangePlanner configurable
core-cube/src/main/java/org/apache/kylin/gridtable/GTScanRangePlanner.java
KYLIN-1585 make MAX_HBASE_FUZZY_KEYS in GTScanRangePlanner configurable
<ide><path>ore-cube/src/main/java/org/apache/kylin/gridtable/GTScanRangePlanner.java <ide> <ide> private static final Logger logger = LoggerFactory.getLogger(GTScanRangePlanner.class); <ide> <del> private static final int MAX_HBASE_FUZZY_KEYS = 100; <del> <ide> protected int maxScanRanges; <add> protected int maxFuzzyKeys; <ide> <ide> //non-GT <ide> protected CubeSegment cubeSegment; <ide> public GTScanRangePlanner(CubeSegment cubeSegment, Cuboid cuboid, TupleFilter filter, Set<TblColRef> dimensions, Set<TblColRef> groupbyDims, // <ide> Collection<FunctionDesc> metrics) { <ide> <del> this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); <add> this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryStorageVisitScanRangeMax(); <add> this.maxFuzzyKeys = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); <ide> <ide> this.cubeSegment = cubeSegment; <ide> this.cubeDesc = cubeSegment.getCubeDesc(); <ide> */ <ide> public GTScanRangePlanner(GTInfo info, Pair<ByteArray, ByteArray> gtStartAndEnd, TblColRef gtPartitionCol, TupleFilter gtFilter) { <ide> <del> this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); <add> this.maxScanRanges = KylinConfig.getInstanceFromEnv().getQueryStorageVisitScanRangeMax(); <add> this.maxFuzzyKeys = KylinConfig.getInstanceFromEnv().getQueryScanFuzzyKeyMax(); <add> <ide> this.gtInfo = info; <ide> <ide> IGTComparator comp = gtInfo.codeSystem.getComparator(); <ide> //start key GTRecord compare to stop key GTRecord <ide> this.rangeStartEndComparator = getRangeStartEndComparator(comp); <ide> <add> <ide> this.gtFilter = gtFilter; <ide> this.gtStartAndEnd = gtStartAndEnd; <ide> this.gtPartitionCol = gtPartitionCol; <ide> } <add> <ide> <ide> public GTScanRequest planScanRequest(boolean allowPreAggregate) { <ide> GTScanRequest scanRequest; <ide> if (gtPartitionCol != null && range.column.equals(gtPartitionCol)) { <ide> if (rangeStartEndComparator.comparator.compare(gtStartAndEnd.getFirst(), range.end) <= 0 // <ide> && (rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) < 0 // <del> || rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) == 0 // <del> && (range.op == FilterOperatorEnum.EQ || range.op == FilterOperatorEnum.LTE || range.op == FilterOperatorEnum.GTE || range.op == FilterOperatorEnum.IN))) { <add> || rangeStartEndComparator.comparator.compare(range.begin, gtStartAndEnd.getSecond()) == 0 // <add> && (range.op == FilterOperatorEnum.EQ || range.op == FilterOperatorEnum.LTE || range.op == FilterOperatorEnum.GTE || range.op == FilterOperatorEnum.IN))) { <ide> //segment range is [Closed,Open), but segmentStartAndEnd.getSecond() might be rounded, so use <= when has equals in condition. <ide> } else { <ide> logger.debug("Pre-check partition col filter failed, partitionColRef {}, segment start {}, segment end {}, range begin {}, range end {}", // <ide> return result; <ide> } <ide> <del> List<Map<Integer, ByteArray>> fuzzyValueCombinations = FuzzyValueCombination.calculate(fuzzyValueSet, MAX_HBASE_FUZZY_KEYS); <add> List<Map<Integer, ByteArray>> fuzzyValueCombinations = FuzzyValueCombination.calculate(fuzzyValueSet, maxFuzzyKeys); <ide> <ide> for (Map<Integer, ByteArray> fuzzyValue : fuzzyValueCombinations) { <ide> <ide> <ide> // if any range is non-fuzzy, then all fuzzy keys must be cleared <ide> // also too many fuzzy keys will slow down HBase scan <del> if (hasNonFuzzyRange || newFuzzyKeys.size() > MAX_HBASE_FUZZY_KEYS) { <add> if (hasNonFuzzyRange || newFuzzyKeys.size() > maxFuzzyKeys) { <ide> newFuzzyKeys.clear(); <ide> } <ide>
Java
mit
c08d2e9d3fbee579236476f843257ce6f7fd2b1b
0
almibe/CodeEditor,almibe/CodeEditor
package org.almibe.codearea; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyBooleanWrapper; import javafx.beans.property.StringProperty; import javafx.concurrent.Worker; import javafx.scene.Parent; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import netscape.javascript.JSObject; public class CodeMirrorArea implements CodeArea { private final WebView webView; private final WebEngine webEngine; private final ReadOnlyBooleanWrapper isInitializedProperty = new ReadOnlyBooleanWrapper(false); public CodeMirrorArea() { webView = new WebView(); webEngine = webView.getEngine(); } @Override public void init() { final String html = CodeMirrorArea.class.getResource("html/editor.html").toExternalForm(); webEngine.load(html); webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { if(newValue == Worker.State.SUCCEEDED) { isInitializedProperty.setValue(true); } }); } @Override public ReadOnlyBooleanProperty isInitializedProperty() { return isInitializedProperty.getReadOnlyProperty(); } @Override public Parent getWidget() { return this.webView; } @Override public boolean isReadOnly() { return (Boolean) fetchEditor().call("getOption","readOnly"); } @Override public void setReadOnly(boolean readOnly) { fetchEditor().call("setOption", "readOnly", readOnly); } @Override public JSObject fetchEditor() { Object editor = webEngine.executeScript("codeMirror;"); if(editor instanceof JSObject) { return (JSObject) editor; } throw new IllegalStateException("CodeMirror not loaded."); } @Override public void setModeByName(String mode) { //webEngine.executeScript("setMode('" + mode + "')"); //TODO implement throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public void includeJSFile(String filePath, Runnable runnable) { //TODO implement throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public void setModeByMIMEType(String mimeType) { //TODO implement throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public String getTheme() { return (String) fetchEditor().call("getOption", "theme"); } @Override public void setTheme(String theme) { webEngine.executeScript("setTheme('" + theme + "')"); } @Override public String getMode() { return (String) fetchEditor().call("getOption", "mode"); } @Override public StringProperty contentProperty() { throw new UnsupportedOperationException("contentProperty is not implemented"); } }
src/main/java/org/almibe/codearea/CodeMirrorArea.java
package org.almibe.codearea; import javafx.beans.property.ReadOnlyBooleanProperty; import javafx.beans.property.ReadOnlyBooleanWrapper; import javafx.beans.property.StringProperty; import javafx.concurrent.Worker; import javafx.scene.Parent; import javafx.scene.web.WebEngine; import javafx.scene.web.WebView; import netscape.javascript.JSObject; import java.util.List; public class CodeMirrorArea implements CodeArea { private final WebView webView; private final WebEngine webEngine; private final ReadOnlyBooleanWrapper isInitializedProperty = new ReadOnlyBooleanWrapper(false); public CodeMirrorArea() { webView = new WebView(); webEngine = webView.getEngine(); } @Override public void init() { final String html = CodeMirrorArea.class.getResource("html/editor.html").toExternalForm(); webEngine.load(html); webEngine.getLoadWorker().stateProperty().addListener((observable, oldValue, newValue) -> { if(newValue == Worker.State.SUCCEEDED) { isInitializedProperty.setValue(true); } }); } @Override public ReadOnlyBooleanProperty isInitializedProperty() { return isInitializedProperty.getReadOnlyProperty(); } @Override public Parent getWidget() { return this.webView; } @Override public boolean isReadOnly() { return (Boolean) fetchEditor().call("getOption","readOnly"); } @Override public void setReadOnly(boolean readOnly) { fetchEditor().call("setOption", "readOnly", readOnly); } @Override public JSObject fetchEditor() { Object editor = webEngine.executeScript("codeMirror;"); if(editor instanceof JSObject) { return (JSObject) editor; } throw new IllegalStateException("CodeMirror not loaded."); } @Override public void setModeByName(String mode) { //webEngine.executeScript("setMode('" + mode + "')"); //TODO implement throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public void includeJSFile(String filePath, Runnable runnable) { //TODO implement throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public void setModeByMIMEType(String mimeType) { //TODO implement throw new UnsupportedOperationException("contentProperty is not implemented"); } @Override public List<String> getAvailableMIMETypes() { //TODO implement throw new RuntimeException(); } @Override public List<String> getAvailableModes() { //TODO implement throw new RuntimeException(); } @Override public String getTheme() { return (String) fetchEditor().call("getOption", "theme"); } @Override public void setTheme(String theme) { webEngine.executeScript("setTheme('" + theme + "')"); } @Override public String getMode() { return (String) fetchEditor().call("getOption", "mode"); } @Override public StringProperty contentProperty() { throw new UnsupportedOperationException("contentProperty is not implemented"); } }
removing get available X methods
src/main/java/org/almibe/codearea/CodeMirrorArea.java
removing get available X methods
<ide><path>rc/main/java/org/almibe/codearea/CodeMirrorArea.java <ide> import javafx.scene.web.WebEngine; <ide> import javafx.scene.web.WebView; <ide> import netscape.javascript.JSObject; <del> <del>import java.util.List; <ide> <ide> public class CodeMirrorArea implements CodeArea { <ide> private final WebView webView; <ide> } <ide> <ide> @Override <del> public List<String> getAvailableMIMETypes() { <del> //TODO implement <del> throw new RuntimeException(); <del> } <del> <del> @Override <del> public List<String> getAvailableModes() { <del> //TODO implement <del> throw new RuntimeException(); <del> } <del> <del> @Override <ide> public String getTheme() { <ide> return (String) fetchEditor().call("getOption", "theme"); <ide> }
Java
mit
bbf5c61c3947e685e1a962d29f4b0ff0a5a647fd
0
bakaschwarz/modules
package org.yabue.baka.modules; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.function.IntFunction; /** * This class manages the loading and accessing of modules. * Interaction between modules shall only be done through this module. * * @author Yannick Bülter * @version 1.0 */ public class ModuleManager { private static String modulesPackagePath = ModuleManager.class.getPackage().getName(); /** * These names will be added into a newly generated module configuration file. */ private static final String[] DEFAULT_MODULES = {"Core"}; private static File moduleFile; private static final HashMap<String, AbstractModule> loadedModules; /** * This method must be called to enable the usage of modules. * You need to provide the location of modules and the location of the configuration file. * * @param modulePackage The package name, that contains modules. * @param moduleConfigurationLocation The location of the module configuration. Will be created if not existent. * @throws ModuleLoadException */ public static void initialize(String modulePackage, File moduleConfigurationLocation) throws ModuleLoadException { moduleFile = moduleConfigurationLocation; modulesPackagePath = modulePackage; loadModules(); } /** * Loads all modules which are enabled in the module.conf. * * @throws IOException * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private static void loadModules() throws ModuleLoadException { try { if (!moduleFile.exists()) { FileUtils.touch(moduleFile); for(String defaultModule : DEFAULT_MODULES) { FileUtils.write(moduleFile, defaultModule + "\n", true); } } List<String> modules = Files.readAllLines(moduleFile.toPath()); for (String module : modules) { AbstractModule abstractModule = (AbstractModule) Class.forName(modulesPackagePath + "." + module + "." + module).newInstance(); loadedModules.put(module, abstractModule); abstractModule.initialize(); } } catch (Exception e) { throw new ModuleLoadException("An error orccured while loading the modules.", e); } } /** * This method enables the interaction between modules. * * @param moduleS The module, whose method shall be called. * @param methodS The method to be called. * @param arguments Possible arguments. * @param <R> Possible return value type. * @return Returns the value which {@param methodS} returns, if any. * @throws ModuleInvocationException */ @SuppressWarnings("unchecked") public static <R> R invoke(String moduleS, String methodS, Object... arguments) throws ModuleInvocationException { try { AbstractModule module = loadedModules.get(moduleS); if(module != null) { Class<?>[] argArray = Arrays.stream(arguments).map(Object::getClass).toArray((IntFunction<Class<?>[]>) Class[]::new); Method method = loadedModules.get(moduleS).getClass().getDeclaredMethod(methodS, argArray); method.setAccessible(true); return (R) method.invoke(module, arguments); } } catch (Exception e) { throw new ModuleInvocationException("Method could not be executed.", e); } throw new ModuleInvocationException(String.format("The module %s is not loaded or does not exist!", moduleS), new Throwable()); } static { loadedModules = new HashMap<>(); } }
src/main/java/org/yabue/baka/modules/ModuleManager.java
package org.yabue.baka.modules; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.Files; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.function.IntFunction; /** * This class manages the loading and accessing of modules. * Interaction between modules shall only be done through this module. * * @author Yannick Bülter * @version 1.0 */ public class ModuleManager { private static String modulesPackagePath = ModuleManager.class.getPackage().getName(); private static final String[] DEFAULT_MODULES = {"Core"}; private static File moduleFile; private static final HashMap<String, AbstractModule> loadedModules; public static void initialize(String modulePackage, File moduleConfigurationLocation) throws ModuleLoadException { moduleFile = moduleConfigurationLocation; modulesPackagePath = modulePackage; loadModules(); } /** * Loads all modules which are enabled in the module.conf. * * @throws IOException * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws InvocationTargetException * @throws IllegalAccessException */ private static void loadModules() throws ModuleLoadException { try { if (!moduleFile.exists()) { FileUtils.touch(moduleFile); for(String defaultModule : DEFAULT_MODULES) { FileUtils.write(moduleFile, defaultModule + "\n", true); } } List<String> modules = Files.readAllLines(moduleFile.toPath()); for (String module : modules) { AbstractModule abstractModule = (AbstractModule) Class.forName(modulesPackagePath + "." + module + "." + module).newInstance(); loadedModules.put(module, abstractModule); abstractModule.initialize(); } } catch (Exception e) { throw new ModuleLoadException("An error orccured while loading the modules.", e); } } /** * This method enables the interaction between modules. * * @param moduleS The module, whose method shall be called. * @param methodS The method to be called. * @param arguments Possible arguments. * @param <R> Possible return value type. * @return Returns the value which {@param methodS} returns, if any. * @throws ModuleInvocationException */ @SuppressWarnings("unchecked") public static <R> R invoke(String moduleS, String methodS, Object... arguments) throws ModuleInvocationException { try { AbstractModule module = loadedModules.get(moduleS); if(module != null) { Class<?>[] argArray = Arrays.stream(arguments).map(Object::getClass).toArray((IntFunction<Class<?>[]>) Class[]::new); Method method = loadedModules.get(moduleS).getClass().getDeclaredMethod(methodS, argArray); method.setAccessible(true); return (R) method.invoke(module, arguments); } } catch (Exception e) { throw new ModuleInvocationException("Method could not be executed.", e); } throw new ModuleInvocationException(String.format("The module %s is not loaded or does not exist!", moduleS), new Throwable()); } static { loadedModules = new HashMap<>(); } }
Some more documentation
src/main/java/org/yabue/baka/modules/ModuleManager.java
Some more documentation
<ide><path>rc/main/java/org/yabue/baka/modules/ModuleManager.java <ide> <ide> private static String modulesPackagePath = ModuleManager.class.getPackage().getName(); <ide> <add> /** <add> * These names will be added into a newly generated module configuration file. <add> */ <ide> private static final String[] DEFAULT_MODULES = {"Core"}; <ide> <ide> private static File moduleFile; <ide> <ide> private static final HashMap<String, AbstractModule> loadedModules; <ide> <add> /** <add> * This method must be called to enable the usage of modules. <add> * You need to provide the location of modules and the location of the configuration file. <add> * <add> * @param modulePackage The package name, that contains modules. <add> * @param moduleConfigurationLocation The location of the module configuration. Will be created if not existent. <add> * @throws ModuleLoadException <add> */ <ide> public static void initialize(String modulePackage, File moduleConfigurationLocation) throws ModuleLoadException { <ide> moduleFile = moduleConfigurationLocation; <ide> modulesPackagePath = modulePackage;
JavaScript
mit
e47d7603ccec64ca78b920052a8d29f6d4967baf
0
onehilltech/ember-cli-gatekeeper,onehilltech/ember-cli-gatekeeper
import Service from '@ember/service'; import { get, getWithDefault, set } from '@ember/object'; import { isPresent, isNone, isEmpty } from '@ember/utils'; import { getOwner } from '@ember/application'; import { resolve, Promise, reject, all } from 'rsvp'; import { assign } from '@ember/polyfills'; import { KJUR, KEYUTIL } from 'jsrsasign'; import { inject as service } from '@ember/service'; import AccessToken from "../-lib/access-token"; import TempSession from '../-lib/temp-session'; import { DefaultConfigurator } from "../-lib/configurator"; import { tracked } from "@glimmer/tracking"; /** * @class GatekeeperService * * The service for the gatekeeper framework. */ export default class GatekeeperService extends Service { constructor () { super (...arguments); this.configurator = this.defaultConfigurator; } @service router; @service storage; @tracked configurator; /** * Create a new instance of a DefaultConfigurator for the service. * * @returns {DefaultConfigurator} */ get defaultConfigurator () { let ENV = getOwner (this).resolveRegistration ('config:environment'); let config = get (ENV, 'gatekeeper'); return new DefaultConfigurator (config); } get storageLocation () { return this.configurator.storageLocation; } storageKey (key) { return `storage.${this.storageLocation}.${key}`; } get _tokenString () { return get (this, this.storageKey ('gatekeeper_ct')); } set _tokenString (value) { return set (this, this.storageKey ('gatekeeper_ct'), value); } /// The singleton access token for the gatekeeper. get accessToken () { return AccessToken.fromString (this._tokenString); } /** * Test if the client has been authenticated. * * @returns {boolean} */ get isAuthenticated () { return this.accessToken.isValid && !this.accessToken.isExpired; } get isUnauthenticated () { return !this.isAuthenticated; } get baseUrl () { return this.configurator.baseUrl; } get tokenOptions () { return this.configurator.tokenOptions; } get authenticateUrl () { return this.configurator.authenticateUrl; } computeUrl (relativeUrl) { return `${this.baseUrl}${relativeUrl}`; } /** * Authenticate the client. * * @param opts * @param force */ authenticate (opts, force = false) { if (this.isAuthenticated && !force) { return Promise.resolve (); } return this._requestClientToken (opts).then (token => { this._tokenString = token.access_token; // Notify all observers that our token has changed. this.notifyPropertyChange ('_tokenString'); }); } /** * Unauthenticate the client on the platform. */ unauthenticate () { return this.signOut (this.accessToken.toString()).then (() => this.reset ()); } /** * Reset the client. */ reset () { this._tokenString = null; } /** * Sign out a token on the system. */ signOut (token) { const url = this.computeUrl ('/oauth2/logout'); const options = { method: 'POST', headers: { Authorization: `Bearer ${token}` } }; return fetch (url, options).then ((response) => { if (response.ok) { return response.json (); } else { return response.json ().then (result => Promise.reject (result)); } }); } /** * Initiate the forgot password process. */ forgotPassword (email, opts) { return this.authenticate (opts) .then (() => { let url = this.computeUrl ('/password/forgot'); let opts = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.accessToken.toString ()}` }, body: JSON.stringify ({ email }) }; return fetch (url, opts); }) .then (response => response.ok ? response.json () : this._handleErrorResponse (response)); } /** * Reset the password for the user. */ resetPassword (token, password) { let url = this.computeUrl ('/password/reset'); let options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify ({'reset-password': {token, password}}) }; return fetch (url, options).then (response => response.ok ? response.json () : this._handleErrorResponse (response)); } get publicKey () { const { publicCert } = this.configurator; return isPresent (publicCert) ? KEYUTIL.getKey (publicCert) : null; } get secretOrPublicKey () { return this.configurator.secretOrPublicKey; } get verifyOptions () { return this.configurator.verifyOptions; } /** * Create a temporary session for the current client. * * @param payload * @param options * @returns {*} */ createTempSession (payload, options) { const tokenOptions = Object.assign ({grant_type: 'temp'}, { payload, options, access_token: this.accessToken.toString () }); const url = this.computeUrl ('/oauth2/token'); return this._requestToken (url, tokenOptions) .then (res => Object.assign ({}, { accessToken: res.access_token, gatekeeper: this})) .then (opts => TempSession.create (opts)); } /** * Verify a token. If there is no secret or public key, then the token is assumed * to be valid. * * @param token */ verifyToken (token) { if (isNone (token)) { return resolve (true); } return new Promise ((resolve, reject) => { const { secretOrPublicKey, verifyOptions } = this; if (isEmpty (secretOrPublicKey)) { return resolve (true); } const verified = KJUR.jws.JWS.verifyJWT (token, secretOrPublicKey, verifyOptions); return verified ? resolve (true) : reject (new Error ('The access token could not be verified.')); }); } /** * Perform the redirect to for the user. This will either take the user to the original * page they accessed before being redirected to the sign-in page, or the start route * if no redirect is present. */ redirect (redirectTo = this.redirectTo) { if (isNone (redirectTo)) { // There is no redirect url. So, we either transition to the default route, or we // transition to the index. let ENV = getOwner (this).resolveRegistration ('config:environment'); redirectTo = getWithDefault (ENV, 'gatekeeper.startRoute', 'index'); } this.router.replaceWith (redirectTo); } get redirectTo () { let currentURL = this.router.currentURL; let [, query] = currentURL.split ('?'); if (isNone (query)) { return null; } let params = query.split ('&'); return params.reduce ((accum, param) => { let [name, value] = param.split ('='); return name === 'redirect' ? decodeURIComponent (value) : accum; }, null); } /** * Requesting an access token from the server. * * @param opts * @returns {RSVP.Promise} * @private */ _requestClientToken (opts) { const url = this.computeUrl ('/oauth2/token'); const options = Object.assign ({}, opts, { grant_type: 'client_credentials' }); return this._requestToken (url, options); } _handleErrorResponse (response) { return response.json ().then (reject); } _requestToken (url, opts) { const data = Object.assign ({}, this.tokenOptions, opts); const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify (data) }; return fetch (url, options) .then (response => { return response.json ().then (res => { if (response.ok) { let checks = []; if (isPresent (res.access_token)) { checks.push (this.verifyToken (res.access_token)) } if (isPresent (res.refresh_token)) { checks.push (this.verifyToken (res.refresh_token)) } return all (checks).then (() => res); } else { return Promise.reject (res); } }); }); } }
addon/services/gatekeeper.js
import Service from '@ember/service'; import { get, getWithDefault, set } from '@ember/object'; import { isPresent, isNone, isEmpty } from '@ember/utils'; import { getOwner } from '@ember/application'; import { resolve, Promise, reject, all } from 'rsvp'; import { assign } from '@ember/polyfills'; import { KJUR, KEYUTIL } from 'jsrsasign'; import { inject as service } from '@ember/service'; import AccessToken from "../-lib/access-token"; import TempSession from '../-lib/temp-session'; import { DefaultConfigurator } from "../-lib/configurator"; import { tracked } from "@glimmer/tracking"; /** * @class GatekeeperService * * The service for the gatekeeper framework. */ export default class GatekeeperService extends Service { constructor () { super (...arguments); this.configurator = this.defaultConfigurator; } @service router; @service storage; @tracked configurator; /** * Create a new instance of a DefaultConfigurator for the service. * * @returns {DefaultConfigurator} */ get defaultConfigurator () { let ENV = getOwner (this).resolveRegistration ('config:environment'); let config = get (ENV, 'gatekeeper'); return new DefaultConfigurator (config); } get storageLocation () { return this.configurator.storageLocation; } storageKey (key) { return `storage.${this.storageLocation}.${key}`; } get _tokenString () { return get (this, this.storageKey ('gatekeeper_ct')); } set _tokenString (value) { return set (this, this.storageKey ('gatekeeper_ct'), value); } /// The singleton access token for the gatekeeper. get accessToken () { return AccessToken.fromString (this._tokenString); } /** * Test if the client has been authenticated. * * @returns {boolean} */ get isAuthenticated () { return this.accessToken.isValid && !this.accessToken.isExpired; } get isUnauthenticated () { return !this.isAuthenticated; } get baseUrl () { return this.configurator.baseUrl; } get tokenOptions () { return this.configurator.tokenOptions; } get authenticateUrl () { return this.configurator.authenticateUrl; } computeUrl (relativeUrl) { return `${this.baseUrl}${relativeUrl}`; } /** * Authenticate the client. * * @param opts * @param force */ authenticate (opts, force = false) { if (this.isAuthenticated && !force) { return Promise.resolve (); } return this._requestClientToken (opts).then (token => { this._tokenString = token.access_token; // Notify all observers that our token has changed. this.notifyPropertyChange ('_tokenString'); }); } /** * Unauthenticate the client on the platform. */ unauthenticate () { return this.signOut (this.accessToken.toString()); } /** * Sign out a token on the system. */ signOut (token) { const url = this.computeUrl ('/oauth2/logout'); const options = { method: 'POST', headers: { Authorization: `Bearer ${token}` } }; return fetch (url, options).then ((response) => { if (response.ok) { return response.json (); } else { return response.json ().then (result => Promise.reject (result)); } }); } /** * Initiate the forgot password process. */ forgotPassword (email, opts) { return this.authenticate (opts) .then (() => { let url = this.computeUrl ('/password/forgot'); let opts = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${this.accessToken.toString ()}` }, body: JSON.stringify ({ email }) }; return fetch (url, opts); }) .then (response => response.ok ? response.json () : this._handleErrorResponse (response)); } /** * Reset the password for the user. */ resetPassword (token, password) { let url = this.computeUrl ('/password/reset'); let options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify ({'reset-password': {token, password}}) }; return fetch (url, options).then (response => response.ok ? response.json () : this._handleErrorResponse (response)); } get publicKey () { const { publicCert } = this.configurator; return isPresent (publicCert) ? KEYUTIL.getKey (publicCert) : null; } get secretOrPublicKey () { return this.configurator.secretOrPublicKey; } get verifyOptions () { return this.configurator.verifyOptions; } /** * Create a temporary session for the current client. * * @param payload * @param options * @returns {*} */ createTempSession (payload, options) { const tokenOptions = Object.assign ({grant_type: 'temp'}, { payload, options, access_token: this.accessToken.toString () }); const url = this.computeUrl ('/oauth2/token'); return this._requestToken (url, tokenOptions) .then (res => Object.assign ({}, { accessToken: res.access_token, gatekeeper: this})) .then (opts => TempSession.create (opts)); } /** * Verify a token. If there is no secret or public key, then the token is assumed * to be valid. * * @param token */ verifyToken (token) { if (isNone (token)) { return resolve (true); } return new Promise ((resolve, reject) => { const { secretOrPublicKey, verifyOptions } = this; if (isEmpty (secretOrPublicKey)) { return resolve (true); } const verified = KJUR.jws.JWS.verifyJWT (token, secretOrPublicKey, verifyOptions); return verified ? resolve (true) : reject (new Error ('The access token could not be verified.')); }); } /** * Perform the redirect to for the user. This will either take the user to the original * page they accessed before being redirected to the sign-in page, or the start route * if no redirect is present. */ redirect (redirectTo = this.redirectTo) { if (isNone (redirectTo)) { // There is no redirect url. So, we either transition to the default route, or we // transition to the index. let ENV = getOwner (this).resolveRegistration ('config:environment'); redirectTo = getWithDefault (ENV, 'gatekeeper.startRoute', 'index'); } this.router.replaceWith (redirectTo); } get redirectTo () { let currentURL = this.router.currentURL; let [, query] = currentURL.split ('?'); if (isNone (query)) { return null; } let params = query.split ('&'); return params.reduce ((accum, param) => { let [name, value] = param.split ('='); return name === 'redirect' ? decodeURIComponent (value) : accum; }, null); } /** * Requesting an access token from the server. * * @param opts * @returns {RSVP.Promise} * @private */ _requestClientToken (opts) { const url = this.computeUrl ('/oauth2/token'); const options = Object.assign ({}, opts, { grant_type: 'client_credentials' }); return this._requestToken (url, options); } _handleErrorResponse (response) { return response.json ().then (reject); } _requestToken (url, opts) { const data = Object.assign ({}, this.tokenOptions, opts); const options = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify (data) }; return fetch (url, options) .then (response => { return response.json ().then (res => { if (response.ok) { let checks = []; if (isPresent (res.access_token)) { checks.push (this.verifyToken (res.access_token)) } if (isPresent (res.refresh_token)) { checks.push (this.verifyToken (res.refresh_token)) } return all (checks).then (() => res); } else { return Promise.reject (res); } }); }); } }
fix: added reset() methot to the client
addon/services/gatekeeper.js
fix: added reset() methot to the client
<ide><path>ddon/services/gatekeeper.js <ide> * Unauthenticate the client on the platform. <ide> */ <ide> unauthenticate () { <del> return this.signOut (this.accessToken.toString()); <add> return this.signOut (this.accessToken.toString()).then (() => this.reset ()); <add> } <add> <add> /** <add> * Reset the client. <add> */ <add> reset () { <add> this._tokenString = null; <ide> } <ide> <ide> /**
Java
agpl-3.0
50dcc7346aad36df4af07a36881d72f95bf3135f
0
geothomasp/kcmit,UniversityOfHawaiiORS/kc,geothomasp/kcmit,ColostateResearchServices/kc,iu-uits-es/kc,jwillia/kc-old1,jwillia/kc-old1,kuali/kc,mukadder/kc,UniversityOfHawaiiORS/kc,geothomasp/kcmit,geothomasp/kcmit,iu-uits-es/kc,geothomasp/kcmit,kuali/kc,ColostateResearchServices/kc,jwillia/kc-old1,ColostateResearchServices/kc,kuali/kc,mukadder/kc,UniversityOfHawaiiORS/kc,mukadder/kc,iu-uits-es/kc,jwillia/kc-old1
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/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.kra.negotiations.sorting; import java.util.Comparator; import org.kuali.kra.negotiations.bo.NegotiationActivity; /** * Activity Sorting Enum for displaying and choosing the correct comparator. */ public enum ActivitySortingType { @SuppressWarnings("unchecked") ST ("Activity Start Date, Activity Type", new MultiComparator<NegotiationActivity>(new Comparator[]{new StartDateComparator(), new ActivityTypeComparator()})), @SuppressWarnings("unchecked") UT ("Last Update, Activity Type", new MultiComparator<NegotiationActivity>(new Comparator[]{new LastUpdateComparator(), new ActivityTypeComparator()})), @SuppressWarnings("unchecked") UU ("Last Update By, Last Update", new MultiComparator<NegotiationActivity>(new Comparator[]{new LastUpdateByComparator(), new LastUpdateComparator()})), @SuppressWarnings("unchecked") TU ("Activity Type, Last Update", new MultiComparator<NegotiationActivity>(new Comparator[]{new ActivityTypeComparator(), new LastUpdateComparator()})), L ("Location", new LocationComparator()); private String desc; private Comparator<NegotiationActivity> comparator; private ActivitySortingType(String desc, Comparator<NegotiationActivity> comparator) { this.desc = desc; this.comparator = comparator; } public String getDesc() { return desc; } public Comparator<NegotiationActivity> getComparator() { return comparator; } } class StartDateComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getStartDate().compareTo(o2.getStartDate()); } } class ActivityTypeComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getActivityType().getDescription().compareTo(o2.getActivityType().getDescription()); } } class LastUpdateComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getLastModifiedDate().compareTo(o2.getLastModifiedDate()); } } class LastUpdateByComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getLastModifiedUser().getUserName().compareTo(o2.getLastModifiedUser().getUserName()); } } class LocationComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getLocation().getDescription().compareTo(o2.getLocation().getDescription()); } }
src/main/java/org/kuali/kra/negotiations/sorting/ActivitySortingType.java
/* * Copyright 2005-2010 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/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.kra.negotiations.sorting; import java.util.Comparator; import org.kuali.kra.negotiations.bo.NegotiationActivity; /** * Activity Sorting Enum for displaying and choosing the correct comparator. */ public enum ActivitySortingType { @SuppressWarnings("unchecked") ST ("Activity Start Date, Activity Type", new MultiComparator<NegotiationActivity>(new Comparator[]{new StartDateComparator(), new ActivityTypeComparator()})), @SuppressWarnings("unchecked") UT ("Last Update, Activity Type", new MultiComparator<NegotiationActivity>(new Comparator[]{new LastUpdateComparator(), new ActivityTypeComparator()})), @SuppressWarnings("unchecked") UU ("Last Update By, Last Update", new MultiComparator<NegotiationActivity>(new Comparator[]{new LastUpdateByComparator(), new LastUpdateComparator()})), @SuppressWarnings("unchecked") TU ("Activity Type, Last Update", new MultiComparator<NegotiationActivity>(new Comparator[]{new ActivityTypeComparator(), new LastUpdateComparator()})); private String desc; private Comparator<NegotiationActivity> comparator; private ActivitySortingType(String desc, Comparator<NegotiationActivity> comparator) { this.desc = desc; this.comparator = comparator; } public String getDesc() { return desc; } public Comparator<NegotiationActivity> getComparator() { return comparator; } } class StartDateComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getStartDate().compareTo(o2.getStartDate()); } } class ActivityTypeComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getActivityType().getDescription().compareTo(o2.getActivityType().getDescription()); } } class LastUpdateComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getLastModifiedDate().compareTo(o2.getLastModifiedDate()); } } class LastUpdateByComparator implements Comparator<NegotiationActivity> { @Override public int compare(NegotiationActivity o1, NegotiationActivity o2) { return o1.getLastModifiedUser().getUserName().compareTo(o2.getLastModifiedUser().getUserName()); } }
KRACOEUS-4977: Adding location as a sorting option for activities.
src/main/java/org/kuali/kra/negotiations/sorting/ActivitySortingType.java
KRACOEUS-4977: Adding location as a sorting option for activities.
<ide><path>rc/main/java/org/kuali/kra/negotiations/sorting/ActivitySortingType.java <ide> new MultiComparator<NegotiationActivity>(new Comparator[]{new LastUpdateByComparator(), new LastUpdateComparator()})), <ide> @SuppressWarnings("unchecked") <ide> TU ("Activity Type, Last Update", <del> new MultiComparator<NegotiationActivity>(new Comparator[]{new ActivityTypeComparator(), new LastUpdateComparator()})); <add> new MultiComparator<NegotiationActivity>(new Comparator[]{new ActivityTypeComparator(), new LastUpdateComparator()})), <add> L ("Location", new LocationComparator()); <ide> <ide> private String desc; <ide> private Comparator<NegotiationActivity> comparator; <ide> return o1.getLastModifiedUser().getUserName().compareTo(o2.getLastModifiedUser().getUserName()); <ide> } <ide> } <add>class LocationComparator implements Comparator<NegotiationActivity> { <add> @Override <add> public int compare(NegotiationActivity o1, NegotiationActivity o2) { <add> return o1.getLocation().getDescription().compareTo(o2.getLocation().getDescription()); <add> } <add>}
Java
mit
5152bcc2945384c555e72ea09bb1b502d8a61343
0
opennars/opennars,opennars/opennars,opennars/opennars,opennars/opennars
/* * Copyright (C) 2014 peiwang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nars.inference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import nars.storage.Memory; import nars.config.Parameters; import nars.control.DerivationContext; import nars.control.TemporalInferenceControl; import nars.entity.BudgetValue; import nars.entity.Concept; import nars.entity.Sentence; import nars.entity.Stamp; import nars.entity.Task; import nars.entity.TaskLink; import nars.entity.TermLink; import nars.entity.TruthValue; import nars.io.Symbols; import nars.language.CompoundTerm; import nars.language.Conjunction; import nars.language.Equivalence; import nars.language.Implication; import nars.language.Inheritance; import nars.language.Interval; import nars.language.Product; import nars.language.Similarity; import nars.language.Statement; import nars.language.Term; import nars.language.Terms; import nars.language.Variable; import nars.operator.Operation; /** * * @author peiwang */ public class TemporalRules { public static final int ORDER_NONE = 2; public static final int ORDER_FORWARD = 1; public static final int ORDER_CONCURRENT = 0; public static final int ORDER_BACKWARD = -1; public static final int ORDER_INVALID = -2; public final static int reverseOrder(final int order) { if (order == ORDER_NONE) { return ORDER_NONE; } else { return -order; } } public final static boolean matchingOrder(final Sentence a, final Sentence b) { return matchingOrder(a.getTemporalOrder(), b.getTemporalOrder()); } public final static boolean matchingOrder(final int order1, final int order2) { return (order1 == order2) || (order1 == ORDER_NONE) || (order2 == ORDER_NONE); } public final static int dedExeOrder(final int order1, final int order2) { int order = ORDER_INVALID; if ((order1 == order2) || (order2 == TemporalRules.ORDER_NONE)) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = order2; } else if (order2 == TemporalRules.ORDER_CONCURRENT) { order = order1; } return order; } public final static int abdIndComOrder(final int order1, final int order2) { int order = ORDER_INVALID; if (order2 == TemporalRules.ORDER_NONE) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = reverseOrder(order2); } else if ((order2 == TemporalRules.ORDER_CONCURRENT) || (order1 == -order2)) { order = order1; } return order; } public final static int analogyOrder(final int order1, final int order2, final int figure) { int order = ORDER_INVALID; if ((order2 == TemporalRules.ORDER_NONE) || (order2 == TemporalRules.ORDER_CONCURRENT)) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = (figure < 20) ? order2 : reverseOrder(order2); } else if (order1 == order2) { if ((figure == 12) || (figure == 21)) { order = order1; } } else if ((order1 == -order2)) { if ((figure == 11) || (figure == 22)) { order = order1; } } return order; } public static final int resemblanceOrder(final int order1, final int order2, final int figure) { int order = ORDER_INVALID; int order1Reverse = reverseOrder(order1); if ((order2 == TemporalRules.ORDER_NONE)) { order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12 } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = (figure % 10 == 1) ? order2 : reverseOrder(order2); // switch when 12 or 22 } else if (order2 == TemporalRules.ORDER_CONCURRENT) { order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12 } else if (order1 == order2) { order = (figure == 21) ? order1 : -order1; } return order; } public static final int composeOrder(final int order1, final int order2) { int order = ORDER_INVALID; if (order2 == TemporalRules.ORDER_NONE) { order = order1; } else if (order1 == TemporalRules.ORDER_NONE) { order = order2; } else if (order1 == order2) { order = order1; } return order; } /** whether temporal induction can generate a task by avoiding producing wrong terms; only one temporal operator is allowed */ public final static boolean tooMuchTemporalStatements(final Term t) { return (t == null) || (t.containedTemporalRelations() > 1); } /** whether a term can be used in temoralInduction(,,) */ protected static boolean termForTemporalInduction(final Term t) { return (t instanceof Inheritance) || (t instanceof Similarity); } public static float ConjunctionPriority(final nars.control.DerivationContext nal, Term t, float value) { if(t instanceof Conjunction) { Conjunction conj = (Conjunction) t; for(Term comp: conj.term) { if(!(comp instanceof Interval)) value = BudgetFunctions.and(value, ConjunctionPriority(nal, comp, value)); } } else { Concept c = nal.memory.concept(t); float mul = 0.0f; if(c != null) mul = c.getPriority(); value *= mul; } return value; } public static float ConjunctionPriority(final nars.control.DerivationContext nal, Term t) { return ConjunctionPriority(nal, t, 1.0f); } public static List<Task> temporalInduction(final Sentence s1, final Sentence s2, final nars.control.DerivationContext nal, boolean SucceedingEventsInduction) { if ((s1.truth==null) || (s2.truth==null) || s1.punctuation!=Symbols.JUDGMENT_MARK || s2.punctuation!=Symbols.JUDGMENT_MARK || s1.isEternal() || s2.isEternal()) return Collections.EMPTY_LIST; Term t1 = s1.term; Term t2 = s2.term; boolean deriveSequenceOnly = Statement.invalidStatement(t1, t2, true); if (Statement.invalidStatement(t1, t2, false)) return Collections.EMPTY_LIST; Term t11=null; Term t22=null; if (!deriveSequenceOnly && termForTemporalInduction(t1) && termForTemporalInduction(t2)) { Statement ss1 = (Statement) t1; Statement ss2 = (Statement) t2; Variable var1 = new Variable("$0"); Variable var2 = new Variable("$1"); /* if (ss1.getSubject().equals(ss2.getSubject())) { t11 = Statement.make(ss1, var1, ss1.getPredicate()); t22 = Statement.make(ss2, var2, ss2.getPredicate()); } else if (ss1.getPredicate().equals(ss2.getPredicate())) { t11 = Statement.make(ss1, ss1.getSubject(), var1); t22 = Statement.make(ss2, ss2.getSubject(), var2); }*/ if(ss2.containsTermRecursively(ss1.getSubject())) { HashMap<Term,Term> subs=new HashMap(); subs.put(ss1.getSubject(), var1); if(ss2.containsTermRecursively(ss1.getPredicate())) { subs.put(ss1.getPredicate(), var2); } t11=ss1.applySubstitute(subs); t22=ss2.applySubstitute(subs); } if(ss1.containsTermRecursively(ss2.getSubject())) { HashMap<Term,Term> subs=new HashMap(); subs.put(ss2.getSubject(), var1); if(ss1.containsTermRecursively(ss2.getPredicate())) { subs.put(ss2.getPredicate(), var2); } t11=ss1.applySubstitute(subs); t22=ss2.applySubstitute(subs); } //allow also temporal induction on operator arguments: if(ss2 instanceof Operation ^ ss1 instanceof Operation) { if(ss2 instanceof Operation && !(ss2.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term Term comp=ss1.getSubject(); Term ss2_term = ((Operation)ss2).getSubject(); boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep()); if(ss2_term instanceof Product) { Product ss2_prod=(Product) ss2_term; if(applicableVariableType && Terms.contains(ss2_prod.term, comp)) { //only if there is one and it isnt a variable already Term[] ars = ss2_prod.cloneTermsReplacing(comp, var1); t11 = Statement.make(ss1, var1, ss1.getPredicate()); Operation op=(Operation) Operation.make( new Product(ars), ss2.getPredicate() ); t22 = op; } } } if(ss1 instanceof Operation && !(ss1.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term Term comp=ss2.getSubject(); Term ss1_term = ((Operation)ss1).getSubject(); boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep()); if(ss1_term instanceof Product) { Product ss1_prod=(Product) ss1_term; if(applicableVariableType && Terms.contains(ss1_prod.term, comp)) { //only if there is one and it isnt a variable already Term[] ars = ss1_prod.cloneTermsReplacing(comp, var1); t22 = Statement.make(ss2, var1, ss2.getPredicate()); Operation op=(Operation) Operation.make( new Product(ars), ss1.getPredicate() ); t11 = op; } } } } } int durationCycles = Parameters.DURATION; long time1 = s1.getOccurenceTime(); long time2 = s2.getOccurenceTime(); long timeDiff = time2 - time1; List<Interval> interval=null; if (!concurrent(time1, time2, durationCycles)) { interval = Interval.intervalTimeSequence(Math.abs(timeDiff), Parameters.TEMPORAL_INTERVAL_PRECISION, nal.mem()); if (timeDiff > 0) { t1 = Conjunction.make(t1, interval, ORDER_FORWARD); if(t11!=null) { t11 = Conjunction.make(t11, interval, ORDER_FORWARD); } } else { t2 = Conjunction.make(t2, interval, ORDER_FORWARD); if(t22!=null) { t22 = Conjunction.make(t22, interval, ORDER_FORWARD); } } } int order = order(timeDiff, durationCycles); TruthValue givenTruth1 = s1.truth; TruthValue givenTruth2 = s2.truth; //This code adds a penalty for large time distance (TODO probably revise) Sentence s3 = s2.projection(s1.getOccurenceTime(), nal.memory.time()); givenTruth2 = s3.truth; // TruthFunctions. TruthValue truth1 = TruthFunctions.induction(givenTruth1, givenTruth2); TruthValue truth2 = TruthFunctions.induction(givenTruth2, givenTruth1); TruthValue truth3 = TruthFunctions.comparison(givenTruth1, givenTruth2); TruthValue truth4 = TruthFunctions.intersection(givenTruth1, givenTruth2); BudgetValue budget1 = BudgetFunctions.forward(truth1, nal); budget1.setPriority(budget1.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY); BudgetValue budget2 = BudgetFunctions.forward(truth2, nal); budget2.setPriority(budget2.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY); BudgetValue budget3 = BudgetFunctions.forward(truth3, nal); budget3.setPriority(budget3.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY); BudgetValue budget4 = BudgetFunctions.forward(truth4, nal); //this one is sequence in sequenceBag, no need to reduce here //https://groups.google.com/forum/#!topic/open-nars/0k-TxYqg4Mc if(!SucceedingEventsInduction) //not used currently as succeeding event induction (involving sequence bag elements) //is the current temporal induction strategy { //reduce priority according to temporal distance //it was not "semantically" connected by temporal succession int tt1=(int) s1.getOccurenceTime(); int tt2=(int) s2.getOccurenceTime(); int d=Math.abs(tt1-tt2)/Parameters.DURATION; if(d!=0) { double mul=1.0/((double)d); mul *= ConjunctionPriority(nal, t1); mul *= ConjunctionPriority(nal, t2); budget1.setPriority((float) (budget1.getPriority()*mul)); budget2.setPriority((float) (budget2.getPriority()*mul)); budget3.setPriority((float) (budget3.getPriority()*mul)); budget4.setPriority((float) (budget4.getPriority()*mul)); } } Statement statement1 = Implication.make(t1, t2, order); Statement statement2 = Implication.make(t2, t1, reverseOrder(order)); Statement statement3 = Equivalence.make(t1, t2, order); Term statement4 = null; switch (order) { case TemporalRules.ORDER_FORWARD: statement4 = Conjunction.make(t1, interval, s2.term, order); break; case TemporalRules.ORDER_BACKWARD: statement4 = Conjunction.make(s2.term, interval, t1, reverseOrder(order)); break; default: statement4 = Conjunction.make(t1, s2.term, order); break; } //maybe this way is also the more flexible and intelligent way to introduce variables for the case above //TODO: rethink this for 1.6.3 //"Perception Variable Introduction Rule" - https://groups.google.com/forum/#!topic/open-nars/uoJBa8j7ryE if(!deriveSequenceOnly && statement2!=null) { //there is no general form //ok then it may be the (&/ =/> case which //is discussed here: https://groups.google.com/forum/#!topic/open-nars/uoJBa8j7ryE Statement st=statement2; if(st.getPredicate() instanceof Inheritance && (st.getSubject() instanceof Conjunction || st.getSubject() instanceof Operation)) { Term precon=(Term) st.getSubject(); Inheritance consequence=(Inheritance) st.getPredicate(); Term pred=consequence.getPredicate(); Term sub=consequence.getSubject(); //look if subject is contained in precon: boolean SubsSub=precon.containsTermRecursively(sub); boolean SubsPred=precon.containsTermRecursively(pred); Variable v1=new Variable("$91"); Variable v2=new Variable("$92"); HashMap<Term,Term> app=new HashMap<Term,Term>(); if(SubsSub || SubsPred) { if(SubsSub) app.put(sub, v1); if(SubsPred) app.put(pred,v2); Term res=((CompoundTerm) statement2).applySubstitute(app); if(res!=null) { //ok we applied it, all we have to do now is to use it t22=((Statement)res).getSubject(); t11=((Statement)res).getPredicate(); } } } } List<Task> success=new ArrayList<Task>(); if(!deriveSequenceOnly && t11!=null && t22!=null) { Statement statement11 = Implication.make(t11, t22, order); Statement statement22 = Implication.make(t22, t11, reverseOrder(order)); Statement statement33 = Equivalence.make(t11, t22, order); if(!tooMuchTemporalStatements(statement11)) { List<Task> t=nal.doublePremiseTask(statement11, truth1, budget1,true, false); if(t!=null) { success.addAll(t); } } if(!tooMuchTemporalStatements(statement22)) { List<Task> t=nal.doublePremiseTask(statement22, truth2, budget2,true, false); if(t!=null) { success.addAll(t); } } if(!tooMuchTemporalStatements(statement33)) { List<Task> t=nal.doublePremiseTask(statement33, truth3, budget3,true, false); if(t!=null) { success.addAll(t); } } } if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement1)) { List<Task> t=nal.doublePremiseTask(statement1, truth1, budget1,true, false); if(t!=null) { success.addAll(t); for(Task task : t) { task.setObservablePrediction(true); //we assume here that this function is used for observable events currently } } } if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement2)) { List<Task> t=nal.doublePremiseTask(statement2, truth2, budget2,true, false); if(t!=null) { success.addAll(t); for(Task task : t) { task.setObservablePrediction(true); //we assume here that this function is used for observable events currently } /*Task task=t; //micropsi inspired strive for knowledge //get strongest belief of that concept and use the revison truth, if there is no, use this truth double conf=task.sentence.truth.getConfidence(); Concept C=nal.memory.concept(task.sentence.term); if(C!=null && C.beliefs!=null && C.beliefs.size()>0) { Sentence bel=C.beliefs.get(0).sentence; TruthValue cur=bel.truth; conf=Math.max(cur.getConfidence(), conf); //no matter if revision is possible, it wont be below max //if there is no overlapping evidental base, use revision: boolean revisable=true; for(long l: bel.stamp.evidentialBase) { for(long h: task.sentence.stamp.evidentialBase) { if(l==h) { revisable=false; break; } } } if(revisable) { conf=TruthFunctions.revision(task.sentence.truth, bel.truth).getConfidence(); } } questionFromLowConfidenceHighPriorityJudgement(task, conf, nal); */ } } if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement3)) { List<Task> t=nal.doublePremiseTask(statement3, truth3, budget3,true, false); if(t!=null) { for(Task task : t) { task.setObservablePrediction(true); //we assume here that this function is used for observable events currently } success.addAll(t); } } if(!tooMuchTemporalStatements(statement4)) { List<Task> tl=nal.doublePremiseTask(statement4, truth4, budget4,true, false); if(tl!=null) { for(Task t : tl) { //fill sequenceTask buffer due to the new derived sequence if(t.sentence.isJudgment() && !t.sentence.isEternal() && t.sentence.term instanceof Conjunction && ((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_NONE && ((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_INVALID) { TemporalInferenceControl.addToSequenceTasks(nal, t); } success.add(t); } } } return success; } private static void questionFromLowConfidenceHighPriorityJudgement(Task task, double conf, final DerivationContext nal) { if(nal.memory.emotion.busy()<Parameters.CURIOSITY_BUSINESS_THRESHOLD && Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF && task.sentence.punctuation==Symbols.JUDGMENT_MARK && conf<Parameters.CURIOSITY_CONFIDENCE_THRESHOLD && task.getPriority()>Parameters.CURIOSITY_PRIORITY_THRESHOLD) { if(task.sentence.term instanceof Implication) { boolean valid=false; if(task.sentence.term instanceof Implication) { Implication equ=(Implication) task.sentence.term; if(equ.getTemporalOrder()!=TemporalRules.ORDER_NONE) { valid=true; } } if(valid) { Sentence tt2=new Sentence(task.sentence.term.clone(),Symbols.QUESTION_MARK,null,new Stamp(task.sentence.stamp.clone(),nal.memory.time())); BudgetValue budg=task.budget.clone(); budg.setPriority(budg.getPriority()*Parameters.CURIOSITY_DESIRE_PRIORITY_MUL); budg.setDurability(budg.getPriority()*Parameters.CURIOSITY_DESIRE_DURABILITY_MUL); nal.singlePremiseTask(tt2, task.budget.clone()); } } } } /** * Evaluate the quality of the judgment as a solution to a problem * * @param problem A goal or question * @param solution The solution to be evaluated * @return The quality of the judgment as the solution */ public static float solutionQuality(boolean rateByConfidence, final Task probT, final Sentence solution, Memory memory) { Sentence problem = probT.sentence; if (!matchingOrder(problem.getTemporalOrder(), solution.getTemporalOrder())) { return 0.0F; } TruthValue truth = solution.truth; if (problem.getOccurenceTime()!=solution.getOccurenceTime()) { truth = solution.projectionTruth(problem.getOccurenceTime(), memory.time()); } //when the solutions are comparable, we have to use confidence!! else truth expectation. //this way negative evidence can update the solution instead of getting ignored due to lower truth expectation. //so the previous handling to let whether the problem has query vars decide was wrong. if (!rateByConfidence) { return (float) (truth.getExpectation() / Math.sqrt(Math.sqrt(Math.sqrt(solution.term.getComplexity()*Parameters.COMPLEXITY_UNIT)))); } else { return truth.getConfidence(); } } /* ----- Functions used both in direct and indirect processing of tasks ----- */ /** * Evaluate the quality of a belief as a solution to a problem, then reward * the belief and de-prioritize the problem * * @param problem The problem (question or goal) to be solved * @param solution The belief as solution * @param task The task to be immediately processed, or null for continued * process * @return The budget for the new task which is the belief activated, if * necessary */ public static BudgetValue solutionEval(final Task problem, final Sentence solution, Task task, final nars.control.DerivationContext nal) { BudgetValue budget = null; boolean feedbackToLinks = false; if (task == null) { task = nal.getCurrentTask(); feedbackToLinks = true; } boolean judgmentTask = task.sentence.isJudgment(); boolean rateByConfidence = problem.getTerm().hasVarQuery(); //here its whether its a what or where question for budget adjustment final float quality = TemporalRules.solutionQuality(rateByConfidence, problem, solution, nal.mem()); if (problem.sentence.isGoal()) { nal.memory.emotion.adjustHappy(quality, task.getPriority(), nal); } if (judgmentTask) { task.incPriority(quality); } else { float taskPriority = task.getPriority(); //+goal satisfication is a matter of degree - https://groups.google.com/forum/#!topic/open-nars/ZfCM416Dx1M budget = new BudgetValue(UtilityFunctions.or(taskPriority, quality), task.getDurability(), BudgetFunctions.truthToQuality(solution.truth)); task.setPriority(Math.min(1 - quality, taskPriority)); } if (feedbackToLinks) { TaskLink tLink = nal.getCurrentTaskLink(); tLink.setPriority(Math.min(1 - quality, tLink.getPriority())); TermLink bLink = nal.getCurrentBeliefLink(); bLink.incPriority(quality); } return budget; } public static int order(final long timeDiff, final int durationCycles) { final int halfDuration = durationCycles/2; if (timeDiff > halfDuration) { return ORDER_FORWARD; } else if (timeDiff < -halfDuration) { return ORDER_BACKWARD; } else { return ORDER_CONCURRENT; } } /** if (relative) event B after (stationary) event A then order=forward; * event B before then order=backward * occur at the same time, relative to duration: order = concurrent */ public static int order(final long a, final long b, final int durationCycles) { if ((a == Stamp.ETERNAL) || (b == Stamp.ETERNAL)) throw new RuntimeException("order() does not compare ETERNAL times"); return order(b - a, durationCycles); } public static boolean concurrent(final long a, final long b, final int durationCycles) { //since Stamp.ETERNAL is Integer.MIN_VALUE, //avoid any overflow errors by checking eternal first if (a == Stamp.ETERNAL) { //if both are eternal, consider concurrent. this is consistent with the original //method of calculation which compared equivalent integer values only return (b == Stamp.ETERNAL); } else if (b == Stamp.ETERNAL) { return false; //a==b was compared above } else { return order(a, b, durationCycles) == ORDER_CONCURRENT; } } }
nars_core/nars/inference/TemporalRules.java
/* * Copyright (C) 2014 peiwang * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nars.inference; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import nars.storage.Memory; import nars.config.Parameters; import nars.control.DerivationContext; import nars.control.TemporalInferenceControl; import nars.entity.BudgetValue; import nars.entity.Concept; import nars.entity.Sentence; import nars.entity.Stamp; import nars.entity.Task; import nars.entity.TaskLink; import nars.entity.TermLink; import nars.entity.TruthValue; import nars.io.Symbols; import nars.language.CompoundTerm; import nars.language.Conjunction; import nars.language.Equivalence; import nars.language.Implication; import nars.language.Inheritance; import nars.language.Interval; import nars.language.Product; import nars.language.Similarity; import nars.language.Statement; import nars.language.Term; import nars.language.Terms; import nars.language.Variable; import nars.operator.Operation; /** * * @author peiwang */ public class TemporalRules { public static final int ORDER_NONE = 2; public static final int ORDER_FORWARD = 1; public static final int ORDER_CONCURRENT = 0; public static final int ORDER_BACKWARD = -1; public static final int ORDER_INVALID = -2; public final static int reverseOrder(final int order) { if (order == ORDER_NONE) { return ORDER_NONE; } else { return -order; } } public final static boolean matchingOrder(final Sentence a, final Sentence b) { return matchingOrder(a.getTemporalOrder(), b.getTemporalOrder()); } public final static boolean matchingOrder(final int order1, final int order2) { return (order1 == order2) || (order1 == ORDER_NONE) || (order2 == ORDER_NONE); } public final static int dedExeOrder(final int order1, final int order2) { int order = ORDER_INVALID; if ((order1 == order2) || (order2 == TemporalRules.ORDER_NONE)) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = order2; } else if (order2 == TemporalRules.ORDER_CONCURRENT) { order = order1; } return order; } public final static int abdIndComOrder(final int order1, final int order2) { int order = ORDER_INVALID; if (order2 == TemporalRules.ORDER_NONE) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = reverseOrder(order2); } else if ((order2 == TemporalRules.ORDER_CONCURRENT) || (order1 == -order2)) { order = order1; } return order; } public final static int analogyOrder(final int order1, final int order2, final int figure) { int order = ORDER_INVALID; if ((order2 == TemporalRules.ORDER_NONE) || (order2 == TemporalRules.ORDER_CONCURRENT)) { order = order1; } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = (figure < 20) ? order2 : reverseOrder(order2); } else if (order1 == order2) { if ((figure == 12) || (figure == 21)) { order = order1; } } else if ((order1 == -order2)) { if ((figure == 11) || (figure == 22)) { order = order1; } } return order; } public static final int resemblanceOrder(final int order1, final int order2, final int figure) { int order = ORDER_INVALID; int order1Reverse = reverseOrder(order1); if ((order2 == TemporalRules.ORDER_NONE)) { order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12 } else if ((order1 == TemporalRules.ORDER_NONE) || (order1 == TemporalRules.ORDER_CONCURRENT)) { order = (figure % 10 == 1) ? order2 : reverseOrder(order2); // switch when 12 or 22 } else if (order2 == TemporalRules.ORDER_CONCURRENT) { order = (figure > 20) ? order1 : order1Reverse; // switch when 11 or 12 } else if (order1 == order2) { order = (figure == 21) ? order1 : -order1; } return order; } public static final int composeOrder(final int order1, final int order2) { int order = ORDER_INVALID; if (order2 == TemporalRules.ORDER_NONE) { order = order1; } else if (order1 == TemporalRules.ORDER_NONE) { order = order2; } else if (order1 == order2) { order = order1; } return order; } /** whether temporal induction can generate a task by avoiding producing wrong terms; only one temporal operator is allowed */ public final static boolean tooMuchTemporalStatements(final Term t) { return (t == null) || (t.containedTemporalRelations() > 1); } /** whether a term can be used in temoralInduction(,,) */ protected static boolean termForTemporalInduction(final Term t) { return (t instanceof Inheritance) || (t instanceof Similarity); } public static float ConjunctionPriority(final nars.control.DerivationContext nal, Term t, float value) { if(t instanceof Conjunction) { Conjunction conj = (Conjunction) t; for(Term comp: conj.term) { if(!(comp instanceof Interval)) value = BudgetFunctions.and(value, ConjunctionPriority(nal, comp, value)); } } else { Concept c = nal.memory.concept(t); float mul = 0.0f; if(c != null) mul = c.getPriority(); value *= mul; } return value; } public static float ConjunctionPriority(final nars.control.DerivationContext nal, Term t) { return ConjunctionPriority(nal, t, 1.0f); } public static List<Task> temporalInduction(final Sentence s1, final Sentence s2, final nars.control.DerivationContext nal, boolean SucceedingEventsInduction) { if ((s1.truth==null) || (s2.truth==null) || s1.punctuation!=Symbols.JUDGMENT_MARK || s2.punctuation!=Symbols.JUDGMENT_MARK || s1.isEternal() || s2.isEternal()) return Collections.EMPTY_LIST; Term t1 = s1.term; Term t2 = s2.term; boolean deriveSequenceOnly = Statement.invalidStatement(t1, t2, true); if (Statement.invalidStatement(t1, t2, false)) return Collections.EMPTY_LIST; Term t11=null; Term t22=null; if (!deriveSequenceOnly && termForTemporalInduction(t1) && termForTemporalInduction(t2)) { Statement ss1 = (Statement) t1; Statement ss2 = (Statement) t2; Variable var1 = new Variable("$0"); Variable var2 = new Variable("$1"); /* if (ss1.getSubject().equals(ss2.getSubject())) { t11 = Statement.make(ss1, var1, ss1.getPredicate()); t22 = Statement.make(ss2, var2, ss2.getPredicate()); } else if (ss1.getPredicate().equals(ss2.getPredicate())) { t11 = Statement.make(ss1, ss1.getSubject(), var1); t22 = Statement.make(ss2, ss2.getSubject(), var2); }*/ if(ss2.containsTermRecursively(ss1.getSubject())) { HashMap<Term,Term> subs=new HashMap(); subs.put(ss1.getSubject(), var1); if(ss2.containsTermRecursively(ss1.getPredicate())) { subs.put(ss1.getPredicate(), var2); } t11=ss1.applySubstitute(subs); t22=ss2.applySubstitute(subs); } if(ss1.containsTermRecursively(ss2.getSubject())) { HashMap<Term,Term> subs=new HashMap(); subs.put(ss2.getSubject(), var1); if(ss1.containsTermRecursively(ss2.getPredicate())) { subs.put(ss2.getPredicate(), var2); } t11=ss1.applySubstitute(subs); t22=ss2.applySubstitute(subs); } //allow also temporal induction on operator arguments: if(ss2 instanceof Operation ^ ss1 instanceof Operation) { if(ss2 instanceof Operation && !(ss2.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term Term comp=ss1.getSubject(); Term ss2_term = ((Operation)ss2).getSubject(); boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep()); if(ss2_term instanceof Product) { Product ss2_prod=(Product) ss2_term; if(applicableVariableType && Terms.contains(ss2_prod.term, comp)) { //only if there is one and it isnt a variable already Term[] ars = ss2_prod.cloneTermsReplacing(comp, var1); t11 = Statement.make(ss1, var1, ss1.getPredicate()); Operation op=(Operation) Operation.make( new Product(ars), ss2.getPredicate() ); t22 = op; } } } if(ss1 instanceof Operation && !(ss1.getSubject() instanceof Variable)) {//it is an operation, let's look if one of the arguments is same as the subject of the other term Term comp=ss2.getSubject(); Term ss1_term = ((Operation)ss1).getSubject(); boolean applicableVariableType = !(comp instanceof Variable && ((Variable)comp).hasVarIndep()); if(ss1_term instanceof Product) { Product ss1_prod=(Product) ss1_term; if(applicableVariableType && Terms.contains(ss1_prod.term, comp)) { //only if there is one and it isnt a variable already Term[] ars = ss1_prod.cloneTermsReplacing(comp, var1); t22 = Statement.make(ss2, var1, ss2.getPredicate()); Operation op=(Operation) Operation.make( new Product(ars), ss1.getPredicate() ); t11 = op; } } } } } int durationCycles = Parameters.DURATION; long time1 = s1.getOccurenceTime(); long time2 = s2.getOccurenceTime(); long timeDiff = time2 - time1; List<Interval> interval=null; if (!concurrent(time1, time2, durationCycles)) { interval = Interval.intervalTimeSequence(Math.abs(timeDiff), Parameters.TEMPORAL_INTERVAL_PRECISION, nal.mem()); if (timeDiff > 0) { t1 = Conjunction.make(t1, interval, ORDER_FORWARD); if(t11!=null) { t11 = Conjunction.make(t11, interval, ORDER_FORWARD); } } else { t2 = Conjunction.make(t2, interval, ORDER_FORWARD); if(t22!=null) { t22 = Conjunction.make(t22, interval, ORDER_FORWARD); } } } int order = order(timeDiff, durationCycles); TruthValue givenTruth1 = s1.truth; TruthValue givenTruth2 = s2.truth; //This code adds a penalty for large time distance (TODO probably revise) Sentence s3 = s2.projection(s1.getOccurenceTime(), nal.memory.time()); givenTruth2 = s3.truth; // TruthFunctions. TruthValue truth1 = TruthFunctions.induction(givenTruth1, givenTruth2); TruthValue truth2 = TruthFunctions.induction(givenTruth2, givenTruth1); TruthValue truth3 = TruthFunctions.comparison(givenTruth1, givenTruth2); TruthValue truth4 = TruthFunctions.intersection(givenTruth1, givenTruth2); BudgetValue budget1 = BudgetFunctions.forward(truth1, nal); budget1.setPriority(budget1.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY); BudgetValue budget2 = BudgetFunctions.forward(truth2, nal); budget2.setPriority(budget2.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY); BudgetValue budget3 = BudgetFunctions.forward(truth3, nal); budget3.setPriority(budget3.getPriority() * Parameters.TEMPORAL_INDUCTION_PRIORITY_PENALTY); BudgetValue budget4 = BudgetFunctions.forward(truth4, nal); //this one is sequence in sequenceBag, no need to reduce here //https://groups.google.com/forum/#!topic/open-nars/0k-TxYqg4Mc /*if(!SucceedingEventsInduction)*/ { //reduce priority according to temporal distance //it was not "semantically" connected by temporal succession int tt1=(int) s1.getOccurenceTime(); int tt2=(int) s2.getOccurenceTime(); int d=Math.abs(tt1-tt2)/Parameters.DURATION; if(d!=0) { double mul=1.0/((double)d); mul *= ConjunctionPriority(nal, t1); mul *= ConjunctionPriority(nal, t2); budget1.setPriority((float) (budget1.getPriority()*mul)); budget2.setPriority((float) (budget2.getPriority()*mul)); budget3.setPriority((float) (budget3.getPriority()*mul)); budget4.setPriority((float) (budget4.getPriority()*mul)); } } Statement statement1 = Implication.make(t1, t2, order); Statement statement2 = Implication.make(t2, t1, reverseOrder(order)); Statement statement3 = Equivalence.make(t1, t2, order); Term statement4 = null; switch (order) { case TemporalRules.ORDER_FORWARD: statement4 = Conjunction.make(t1, interval, s2.term, order); break; case TemporalRules.ORDER_BACKWARD: statement4 = Conjunction.make(s2.term, interval, t1, reverseOrder(order)); break; default: statement4 = Conjunction.make(t1, s2.term, order); break; } //maybe this way is also the more flexible and intelligent way to introduce variables for the case above //TODO: rethink this for 1.6.3 //"Perception Variable Introduction Rule" - https://groups.google.com/forum/#!topic/open-nars/uoJBa8j7ryE if(!deriveSequenceOnly && statement2!=null) { //there is no general form //ok then it may be the (&/ =/> case which //is discussed here: https://groups.google.com/forum/#!topic/open-nars/uoJBa8j7ryE Statement st=statement2; if(st.getPredicate() instanceof Inheritance && (st.getSubject() instanceof Conjunction || st.getSubject() instanceof Operation)) { Term precon=(Term) st.getSubject(); Inheritance consequence=(Inheritance) st.getPredicate(); Term pred=consequence.getPredicate(); Term sub=consequence.getSubject(); //look if subject is contained in precon: boolean SubsSub=precon.containsTermRecursively(sub); boolean SubsPred=precon.containsTermRecursively(pred); Variable v1=new Variable("$91"); Variable v2=new Variable("$92"); HashMap<Term,Term> app=new HashMap<Term,Term>(); if(SubsSub || SubsPred) { if(SubsSub) app.put(sub, v1); if(SubsPred) app.put(pred,v2); Term res=((CompoundTerm) statement2).applySubstitute(app); if(res!=null) { //ok we applied it, all we have to do now is to use it t22=((Statement)res).getSubject(); t11=((Statement)res).getPredicate(); } } } } List<Task> success=new ArrayList<Task>(); if(!deriveSequenceOnly && t11!=null && t22!=null) { Statement statement11 = Implication.make(t11, t22, order); Statement statement22 = Implication.make(t22, t11, reverseOrder(order)); Statement statement33 = Equivalence.make(t11, t22, order); if(!tooMuchTemporalStatements(statement11)) { List<Task> t=nal.doublePremiseTask(statement11, truth1, budget1,true, false); if(t!=null) { success.addAll(t); } } if(!tooMuchTemporalStatements(statement22)) { List<Task> t=nal.doublePremiseTask(statement22, truth2, budget2,true, false); if(t!=null) { success.addAll(t); } } if(!tooMuchTemporalStatements(statement33)) { List<Task> t=nal.doublePremiseTask(statement33, truth3, budget3,true, false); if(t!=null) { success.addAll(t); } } } if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement1)) { List<Task> t=nal.doublePremiseTask(statement1, truth1, budget1,true, false); if(t!=null) { success.addAll(t); for(Task task : t) { task.setObservablePrediction(true); //we assume here that this function is used for observable events currently } } } if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement2)) { List<Task> t=nal.doublePremiseTask(statement2, truth2, budget2,true, false); if(t!=null) { success.addAll(t); for(Task task : t) { task.setObservablePrediction(true); //we assume here that this function is used for observable events currently } /*Task task=t; //micropsi inspired strive for knowledge //get strongest belief of that concept and use the revison truth, if there is no, use this truth double conf=task.sentence.truth.getConfidence(); Concept C=nal.memory.concept(task.sentence.term); if(C!=null && C.beliefs!=null && C.beliefs.size()>0) { Sentence bel=C.beliefs.get(0).sentence; TruthValue cur=bel.truth; conf=Math.max(cur.getConfidence(), conf); //no matter if revision is possible, it wont be below max //if there is no overlapping evidental base, use revision: boolean revisable=true; for(long l: bel.stamp.evidentialBase) { for(long h: task.sentence.stamp.evidentialBase) { if(l==h) { revisable=false; break; } } } if(revisable) { conf=TruthFunctions.revision(task.sentence.truth, bel.truth).getConfidence(); } } questionFromLowConfidenceHighPriorityJudgement(task, conf, nal); */ } } if(!deriveSequenceOnly && !tooMuchTemporalStatements(statement3)) { List<Task> t=nal.doublePremiseTask(statement3, truth3, budget3,true, false); if(t!=null) { for(Task task : t) { task.setObservablePrediction(true); //we assume here that this function is used for observable events currently } success.addAll(t); } } if(!tooMuchTemporalStatements(statement4)) { List<Task> tl=nal.doublePremiseTask(statement4, truth4, budget4,true, false); if(tl!=null) { for(Task t : tl) { //fill sequenceTask buffer due to the new derived sequence if(t.sentence.isJudgment() && !t.sentence.isEternal() && t.sentence.term instanceof Conjunction && ((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_NONE && ((Conjunction) t.sentence.term).getTemporalOrder() != TemporalRules.ORDER_INVALID) { TemporalInferenceControl.addToSequenceTasks(nal, t); } success.add(t); } } } return success; } private static void questionFromLowConfidenceHighPriorityJudgement(Task task, double conf, final DerivationContext nal) { if(nal.memory.emotion.busy()<Parameters.CURIOSITY_BUSINESS_THRESHOLD && Parameters.CURIOSITY_ALSO_ON_LOW_CONFIDENT_HIGH_PRIORITY_BELIEF && task.sentence.punctuation==Symbols.JUDGMENT_MARK && conf<Parameters.CURIOSITY_CONFIDENCE_THRESHOLD && task.getPriority()>Parameters.CURIOSITY_PRIORITY_THRESHOLD) { if(task.sentence.term instanceof Implication) { boolean valid=false; if(task.sentence.term instanceof Implication) { Implication equ=(Implication) task.sentence.term; if(equ.getTemporalOrder()!=TemporalRules.ORDER_NONE) { valid=true; } } if(valid) { Sentence tt2=new Sentence(task.sentence.term.clone(),Symbols.QUESTION_MARK,null,new Stamp(task.sentence.stamp.clone(),nal.memory.time())); BudgetValue budg=task.budget.clone(); budg.setPriority(budg.getPriority()*Parameters.CURIOSITY_DESIRE_PRIORITY_MUL); budg.setDurability(budg.getPriority()*Parameters.CURIOSITY_DESIRE_DURABILITY_MUL); nal.singlePremiseTask(tt2, task.budget.clone()); } } } } /** * Evaluate the quality of the judgment as a solution to a problem * * @param problem A goal or question * @param solution The solution to be evaluated * @return The quality of the judgment as the solution */ public static float solutionQuality(boolean rateByConfidence, final Task probT, final Sentence solution, Memory memory) { Sentence problem = probT.sentence; if (!matchingOrder(problem.getTemporalOrder(), solution.getTemporalOrder())) { return 0.0F; } TruthValue truth = solution.truth; if (problem.getOccurenceTime()!=solution.getOccurenceTime()) { truth = solution.projectionTruth(problem.getOccurenceTime(), memory.time()); } //when the solutions are comparable, we have to use confidence!! else truth expectation. //this way negative evidence can update the solution instead of getting ignored due to lower truth expectation. //so the previous handling to let whether the problem has query vars decide was wrong. if (!rateByConfidence) { return (float) (truth.getExpectation() / Math.sqrt(Math.sqrt(Math.sqrt(solution.term.getComplexity()*Parameters.COMPLEXITY_UNIT)))); } else { return truth.getConfidence(); } } /* ----- Functions used both in direct and indirect processing of tasks ----- */ /** * Evaluate the quality of a belief as a solution to a problem, then reward * the belief and de-prioritize the problem * * @param problem The problem (question or goal) to be solved * @param solution The belief as solution * @param task The task to be immediately processed, or null for continued * process * @return The budget for the new task which is the belief activated, if * necessary */ public static BudgetValue solutionEval(final Task problem, final Sentence solution, Task task, final nars.control.DerivationContext nal) { BudgetValue budget = null; boolean feedbackToLinks = false; if (task == null) { task = nal.getCurrentTask(); feedbackToLinks = true; } boolean judgmentTask = task.sentence.isJudgment(); boolean rateByConfidence = problem.getTerm().hasVarQuery(); //here its whether its a what or where question for budget adjustment final float quality = TemporalRules.solutionQuality(rateByConfidence, problem, solution, nal.mem()); if (problem.sentence.isGoal()) { nal.memory.emotion.adjustHappy(quality, task.getPriority(), nal); } if (judgmentTask) { task.incPriority(quality); } else { float taskPriority = task.getPriority(); //+goal satisfication is a matter of degree - https://groups.google.com/forum/#!topic/open-nars/ZfCM416Dx1M budget = new BudgetValue(UtilityFunctions.or(taskPriority, quality), task.getDurability(), BudgetFunctions.truthToQuality(solution.truth)); task.setPriority(Math.min(1 - quality, taskPriority)); } if (feedbackToLinks) { TaskLink tLink = nal.getCurrentTaskLink(); tLink.setPriority(Math.min(1 - quality, tLink.getPriority())); TermLink bLink = nal.getCurrentBeliefLink(); bLink.incPriority(quality); } return budget; } public static int order(final long timeDiff, final int durationCycles) { final int halfDuration = durationCycles/2; if (timeDiff > halfDuration) { return ORDER_FORWARD; } else if (timeDiff < -halfDuration) { return ORDER_BACKWARD; } else { return ORDER_CONCURRENT; } } /** if (relative) event B after (stationary) event A then order=forward; * event B before then order=backward * occur at the same time, relative to duration: order = concurrent */ public static int order(final long a, final long b, final int durationCycles) { if ((a == Stamp.ETERNAL) || (b == Stamp.ETERNAL)) throw new RuntimeException("order() does not compare ETERNAL times"); return order(b - a, durationCycles); } public static boolean concurrent(final long a, final long b, final int durationCycles) { //since Stamp.ETERNAL is Integer.MIN_VALUE, //avoid any overflow errors by checking eternal first if (a == Stamp.ETERNAL) { //if both are eternal, consider concurrent. this is consistent with the original //method of calculation which compared equivalent integer values only return (b == Stamp.ETERNAL); } else if (b == Stamp.ETERNAL) { return false; //a==b was compared above } else { return order(a, b, durationCycles) == ORDER_CONCURRENT; } } }
Comments, and as before. So it is like 1.6.5 but with an interval fix now.
nars_core/nars/inference/TemporalRules.java
Comments, and as before. So it is like 1.6.5 but with an interval fix now.
<ide><path>ars_core/nars/inference/TemporalRules.java <ide> BudgetValue budget4 = BudgetFunctions.forward(truth4, nal); //this one is sequence in sequenceBag, no need to reduce here <ide> <ide> //https://groups.google.com/forum/#!topic/open-nars/0k-TxYqg4Mc <del> /*if(!SucceedingEventsInduction)*/ <add> if(!SucceedingEventsInduction) //not used currently as succeeding event induction (involving sequence bag elements) <add> //is the current temporal induction strategy <ide> { //reduce priority according to temporal distance <ide> //it was not "semantically" connected by temporal succession <ide> int tt1=(int) s1.getOccurenceTime();
Java
apache-2.0
971bd20722c788a1918649862a27068808219096
0
lovemomia/mapi,lovemomia/mapi
package cn.momia.mapi.api.v1.course; import cn.momia.api.base.MetaUtil; import cn.momia.api.base.dto.AgeRangeDto; import cn.momia.api.base.dto.SortTypeDto; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.SubjectServiceApi; import cn.momia.api.course.dto.CourseCommentDto; import cn.momia.api.course.dto.CourseDto; import cn.momia.api.course.dto.SubjectDto; import cn.momia.api.course.dto.SubjectSkuDto; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.ContactDto; import cn.momia.api.user.dto.UserDto; import cn.momia.common.api.dto.PagedList; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.common.webapp.config.Configuration; import cn.momia.image.api.ImageFile; import cn.momia.mapi.api.v1.AbstractV1Api; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/v1/subject") public class SubjectV1Api extends AbstractV1Api { @Autowired private CourseServiceApi courseServiceApi; @Autowired private SubjectServiceApi subjectServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; SubjectDto subject = subjectServiceApi.get(id); subject.setCover(ImageFile.largeUrl(subject.getCover())); subject.setImgs(completeLargeImgs(subject.getImgs())); PagedList<CourseDto> courses = courseServiceApi.query(id, 0, 2); processCourses(courses.getList()); PagedList<CourseCommentDto> comments = courseServiceApi.queryCommentsBySubject(id, 0, 2); processCourseComments(comments.getList()); JSONObject responseJson = new JSONObject(); responseJson.put("subject", subject); responseJson.put("courses", courses); if (!comments.getList().isEmpty()) responseJson.put("comments", comments); return MomiaHttpResponse.SUCCESS(responseJson); } private void processCourses(List<CourseDto> courses) { for (CourseDto course : courses) { course.setCover(ImageFile.middleUrl(course.getCover())); } } @RequestMapping(value = "/course", method = RequestMethod.GET) public MomiaHttpResponse listCourses(@RequestParam long id, @RequestParam(value = "pid", required = false, defaultValue = "0") long packageId, @RequestParam(required = false, defaultValue = "0") int age, @RequestParam(required = false, defaultValue = "0") int sort, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; AgeRangeDto ageRange = MetaUtil.getAgeRange(age); SortTypeDto sortType = MetaUtil.getSortType(sort); PagedList<CourseDto> courses = courseServiceApi.query(id, packageId, ageRange.getMin(), ageRange.getMax(), sortType.getId(), start, Configuration.getInt("PageSize.Course")); processCourses(courses.getList()); JSONObject responseJson = new JSONObject(); responseJson.put("ages", MetaUtil.listAgeRanges()); responseJson.put("sorts", MetaUtil.listSortTypes()); responseJson.put("currentAge", ageRange.getId()); responseJson.put("currentSort", sortType.getId()); responseJson.put("courses", courses); return MomiaHttpResponse.SUCCESS(responseJson); } @RequestMapping(value = "/comment/list", method = RequestMethod.GET) public MomiaHttpResponse listComments(@RequestParam long id, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<CourseCommentDto> pageComments = courseServiceApi.queryCommentsBySubject(id, start, Configuration.getInt("PageSize.CourseComment")); processCourseComments(pageComments.getList()); return MomiaHttpResponse.SUCCESS(pageComments); } @RequestMapping(value = "/sku", method = RequestMethod.GET) public MomiaHttpResponse sku(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; List<SubjectSkuDto> skus = subjectServiceApi.querySkus(id); ContactDto contact = userServiceApi.getContact(utoken); JSONObject responseJson = new JSONObject(); responseJson.put("skus", skus); responseJson.put("contact", contact); return MomiaHttpResponse.SUCCESS(responseJson); } @RequestMapping(value = "/order", method = RequestMethod.POST) public MomiaHttpResponse order(@RequestParam String utoken, @RequestParam String order) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(order)) return MomiaHttpResponse.BAD_REQUEST; JSONObject orderJson = JSON.parseObject(order); UserDto user = userServiceApi.get(utoken); orderJson.put("userId", user.getId()); JSONObject contactJson = orderJson.getJSONObject("contact"); orderJson.put("contact", contactJson.getString("name")); orderJson.put("mobile", contactJson.getString("mobile")); JSONArray packagesJson = new JSONArray(); JSONArray skusJson = orderJson.getJSONArray("skus"); for (int i = 0; i < skusJson.size(); i++) { JSONObject skuJson = skusJson.getJSONObject(i); orderJson.put("subjectId", skuJson.getLong("subjectId")); int count = skuJson.getInteger("count"); for (int j = 0; j < count; j++) { JSONObject packageJson = new JSONObject(); packageJson.put("skuId", skuJson.getLong("id")); packagesJson.add(packageJson); } } orderJson.put("packages", packagesJson); return MomiaHttpResponse.SUCCESS(subjectServiceApi.placeOrder(orderJson)); } @RequestMapping(value = "/order/delete", method = RequestMethod.POST) public MomiaHttpResponse deleteOrder(@RequestParam String utoken, @RequestParam(value = "oid") long orderId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (orderId <= 0) return MomiaHttpResponse.BAD_REQUEST; if (!subjectServiceApi.deleteOrder(utoken, orderId)) return MomiaHttpResponse.FAILED("删除订单失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/order/refund", method = RequestMethod.POST) public MomiaHttpResponse refund(@RequestParam String utoken, @RequestParam(value = "oid") long orderId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (orderId <= 0) return MomiaHttpResponse.BAD_REQUEST; if (!subjectServiceApi.refundOrder(utoken, orderId)) return MomiaHttpResponse.FAILED("申请退款失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/order/coupon", method = RequestMethod.GET) public MomiaHttpResponse coupon(@RequestParam String utoken, @RequestParam(value = "oid") long orderId, @RequestParam(value = "coupon") long userCouponId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (orderId <= 0 || userCouponId <= 0) return MomiaHttpResponse.BAD_REQUEST; return MomiaHttpResponse.SUCCESS(subjectServiceApi.coupon(utoken, orderId, userCouponId)); } @RequestMapping(value = "/favor", method = RequestMethod.POST) public MomiaHttpResponse favor(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!subjectServiceApi.favor(user.getId(), id)) return MomiaHttpResponse.FAILED("添加收藏失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/unfavor", method = RequestMethod.POST) public MomiaHttpResponse unfavor(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!subjectServiceApi.unfavor(user.getId(), id)) return MomiaHttpResponse.FAILED("取消收藏失败"); return MomiaHttpResponse.SUCCESS; } }
src/main/java/cn/momia/mapi/api/v1/course/SubjectV1Api.java
package cn.momia.mapi.api.v1.course; import cn.momia.api.base.MetaUtil; import cn.momia.api.base.dto.AgeRangeDto; import cn.momia.api.base.dto.SortTypeDto; import cn.momia.api.course.CourseServiceApi; import cn.momia.api.course.SubjectServiceApi; import cn.momia.api.course.dto.CourseCommentDto; import cn.momia.api.course.dto.CourseDto; import cn.momia.api.course.dto.SubjectDto; import cn.momia.api.course.dto.SubjectSkuDto; import cn.momia.api.user.UserServiceApi; import cn.momia.api.user.dto.ContactDto; import cn.momia.api.user.dto.UserDto; import cn.momia.common.api.dto.PagedList; import cn.momia.common.api.http.MomiaHttpResponse; import cn.momia.common.webapp.config.Configuration; import cn.momia.image.api.ImageFile; import cn.momia.mapi.api.v1.AbstractV1Api; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/v1/subject") public class SubjectV1Api extends AbstractV1Api { @Autowired private CourseServiceApi courseServiceApi; @Autowired private SubjectServiceApi subjectServiceApi; @Autowired private UserServiceApi userServiceApi; @RequestMapping(method = RequestMethod.GET) public MomiaHttpResponse get(@RequestParam long id) { if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; SubjectDto subject = subjectServiceApi.get(id); subject.setCover(ImageFile.largeUrl(subject.getCover())); subject.setImgs(completeLargeImgs(subject.getImgs())); PagedList<CourseDto> courses = courseServiceApi.query(id, 0, 2); processCourses(courses.getList()); PagedList<CourseCommentDto> comments = courseServiceApi.queryCommentsBySubject(id, 0, 2); processCourseComments(comments.getList()); JSONObject responseJson = new JSONObject(); responseJson.put("subject", subject); responseJson.put("courses", courses); if (!comments.getList().isEmpty()) responseJson.put("comments", comments); return MomiaHttpResponse.SUCCESS(responseJson); } private void processCourses(List<CourseDto> courses) { for (CourseDto course : courses) { course.setCover(ImageFile.middleUrl(course.getCover())); } } @RequestMapping(value = "/course", method = RequestMethod.GET) public MomiaHttpResponse listCourses(@RequestParam long id, @RequestParam(value = "pid", required = false, defaultValue = "0") long packageId, @RequestParam(required = false, defaultValue = "0") int age, @RequestParam(required = false, defaultValue = "0") int sort, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; AgeRangeDto ageRange = MetaUtil.getAgeRange(age); SortTypeDto sortType = MetaUtil.getSortType(sort); PagedList<CourseDto> courses = courseServiceApi.query(id, packageId, ageRange.getMin(), ageRange.getMax(), sortType.getId(), start, Configuration.getInt("PageSize.Course")); processCourses(courses.getList()); JSONObject responseJson = new JSONObject(); responseJson.put("ages", MetaUtil.listAgeRanges()); responseJson.put("sorts", MetaUtil.listSortTypes()); responseJson.put("currentAge", ageRange.getId()); responseJson.put("currentSort", sortType.getId()); responseJson.put("courses", courses); return MomiaHttpResponse.SUCCESS(responseJson); } @RequestMapping(value = "/comment/list", method = RequestMethod.GET) public MomiaHttpResponse listComments(@RequestParam long id, @RequestParam int start) { if (id <= 0 || start < 0) return MomiaHttpResponse.BAD_REQUEST; PagedList<CourseCommentDto> pageComments = courseServiceApi.queryCommentsBySubject(id, start, Configuration.getInt("PageSize.CourseComment")); processCourseComments(pageComments.getList()); return MomiaHttpResponse.SUCCESS(pageComments); } @RequestMapping(value = "/sku", method = RequestMethod.GET) public MomiaHttpResponse sku(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; List<SubjectSkuDto> skus = subjectServiceApi.querySkus(id); ContactDto contact = userServiceApi.getContact(utoken); JSONObject responseJson = new JSONObject(); responseJson.put("skus", skus); responseJson.put("contact", contact); return MomiaHttpResponse.SUCCESS(responseJson); } @RequestMapping(value = "/order", method = RequestMethod.POST) public MomiaHttpResponse order(@RequestParam String utoken, @RequestParam String order) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (StringUtils.isBlank(order)) return MomiaHttpResponse.BAD_REQUEST; JSONObject orderJson = JSON.parseObject(order); UserDto user = userServiceApi.get(utoken); orderJson.put("userId", user.getId()); JSONObject contactJson = orderJson.getJSONObject("contact"); orderJson.put("contact", contactJson.getString("name")); orderJson.put("mobile", contactJson.getString("mobile")); JSONArray packagesJson = new JSONArray(); JSONArray skusJson = orderJson.getJSONArray("skus"); for (int i = 0; i < skusJson.size(); i++) { JSONObject skuJson = skusJson.getJSONObject(i); orderJson.put("subjectId", skuJson.getLong("subjectId")); int count = skuJson.getInteger("count"); for (int j = 0; j < count; j++) { JSONObject packageJson = new JSONObject(); packageJson.put("skuId", skuJson.getLong("id")); packagesJson.add(packageJson); } } orderJson.put("packages", packagesJson); return MomiaHttpResponse.SUCCESS(subjectServiceApi.placeOrder(orderJson)); } @RequestMapping(value = "/order/delete", method = RequestMethod.POST) public MomiaHttpResponse deleteOrder(@RequestParam String utoken, @RequestParam(value = "oid") long orderId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (orderId <= 0) return MomiaHttpResponse.BAD_REQUEST; if (!subjectServiceApi.deleteOrder(utoken, orderId)) return MomiaHttpResponse.FAILED("删除订单失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/order/refund", method = RequestMethod.POST) public MomiaHttpResponse refund(@RequestParam String utoken, @RequestParam(value = "oid") long orderId) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (orderId <= 0) return MomiaHttpResponse.BAD_REQUEST; if (!subjectServiceApi.refundOrder(utoken, orderId)) return MomiaHttpResponse.FAILED("申请退款失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/favor", method = RequestMethod.POST) public MomiaHttpResponse favor(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!subjectServiceApi.favor(user.getId(), id)) return MomiaHttpResponse.FAILED("添加收藏失败"); return MomiaHttpResponse.SUCCESS; } @RequestMapping(value = "/unfavor", method = RequestMethod.POST) public MomiaHttpResponse unfavor(@RequestParam String utoken, @RequestParam long id) { if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; if (id <= 0) return MomiaHttpResponse.BAD_REQUEST; UserDto user = userServiceApi.get(utoken); if (!subjectServiceApi.unfavor(user.getId(), id)) return MomiaHttpResponse.FAILED("取消收藏失败"); return MomiaHttpResponse.SUCCESS; } }
计算优惠后的价格
src/main/java/cn/momia/mapi/api/v1/course/SubjectV1Api.java
计算优惠后的价格
<ide><path>rc/main/java/cn/momia/mapi/api/v1/course/SubjectV1Api.java <ide> return MomiaHttpResponse.SUCCESS; <ide> } <ide> <add> @RequestMapping(value = "/order/coupon", method = RequestMethod.GET) <add> public MomiaHttpResponse coupon(@RequestParam String utoken, <add> @RequestParam(value = "oid") long orderId, <add> @RequestParam(value = "coupon") long userCouponId) { <add> if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED; <add> if (orderId <= 0 || userCouponId <= 0) return MomiaHttpResponse.BAD_REQUEST; <add> <add> return MomiaHttpResponse.SUCCESS(subjectServiceApi.coupon(utoken, orderId, userCouponId)); <add> } <add> <ide> @RequestMapping(value = "/favor", method = RequestMethod.POST) <ide> public MomiaHttpResponse favor(@RequestParam String utoken, @RequestParam long id) { <ide> if (StringUtils.isBlank(utoken)) return MomiaHttpResponse.TOKEN_EXPIRED;
Java
apache-2.0
ea02c02394255cbcafff69c15eadd95cadc2c03c
0
CloudSlang/cs-actions,CloudSlang/score-actions,CloudSlang/cs-actions,victorursan/cs-actions
/******************************************************************************* * (c) Copyright 2017 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package io.cloudslang.content.httpclient; import com.hp.oo.sdk.content.annotations.Action; import com.hp.oo.sdk.content.annotations.Output; import com.hp.oo.sdk.content.annotations.Param; import com.hp.oo.sdk.content.annotations.Response; import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType; import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType; import com.hp.oo.sdk.content.plugin.GlobalSessionObject; import com.hp.oo.sdk.content.plugin.SerializableSessionObject; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import static org.apache.commons.lang3.StringUtils.defaultIfEmpty; /** * Created with IntelliJ IDEA. * User: davidmih * Date: 7/15/14 */ public class HttpClientAction { private static final String DEFAULT_JAVA_KEYSTORE = System.getProperty("java.home") + "/lib/security/cacerts"; private static final String CHANGEIT = "changeit"; /** * This operation does an http request and a parsing of the response. * It provides features like: http autentication, http secure, connection pool, cookies, proxy. * To acomplish this it uses the third parties from Apache: HttpClient 4.3, HttpCore 4.3. * It also uses the JCIFS library from the Samba for the 'NTLM' authentication. * <p/> * <br><b>For more info about http client operations see the <i>org.cloudslang.content.httpclient</i> package description.</b> * * @param url The web address to make the request to. This must be a standard URL as specified in RFC 3986. This is a required input. * <br>Format: scheme://domain:port/path?query_string#fragment_id. * <br>Examples: https://[fe80::1260:4bff:fe49:42fc]:8080/my/path?key1=val1&key2=val2#my_fragment * @param authType The type of authentication used by this operation when trying to execute the request on the target server. * The authentication is not preemptive: a plain request not including authentication info * will be made and only when the server responds with a 'WWW-Authenticate' header the client will * send required headers. If the server needs no authentication but you specify one in this input * the request will work nevertheless. Then client cannot choose the authentication method and there * is no fallback so you have to know which one you need. If the web application and proxy use * different authentication types, these must be specified like in the Example model. * <br>Default value: basic. Valid values: basic, digest, ntlm, kerberos, any, anonymous, "" or a list of valid values separated by comma. * @param preemptiveAuth If this field is 'true' authentication info will be sent in the first request. * If this is 'false' a request with no authentication info will be made and if server responds * with 401 and a header like WWW-Authenticate: Basic realm="myRealm" only then the authentication * info will be sent. Default value: true. Valid values: true, false * @param username The user name used for authentication. For NTLM authentication, the required format is 'domain\\user' * and if you only specify the 'user' it will append a dot like '.\\user' so that a local user on the * target machine can be used. In order for all authentication schemes to work (except Kerberos) username is required. * @param password The password used for authentication. * @param kerberosConfFile A krb5.conf file with content similar to the one in the examples * (where you replace CONTOSO.COM with your domain and 'ad.contoso.com' with your kdc FQDN). * This configures the Kerberos mechanism required by the Java GSS-API methods. * <br>Format: http://web.mit.edu/kerberos/krb5-1.4/krb5-1.4.4/doc/krb5-admin/krb5.conf.html * @param kerberosLoginConfFile A login.conf file needed by the JAAS framework with the content similar to the one in examples * Format: http://docs.oracle.com/javase/7/docs/jre/api/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html * @param kerberosSkipPortForLookup Do not include port in the key distribution center database lookup. Default value: true. Valid values: true, false * @param proxyHost The proxy server used to access the web site. * @param proxyPort The proxy server port. Default value: 8080. Valid values: -1 and integer values greater than 0. * The value '-1' indicates that the proxy port is not set and the scheme default port will be used. * If the scheme is 'http://' and the 'proxyPort' is set to '-1' then port '80' will be used. * @param proxyUsername The user name used when connecting to the proxy. The 'authType' input will be used to choose authentication type. * The 'Basic' and 'Digest' proxy authentication types are supported. * @param proxyPassword The proxy server password associated with the proxyUsername input value. * @param trustAllRoots Specifies whether to enable weak security over SSL/TSL. A certificate is trusted even if no trusted * certification authority issued it. Default value: false. Valid values: true, false * @param x509HostnameVerifier Specifies the way the server hostname must match a domain name in the subject's Common Name (CN) * or subjectAltName field of the X.509 certificate. Set this to "allow_all" to skip any checking. * For the value "browser_compatible" the hostname verifier works the same way as Curl and Firefox. * The hostname must match either the first CN, or any of the subject-alts. * A wildcard can occur in the CN, and in any of the subject-alts. The only difference * between "browser_compatible" and "strict" is that a wildcard (such as "*.foo.com") * with "browser_compatible" matches all subdomains, including "a.b.foo.com". * Default value: strict. Valid values: strict,browser_compatible,allow_all * @param trustKeystore The pathname of the Java TrustStore file. This contains certificates from other parties * that you expect to communicate with, or from Certificate Authorities that you trust to * identify other parties. If the protocol (specified by the 'url') is not 'https' or if * trustAllRoots is 'true' this input is ignored. Default value: <OO_Home>/java/lib/security/cacerts. Format: Java KeyStore (JKS) * @param trustPassword The password associated with the TrustStore file. If trustAllRoots is false and trustKeystore is empty, * trustPassword default will be supplied. Default value: changeit * @param keystore The pathname of the Java KeyStore file. You only need this if the server requires client authentication. * If the protocol (specified by the 'url') is not 'https' or if trustAllRoots is 'true' this input is ignored. * <br>Default value: <OO_Home>/java/lib/security/cacerts. Format: Java KeyStore (JKS) * @param keystorePassword The password associated with the KeyStore file. If trustAllRoots is false and keystore * is empty, keystorePassword default will be supplied. Default value: changeit * @param connectTimeout The time to wait for a connection to be established, in seconds. * A timeout value of '0' represents an infinite timeout. Default value: 0 * @param socketTimeout The timeout for waiting for data (a maximum period inactivity between two consecutive data packets), * in seconds. A socketTimeout value of '0' represents an infinite timeout. Default value: 0. * @param useCookies Specifies whether to enable cookie tracking or not. Cookies are stored between consecutive calls * in a serializable session object therefore they will be available on a branch level. * If you specify a non-boolean value, the default value is used. Default value: true. Valid values: true, false * @param keepAlive Specifies whether to create a shared connection that will be used in subsequent calls. * If keepAlive is false, the already open connection will be used and after execution it will close it. * The operation will use a connection pool stored in a GlobalSessionObject that will be available throughout * the execution (the flow and subflows, between parallel split lanes). Default value: true. Valid values: true, false. * @param connectionsMaxPerRoot The maximum limit of connections on a per route basis. * The default will create no more than 2 concurrent connections per given route. Default value: 2 * @param connectionsMaxTotal The maximum limit of connections in total. * The default will create no more than 2 concurrent connections in total. Default value: 20 * @param headers The list containing the headers to use for the request separated by new line (CRLF). * The header name - value pair will be separated by ":". Format: According to HTTP standard for headers (RFC 2616). * Examples: Accept:text/plain * @param responseCharacterSet The character encoding to be used for the HTTP response. * If responseCharacterSet is empty, the charset from the 'Content-Type' HTTP response header will be used. * If responseCharacterSet is empty and the charset from the HTTP response Content-Type header is empty, * the default value will be used. You should not use this for method=HEAD or OPTIONS. Default value: ISO-8859-1 * @param destinationFile The absolute path of a file on disk where to save the entity returned by the response. * 'returnResult' will no longer be populated with the entity if this is specified. * You should not use this for method=HEAD or OPTIONS. Example: C:\temp\destinationFile.txt * @param followRedirects Specifies whether the HTTP client automatically follows redirects. * Redirects explicitly prohibited by the HTTP specification as requiring user intervention * will not be followed (redirects on POST and PUT requests that are converted to GET requests). * If you specify a non-boolean value, the default value is used. Default value: true. Valid values: true, false * @param queryParams The list containing query parameters to append to the URL. The names and the values must not * be URL encoded unless you specify "queryParamsAreURLEncoded"=true because if they are encoded * and "queryParamsAreURLEncoded"=false they will get double encoded. * The separator between name-value pairs is "&". The query name will be separated from query * value by "=". Note that you need to URL encode at least "&" to "%26" and "=" to "%3D" and * set "queryParamsAreURLEncoded"="true" if you leave the other special URL characters un-encoded * they will be encoded by the HTTP Client. Examples: parameterName1=parameterValue1&parameterName2=parameterValue2; * @param queryParamsAreURLEncoded Specifies whether to encode (according to the url encoding standard) the queryParams. * If you set "queryParamsAreURLEncoded"=true and you have invalid characters in 'queryParams' * they will get encoded anyway. If "queryParamsAreURLEncoded"=false all characters will be encoded. * But the ' ' (space) character will be encoded as + if queryParamsAreURLEncoded is either true or false. * Also %20 will be encoded as + if "queryParamsAreURLEncoded"=true. * If you specify a non-boolean value, the default value is used. * Default value: false. Valid values: true, false * @param queryParamsAreFormEncoded Specifies whether to encode the queryParams in the form request format or not. * This format is the default format used by the apache http client library. * If queryParamsAreFormEncoded=true then all characters will be encoded based on the queryParamsAreURLEncoded * input. If queryParamsAreFormEncoded=false all reserved characters are not encoded no matter of * queryParamsAreURLEncoded input. The only exceptions are for ' ' (space) character which is encoded as %20 in both * cases of queryParamsAreURLEncoded input and + (plus) which is encoded as %20 if queryParamsAreURLEncoded=true * and not encoded if queryParamsAreURLEncoded=false. If the special characters are already encoded * and queryParamsAreURLEncoded=true then they will be transformed into their original format. * For example: %40 will be @, %2B will be +. But %20 (space) will not be transformed. * The list of reserved chars is: ;/?:@&=+,$ * Default value: true. Valid values: true, false * Example: query=test te%20@st will be encoded in query=test%20te%20@st * @param formParams This input needs to be given in form encoded format and will set the entity to be sent in the request. * It will also set the content-type to application/x-www-form-urlencoded. * This should only be used with method=POST. Note that you need to URL encode at * least "&" to "%26" and "=" to "%3D" and set "queryParamsAreURLEncoded"="true" if you leave the * other special URL characters un-encoded they will be encoded by the HTTP Client. * <br>Examples: input1=value1&input2=value2. (The client will send: input1=value1&in+put+2=val+u%0A+e2) * @param formParamsAreURLEncoded formParams will be encoding (according to the url encoding standard) if this is 'true'. * If you set "formParamsAreURLEncoded"=true and you have invalid characters in 'formParams' * they will get encoded anyway. This should only be used with method=POST. * Default value: false. Valid values: true, false * @param sourceFile The absolute path of a file on disk from where to read the entity for the http request. * This will be read using 'requestCharacterSet' or 'contentType' input (see below). * This should not be provided for method=GET, HEAD, TRACE. Examples: C:\temp\sourceFile.txt * @param body The string to include in body for HTTP POST operation. If both sourceFile and body will be provided, * the body input has priority over sourceFile. This should not be provided for method=GET, HEAD, TRACE * @param contentType The content type that should be set in the request header, representing the MIME-type of the * data in the message body. Default value: text/plain. Examples: "text/html", "application/x-www-form-urlencoded" * @param requestCharacterSet The character encoding to be used for the HTTP request body. * If contentType is empty, the requestCharacterSet will use the default value. * If contentType will include charset (ex.: "application/json; charset=UTF-8"), * the requestCharacterSet value will overwrite the charset value from contentType input. * This should not be provided for method=GET, HEAD, TRACE. Default value: ISO-8859-1 * @param multipartBodies This is a name=textValue list of pairs separated by "&". This will also take into account * the "contentType" and "charset" inputs. The request entity will be like: * <br>Content-Disposition: form-data; name="name1" * <br>Content-Type: text/plain; charset=UTF-8 * <br>Content-Transfer-Encoding: 8bit * <br> * <br>textvalue1 * <br>Examples: name1=textvalue1&name2=textvalue2 * @param multipartBodiesContentType Each entity from the multipart entity has a content-type header. * You can only specify it once for all the parts and it is the only way to change * the characterSet of the encoding. Default value: text/plain; charset=ISO-8859-1 * Examples: text/plain; charset=UTF-8 * @param multipartFiles This is a list of name=filePath pairs. This will also take into account the "contentType" * and "charset" inputs. The request entity will be like: * <br>Content-Disposition: form-data; name="name3"; filename="readme.txt" * <br>Content-Type: application/octet-stream; charset=UTF-8 * <br>Content-Transfer-Encoding: binary the text in readme.txt * <br>Examples: name3=c:\temp\readme.txt&name4=c:\temp\log4j.properties * @param multipartFilesContentType Each entity from the multipart entity has a content-type header. You can only specify it once for all parts. * Default value: application/octet-stream. Examples: image/png,text/plain * @param multipartValuesAreURLEncoded You need to set this to 'true' if the bodies may contain the "&" and "=" * separators and you also need to URL encode them so that "&" becomes %26 and "=" becomes %3D * (using the URL Encoder operation on each value or by a simple replace). Default value: false * @param chunkedRequestEntity Data is sent in a series of "chunks". It uses the Transfer-Encoding HTTP header in place * of the Content-Length header.Generally it is recommended to let HttpClient choose the * most appropriate transfer encoding based on the properties of the HTTP message being transferred. * It is possible, however, to inform HttpClient that chunk coding is preferred by setting this input to "true". * Please note that HttpClient will use this flag as a hint only. * This value will be ignored when using HTTP protocol versions that do not support chunk coding, such as HTTP/1.0. * This setting is ignored for multipart post entities. * @param method The HTTP method used. This is a required input. * @param httpClientCookieSession the session object that holds the cookies if the useCookies input is true. * @param httpClientPoolingConnectionManager the GlobalSessionObject that holds the http client pooling connection manager. * @return a map containing the output of the operation. Keys present in the map are: * <br><br><b>returnResult</b> - This will contain the response entity (unless 'destinationFile' is specified). * In case of an error this output will contain the error message. * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, * this result contains the java stack trace of the runtime exception. * <br><b>statusCode</b> - The HTTP status code. * <br><i>Format</i>: <br>1xx (Informational - Request received, continuing process), * <br>2xx (Success - The action was successfully received, understood, and accepted), * <br>3xx (Redirection - Further action must be taken in order to complete the request), * <br>4xx (Client Error - The request contains bad syntax or cannot be fulfilled), * <br>5xx Server Error - The server failed to fulfil an apparently valid request) * <br>Examples: 200, 404 * <br><br><b>finalLocation</b> - The final location after redirects. Format: URL * <br><b>responseHeaders</b> - The list containing the headers of the response message, separated by newline. * Format: This is conforming to HTTP standard for headers (RFC 2616). * <br><b>protocolVersion</b> - The HTTP protocol version. Examples: HTTP/1.1 * <br><b>reasonPhrase</b> - The reason phrase from the origin HTTP response. This depends on the status code and are according to RFC 1945 and RFC 2048 * <br>Examples: (HTTP 1.0): OK, Created, Accepted, No Content, Moved Permanently, Moved Temporarily, Not Modified, Bad Request, * Unauthorized, Forbidden, Not Found, Internal Server Error, Not Implemented, Bad Gateway, * Service Unavailable Values (HTTP 1.1): Continue, Temporary Redirect, Method Not Allowed, * Conflict, Precondition Failed, Request Too Long, Request-URI Too Long, Unsupported Media Type, * Multiple Choices, See Other, Use Proxy, Payment Required, Not Acceptable, Proxy Authentication Required, * Request Timeout, Switching Protocols, Non Authoritative Information, Reset Content, Partial Content, * Gateway Timeout, Http Version Not Supported, Gone, Length Required, Requested Range Not Satisfiable, Expectation Failed * <p/> * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure. * @see io.cloudslang.content.httpclient */ @Action(name = "Http Client", outputs = { @Output(CSHttpClient.EXCEPTION), @Output(CSHttpClient.STATUS_CODE), @Output(CSHttpClient.FINAL_LOCATION), @Output(CSHttpClient.RESPONSE_HEADERS), @Output(CSHttpClient.PROTOCOL_VERSION), @Output(CSHttpClient.REASON_PHRASE), @Output("returnCode"), @Output("returnResult") }, responses = { @Response(text = "success", field = "returnCode", value = "0", matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = "failure", field = "returnCode", value = "-1", matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR) } ) public Map<String, String> execute( @Param(value = HttpClientInputs.URL, required = true) String url, @Param(HttpClientInputs.AUTH_TYPE) String authType, @Param(HttpClientInputs.PREEMPTIVE_AUTH) String preemptiveAuth, @Param(HttpClientInputs.USERNAME) String username, @Param(HttpClientInputs.PASSWORD) String password, @Param(HttpClientInputs.KERBEROS_CONFIG_FILE) String kerberosConfFile, @Param(HttpClientInputs.KERBEROS_LOGIN_CONFIG_FILE) String kerberosLoginConfFile, @Param(HttpClientInputs.KERBEROS_SKIP_PORT_CHECK) String kerberosSkipPortForLookup, @Param(HttpClientInputs.PROXY_HOST) String proxyHost, @Param(HttpClientInputs.PROXY_PORT) String proxyPort, @Param(HttpClientInputs.PROXY_USERNAME) String proxyUsername, @Param(HttpClientInputs.PROXY_PASSWORD) String proxyPassword, @Param(HttpClientInputs.TRUST_ALL_ROOTS) String trustAllRoots, @Param(HttpClientInputs.X509_HOSTNAME_VERIFIER) String x509HostnameVerifier, @Param(HttpClientInputs.TRUST_KEYSTORE) String trustKeystore, @Param(HttpClientInputs.TRUST_PASSWORD) String trustPassword, @Param(HttpClientInputs.KEYSTORE) String keystore, @Param(HttpClientInputs.KEYSTORE_PASSWORD) String keystorePassword, @Param(HttpClientInputs.CONNECT_TIMEOUT) String connectTimeout, @Param(HttpClientInputs.SOCKET_TIMEOUT) String socketTimeout, @Param(HttpClientInputs.USE_COOKIES) String useCookies, @Param(HttpClientInputs.KEEP_ALIVE) String keepAlive, @Param(HttpClientInputs.CONNECTIONS_MAX_PER_ROUTE) String connectionsMaxPerRoot, @Param(HttpClientInputs.CONNECTIONS_MAX_TOTAL) String connectionsMaxTotal, @Param(HttpClientInputs.HEADERS) String headers, @Param(HttpClientInputs.RESPONSE_CHARACTER_SET) String responseCharacterSet, @Param(HttpClientInputs.DESTINATION_FILE) String destinationFile, @Param(HttpClientInputs.FOLLOW_REDIRECTS) String followRedirects, @Param(HttpClientInputs.QUERY_PARAMS) String queryParams, @Param(HttpClientInputs.QUERY_PARAMS_ARE_URLENCODED) String queryParamsAreURLEncoded, @Param(HttpClientInputs.QUERY_PARAMS_ARE_FORM_ENCODED) String queryParamsAreFormEncoded, @Param(HttpClientInputs.FORM_PARAMS) String formParams, @Param(HttpClientInputs.FORM_PARAMS_ARE_URLENCODED) String formParamsAreURLEncoded, @Param(HttpClientInputs.SOURCE_FILE) String sourceFile, @Param(HttpClientInputs.BODY) String body, @Param(HttpClientInputs.CONTENT_TYPE) String contentType, @Param(HttpClientInputs.REQUEST_CHARACTER_SET) String requestCharacterSet, @Param(HttpClientInputs.MULTIPART_BODIES) String multipartBodies, @Param(HttpClientInputs.MULTIPART_BODIES_CONTENT_TYPE) String multipartBodiesContentType, @Param(HttpClientInputs.MULTIPART_FILES) String multipartFiles, @Param(HttpClientInputs.MULTIPART_FILES_CONTENT_TYPE) String multipartFilesContentType, @Param(HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED) String multipartValuesAreURLEncoded, @Param(HttpClientInputs.CHUNKED_REQUEST_ENTITY) String chunkedRequestEntity, @Param(value = HttpClientInputs.METHOD, required = true) String method, @Param(HttpClientInputs.SESSION_COOKIES) SerializableSessionObject httpClientCookieSession, @Param(HttpClientInputs.SESSION_CONNECTION_POOL) GlobalSessionObject httpClientPoolingConnectionManager) { HttpClientInputs httpClientInputs = new HttpClientInputs(); httpClientInputs.setUrl(url); httpClientInputs.setAuthType(authType); httpClientInputs.setPreemptiveAuth(preemptiveAuth); httpClientInputs.setUsername(username); httpClientInputs.setPassword(password); httpClientInputs.setKerberosConfFile(kerberosConfFile); httpClientInputs.setKerberosLoginConfFile(kerberosLoginConfFile); // httpClientInputs.setKerberosDomain(kerberosDomain); // httpClientInputs.setKerberosKdc(kerberosKdc); httpClientInputs.setKerberosSkipPortCheck(kerberosSkipPortForLookup); httpClientInputs.setProxyHost(proxyHost); httpClientInputs.setProxyPort(proxyPort); httpClientInputs.setProxyUsername(proxyUsername); httpClientInputs.setProxyPassword(proxyPassword); httpClientInputs.setTrustAllRoots(trustAllRoots); httpClientInputs.setX509HostnameVerifier(x509HostnameVerifier); httpClientInputs.setTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE)); httpClientInputs.setTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT)); httpClientInputs.setKeystore(defaultIfEmpty(keystore, DEFAULT_JAVA_KEYSTORE)); httpClientInputs.setKeystorePassword(defaultIfEmpty(keystorePassword, CHANGEIT)); httpClientInputs.setConnectTimeout(connectTimeout); httpClientInputs.setSocketTimeout(socketTimeout); httpClientInputs.setUseCookies(useCookies); httpClientInputs.setKeepAlive(keepAlive); httpClientInputs.setConnectionsMaxPerRoute(connectionsMaxPerRoot); httpClientInputs.setConnectionsMaxTotal(connectionsMaxTotal); httpClientInputs.setHeaders(headers); httpClientInputs.setResponseCharacterSet(responseCharacterSet); httpClientInputs.setDestinationFile(destinationFile); httpClientInputs.setFollowRedirects(followRedirects); httpClientInputs.setQueryParams(queryParams); httpClientInputs.setQueryParamsAreURLEncoded(queryParamsAreURLEncoded); httpClientInputs.setQueryParamsAreFormEncoded(queryParamsAreFormEncoded); httpClientInputs.setFormParams(formParams); httpClientInputs.setFormParamsAreURLEncoded(formParamsAreURLEncoded); httpClientInputs.setSourceFile(sourceFile); httpClientInputs.setBody(body); httpClientInputs.setContentType(contentType); httpClientInputs.setRequestCharacterSet(requestCharacterSet); httpClientInputs.setMultipartBodies(multipartBodies); httpClientInputs.setMultipartFiles(multipartFiles); httpClientInputs.setMultipartBodiesContentType(multipartBodiesContentType); httpClientInputs.setMultipartFilesContentType(multipartFilesContentType); httpClientInputs.setMultipartValuesAreURLEncoded(multipartValuesAreURLEncoded); httpClientInputs.setChunkedRequestEntity(chunkedRequestEntity); httpClientInputs.setMethod(method); httpClientInputs.setCookieStoreSessionObject(httpClientCookieSession); httpClientInputs.setConnectionPoolSessionObject(httpClientPoolingConnectionManager); try { return new CSHttpClient().execute(httpClientInputs); } catch (Exception e) { return exceptionResult(e.getMessage(), e); } } private Map<String, String> exceptionResult(String message, Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String eStr = writer.toString().replace("" + (char) 0x00, ""); Map<String, String> returnResult = new HashMap<>(); returnResult.put("returnResult", message); returnResult.put("returnCode", "-1"); returnResult.put("exception", eStr); return returnResult; } }
cs-http-client/src/main/java/io/cloudslang/content/httpclient/HttpClientAction.java
/******************************************************************************* * (c) Copyright 2017 Hewlett-Packard Development Company, L.P. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Apache License v2.0 which accompany this distribution. * * The Apache License is available at * http://www.apache.org/licenses/LICENSE-2.0 * *******************************************************************************/ package io.cloudslang.content.httpclient; import com.hp.oo.sdk.content.annotations.Action; import com.hp.oo.sdk.content.annotations.Output; import com.hp.oo.sdk.content.annotations.Param; import com.hp.oo.sdk.content.annotations.Response; import com.hp.oo.sdk.content.plugin.ActionMetadata.MatchType; import com.hp.oo.sdk.content.plugin.ActionMetadata.ResponseType; import com.hp.oo.sdk.content.plugin.GlobalSessionObject; import com.hp.oo.sdk.content.plugin.SerializableSessionObject; import java.io.PrintWriter; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; import static org.apache.commons.lang3.StringUtils.defaultIfEmpty; /** * Created with IntelliJ IDEA. * User: davidmih * Date: 7/15/14 */ public class HttpClientAction { private static final String DEFAULT_JAVA_KEYSTORE = System.getProperty("java.home") + "/lib/security/cacerts"; private static final String CHANGEIT = "changeit"; /** * This operation does an http request and a parsing of the response. * It provides features like: http autentication, http secure, connection pool, cookies, proxy. * To acomplish this it uses the third parties from Apache: HttpClient 4.3, HttpCore 4.3. * It also uses the JCIFS library from the Samba for the 'NTLM' authentication. * <p/> * <br><b>For more info about http client operations see the <i>org.cloudslang.content.httpclient</i> package description.</b> * * @param url The web address to make the request to. This must be a standard URL as specified in RFC 3986. This is a required input. * <br>Format: scheme://domain:port/path?query_string#fragment_id. * <br>Examples: https://[fe80::1260:4bff:fe49:42fc]:8080/my/path?key1=val1&key2=val2#my_fragment * @param authType The type of authentication used by this operation when trying to execute the request on the target server. * The authentication is not preemptive: a plain request not including authentication info * will be made and only when the server responds with a 'WWW-Authenticate' header the client will * send required headers. If the server needs no authentication but you specify one in this input * the request will work nevertheless. Then client cannot choose the authentication method and there * is no fallback so you have to know which one you need. If the web application and proxy use * different authentication types, these must be specified like in the Example model. * <br>Default value: basic. Valid values: basic, digest, ntlm, kerberos, any, anonymous, "" or a list of valid values separated by comma. * @param preemptiveAuth If this field is 'true' authentication info will be sent in the first request. * If this is 'false' a request with no authentication info will be made and if server responds * with 401 and a header like WWW-Authenticate: Basic realm="myRealm" only then the authentication * info will be sent. Default value: true. Valid values: true, false * @param username The user name used for authentication. For NTLM authentication, the required format is 'domain\\user' * and if you only specify the 'user' it will append a dot like '.\\user' so that a local user on the * target machine can be used. In order for all authentication schemes to work (except Kerberos) username is required. * @param password The password used for authentication. * @param kerberosConfFile A krb5.conf file with content similar to the one in the examples * (where you replace CONTOSO.COM with your domain and 'ad.contoso.com' with your kdc FQDN). * This configures the Kerberos mechanism required by the Java GSS-API methods. * <br>Format: http://web.mit.edu/kerberos/krb5-1.4/krb5-1.4.4/doc/krb5-admin/krb5.conf.html * @param kerberosLoginConfFile A login.conf file needed by the JAAS framework with the content similar to the one in examples * Format: http://docs.oracle.com/javase/7/docs/jre/api/security/jaas/spec/com/sun/security/auth/module/Krb5LoginModule.html * @param kerberosSkipPortForLookup Do not include port in the key distribution center database lookup. Default value: true. Valid values: true, false * @param proxyHost The proxy server used to access the web site. * @param proxyPort The proxy server port. Default value: 8080. Valid values: -1 and integer values greater than 0. * The value '-1' indicates that the proxy port is not set and the scheme default port will be used. * If the scheme is 'http://' and the 'proxyPort' is set to '-1' then port '80' will be used. * @param proxyUsername The user name used when connecting to the proxy. The 'authType' input will be used to choose authentication type. * The 'Basic' and 'Digest' proxy authentication types are supported. * @param proxyPassword The proxy server password associated with the proxyUsername input value. * @param trustAllRoots Specifies whether to enable weak security over SSL/TSL. A certificate is trusted even if no trusted * certification authority issued it. Default value: false. Valid values: true, false * @param x509HostnameVerifier Specifies the way the server hostname must match a domain name in the subject's Common Name (CN) * or subjectAltName field of the X.509 certificate. Set this to "allow_all" to skip any checking. * For the value "browser_compatible" the hostname verifier works the same way as Curl and Firefox. * The hostname must match either the first CN, or any of the subject-alts. * A wildcard can occur in the CN, and in any of the subject-alts. The only difference * between "browser_compatible" and "strict" is that a wildcard (such as "*.foo.com") * with "browser_compatible" matches all subdomains, including "a.b.foo.com". * Default value: strict. Valid values: strict,browser_compatible,allow_all * @param trustKeystore The pathname of the Java TrustStore file. This contains certificates from other parties * that you expect to communicate with, or from Certificate Authorities that you trust to * identify other parties. If the protocol (specified by the 'url') is not 'https' or if * trustAllRoots is 'true' this input is ignored. Default value: <OO_Home>/java/lib/security/cacerts. Format: Java KeyStore (JKS) * @param trustPassword The password associated with the TrustStore file. If trustAllRoots is false and trustKeystore is empty, * trustPassword default will be supplied. Default value: changeit * @param keystore The pathname of the Java KeyStore file. You only need this if the server requires client authentication. * If the protocol (specified by the 'url') is not 'https' or if trustAllRoots is 'true' this input is ignored. * <br>Default value: <OO_Home>/java/lib/security/cacerts. Format: Java KeyStore (JKS) * @param keystorePassword The password associated with the KeyStore file. If trustAllRoots is false and keystore * is empty, keystorePassword default will be supplied. Default value: changeit * @param connectTimeout The time to wait for a connection to be established, in seconds. * A timeout value of '0' represents an infinite timeout. Default value: 0 * @param socketTimeout The timeout for waiting for data (a maximum period inactivity between two consecutive data packets), * in seconds. A socketTimeout value of '0' represents an infinite timeout. Default value: 0. * @param useCookies Specifies whether to enable cookie tracking or not. Cookies are stored between consecutive calls * in a serializable session object therefore they will be available on a branch level. * If you specify a non-boolean value, the default value is used. Default value: true. Valid values: true, false * @param keepAlive Specifies whether to create a shared connection that will be used in subsequent calls. * If keepAlive is false, the already open connection will be used and after execution it will close it. * The operation will use a connection pool stored in a GlobalSessionObject that will be available throughout * the execution (the flow and subflows, between parallel split lanes). Default value: true. Valid values: true, false. * @param connectionsMaxPerRoot The maximum limit of connections on a per route basis. * The default will create no more than 2 concurrent connections per given route. Default value: 2 * @param connectionsMaxTotal The maximum limit of connections in total. * The default will create no more than 2 concurrent connections in total. Default value: 20 * @param headers The list containing the headers to use for the request separated by new line (CRLF). * The header name - value pair will be separated by ":". Format: According to HTTP standard for headers (RFC 2616). * Examples: Accept:text/plain * @param responseCharacterSet The character encoding to be used for the HTTP response. * If responseCharacterSet is empty, the charset from the 'Content-Type' HTTP response header will be used. * If responseCharacterSet is empty and the charset from the HTTP response Content-Type header is empty, * the default value will be used. You should not use this for method=HEAD or OPTIONS. Default value: ISO-8859-1 * @param destinationFile The absolute path of a file on disk where to save the entity returned by the response. * 'returnResult' will no longer be populated with the entity if this is specified. * You should not use this for method=HEAD or OPTIONS. Example: C:\temp\destinationFile.txt * @param followRedirects Specifies whether the HTTP client automatically follows redirects. * Redirects explicitly prohibited by the HTTP specification as requiring user intervention * will not be followed (redirects on POST and PUT requests that are converted to GET requests). * If you specify a non-boolean value, the default value is used. Default value: true. Valid values: true, false * @param queryParams The list containing query parameters to append to the URL. The names and the values must not * be URL encoded unless you specify "queryParamsAreURLEncoded"=true because if they are encoded * and "queryParamsAreURLEncoded"=false they will get double encoded. * The separator between name-value pairs is "&". The query name will be separated from query * value by "=". Note that you need to URL encode at least "&" to "%26" and "=" to "%3D" and * set "queryParamsAreURLEncoded"="true" if you leave the other special URL characters un-encoded * they will be encoded by the HTTP Client. Examples: parameterName1=parameterValue1&parameterName2=parameterValue2; * @param queryParamsAreURLEncoded Specifies whether to encode (according to the url encoding standard) the queryParams. * If you set "queryParamsAreURLEncoded"=true and you have invalid characters in 'queryParams' * they will get encoded anyway. If "queryParamsAreURLEncoded"=false all characters will be encoded. * But the ' ' (space) character will be encoded as + if queryParamsAreURLEncoded is either true or false. * Also %20 will be encoded as + if "queryParamsAreURLEncoded"=true. * If you specify a non-boolean value, the default value is used. * Default value: false. Valid values: true, false * @param queryParamsAreFormEncoded Specifies whether to encode the queryParams in the form request format or not. * This format is the default format used by the apache http client library. * If queryParamsAreFormEncoded=true then all characters will be encoded based on the queryParamsAreURLEncoded * input. If queryParamsAreFormEncoded=false all reserved characters are not encoded no matter of * queryParamsAreURLEncoded input. The only exceptions are for ' ' (space) character which is encoded as %20 in both * cases of queryParamsAreURLEncoded input and + (plus) which is encoded as %20 if queryParamsAreURLEncoded=true * and not encoded if queryParamsAreURLEncoded=false. If the special characters are already encoded * and queryParamsAreURLEncoded=true then they will be transformed into their original format. * For example: %40 will be @, %2B will be +. But %20 (space) will not be transformed. * The list of reserved chars is: ;/?:@&=+,$ * Default value: true. Valid values: true, false * Example: query=test te%20@st will be encoded in query=test%20te%20@st * @param formParams This input needs to be given in form encoded format and will set the entity to be sent in the request. * It will also set the content-type to application/x-www-form-urlencoded. * This should only be used with method=POST. Note that you need to URL encode at * least "&" to "%26" and "=" to "%3D" and set "queryParamsAreURLEncoded"="true" if you leave the * other special URL characters un-encoded they will be encoded by the HTTP Client. * <br>Examples: input1=value1&input2=value2. (The client will send: input1=value1&in+put+2=val+u%0A+e2) * @param formParamsAreURLEncoded formParams will be encoding (according to the url encoding standard) if this is 'true'. * If you set "formParamsAreURLEncoded"=true and you have invalid characters in 'formParams' * they will get encoded anyway. This should only be used with method=POST. * Default value: false. Valid values: true, false * @param sourceFile The absolute path of a file on disk from where to read the entity for the http request. * This will be read using 'requestCharacterSet' or 'contentType' input (see below). * This should not be provided for method=GET, HEAD, TRACE. Examples: C:\temp\sourceFile.txt * @param body The string to include in body for HTTP POST operation. If both sourceFile and body will be provided, * the body input has priority over sourceFile. This should not be provided for method=GET, HEAD, TRACE * @param contentType The content type that should be set in the request header, representing the MIME-type of the * data in the message body. Default value: text/plain. Examples: "text/html", "application/x-www-form-urlencoded" * @param requestCharacterSet The character encoding to be used for the HTTP request body. * If contentType is empty, the requestCharacterSet will use the default value. * If contentType will include charset (ex.: "application/json; charset=UTF-8"), * the requestCharacterSet value will overwrite the charset value from contentType input. * This should not be provided for method=GET, HEAD, TRACE. Default value: ISO-8859-1 * @param multipartBodies This is a name=textValue list of pairs separated by "&". This will also take into account * the "contentType" and "charset" inputs. The request entity will be like: * <br>Content-Disposition: form-data; name="name1" * <br>Content-Type: text/plain; charset=UTF-8 * <br>Content-Transfer-Encoding: 8bit * <br> * <br>textvalue1 * <br>Examples: name1=textvalue1&name2=textvalue2 * @param multipartBodiesContentType Each entity from the multipart entity has a content-type header. * You can only specify it once for all the parts and it is the only way to change * the characterSet of the encoding. Default value: text/plain; charset=ISO-8859-1 * Examples: text/plain; charset=UTF-8 * @param multipartFiles This is a list of name=filePath pairs. This will also take into account the "contentType" * and "charset" inputs. The request entity will be like: * <br>Content-Disposition: form-data; name="name3"; filename="readme.txt" * <br>Content-Type: application/octet-stream; charset=UTF-8 * <br>Content-Transfer-Encoding: binary the text in readme.txt * <br>Examples: name3=c:\temp\readme.txt&name4=c:\temp\log4j.properties * @param multipartFilesContentType Each entity from the multipart entity has a content-type header. You can only specify it once for all parts. * Default value: application/octet-stream. Examples: image/png,text/plain * @param multipartValuesAreURLEncoded You need to set this to 'true' if the bodies may contain the "&" and "=" * separators and you also need to URL encode them so that "&" becomes %26 and "=" becomes %3D * (using the URL Encoder operation on each value or by a simple replace). Default value: false * @param chunkedRequestEntity Data is sent in a series of "chunks". It uses the Transfer-Encoding HTTP header in place * of the Content-Length header.Generally it is recommended to let HttpClient choose the * most appropriate transfer encoding based on the properties of the HTTP message being transferred. * It is possible, however, to inform HttpClient that chunk coding is preferred by setting this input to "true". * Please note that HttpClient will use this flag as a hint only. * This value will be ignored when using HTTP protocol versions that do not support chunk coding, such as HTTP/1.0. * This setting is ignored for multipart post entities. * @param method The HTTP method used. This is a required input. * @param httpClientCookieSession the session object that holds the cookies if the useCookies input is true. * @param httpClientPoolingConnectionManager the GlobalSessionObject that holds the http client pooling connection manager. * @return a map containing the output of the operation. Keys present in the map are: * <br><br><b>returnResult</b> - This will contain the response entity (unless 'destinationFile' is specified). * In case of an error this output will contain the error message. * <br><b>exception</b> - In case of success response, this result is empty. In case of failure response, * this result contains the java stack trace of the runtime exception. * <br><b>statusCode</b> - The HTTP status code. * <br><i>Format</i>: <br>1xx (Informational - Request received, continuing process), * <br>2xx (Success - The action was successfully received, understood, and accepted), * <br>3xx (Redirection - Further action must be taken in order to complete the request), * <br>4xx (Client Error - The request contains bad syntax or cannot be fulfilled), * <br>5xx Server Error - The server failed to fulfil an apparently valid request) * <br>Examples: 200, 404 * <br><br><b>finalLocation</b> - The final location after redirects. Format: URL * <br><b>responseHeaders</b> - The list containing the headers of the response message, separated by newline. * Format: This is conforming to HTTP standard for headers (RFC 2616). * <br><b>protocolVersion</b> - The HTTP protocol version. Examples: HTTP/1.1 * <br><b>reasonPhrase</b> - The reason phrase from the origin HTTP response. This depends on the status code and are according to RFC 1945 and RFC 2048 * <br>Examples: (HTTP 1.0): OK, Created, Accepted, No Content, Moved Permanently, Moved Temporarily, Not Modified, Bad Request, * Unauthorized, Forbidden, Not Found, Internal Server Error, Not Implemented, Bad Gateway, * Service Unavailable Values (HTTP 1.1): Continue, Temporary Redirect, Method Not Allowed, * Conflict, Precondition Failed, Request Too Long, Request-URI Too Long, Unsupported Media Type, * Multiple Choices, See Other, Use Proxy, Payment Required, Not Acceptable, Proxy Authentication Required, * Request Timeout, Switching Protocols, Non Authoritative Information, Reset Content, Partial Content, * Gateway Timeout, Http Version Not Supported, Gone, Length Required, Requested Range Not Satisfiable, Expectation Failed * <p/> * <br><br><b>returnCode</b> - The returnCode of the operation: 0 for success, -1 for failure. * @see io.cloudslang.content.httpclient */ @Action(name = "Http Client", outputs = { @Output(CSHttpClient.EXCEPTION), @Output(CSHttpClient.STATUS_CODE), @Output(CSHttpClient.FINAL_LOCATION), @Output(CSHttpClient.RESPONSE_HEADERS), @Output(CSHttpClient.PROTOCOL_VERSION), @Output(CSHttpClient.REASON_PHRASE), @Output("returnCode"), @Output("returnResult") }, responses = { @Response(text = "success", field = "returnCode", value = "0", matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.RESOLVED), @Response(text = "failure", field = "returnCode", value = "-1", matchType = MatchType.COMPARE_EQUAL, responseType = ResponseType.ERROR) } ) public Map<String, String> execute( @Param(value = HttpClientInputs.URL, required = true) String url, @Param(HttpClientInputs.AUTH_TYPE) String authType, @Param(HttpClientInputs.PREEMPTIVE_AUTH) String preemptiveAuth, @Param(HttpClientInputs.USERNAME) String username, @Param(HttpClientInputs.PASSWORD) String password, @Param(HttpClientInputs.KERBEROS_CONFIG_FILE) String kerberosConfFile, @Param(HttpClientInputs.KERBEROS_LOGIN_CONFIG_FILE) String kerberosLoginConfFile, @Param(HttpClientInputs.KERBEROS_SKIP_PORT_CHECK) String kerberosSkipPortForLookup, @Param(HttpClientInputs.PROXY_HOST) String proxyHost, @Param(HttpClientInputs.PROXY_PORT) String proxyPort, @Param(HttpClientInputs.PROXY_USERNAME) String proxyUsername, @Param(HttpClientInputs.PROXY_PASSWORD) String proxyPassword, @Param(HttpClientInputs.TRUST_ALL_ROOTS) String trustAllRoots, @Param(HttpClientInputs.X509_HOSTNAME_VERIFIER) String x509HostnameVerifier, @Param(HttpClientInputs.TRUST_KEYSTORE) String trustKeystore, @Param(HttpClientInputs.TRUST_PASSWORD) String trustPassword, @Param(HttpClientInputs.KEYSTORE) String keystore, @Param(HttpClientInputs.KEYSTORE_PASSWORD) String keystorePassword, @Param(HttpClientInputs.CONNECT_TIMEOUT) String connectTimeout, @Param(HttpClientInputs.SOCKET_TIMEOUT) String socketTimeout, @Param(HttpClientInputs.USE_COOKIES) String useCookies, @Param(HttpClientInputs.KEEP_ALIVE) String keepAlive, @Param(HttpClientInputs.CONNECTIONS_MAX_PER_ROUTE) String connectionsMaxPerRoot, @Param(HttpClientInputs.CONNECTIONS_MAX_TOTAL) String connectionsMaxTotal, @Param(HttpClientInputs.HEADERS) String headers, @Param(HttpClientInputs.RESPONSE_CHARACTER_SET) String responseCharacterSet, @Param(HttpClientInputs.DESTINATION_FILE) String destinationFile, @Param(HttpClientInputs.FOLLOW_REDIRECTS) String followRedirects, @Param(HttpClientInputs.QUERY_PARAMS) String queryParams, @Param(HttpClientInputs.QUERY_PARAMS_ARE_URLENCODED) String queryParamsAreURLEncoded, @Param(HttpClientInputs.QUERY_PARAMS_ARE_FORM_ENCODED) String queryParamsAreFormEncoded, @Param(HttpClientInputs.FORM_PARAMS) String formParams, @Param(HttpClientInputs.FORM_PARAMS_ARE_URLENCODED) String formParamsAreURLEncoded, @Param(HttpClientInputs.SOURCE_FILE) String sourceFile, @Param(HttpClientInputs.BODY) String body, @Param(HttpClientInputs.CONTENT_TYPE) String contentType, @Param(HttpClientInputs.REQUEST_CHARACTER_SET) String requestCharacterSet, @Param(HttpClientInputs.MULTIPART_BODIES) String multipartBodies, @Param(HttpClientInputs.MULTIPART_BODIES_CONTENT_TYPE) String multipartBodiesContentType, @Param(HttpClientInputs.MULTIPART_FILES) String multipartFiles, @Param(HttpClientInputs.MULTIPART_FILES_CONTENT_TYPE) String multipartFilesContentType, @Param(HttpClientInputs.MULTIPART_VALUES_ARE_URLENCODED) String multipartValuesAreURLEncoded, @Param(HttpClientInputs.CHUNKED_REQUEST_ENTITY) String chunkedRequestEntity, @Param(value = HttpClientInputs.METHOD, required = true) String method, @Param(HttpClientInputs.SESSION_COOKIES) SerializableSessionObject httpClientCookieSession, @Param(HttpClientInputs.SESSION_CONNECTION_POOL) GlobalSessionObject httpClientPoolingConnectionManager) { HttpClientInputs httpClientInputs = new HttpClientInputs(); httpClientInputs.setUrl(url); httpClientInputs.setAuthType(authType); httpClientInputs.setPreemptiveAuth(preemptiveAuth); httpClientInputs.setUsername(username); httpClientInputs.setPassword(password); httpClientInputs.setKerberosConfFile(kerberosConfFile); httpClientInputs.setKerberosLoginConfFile(kerberosLoginConfFile); // httpClientInputs.setKerberosDomain(kerberosDomain); // httpClientInputs.setKerberosKdc(kerberosKdc); httpClientInputs.setKerberosSkipPortCheck(kerberosSkipPortForLookup); httpClientInputs.setProxyHost(proxyHost); httpClientInputs.setProxyPort(proxyPort); httpClientInputs.setProxyUsername(proxyUsername); httpClientInputs.setProxyPassword(proxyPassword); httpClientInputs.setTrustAllRoots(trustAllRoots); httpClientInputs.setX509HostnameVerifier(x509HostnameVerifier); httpClientInputs.setTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE)); httpClientInputs.setTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT)); httpClientInputs.setKeystore(keystore); httpClientInputs.setKeystorePassword(keystorePassword); httpClientInputs.setConnectTimeout(connectTimeout); httpClientInputs.setSocketTimeout(socketTimeout); httpClientInputs.setUseCookies(useCookies); httpClientInputs.setKeepAlive(keepAlive); httpClientInputs.setConnectionsMaxPerRoute(connectionsMaxPerRoot); httpClientInputs.setConnectionsMaxTotal(connectionsMaxTotal); httpClientInputs.setHeaders(headers); httpClientInputs.setResponseCharacterSet(responseCharacterSet); httpClientInputs.setDestinationFile(destinationFile); httpClientInputs.setFollowRedirects(followRedirects); httpClientInputs.setQueryParams(queryParams); httpClientInputs.setQueryParamsAreURLEncoded(queryParamsAreURLEncoded); httpClientInputs.setQueryParamsAreFormEncoded(queryParamsAreFormEncoded); httpClientInputs.setFormParams(formParams); httpClientInputs.setFormParamsAreURLEncoded(formParamsAreURLEncoded); httpClientInputs.setSourceFile(sourceFile); httpClientInputs.setBody(body); httpClientInputs.setContentType(contentType); httpClientInputs.setRequestCharacterSet(requestCharacterSet); httpClientInputs.setMultipartBodies(multipartBodies); httpClientInputs.setMultipartFiles(multipartFiles); httpClientInputs.setMultipartBodiesContentType(multipartBodiesContentType); httpClientInputs.setMultipartFilesContentType(multipartFilesContentType); httpClientInputs.setMultipartValuesAreURLEncoded(multipartValuesAreURLEncoded); httpClientInputs.setChunkedRequestEntity(chunkedRequestEntity); httpClientInputs.setMethod(method); httpClientInputs.setCookieStoreSessionObject(httpClientCookieSession); httpClientInputs.setConnectionPoolSessionObject(httpClientPoolingConnectionManager); try { return new CSHttpClient().execute(httpClientInputs); } catch (Exception e) { return exceptionResult(e.getMessage(), e); } } private Map<String, String> exceptionResult(String message, Exception e) { StringWriter writer = new StringWriter(); e.printStackTrace(new PrintWriter(writer)); String eStr = writer.toString().replace("" + (char) 0x00, ""); Map<String, String> returnResult = new HashMap<>(); returnResult.put("returnResult", message); returnResult.put("returnCode", "-1"); returnResult.put("exception", eStr); return returnResult; } }
added defaults to the keystore inputs
cs-http-client/src/main/java/io/cloudslang/content/httpclient/HttpClientAction.java
added defaults to the keystore inputs
<ide><path>s-http-client/src/main/java/io/cloudslang/content/httpclient/HttpClientAction.java <ide> httpClientInputs.setX509HostnameVerifier(x509HostnameVerifier); <ide> httpClientInputs.setTrustKeystore(defaultIfEmpty(trustKeystore, DEFAULT_JAVA_KEYSTORE)); <ide> httpClientInputs.setTrustPassword(defaultIfEmpty(trustPassword, CHANGEIT)); <del> httpClientInputs.setKeystore(keystore); <del> httpClientInputs.setKeystorePassword(keystorePassword); <add> httpClientInputs.setKeystore(defaultIfEmpty(keystore, DEFAULT_JAVA_KEYSTORE)); <add> httpClientInputs.setKeystorePassword(defaultIfEmpty(keystorePassword, CHANGEIT)); <ide> httpClientInputs.setConnectTimeout(connectTimeout); <ide> httpClientInputs.setSocketTimeout(socketTimeout); <ide> httpClientInputs.setUseCookies(useCookies);
JavaScript
mit
c3b41e308ad97181496baa916cec50eed2d42495
0
vfile/to-vfile
/** * @typedef {import('vfile').VFileValue} Value * @typedef {import('vfile').VFileOptions} Options * @typedef {import('vfile').BufferEncoding} BufferEncoding * * @typedef {number|string} Mode * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, flag?: string}} ReadOptions * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, mode: Mode?, flag?: string}} WriteOptions * * @typedef {URL|Value} Path Path of the file. * Note: `Value` is used here because it’s a smarter `Buffer` * @typedef {Path|Options|VFile} Compatible Things that can be * passed to the function. */ /** * @callback Callback * @param {NodeJS.ErrnoException|null} error * @param {VFile|null} file */ import fs from 'fs' import path from 'path' import {URL} from 'url' import buffer from 'is-buffer' import {VFile} from 'vfile' /** * Create a virtual file from a description. * If `options` is a string or a buffer, it’s used as the path. * If it’s a VFile itself, it’s returned instead. * In all other cases, the options are passed through to `vfile()`. * * @param {Compatible} [options] * @returns {VFile} */ export function toVFile(options) { if (typeof options === 'string' || options instanceof URL) { options = {path: options} } else if (buffer(options)) { options = {path: String(options)} } return looksLikeAVFile(options) ? options : new VFile(options) } /** * Create a virtual file and read it in, synchronously. * * @param {Compatible} description * @param {ReadOptions} [options] * @returns {VFile} */ export function readSync(description, options) { const file = toVFile(description) file.value = fs.readFileSync(path.resolve(file.cwd, file.path), options) return file } /** * Create a virtual file and write it in, synchronously. * * @param {Compatible} description * @param {WriteOptions} [options] * @returns {VFile} */ export function writeSync(description, options) { const file = toVFile(description) fs.writeFileSync(path.resolve(file.cwd, file.path), file.value || '', options) return file } export const read = /** * @type {{ * (description: Compatible, options: ReadOptions, callback: Callback): void * (description: Compatible, callback: Callback): void * (description: Compatible, options?: ReadOptions): Promise<VFile> * }} */ ( /** * Create a virtual file and read it in, asynchronously. * * @param {Compatible} description * @param {ReadOptions} [options] * @param {Callback} [callback] */ function (description, options, callback) { const file = toVFile(description) if (!callback && typeof options === 'function') { callback = options options = null } if (!callback) { return new Promise(executor) } executor(resolve, callback) /** * @param {VFile} result */ function resolve(result) { callback(null, result) } /** * @param {(x: VFile) => void} resolve * @param {(x: Error, y?: VFile) => void} reject */ function executor(resolve, reject) { /** @type {string} */ let fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.readFile(fp, options, done) /** * @param {Error} error * @param {Value} result */ function done(error, result) { if (error) { reject(error) } else { file.value = result resolve(file) } } } } ) export const write = /** * @type {{ * (description: Compatible, options: WriteOptions, callback: Callback): void * (description: Compatible, callback: Callback): void * (description: Compatible, options?: WriteOptions): Promise<VFile> * }} */ ( /** * Create a virtual file and write it in, asynchronously. * * @param {Compatible} description * @param {WriteOptions} [options] * @param {Callback} [callback] */ function (description, options, callback) { const file = toVFile(description) // Weird, right? Otherwise `fs` doesn’t accept it. if (!callback && typeof options === 'function') { callback = options options = undefined } if (!callback) { return new Promise(executor) } executor(resolve, callback) /** * @param {VFile} result */ function resolve(result) { callback(null, result) } /** * @param {(x: VFile) => void} resolve * @param {(x: Error, y?: VFile) => void} reject */ function executor(resolve, reject) { /** @type {string} */ let fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.writeFile(fp, file.value || '', options, done) /** * @param {Error} error */ function done(error) { if (error) { reject(error) } else { resolve(file) } } } } ) /** * @param {Compatible} value * @returns {value is VFile} */ function looksLikeAVFile(value) { return ( value && typeof value === 'object' && 'message' in value && 'messages' in value ) } toVFile.readSync = readSync toVFile.writeSync = writeSync toVFile.read = read toVFile.write = write
lib/index.js
/** * @typedef {import('vfile').VFileValue} Value * @typedef {import('vfile').VFileOptions} Options * @typedef {import('vfile').BufferEncoding} BufferEncoding * * @typedef {number|string} Mode * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, flag?: string}} ReadOptions * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, mode: Mode?, flag?: string}} WriteOptions * * @typedef {string|Uint8Array} Path Path of the file. * @typedef {Path|URL|Options|VFile} Compatible Things that can be * passed to the function. */ /** * @callback Callback * @param {NodeJS.ErrnoException|null} error * @param {VFile|null} file */ import fs from 'fs' import path from 'path' import {URL} from 'url' import buffer from 'is-buffer' import {VFile} from 'vfile' /** * Create a virtual file from a description. * If `options` is a string or a buffer, it’s used as the path. * If it’s a VFile itself, it’s returned instead. * In all other cases, the options are passed through to `vfile()`. * * @param {Compatible} [options] * @returns {VFile} */ export function toVFile(options) { if (typeof options === 'string' || options instanceof URL) { options = {path: options} } else if (buffer(options)) { options = {path: String(options)} } return looksLikeAVFile(options) ? options : new VFile(options) } /** * Create a virtual file and read it in, synchronously. * * @param {Compatible} description * @param {ReadOptions} [options] * @returns {VFile} */ export function readSync(description, options) { const file = toVFile(description) file.value = fs.readFileSync(path.resolve(file.cwd, file.path), options) return file } /** * Create a virtual file and write it in, synchronously. * * @param {Compatible} description * @param {WriteOptions} [options] * @returns {VFile} */ export function writeSync(description, options) { const file = toVFile(description) fs.writeFileSync(path.resolve(file.cwd, file.path), file.value || '', options) return file } export const read = /** * @type {{ * (description: Compatible, options: ReadOptions, callback: Callback): void * (description: Compatible, callback: Callback): void * (description: Compatible, options?: ReadOptions): Promise<VFile> * }} */ ( /** * Create a virtual file and read it in, asynchronously. * * @param {Compatible} description * @param {ReadOptions} [options] * @param {Callback} [callback] */ function (description, options, callback) { const file = toVFile(description) if (!callback && typeof options === 'function') { callback = options options = null } if (!callback) { return new Promise(executor) } executor(resolve, callback) /** * @param {VFile} result */ function resolve(result) { callback(null, result) } /** * @param {(x: VFile) => void} resolve * @param {(x: Error, y?: VFile) => void} reject */ function executor(resolve, reject) { /** @type {string} */ let fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.readFile(fp, options, done) /** * @param {Error} error * @param {Value} result */ function done(error, result) { if (error) { reject(error) } else { file.value = result resolve(file) } } } } ) export const write = /** * @type {{ * (description: Compatible, options: WriteOptions, callback: Callback): void * (description: Compatible, callback: Callback): void * (description: Compatible, options?: WriteOptions): Promise<VFile> * }} */ ( /** * Create a virtual file and write it in, asynchronously. * * @param {Compatible} description * @param {WriteOptions} [options] * @param {Callback} [callback] */ function (description, options, callback) { const file = toVFile(description) // Weird, right? Otherwise `fs` doesn’t accept it. if (!callback && typeof options === 'function') { callback = options options = undefined } if (!callback) { return new Promise(executor) } executor(resolve, callback) /** * @param {VFile} result */ function resolve(result) { callback(null, result) } /** * @param {(x: VFile) => void} resolve * @param {(x: Error, y?: VFile) => void} reject */ function executor(resolve, reject) { /** @type {string} */ let fp try { fp = path.resolve(file.cwd, file.path) } catch (error) { return reject(error) } fs.writeFile(fp, file.value || '', options, done) /** * @param {Error} error */ function done(error) { if (error) { reject(error) } else { resolve(file) } } } } ) /** * @param {Compatible} value * @returns {value is VFile} */ function looksLikeAVFile(value) { return ( value && typeof value === 'object' && 'message' in value && 'messages' in value ) } toVFile.readSync = readSync toVFile.writeSync = writeSync toVFile.read = read toVFile.write = write
Fix `Buffer` type Closes GH-20. Reviewed-by: Christian Murphy <[email protected]> Reviewed-by: Titus Wormer <[email protected]>
lib/index.js
Fix `Buffer` type
<ide><path>ib/index.js <ide> * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, flag?: string}} ReadOptions <ide> * @typedef {BufferEncoding|{encoding?: null|BufferEncoding, mode: Mode?, flag?: string}} WriteOptions <ide> * <del> * @typedef {string|Uint8Array} Path Path of the file. <del> * @typedef {Path|URL|Options|VFile} Compatible Things that can be <add> * @typedef {URL|Value} Path Path of the file. <add> * Note: `Value` is used here because it’s a smarter `Buffer` <add> * @typedef {Path|Options|VFile} Compatible Things that can be <ide> * passed to the function. <ide> */ <ide>
Java
apache-2.0
46f8473fa7ffb8aafc577e69c3b19bd75ee29b30
0
nus-ncl/services-in-one,nus-ncl/services-in-one
package sg.ncl.service.team.data.jpa; import org.hibernate.annotations.GenericGenerator; import sg.ncl.common.jpa.AbstractEntity; import sg.ncl.service.team.domain.*; import sg.ncl.service.team.web.TeamMemberInfo; import javax.persistence.*; import java.time.ZonedDateTime; import java.util.*; /** * @author Christopher Zhong */ @Entity @Table(name = "teams") public class TeamEntity extends AbstractEntity implements Team { @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(name = "id", nullable = false, unique = true, updatable = false) private String id; @Column(name = "name", nullable = false, unique = true) private String name; @Column(name = "description") private String description; @Column(name = "website", nullable = false) private String website; @Column(name = "organisation_type", nullable = false) private String organisationType; @Column(name = "visibility", nullable = false) @Enumerated(EnumType.STRING) private TeamVisibility visibility = TeamVisibility.PUBLIC; @Column(name = "privacy", nullable = false) @Enumerated(EnumType.STRING) private TeamPrivacy privacy = TeamPrivacy.OPEN; @Column(name = "status", nullable = false) @Enumerated(EnumType.STRING) private TeamStatus status = TeamStatus.PENDING; @Column(name = "application_date", nullable = false) private ZonedDateTime applicationDate; @Column(name = "processed_date") private ZonedDateTime processedDate; @ManyToMany(cascade = CascadeType.ALL, mappedBy = "team") @MapKey(name = "userId") private final Map<String, TeamMemberEntity> members = new HashMap<>(); @Override public String getId() { return id; } public void setId(final String id) { this.id = id; } @Override public String getName() { return name; } public void setName(final String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } @Override public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } @Override public String getOrganisationType() { return organisationType; } public void setOrganisationType(String organisationType) { this.organisationType = organisationType; } @Override public TeamVisibility getVisibility() { return visibility; } public void setVisibility(final TeamVisibility visibility) { this.visibility = visibility; } @Override public TeamPrivacy getPrivacy() { return privacy; } public void setPrivacy(final TeamPrivacy privacy) { this.privacy = privacy; } @Override public TeamStatus getStatus() { return status; } public void setStatus(final TeamStatus status) { this.status = status; } @Override public ZonedDateTime getApplicationDate() { return applicationDate; } public void setApplicationDate(ZonedDateTime applicationDate) { this.applicationDate = applicationDate; } @Override public ZonedDateTime getProcessedDate() { return processedDate; } public void setProcessedDate(ZonedDateTime processedDate) { this.processedDate = processedDate; } @Override public List<TeamMemberEntity> getMembers() { return new ArrayList<>(members.values()); } public void addMember(final TeamMember member) { final String userId = member.getUserId(); if (members.containsKey(userId)) { return; } TeamMemberEntity entity = new TeamMemberEntity(); entity.setUserId(userId); entity.setTeam(this); entity.setJoinedDate(ZonedDateTime.now()); entity.setMemberType(member.getMemberType()); if (member.getMemberStatus() != null) { entity.setMemberStatus(member.getMemberStatus()); } members.put(userId, entity); } public void removeMember(final TeamMember member) { for (Iterator<Map.Entry<String, TeamMemberEntity>> it = members.entrySet().iterator(); it.hasNext();) { Map.Entry<String, TeamMemberEntity> entry = it.next(); if (entry.getKey().equals(member.getUserId())) { it.remove(); } } } public TeamMember getMember(final String userId) { if (members.containsKey(userId)) { return new TeamMemberInfo(members.get(userId)); } else { return null; } } public TeamMember changeMemberStatus(final TeamMember member, TeamMemberStatus teamMemberStatus) { final String userId = member.getUserId(); if (members.containsKey(userId)) { TeamMemberEntity entity = members.get(userId); entity.setMemberStatus(teamMemberStatus); members.put(userId, entity); return new TeamMemberInfo(members.get(userId)); } else { return null; } } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Team that = (Team) o; return getId() == null ? that.getId() == null : getId().equals(that.getId()); } @Override public int hashCode() { return getId() == null ? 0 : getId().hashCode(); } @Override public String toString() { return "TeamEntity{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", website='" + website + '\'' + ", organisationType='" + organisationType + '\'' + ", visibility=" + visibility + ", privacy=" + privacy + ", status=" + status + ", applicationDate=" + applicationDate + ", processedDate=" + processedDate + ", members=" + members + "} " + super.toString(); } }
service-team/src/main/java/sg/ncl/service/team/data/jpa/TeamEntity.java
package sg.ncl.service.team.data.jpa; import org.hibernate.annotations.GenericGenerator; import sg.ncl.common.jpa.AbstractEntity; import sg.ncl.service.team.domain.*; import sg.ncl.service.team.web.TeamMemberInfo; import javax.persistence.*; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @author Christopher Zhong */ @Entity @Table(name = "teams") public class TeamEntity extends AbstractEntity implements Team { @Id @GeneratedValue(generator = "uuid2") @GenericGenerator(name = "uuid2", strategy = "uuid2") @Column(name = "id", nullable = false, unique = true, updatable = false) private String id; @Column(name = "name", nullable = false, unique = true) private String name; @Column(name = "description") private String description; @Column(name = "website", nullable = false) private String website; @Column(name = "organisation_type", nullable = false) private String organisationType; @Column(name = "visibility", nullable = false) @Enumerated(EnumType.STRING) private TeamVisibility visibility = TeamVisibility.PUBLIC; @Column(name = "privacy", nullable = false) @Enumerated(EnumType.STRING) private TeamPrivacy privacy = TeamPrivacy.OPEN; @Column(name = "status", nullable = false) @Enumerated(EnumType.STRING) private TeamStatus status = TeamStatus.PENDING; @Column(name = "application_date", nullable = false) private ZonedDateTime applicationDate; @Column(name = "processed_date") private ZonedDateTime processedDate; @ManyToMany(cascade = CascadeType.ALL, mappedBy = "team") @MapKey(name = "userId") private final Map<String, TeamMemberEntity> members = new HashMap<>(); @Override public String getId() { return id; } public void setId(final String id) { this.id = id; } @Override public String getName() { return name; } public void setName(final String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(final String description) { this.description = description; } @Override public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } @Override public String getOrganisationType() { return organisationType; } public void setOrganisationType(String organisationType) { this.organisationType = organisationType; } @Override public TeamVisibility getVisibility() { return visibility; } public void setVisibility(final TeamVisibility visibility) { this.visibility = visibility; } @Override public TeamPrivacy getPrivacy() { return privacy; } public void setPrivacy(final TeamPrivacy privacy) { this.privacy = privacy; } @Override public TeamStatus getStatus() { return status; } public void setStatus(final TeamStatus status) { this.status = status; } @Override public ZonedDateTime getApplicationDate() { return applicationDate; } public void setApplicationDate(ZonedDateTime applicationDate) { this.applicationDate = applicationDate; } @Override public ZonedDateTime getProcessedDate() { return processedDate; } public void setProcessedDate(ZonedDateTime processedDate) { this.processedDate = processedDate; } @Override public List<TeamMemberEntity> getMembers() { return new ArrayList<>(members.values()); } public void addMember(final TeamMember member) { final String userId = member.getUserId(); if (members.containsKey(userId)) { return; } TeamMemberEntity entity = new TeamMemberEntity(); entity.setUserId(userId); entity.setTeam(this); entity.setJoinedDate(ZonedDateTime.now()); entity.setMemberType(member.getMemberType()); if (member.getMemberStatus() != null) { entity.setMemberStatus(member.getMemberStatus()); } members.put(userId, entity); } public void removeMember(final TeamMember member) { members.remove(member.getUserId()); } public TeamMember getMember(final String userId) { if (members.containsKey(userId)) { return new TeamMemberInfo(members.get(userId)); } else { return null; } } public TeamMember changeMemberStatus(final TeamMember member, TeamMemberStatus teamMemberStatus) { final String userId = member.getUserId(); if (members.containsKey(userId)) { TeamMemberEntity entity = members.get(userId); entity.setMemberStatus(teamMemberStatus); members.put(userId, entity); return new TeamMemberInfo(members.get(userId)); } else { return null; } } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final Team that = (Team) o; return getId() == null ? that.getId() == null : getId().equals(that.getId()); } @Override public int hashCode() { return getId() == null ? 0 : getId().hashCode(); } @Override public String toString() { return "TeamEntity{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", description='" + description + '\'' + ", website='" + website + '\'' + ", organisationType='" + organisationType + '\'' + ", visibility=" + visibility + ", privacy=" + privacy + ", status=" + status + ", applicationDate=" + applicationDate + ", processedDate=" + processedDate + ", members=" + members + "} " + super.toString(); } }
use iterator to remove instead of map method
service-team/src/main/java/sg/ncl/service/team/data/jpa/TeamEntity.java
use iterator to remove instead of map method
<ide><path>ervice-team/src/main/java/sg/ncl/service/team/data/jpa/TeamEntity.java <ide> <ide> import javax.persistence.*; <ide> import java.time.ZonedDateTime; <del>import java.util.ArrayList; <del>import java.util.HashMap; <del>import java.util.List; <del>import java.util.Map; <add>import java.util.*; <ide> <ide> /** <ide> * @author Christopher Zhong <ide> } <ide> <ide> public void removeMember(final TeamMember member) { <del> members.remove(member.getUserId()); <add> for (Iterator<Map.Entry<String, TeamMemberEntity>> it = members.entrySet().iterator(); it.hasNext();) { <add> Map.Entry<String, TeamMemberEntity> entry = it.next(); <add> if (entry.getKey().equals(member.getUserId())) { <add> it.remove(); <add> } <add> } <ide> } <ide> <ide> public TeamMember getMember(final String userId) {
Java
mit
98acd0ce128c71e0dabe79f2d557c6e648e5d40f
0
companieshouse/forms-enablement-api,companieshouse/forms-enablement-api
package com.ch.client; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; /** * Created by elliott.jenkins on 05/04/2016. */ public final class ClientHelper { private final Client client; public ClientHelper(Client client) { this.client = client; } /** * Send json to the desired url. * * @param url destination * @param json json to send * @return response from url */ public Response postJson(String url, String json) { final WebTarget target = client.target(url); return target.request().post(Entity.json(json)); } }
src/main/java/com/ch/client/ClientHelper.java
package com.ch.client; import com.ch.exception.ConnectionException; import javax.ws.rs.client.Client; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; /** * Created by elliott.jenkins on 05/04/2016. */ public final class ClientHelper { private final Client client; public ClientHelper(Client client) { this.client = client; } /** * Send json to the desired url. * * @param url destination * @param json json to send * @return response from url */ public Response postJson(String url, String json) { final WebTarget target = client.target(url); Response response = target.request().post(Entity.json(json)); if (response.getStatus() != 200) { throw new ConnectionException(url); } return response; } }
remove connection exception until it is fixed
src/main/java/com/ch/client/ClientHelper.java
remove connection exception until it is fixed
<ide><path>rc/main/java/com/ch/client/ClientHelper.java <ide> package com.ch.client; <del> <del>import com.ch.exception.ConnectionException; <ide> <ide> import javax.ws.rs.client.Client; <ide> import javax.ws.rs.client.Entity; <ide> */ <ide> public Response postJson(String url, String json) { <ide> final WebTarget target = client.target(url); <del> Response response = target.request().post(Entity.json(json)); <del> if (response.getStatus() != 200) { <del> throw new ConnectionException(url); <del> } <del> return response; <add> return target.request().post(Entity.json(json)); <ide> } <ide> }
Java
bsd-3-clause
782e2b25e3cf415c8895cebe036cca9f30b85b01
0
Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java,Unidata/netcdf-java
/* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package thredds.catalog; import ucar.nc2.units.DateType; import java.util.*; import java.net.*; /** * Concrete implementation of a Thredds catalog object. Use this when you are constructing or modifying. * * @author john caron * @see InvCatalog */ public class InvCatalogImpl extends InvCatalog { private String createFrom; private List<DataRootConfig> roots = new ArrayList<DataRootConfig>(); // validation private StringBuilder log = new StringBuilder(); private boolean hasError = false; private boolean isStatic = false; /** * Munge this catalog so the given dataset is the top catalog. * * @param ds make this top; must be existing dataset in this catalog. * * @deprecated in favor of thredds.catalog.util.DeepCopyUtils.subsetCatalogOnDataset */ public void subset(InvDataset ds) { InvDatasetImpl dataset = (InvDatasetImpl) ds; // Make all inherited metadata local. dataset.transferMetadata(dataset, true); topDataset = dataset; datasets.clear(); // throw away the rest datasets.add(topDataset); // parent lookups need to be local //InvService service = dataset.getServiceDefault(); //if (service != null) LOOK // dataset.serviceName = service.getName(); dataset.dataType = dataset.getDataType(); // all properties need to be local // LOOK dataset.setPropertiesLocal( new ArrayList(dataset.getProperties())); // next part requires this before it dataset.setCatalog(this); dataset.parent = null; // any referenced services need to be local List<InvService> services = new ArrayList<InvService>(dataset.getServicesLocal()); findServices(services, dataset); dataset.setServicesLocal(services); finish(); } // /** // * Return a catalog with a shallow copy of the given dataset as the top dataset. // * // * @param dataset the dataset to copy into a new catalog // * @return A new catalog with a shallow copy of the given dataset as the top dataset. // */ // public InvCatalogImpl subsetShallowCopy( InvDatasetImpl dataset) // { // InvCatalogImpl newCatalog = new InvCatalogImpl( null, "1.0.2", null); // InvDatasetImpl newTopDataset = new InvDatasetImpl( null, dataset.getName()); // newTopDataset.transferMetadata( dataset ); // if (dataset.getAccess() != null && ! dataset.getAccess().isEmpty()) // { // newTopDataset.addAccess( dataset.getAccess() ); // } // dataset.getDatasets(); // dataset.getID(); // dataset.getServiceName(); // dataset.getServicesLocal(); // dataset.getUrlPath(); // // // ToDo LOOK Probably fine for throw away catalog that is only generated so that XML can be generated. // dataset.finish(); // // newCatalog.addDataset( newTopDataset ); // // return newCatalog; // } void findServices(List<InvService> result, InvDataset ds) { if (ds instanceof InvCatalogRef) return; // look for access elements with unresolved services for (InvAccess a : ds.getAccess()) { InvService s = a.getService(); InvDataset d = a.getDataset(); if (null == d.findService(s.getName()) && !(result.contains(s))) result.add(s); } // recurse into nested datasets for (InvDataset nested : ds.getDatasets()) { findServices(result, nested); } } /** * Munge this catalog to remove any dataset that doesnt pass through the filter. * * @param filter remove datasets that dont pass this filter. */ public void filter(DatasetFilter filter) { mark(filter, topDataset); delete(topDataset); this.filter = filter; } // got to keep it for catalogRef's private DatasetFilter filter = null; protected DatasetFilter getDatasetFilter() { return filter; } // see if this ds should be filtered out. // if so, setMark and return true. // if any nested dataset are kept, then keep it. // unread CatalogRefs are always kept. private boolean mark(DatasetFilter filter, InvDatasetImpl ds) { if (ds instanceof InvCatalogRef) { InvCatalogRef catRef = (InvCatalogRef) ds; if (!catRef.isRead()) return false; } // recurse into nested datasets first boolean allMarked = true; for (InvDataset nested : ds.getDatasets()) { allMarked &= mark(filter, (InvDatasetImpl) nested); } if (!allMarked) return false; if (filter.accept(ds) >= 0) return false; // mark for deletion ds.setMark(true); if (debugFilter) System.out.println(" mark " + ds.getName()); return true; } private boolean debugFilter = false; // remove marked datasets private void delete(InvDatasetImpl ds) { if (ds instanceof InvCatalogRef) { InvCatalogRef catRef = (InvCatalogRef) ds; if (!catRef.isRead()) return; } Iterator iter = ds.getDatasets().iterator(); while (iter.hasNext()) { InvDatasetImpl nested = (InvDatasetImpl) iter.next(); if (nested.getMark()) { iter.remove(); if (debugFilter) System.out.println(" remove " + nested.getName()); } else delete(nested); } } /////////////////////////////////////////////////////////////////////////////// // construction and internals /** * Construct an InvCatalog. * You must call finish() after all objects are added. * * @param name : catalog name. * @param version : catalog version. * @param baseURI : catalog base URI (external). */ public InvCatalogImpl(String name, String version, URI baseURI) { this(name, version, null, baseURI); } /** * Construct an InvCatalog. * You must call finish() after all objects are added. * * @param name : catalog name. * @param version : catalog version. * @param expires : date/time catalog expires. * @param baseURI : catalog base URI (external). */ public InvCatalogImpl(String name, String version, DateType expires, URI baseURI) { this.name = name; this.version = version; this.expires = expires; this.baseURI = baseURI; } /** * Finish constructing after all elements have been added or modified. * This routine will do any needed internal consistency work. * Its ok to call multiple times. * * @return true if successful. */ public boolean finish() { // make topDataset if needed //if (topDataset == null) { if (datasets.size() == 1) { // already only one; make it top topDataset = (InvDatasetImpl) datasets.get(0); } else { // create one topDataset = new InvDatasetImpl(null, name == null ? "Top Dataset" : name); for (InvDataset dataset : datasets) topDataset.addDataset((InvDatasetImpl) dataset); topDataset.setServicesLocal(services); } //} topDataset.setCatalog(this); // build dataset hash table dsHash = new HashMap<String, InvDataset>(); addDatasetIds(topDataset); // recurse through the datasets and finish them return topDataset.finish(); } private void addDatasetIds(InvDatasetImpl ds) { addDatasetByID(ds); if (ds instanceof InvCatalogRef) return; //if (ds instanceof InvDatasetFmrc) return; // recurse into nested for (InvDataset invDataset : ds.getDatasets()) { InvDatasetImpl nested = (InvDatasetImpl) invDataset; addDatasetIds(nested); } } /** * Add Dataset to internal hash. * * @param ds : add this dataset if ds.getID() != null * @see InvCatalog#findDatasetByID */ public void addDatasetByID(InvDatasetImpl ds) { if (ds.getID() != null && ds.getID().startsWith("null")) System.out.printf("HEY addDatasetByID %s%n", ds.getID()); if (ds.getID() != null) dsHash.put(ds.getID(), ds); } /** * Find the dataset in this catalog by its ID. If found, remove it. * * @param ds Remove this dataset from the hash */ public void removeDatasetByID(InvDatasetImpl ds) { if (ds.getID() != null) dsHash.remove(ds.getID()); } /** * Add Dataset (1.0) * * @param ds add this dataset */ public void addDataset(InvDatasetImpl ds) { if (ds != null) datasets.add(ds); } /** * Remove the given dataset from this catalog if it is a direct child of this catalog. * * @param ds remove this dataset * @return true if found and removed */ public boolean removeDataset(InvDatasetImpl ds) { if (this.datasets.remove(ds)) { ds.setParent(null); removeDatasetByID(ds); return true; } return false; } /** * Replace the given dataset if it is a nested dataset. * * @param remove - the dataset element to be removed * @param add - the dataset element to be added * @return true on success */ public boolean replaceDataset(InvDatasetImpl remove, InvDatasetImpl add) { if (topDataset.equals(remove)) { topDataset = add; topDataset.setCatalog(this); } for (int i = 0; i < datasets.size(); i++) { InvDataset dataset = datasets.get(i); if (dataset.equals(remove)) { datasets.set(i, add); removeDatasetByID(remove); addDatasetByID(add); return true; } } return false; } /** * Add Property (1.0) * * @param p add this property */ public void addProperty(InvProperty p) { properties.add(p); } /** * Add Service (1.0) * * @param s add this service */ public void addService(InvService s) { if (s == null) throw new IllegalArgumentException("Service to add was null."); // While adding a service, there are three possible results: if (s.getName() != null) { Object obj = serviceHash.get(s.getName()); if (obj == null) { // 1) No service with matching name entry was found, add given service; serviceHash.put(s.getName(), s); services.add(s); return; } else { // A service with matching name was found. if (s.equals(obj)) { // 2) matching name entry, objects are equal so OK; return; } else { // 3) matching name entry, objects are not equal so ??? // @todo throw an exception??? // Currently just dropping given service log.append("Multiple Services with the same name\n"); return; } } } } /** * Add top-level InvDataset to this catalog. * * @deprecated Use addDataset() instead; datamodel now allows multiple top level datasets. */ public void setDataset(InvDatasetImpl ds) { topDataset = ds; addDataset(ds); } /** * String describing how the catalog was created, for debugging. * * @return how the catalog was created, for debugging */ public String getCreateFrom() { return createFrom; } /** * Set how the catalog was created, for debugging. * @param createFrom how the catalog was created, for debugging */ public void setCreateFrom(String createFrom) { this.createFrom = createFrom; } /** * Set the catalog base URI. * Its used to resolve reletive URLS. * @param baseURI set to this */ public void setBaseURI(URI baseURI) { this.baseURI = baseURI; } /** * @return the catalog base URI. */ public URI getBaseURI() { return baseURI; } /* * @return DTD string * public String getDTDid() { return dtdID; } /* * set DTD * public void setDTDid(String dtdID) { this.dtdID = dtdID; } */ /** * Set the expires date after which the catalog is no longer valid. * * @param expiresDate a {@link DateType} representing the date after which the catlog is no longer valid. */ public void setExpires(DateType expiresDate) { this.expires = expiresDate; } /** * Check if there is a fatal error and catalog should not be used. * * @return true if catalog not useable. */ public boolean hasFatalError() { return hasError; } /** * Append an error message to the message log. Call check() to get the log when * everything is done. * * @param message append this message to log * @param isInvalid true if this is a fatal error. */ public void appendErrorMessage(String message, boolean isInvalid) { log.append(message); hasError = hasError | isInvalid; } /** * Check internal data structures. * * @param out : print errors here * @param show : print messages for each object (debug) * @return true if no fatal consistency errors. */ public boolean check(StringBuilder out, boolean show) { boolean isValid = !hasError; out.append("----Catalog Validation\n"); if (log.length() > 0) out.append(log); if (show) System.out.println(" catalog valid = " + isValid); //if (topDataset != null) // isValid &= topDataset.check( out, show); for (InvDataset ds : datasets) { InvDatasetImpl dsi = (InvDatasetImpl) ds; dsi.check(out, show); // cant make it invalid !! } return isValid; } public String getLog() { return log.toString(); } /** * Debugging: dump entire data structure. * * @return String representation. */ public String dump() { StringBuilder buff = new StringBuilder(1000); buff.setLength(0); buff.append("Catalog <").append(getName()) .append("> <").append(getVersion()) .append("> <").append(getCreateFrom()).append(">\n"); buff.append(topDataset.dump(2)); return buff.toString(); } /* * Add a PropertyChangeEvent Listener. THIS IS EXPERIMENTAL DO NOT RELY ON. * Throws a PropertyChangeEvent: * <ul><li>propertyName = "InvCatalogRefInit", getNewValue() = InvCatalogRef that was just initialized * </ul> * @param l the listener * public void addPropertyChangeListener(PropertyChangeListener l) { if (listenerList == null) listenerList = new EventListenerList(); listenerList.add(PropertyChangeListener.class, l); } /** * Remove a PropertyChangeEvent Listener. * @param l the listener * public void removePropertyChangeListener(PropertyChangeListener l) { listenerList.remove(PropertyChangeListener.class, l); } private EventListenerList listenerList = null; // PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue) void firePropertyChangeEvent(PropertyChangeEvent event) { // System.out.println("firePropertyChangeEvent "+event); if (listenerList == null) return; // Process the listeners last to first Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == PropertyChangeListener.class) { ((PropertyChangeListener) listeners[i + 1]).propertyChange(event); } } } */ /** * This finds the topmost catalog, even when its a InvCatalogRef. * Used to throw a PropertyChange event on the top catalog. * * @return top catalog */ InvCatalogImpl getTopCatalog() { return (top == null) ? this : top; } void setTopCatalog(InvCatalogImpl top) { this.top = top; } private InvCatalogImpl top = null; //////////////////////////////////////////// /* private InvCatalogFactory factory = null; // private InvCatalogConvertIF converter = null; // this is how catalogRefs read their catalogs InvCatalogFactory getCatalogFactory() { return factory; } void setCatalogFactory(InvCatalogFactory factory) { this.factory = factory; } // track converter InvCatalogConvertIF getCatalogConverter() { return converter; } void setCatalogConverter(InvCatalogConvertIF converter) { this.converter = converter; } */ /* * Set the connverter to 1.0, typically to write a 0.6 out to a 1.0 * public void setCatalogConverterToVersion1() { setCatalogConverter(factory.getCatalogConverter(XMLEntityResolver.CATALOG_NAMESPACE_10)); } */ /** * Write the catalog as an XML document to the specified stream. * * @param os write to this OutputStream * @throws java.io.IOException on an error. */ public void writeXML(java.io.OutputStream os) throws java.io.IOException { InvCatalogConvertIF converter = InvCatalogFactory.getDefaultConverter(); converter.writeXML(this, os); } /** * Write the catalog as an XML document to the specified stream. * * @param os write to this OutputStream * @param raw if true, write original (server) version, else write client version * @throws java.io.IOException on an error. */ public void writeXML(java.io.OutputStream os, boolean raw) throws java.io.IOException { InvCatalogConvertIF converter = InvCatalogFactory.getDefaultConverter(); converter.writeXML(this, os, raw); } ////////////////////////////////////////////////////////////////////////// /** * Get dataset roots. * * @return List of InvProperty. May be empty, may not be null. */ public java.util.List<DataRootConfig> getDatasetRoots() { return roots; } /** * Add Dataset Root, key = path, value = location. * @param root add a dataset root */ public void addDatasetRoot(DataRootConfig root) { roots.add(root); } /** * InvCatalogImpl elements with same values are equal. */ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InvCatalogImpl)) return false; return o.hashCode() == this.hashCode(); } /** * Override Object.hashCode() to implement equals. */ public int hashCode() { if (hashCode == 0) { int result = 17; if (null != getName()) result = 37 * result + getName().hashCode(); result = 37 * result + getServices().hashCode(); result = 37 * result + getDatasets().hashCode(); hashCode = result; } return hashCode; } private volatile int hashCode = 0; // Bloch, item 8 public boolean isStatic() { return isStatic; } public void setStatic(boolean aStatic) { isStatic = aStatic; } }
cdm/src/main/java/thredds/catalog/InvCatalogImpl.java
/* * Copyright 1998-2009 University Corporation for Atmospheric Research/Unidata * * Portions of this software were developed by the Unidata Program at the * University Corporation for Atmospheric Research. * * Access and use of this software shall impose the following obligations * and understandings on the user. The user is granted the right, without * any fee or cost, to use, copy, modify, alter, enhance and distribute * this software, and any derivative works thereof, and its supporting * documentation for any purpose whatsoever, provided that this entire * notice appears in all copies of the software, derivative works and * supporting documentation. Further, UCAR requests that the user credit * UCAR/Unidata in any publications that result from the use of this * software or in any product that includes this software. The names UCAR * and/or Unidata, however, may not be used in any advertising or publicity * to endorse or promote any products or commercial entity unless specific * written permission is obtained from UCAR/Unidata. The user also * understands that UCAR/Unidata is not obligated to provide the user with * any support, consulting, training or assistance of any kind with regard * to the use, operation and performance of this software nor to provide * the user with any updates, revisions, new versions or "bug fixes." * * THIS SOFTWARE IS PROVIDED BY UCAR/UNIDATA "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL UCAR/UNIDATA BE LIABLE FOR ANY SPECIAL, * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING * FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, * NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION * WITH THE ACCESS, USE OR PERFORMANCE OF THIS SOFTWARE. */ package thredds.catalog; import ucar.nc2.units.DateType; import java.util.*; import java.net.*; /** * Concrete implementation of a Thredds catalog object. Use this when you are constructing or modifying. * * @author john caron * @see InvCatalog */ public class InvCatalogImpl extends InvCatalog { private String createFrom; private List<DataRootConfig> roots = new ArrayList<DataRootConfig>(); // validation private StringBuilder log = new StringBuilder(); private boolean hasError = false; private boolean isStatic = false; /** * Munge this catalog so the given dataset is the top catalog. * * @param ds make this top; must be existing dataset in this catalog. * * @deprecated in favor of thredds.catalog.util.DeepCopyUtils.subsetCatalogOnDataset */ public void subset(InvDataset ds) { InvDatasetImpl dataset = (InvDatasetImpl) ds; // Make all inherited metadata local. dataset.transferMetadata(dataset, true); topDataset = dataset; datasets.clear(); // throw away the rest datasets.add(topDataset); // parent lookups need to be local //InvService service = dataset.getServiceDefault(); //if (service != null) LOOK // dataset.serviceName = service.getName(); dataset.dataType = dataset.getDataType(); // all properties need to be local // LOOK dataset.setPropertiesLocal( new ArrayList(dataset.getProperties())); // next part requires this before it dataset.setCatalog(this); dataset.parent = null; // any referenced services need to be local List<InvService> services = new ArrayList<InvService>(dataset.getServicesLocal()); findServices(services, dataset); dataset.setServicesLocal(services); finish(); } // /** // * Return a catalog with a shallow copy of the given dataset as the top dataset. // * // * @param dataset the dataset to copy into a new catalog // * @return A new catalog with a shallow copy of the given dataset as the top dataset. // */ // public InvCatalogImpl subsetShallowCopy( InvDatasetImpl dataset) // { // InvCatalogImpl newCatalog = new InvCatalogImpl( null, "1.0.2", null); // InvDatasetImpl newTopDataset = new InvDatasetImpl( null, dataset.getName()); // newTopDataset.transferMetadata( dataset ); // if (dataset.getAccess() != null && ! dataset.getAccess().isEmpty()) // { // newTopDataset.addAccess( dataset.getAccess() ); // } // dataset.getDatasets(); // dataset.getID(); // dataset.getServiceName(); // dataset.getServicesLocal(); // dataset.getUrlPath(); // // // ToDo LOOK Probably fine for throw away catalog that is only generated so that XML can be generated. // dataset.finish(); // // newCatalog.addDataset( newTopDataset ); // // return newCatalog; // } void findServices(List<InvService> result, InvDataset ds) { if (ds instanceof InvCatalogRef) return; // look for access elements with unresolved services for (InvAccess a : ds.getAccess()) { InvService s = a.getService(); InvDataset d = a.getDataset(); if (null == d.findService(s.getName()) && !(result.contains(s))) result.add(s); } // recurse into nested datasets for (InvDataset nested : ds.getDatasets()) { findServices(result, nested); } } /** * Munge this catalog to remove any dataset that doesnt pass through the filter. * * @param filter remove datasets that dont pass this filter. */ public void filter(DatasetFilter filter) { mark(filter, topDataset); delete(topDataset); this.filter = filter; } // got to keep it for catalogRef's private DatasetFilter filter = null; protected DatasetFilter getDatasetFilter() { return filter; } // see if this ds should be filtered out. // if so, setMark and return true. // if any nested dataset are kept, then keep it. // unread CatalogRefs are always kept. private boolean mark(DatasetFilter filter, InvDatasetImpl ds) { if (ds instanceof InvCatalogRef) { InvCatalogRef catRef = (InvCatalogRef) ds; if (!catRef.isRead()) return false; } // recurse into nested datasets first boolean allMarked = true; for (InvDataset nested : ds.getDatasets()) { allMarked &= mark(filter, (InvDatasetImpl) nested); } if (!allMarked) return false; if (filter.accept(ds) >= 0) return false; // mark for deletion ds.setMark(true); if (debugFilter) System.out.println(" mark " + ds.getName()); return true; } private boolean debugFilter = false; // remove marked datasets private void delete(InvDatasetImpl ds) { if (ds instanceof InvCatalogRef) { InvCatalogRef catRef = (InvCatalogRef) ds; if (!catRef.isRead()) return; } Iterator iter = ds.getDatasets().iterator(); while (iter.hasNext()) { InvDatasetImpl nested = (InvDatasetImpl) iter.next(); if (nested.getMark()) { iter.remove(); if (debugFilter) System.out.println(" remove " + nested.getName()); } else delete(nested); } } /////////////////////////////////////////////////////////////////////////////// // construction and internals /** * Construct an InvCatalog. * You must call finish() after all objects are added. * * @param name : catalog name. * @param version : catalog version. * @param baseURI : catalog base URI (external). */ public InvCatalogImpl(String name, String version, URI baseURI) { this(name, version, null, baseURI); } /** * Construct an InvCatalog. * You must call finish() after all objects are added. * * @param name : catalog name. * @param version : catalog version. * @param expires : date/time catalog expires. * @param baseURI : catalog base URI (external). */ public InvCatalogImpl(String name, String version, DateType expires, URI baseURI) { this.name = name; this.version = version; this.expires = expires; this.baseURI = baseURI; } /** * Finish constructing after all elements have been added or modified. * This routine will do any needed internal consistency work. * Its ok to call multiple times. * * @return true if successful. */ public boolean finish() { // make topDataset if needed //if (topDataset == null) { if (datasets.size() == 1) { // already only one; make it top topDataset = (InvDatasetImpl) datasets.get(0); } else { // create one topDataset = new InvDatasetImpl(null, name == null ? "Top Dataset" : name); for (InvDataset dataset : datasets) topDataset.addDataset((InvDatasetImpl) dataset); topDataset.setServicesLocal(services); } //} topDataset.setCatalog(this); // build dataset hash table dsHash = new HashMap<String, InvDataset>(); addDatasetIds(topDataset); // recurse through the datasets and finish them return topDataset.finish(); } private void addDatasetIds(InvDatasetImpl ds) { addDatasetByID(ds); if (ds instanceof InvCatalogRef) return; //if (ds instanceof InvDatasetFmrc) return; // recurse into nested for (InvDataset invDataset : ds.getDatasets()) { InvDatasetImpl nested = (InvDatasetImpl) invDataset; addDatasetIds(nested); } } /** * Add Dataset to internal hash. * * @param ds : add this dataset if ds.getID() != null * @see InvCatalog#findDatasetByID */ public void addDatasetByID(InvDatasetImpl ds) { if (ds.getID().startsWith("null")) System.out.printf("HEY addDatasetByID %s%n", ds.getID()); if (ds.getID() != null) dsHash.put(ds.getID(), ds); } /** * Find the dataset in this catalog by its ID. If found, remove it. * * @param ds Remove this dataset from the hash */ public void removeDatasetByID(InvDatasetImpl ds) { if (ds.getID() != null) dsHash.remove(ds.getID()); } /** * Add Dataset (1.0) * * @param ds add this dataset */ public void addDataset(InvDatasetImpl ds) { if (ds != null) datasets.add(ds); } /** * Remove the given dataset from this catalog if it is a direct child of this catalog. * * @param ds remove this dataset * @return true if found and removed */ public boolean removeDataset(InvDatasetImpl ds) { if (this.datasets.remove(ds)) { ds.setParent(null); removeDatasetByID(ds); return true; } return false; } /** * Replace the given dataset if it is a nested dataset. * * @param remove - the dataset element to be removed * @param add - the dataset element to be added * @return true on success */ public boolean replaceDataset(InvDatasetImpl remove, InvDatasetImpl add) { if (topDataset.equals(remove)) { topDataset = add; topDataset.setCatalog(this); } for (int i = 0; i < datasets.size(); i++) { InvDataset dataset = datasets.get(i); if (dataset.equals(remove)) { datasets.set(i, add); removeDatasetByID(remove); addDatasetByID(add); return true; } } return false; } /** * Add Property (1.0) * * @param p add this property */ public void addProperty(InvProperty p) { properties.add(p); } /** * Add Service (1.0) * * @param s add this service */ public void addService(InvService s) { if (s == null) throw new IllegalArgumentException("Service to add was null."); // While adding a service, there are three possible results: if (s.getName() != null) { Object obj = serviceHash.get(s.getName()); if (obj == null) { // 1) No service with matching name entry was found, add given service; serviceHash.put(s.getName(), s); services.add(s); return; } else { // A service with matching name was found. if (s.equals(obj)) { // 2) matching name entry, objects are equal so OK; return; } else { // 3) matching name entry, objects are not equal so ??? // @todo throw an exception??? // Currently just dropping given service log.append("Multiple Services with the same name\n"); return; } } } } /** * Add top-level InvDataset to this catalog. * * @deprecated Use addDataset() instead; datamodel now allows multiple top level datasets. */ public void setDataset(InvDatasetImpl ds) { topDataset = ds; addDataset(ds); } /** * String describing how the catalog was created, for debugging. * * @return how the catalog was created, for debugging */ public String getCreateFrom() { return createFrom; } /** * Set how the catalog was created, for debugging. * @param createFrom how the catalog was created, for debugging */ public void setCreateFrom(String createFrom) { this.createFrom = createFrom; } /** * Set the catalog base URI. * Its used to resolve reletive URLS. * @param baseURI set to this */ public void setBaseURI(URI baseURI) { this.baseURI = baseURI; } /** * @return the catalog base URI. */ public URI getBaseURI() { return baseURI; } /* * @return DTD string * public String getDTDid() { return dtdID; } /* * set DTD * public void setDTDid(String dtdID) { this.dtdID = dtdID; } */ /** * Set the expires date after which the catalog is no longer valid. * * @param expiresDate a {@link DateType} representing the date after which the catlog is no longer valid. */ public void setExpires(DateType expiresDate) { this.expires = expiresDate; } /** * Check if there is a fatal error and catalog should not be used. * * @return true if catalog not useable. */ public boolean hasFatalError() { return hasError; } /** * Append an error message to the message log. Call check() to get the log when * everything is done. * * @param message append this message to log * @param isInvalid true if this is a fatal error. */ public void appendErrorMessage(String message, boolean isInvalid) { log.append(message); hasError = hasError | isInvalid; } /** * Check internal data structures. * * @param out : print errors here * @param show : print messages for each object (debug) * @return true if no fatal consistency errors. */ public boolean check(StringBuilder out, boolean show) { boolean isValid = !hasError; out.append("----Catalog Validation\n"); if (log.length() > 0) out.append(log); if (show) System.out.println(" catalog valid = " + isValid); //if (topDataset != null) // isValid &= topDataset.check( out, show); for (InvDataset ds : datasets) { InvDatasetImpl dsi = (InvDatasetImpl) ds; dsi.check(out, show); // cant make it invalid !! } return isValid; } public String getLog() { return log.toString(); } /** * Debugging: dump entire data structure. * * @return String representation. */ public String dump() { StringBuilder buff = new StringBuilder(1000); buff.setLength(0); buff.append("Catalog <").append(getName()) .append("> <").append(getVersion()) .append("> <").append(getCreateFrom()).append(">\n"); buff.append(topDataset.dump(2)); return buff.toString(); } /* * Add a PropertyChangeEvent Listener. THIS IS EXPERIMENTAL DO NOT RELY ON. * Throws a PropertyChangeEvent: * <ul><li>propertyName = "InvCatalogRefInit", getNewValue() = InvCatalogRef that was just initialized * </ul> * @param l the listener * public void addPropertyChangeListener(PropertyChangeListener l) { if (listenerList == null) listenerList = new EventListenerList(); listenerList.add(PropertyChangeListener.class, l); } /** * Remove a PropertyChangeEvent Listener. * @param l the listener * public void removePropertyChangeListener(PropertyChangeListener l) { listenerList.remove(PropertyChangeListener.class, l); } private EventListenerList listenerList = null; // PropertyChangeEvent(Object source, String propertyName, Object oldValue, Object newValue) void firePropertyChangeEvent(PropertyChangeEvent event) { // System.out.println("firePropertyChangeEvent "+event); if (listenerList == null) return; // Process the listeners last to first Object[] listeners = listenerList.getListenerList(); for (int i = listeners.length - 2; i >= 0; i -= 2) { if (listeners[i] == PropertyChangeListener.class) { ((PropertyChangeListener) listeners[i + 1]).propertyChange(event); } } } */ /** * This finds the topmost catalog, even when its a InvCatalogRef. * Used to throw a PropertyChange event on the top catalog. * * @return top catalog */ InvCatalogImpl getTopCatalog() { return (top == null) ? this : top; } void setTopCatalog(InvCatalogImpl top) { this.top = top; } private InvCatalogImpl top = null; //////////////////////////////////////////// /* private InvCatalogFactory factory = null; // private InvCatalogConvertIF converter = null; // this is how catalogRefs read their catalogs InvCatalogFactory getCatalogFactory() { return factory; } void setCatalogFactory(InvCatalogFactory factory) { this.factory = factory; } // track converter InvCatalogConvertIF getCatalogConverter() { return converter; } void setCatalogConverter(InvCatalogConvertIF converter) { this.converter = converter; } */ /* * Set the connverter to 1.0, typically to write a 0.6 out to a 1.0 * public void setCatalogConverterToVersion1() { setCatalogConverter(factory.getCatalogConverter(XMLEntityResolver.CATALOG_NAMESPACE_10)); } */ /** * Write the catalog as an XML document to the specified stream. * * @param os write to this OutputStream * @throws java.io.IOException on an error. */ public void writeXML(java.io.OutputStream os) throws java.io.IOException { InvCatalogConvertIF converter = InvCatalogFactory.getDefaultConverter(); converter.writeXML(this, os); } /** * Write the catalog as an XML document to the specified stream. * * @param os write to this OutputStream * @param raw if true, write original (server) version, else write client version * @throws java.io.IOException on an error. */ public void writeXML(java.io.OutputStream os, boolean raw) throws java.io.IOException { InvCatalogConvertIF converter = InvCatalogFactory.getDefaultConverter(); converter.writeXML(this, os, raw); } ////////////////////////////////////////////////////////////////////////// /** * Get dataset roots. * * @return List of InvProperty. May be empty, may not be null. */ public java.util.List<DataRootConfig> getDatasetRoots() { return roots; } /** * Add Dataset Root, key = path, value = location. * @param root add a dataset root */ public void addDatasetRoot(DataRootConfig root) { roots.add(root); } /** * InvCatalogImpl elements with same values are equal. */ public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof InvCatalogImpl)) return false; return o.hashCode() == this.hashCode(); } /** * Override Object.hashCode() to implement equals. */ public int hashCode() { if (hashCode == 0) { int result = 17; if (null != getName()) result = 37 * result + getName().hashCode(); result = 37 * result + getServices().hashCode(); result = 37 * result + getDatasets().hashCode(); hashCode = result; } return hashCode; } private volatile int hashCode = 0; // Bloch, item 8 public boolean isStatic() { return isStatic; } public void setStatic(boolean aStatic) { isStatic = aStatic; } }
fix debug statement throwing NPE
cdm/src/main/java/thredds/catalog/InvCatalogImpl.java
fix debug statement throwing NPE
<ide><path>dm/src/main/java/thredds/catalog/InvCatalogImpl.java <ide> * @see InvCatalog#findDatasetByID <ide> */ <ide> public void addDatasetByID(InvDatasetImpl ds) { <del> if (ds.getID().startsWith("null")) <add> if (ds.getID() != null && ds.getID().startsWith("null")) <ide> System.out.printf("HEY addDatasetByID %s%n", ds.getID()); <ide> <ide> if (ds.getID() != null)
Java
apache-2.0
fa4bcd441fef305cd6f443c4c7620c84bee3d354
0
kantega/Flyt-cms,kantega/Flyt-cms,kantega/Flyt-cms
/* * Copyright 2010 Kantega AS * * 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 no.kantega.publishing.common.util.templates; import no.kantega.commons.exception.InvalidFileException; import no.kantega.commons.exception.SystemException; import no.kantega.commons.util.XMLHelper; import no.kantega.commons.util.XPathHelper; import no.kantega.publishing.admin.content.util.ResourceLoaderEntityResolver; import no.kantega.publishing.common.data.ContentTemplate; import no.kantega.publishing.common.data.TemplateConfigurationValidationError; import org.apache.xpath.XPathAPI; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.transform.TransformerException; import java.util.ArrayList; import java.util.List; public class ContentTemplateReader { private static final Logger log = LoggerFactory.getLogger(ContentTemplateReader.class); private ResourceLoader contentTemplateResourceLoader; /** * Validates attributes in contenttemplate * @param contentTemplate - contenttemplate * @return */ public List<TemplateConfigurationValidationError> updateContentTemplateFromTemplateFile(ContentTemplate contentTemplate) { List<TemplateConfigurationValidationError> errors = new ArrayList<TemplateConfigurationValidationError>(); contentTemplate.setAttributeElements(new ArrayList<Element>()); contentTemplate.setPropertyElements(new ArrayList<Element>()); // Check attributes in XML file try { Resource resource = contentTemplateResourceLoader.getResource(contentTemplate.getTemplateFile()); if (resource == null) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.missingtemplatefile", contentTemplate.getTemplateFile())); return errors; } ResourceLoaderEntityResolver entityResolver = new ResourceLoaderEntityResolver(contentTemplateResourceLoader); Document def = XMLHelper.openDocument(resource, entityResolver); NodeList attributes = XPathAPI.selectNodeList(def.getDocumentElement(), "attributes/attribute|attributes/repeater"); if (attributes.getLength() == 0) { attributes = XPathAPI.selectNodeList(def.getDocumentElement(), "attribute|repeater"); } for (int i = 0; i < attributes.getLength(); i++) { Element attr = (Element)attributes.item(i); contentTemplate.getAttributeElements().add(attr); } if (contentTemplate.getAttributeElements().size() == 0) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.emptyfile", contentTemplate.getTemplateFile())); } NodeList properties = XPathAPI.selectNodeList(def.getDocumentElement(), "properties/property"); for (int i = 0; i < properties.getLength(); i++) { Element prop = (Element)properties.item(i); contentTemplate.getPropertyElements().add(prop); } String helptext = XPathHelper.getString(def.getDocumentElement(), "helptext"); contentTemplate.setHelptext(helptext); } catch (SystemException | InvalidFileException e) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.missingtemplatefile", contentTemplate.getTemplateFile())); log.error("Error loading: " + contentTemplate.getTemplateFile(), e); } catch (TransformerException e) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.transformerexception", contentTemplate.getTemplateFile())); log.error("Error transforming: " + contentTemplate.getTemplateFile(), e); } return errors; } public void setContentTemplateResourceLoader(ResourceLoader contentTemplateResourceLoader) { this.contentTemplateResourceLoader = contentTemplateResourceLoader; } }
modules/core/src/java/no/kantega/publishing/common/util/templates/ContentTemplateReader.java
/* * Copyright 2010 Kantega AS * * 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 no.kantega.publishing.common.util.templates; import no.kantega.commons.exception.InvalidFileException; import no.kantega.commons.util.XMLHelper; import no.kantega.commons.util.XPathHelper; import no.kantega.publishing.admin.content.util.ResourceLoaderEntityResolver; import no.kantega.publishing.common.data.ContentTemplate; import no.kantega.publishing.common.data.TemplateConfigurationValidationError; import org.apache.xpath.XPathAPI; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import javax.xml.transform.TransformerException; import java.util.ArrayList; import java.util.List; public class ContentTemplateReader { private ResourceLoader contentTemplateResourceLoader; /** * Validates attributes in contenttemplate * @param contentTemplate - contenttemplate * @return */ public List<TemplateConfigurationValidationError> updateContentTemplateFromTemplateFile(ContentTemplate contentTemplate) { List<TemplateConfigurationValidationError> errors = new ArrayList<TemplateConfigurationValidationError>(); contentTemplate.setAttributeElements(new ArrayList<Element>()); contentTemplate.setPropertyElements(new ArrayList<Element>()); // Check attributes in XML file try { Resource resource = contentTemplateResourceLoader.getResource(contentTemplate.getTemplateFile()); if (resource == null) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.missingtemplatefile", contentTemplate.getTemplateFile())); return errors; } ResourceLoaderEntityResolver entityResolver = new ResourceLoaderEntityResolver(contentTemplateResourceLoader); Document def = XMLHelper.openDocument(resource, entityResolver); NodeList attributes = XPathAPI.selectNodeList(def.getDocumentElement(), "attributes/attribute|attributes/repeater"); if (attributes.getLength() == 0) { attributes = XPathAPI.selectNodeList(def.getDocumentElement(), "attribute|repeater"); } for (int i = 0; i < attributes.getLength(); i++) { Element attr = (Element)attributes.item(i); contentTemplate.getAttributeElements().add(attr); } if (contentTemplate.getAttributeElements().size() == 0) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.emptyfile", contentTemplate.getTemplateFile())); } NodeList properties = XPathAPI.selectNodeList(def.getDocumentElement(), "properties/property"); for (int i = 0; i < properties.getLength(); i++) { Element prop = (Element)properties.item(i); contentTemplate.getPropertyElements().add(prop); } String helptext = XPathHelper.getString(def.getDocumentElement(), "helptext"); contentTemplate.setHelptext(helptext); } catch (InvalidFileException e) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.missingtemplatefile", contentTemplate.getTemplateFile())); } catch (TransformerException e) { errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.transformerexception", contentTemplate.getTemplateFile())); } return errors; } public void setContentTemplateResourceLoader(ResourceLoader contentTemplateResourceLoader) { this.contentTemplateResourceLoader = contentTemplateResourceLoader; } }
AP-1660 git-svn-id: 8def386c603904b39326d3fc08add479b8279298@4816 fd808399-8219-4f14-9d4c-37719d9ec93d
modules/core/src/java/no/kantega/publishing/common/util/templates/ContentTemplateReader.java
AP-1660
<ide><path>odules/core/src/java/no/kantega/publishing/common/util/templates/ContentTemplateReader.java <ide> package no.kantega.publishing.common.util.templates; <ide> <ide> import no.kantega.commons.exception.InvalidFileException; <add>import no.kantega.commons.exception.SystemException; <ide> import no.kantega.commons.util.XMLHelper; <ide> import no.kantega.commons.util.XPathHelper; <ide> import no.kantega.publishing.admin.content.util.ResourceLoaderEntityResolver; <ide> import no.kantega.publishing.common.data.ContentTemplate; <ide> import no.kantega.publishing.common.data.TemplateConfigurationValidationError; <ide> import org.apache.xpath.XPathAPI; <add>import org.slf4j.Logger; <add>import org.slf4j.LoggerFactory; <ide> import org.springframework.core.io.Resource; <ide> import org.springframework.core.io.ResourceLoader; <ide> import org.w3c.dom.Document; <ide> import java.util.List; <ide> <ide> public class ContentTemplateReader { <add> private static final Logger log = LoggerFactory.getLogger(ContentTemplateReader.class); <ide> private ResourceLoader contentTemplateResourceLoader; <ide> /** <ide> * Validates attributes in contenttemplate <ide> String helptext = XPathHelper.getString(def.getDocumentElement(), "helptext"); <ide> contentTemplate.setHelptext(helptext); <ide> <del> } catch (InvalidFileException e) { <add> } catch (SystemException | InvalidFileException e) { <ide> errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.missingtemplatefile", contentTemplate.getTemplateFile())); <add> log.error("Error loading: " + contentTemplate.getTemplateFile(), e); <ide> } catch (TransformerException e) { <ide> errors.add(new TemplateConfigurationValidationError(contentTemplate.getName(), "aksess.templateconfig.error.attribute.transformerexception", contentTemplate.getTemplateFile())); <add> log.error("Error transforming: " + contentTemplate.getTemplateFile(), e); <ide> } <ide> return errors; <ide> }
Java
agpl-3.0
80fd089bf61884062b49ca4ba3f735d31042996a
0
objectiveCarlo/player-sdk-native-android,objectiveCarlo/player-sdk-native-android,kaltura/player-sdk-native-android,kaltura/player-sdk-native-android
package com.kaltura.playersdk.players; import android.app.Activity; import android.util.Log; import android.view.Gravity; import com.kaltura.hlsplayersdk.HLSPlayerViewController; import com.kaltura.hlsplayersdk.events.OnDurationChangedListener; import com.kaltura.hlsplayersdk.types.PlayerStates; import com.kaltura.playersdk.AlternateAudioTracksInterface; import com.kaltura.playersdk.LiveStreamInterface; import com.kaltura.playersdk.QualityTrack; import com.kaltura.playersdk.QualityTracksInterface; import com.kaltura.playersdk.TextTracksInterface; import com.kaltura.playersdk.events.Listener; import com.kaltura.playersdk.types.TrackType; import java.util.ArrayList; import java.util.List; public class HLSPlayer extends BasePlayerView implements TextTracksInterface, AlternateAudioTracksInterface, QualityTracksInterface, com.kaltura.hlsplayersdk.events.OnPlayheadUpdateListener, com.kaltura.hlsplayersdk.events.OnErrorListener, com.kaltura.hlsplayersdk.events.OnPlayerStateChangeListener, com.kaltura.hlsplayersdk.events.OnProgressListener, com.kaltura.hlsplayersdk.events.OnAudioTracksListListener, com.kaltura.hlsplayersdk.events.OnAudioTrackSwitchingListener, com.kaltura.hlsplayersdk.events.OnQualityTracksListListener, com.kaltura.hlsplayersdk.events.OnQualitySwitchingListener, OnDurationChangedListener, LiveStreamInterface { private static final String TAG = HLSPlayer.class.getSimpleName(); private HLSPlayerViewController mPlayer; public HLSPlayer(Activity activity) { super(activity); mPlayer = new HLSPlayerViewController(activity); LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER); this.addView(mPlayer, lp); mPlayer.initialize(); } public void close(){ mPlayer.close(); mPlayer = null; } @Override public String getVideoUrl() { return mPlayer.getVideoUrl(); } @Override public void setVideoUrl(String url) { if ( mPlayer.getVideoUrl() == null || !url.equals(mPlayer.getVideoUrl())) { mPlayer.setVideoUrl(url); } } @Override public int getDuration() { return mPlayer.getDuration() - 1; } @Override public void play() { mPlayer.play(); } @Override public void pause() { mPlayer.pause(); } @Override public void stop() { mPlayer.stop(); } @Override public void seek(int msec) { mPlayer.seek(msec); } @Override public boolean isPlaying() { return mPlayer.isPlaying(); } @Override public boolean canPause() { return mPlayer != null; } @Override public void setStartingPoint(int point) { mPlayer.setStartingPoint(point); } @Override public void release() { mPlayer.release(); } @Override public void recoverRelease() { mPlayer.recoverRelease(); } @Override public void setBufferTime(int newTime) { mPlayer.setBufferTime(newTime); } @Override public void switchQualityTrack(int newIndex) { mPlayer.switchQualityTrack(newIndex); } @Override public void setAutoSwitch(boolean autoSwitch) { mPlayer.setAutoSwitch(autoSwitch); } @Override public float getLastDownloadTransferRate() { return mPlayer.getLastDownloadTransferRate(); } @Override public float getDroppedFramesPerSecond() { return mPlayer.getDroppedFramesPerSecond(); } @Override public float getBufferPercentage() { return mPlayer.getBufferPercentage(); } @Override public int getCurrentQualityIndex() { return mPlayer.getCurrentQualityIndex(); } @Override public void hardSwitchAudioTrack(int newAudioIndex) { mPlayer.hardSwitchAudioTrack(newAudioIndex); } @Override public void softSwitchAudioTrack(int newAudioIndex) { mPlayer.softSwitchAudioTrack(newAudioIndex); } @Override public void switchTextTrack(int newIndex) { mPlayer.switchTextTrack(newIndex); } @Override public void switchToLive() { mPlayer.goToLive(); } ///////////////////////////////////////////////////////// // // HlsPlayerSDK Listeners // //////////////////////////////////////////////////////// @Override public boolean onStateChanged(PlayerStates state) { com.kaltura.playersdk.types.PlayerStates kState; switch (state) { case START: kState = com.kaltura.playersdk.types.PlayerStates.START; break; case LOAD: kState = com.kaltura.playersdk.types.PlayerStates.LOAD; break; case PLAY: kState = com.kaltura.playersdk.types.PlayerStates.PLAY; break; case PAUSE: kState = com.kaltura.playersdk.types.PlayerStates.PAUSE; break; case END: kState = com.kaltura.playersdk.types.PlayerStates.END; break; case SEEKING: kState = com.kaltura.playersdk.types.PlayerStates.SEEKING; break; case SEEKED: kState = com.kaltura.playersdk.types.PlayerStates.SEEKED; break; default: kState = com.kaltura.playersdk.types.PlayerStates.START; } mListenerExecutor.executeOnStateChanged(kState); return false; } @Override public void onPlayheadUpdated(int msec) { mListenerExecutor.executeOnPlayheadUpdated(msec); } @Override public void onProgressUpdate(int progress) { mListenerExecutor.executeOnProgressUpdate(progress); } @Override public void OnQualityTracksList(List<com.kaltura.hlsplayersdk.QualityTrack> list, int defaultTrackIndex) { List<QualityTrack> newList = new ArrayList<QualityTrack>(); for ( int i=0; i < list.size(); i++ ) { com.kaltura.hlsplayersdk.QualityTrack currentTrack = list.get(i); QualityTrack newTrack = new QualityTrack(); newTrack.bitrate = currentTrack.bitrate; newTrack.height = currentTrack.height; newTrack.width = currentTrack.width; newTrack.trackId = currentTrack.trackId; newTrack.type = currentTrack.type == com.kaltura.hlsplayersdk.types.TrackType.VIDEO ? TrackType.VIDEO: TrackType.AUDIO; newList.add(newTrack); } mListenerExecutor.executeOnQualityTracksList(newList,defaultTrackIndex); } @Override public void onError(int errorCode, String errorMessage) { Log.e(TAG, "HLS Error Occurred - error code: " + errorCode + " " + "msg: " + errorMessage); } @Override public void onFatalError(int errorCode, String errorMessage) { mListenerExecutor.executeOnError(errorCode,errorMessage); } @Override public void onAudioSwitchingStart(int oldTrackIndex, int newTrackIndex) { mListenerExecutor.executeOnAudioSwitchingStart(oldTrackIndex, newTrackIndex); } @Override public void onAudioSwitchingEnd(int newTrackIndex) { mListenerExecutor.executeonAudioSwitchingEnd(newTrackIndex); } @Override public void OnAudioTracksList(List<String> list, int defaultTrackIndex) { mListenerExecutor.executeOnAudioTracksList(list,defaultTrackIndex); } @Override public void onQualitySwitchingStart(int oldTrackIndex, int newTrackIndex) { } @Override public void onQualitySwitchingEnd(int newTrackIndex) { } @Override public void onDurationChanged(int msec) { mListenerExecutor.executeOnDurationChanged(msec); } @Override protected List<Listener.EventType> getCompatibleListenersList() { List<Listener.EventType> list = super.getCompatibleListenersList(); list.add(Listener.EventType.AUDIO_TRACK_SWITCH_LISTENER_TYPE); list.add(Listener.EventType.AUDIO_TRACKS_LIST_LISTENER_TYPE); list.add(Listener.EventType.QUALITY_SWITCHING_LISTENER_TYPE); list.add(Listener.EventType.QUALITY_TRACKS_LIST_LISTENER_TYPE); list.add(Listener.EventType.DURATION_CHANGED_LISTENER_TYPE); return list; } @Override public void removeListener(Listener.EventType eventType) { super.removeListener(eventType); registerHLSListener(eventType, false); } @Override public void registerListener(Listener listener){ super.registerListener(listener); if (listener != null) { registerHLSListener(listener.getEventType(), true); } } // TODO: discuss this issue with dp so they will change their player listeners scheme private void registerHLSListener(Listener.EventType eventType, boolean shouldRegister){ switch(eventType){ case JS_CALLBACK_READY_LISTENER_TYPE: break; case AUDIO_TRACKS_LIST_LISTENER_TYPE: mPlayer.registerAudioTracksList(shouldRegister ? this : null); break; case AUDIO_TRACK_SWITCH_LISTENER_TYPE: mPlayer.registerAudioSwitchingChange(shouldRegister ? this : null); break; case CAST_DEVICE_CHANGE_LISTENER_TYPE: break; case CAST_ROUTE_DETECTED_LISTENER_TYPE: break; case ERROR_LISTENER_TYPE: mPlayer.registerError(shouldRegister ? this : null); break; case PLAYER_STATE_CHANGE_LISTENER_TYPE: mPlayer.registerPlayerStateChange(shouldRegister ? this : null); break; case PLAYHEAD_UPDATE_LISTENER_TYPE: mPlayer.registerPlayheadUpdate(shouldRegister ? this : null); break; case PROGRESS_UPDATE_LISTENER_TYPE: mPlayer.registerProgressUpdate(shouldRegister ? this : null); break; case QUALITY_SWITCHING_LISTENER_TYPE: mPlayer.registerQualitySwitchingChange(shouldRegister ? this : null); break; case QUALITY_TRACKS_LIST_LISTENER_TYPE: mPlayer.registerQualityTracksList(shouldRegister ? this : null); break; case TEXT_TRACK_CHANGE_LISTENER_TYPE: break; case TEXT_TRACK_LIST_LISTENER_TYPE: break; case TEXT_TRACK_TEXT_LISTENER_TYPE: break; case TOGGLE_FULLSCREEN_LISTENER_TYPE: break; case WEB_VIEW_MINIMIZE_LISTENER_TYPE: break; case KPLAYER_EVENT_LISTENER_TYPE: break; case DURATION_CHANGED_LISTENER_TYPE: mPlayer.registerDurationChanged(shouldRegister ? this : null); } } }
playerSDK/src/main/java/com/kaltura/playersdk/players/HLSPlayer.java
package com.kaltura.playersdk.players; import android.app.Activity; import android.util.Log; import android.view.Gravity; import com.kaltura.hlsplayersdk.HLSPlayerViewController; import com.kaltura.hlsplayersdk.events.OnDurationChangedListener; import com.kaltura.hlsplayersdk.types.PlayerStates; import com.kaltura.playersdk.AlternateAudioTracksInterface; import com.kaltura.playersdk.LiveStreamInterface; import com.kaltura.playersdk.QualityTrack; import com.kaltura.playersdk.QualityTracksInterface; import com.kaltura.playersdk.TextTracksInterface; import com.kaltura.playersdk.events.Listener; import com.kaltura.playersdk.types.TrackType; import java.util.ArrayList; import java.util.List; public class HLSPlayer extends BasePlayerView implements TextTracksInterface, AlternateAudioTracksInterface, QualityTracksInterface, com.kaltura.hlsplayersdk.events.OnPlayheadUpdateListener, com.kaltura.hlsplayersdk.events.OnErrorListener, com.kaltura.hlsplayersdk.events.OnPlayerStateChangeListener, com.kaltura.hlsplayersdk.events.OnProgressListener, com.kaltura.hlsplayersdk.events.OnAudioTracksListListener, com.kaltura.hlsplayersdk.events.OnAudioTrackSwitchingListener, com.kaltura.hlsplayersdk.events.OnQualityTracksListListener, com.kaltura.hlsplayersdk.events.OnQualitySwitchingListener, OnDurationChangedListener, LiveStreamInterface { private static final String TAG = HLSPlayer.class.getSimpleName(); private HLSPlayerViewController mPlayer; public HLSPlayer(Activity activity) { super(activity); mPlayer = new HLSPlayerViewController(activity); LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, Gravity.CENTER); this.addView(mPlayer, lp); mPlayer.initialize(); } public void close(){ mPlayer.close(); mPlayer = null; } @Override public String getVideoUrl() { return mPlayer.getVideoUrl(); } @Override public void setVideoUrl(String url) { if ( mPlayer.getVideoUrl() == null || !url.equals(mPlayer.getVideoUrl())) { mPlayer.setVideoUrl(url); } } @Override public int getDuration() { return mPlayer.getDuration() - 1; } @Override public void play() { mPlayer.play(); } @Override public void pause() { mPlayer.pause(); } @Override public void stop() { mPlayer.stop(); } @Override public void seek(int msec) { mPlayer.seek(msec); } @Override public boolean isPlaying() { return mPlayer.isPlaying(); } @Override public boolean canPause() { return mPlayer != null; } @Override public void setStartingPoint(int point) { mPlayer.setStartingPoint(point); } @Override public void release() { mPlayer.release(); } @Override public void recoverRelease() { mPlayer.recoverRelease(); } @Override public void setBufferTime(int newTime) { mPlayer.setBufferTime(newTime); } @Override public void switchQualityTrack(int newIndex) { mPlayer.switchQualityTrack(newIndex); } @Override public void setAutoSwitch(boolean autoSwitch) { mPlayer.setAutoSwitch(autoSwitch); } @Override public float getLastDownloadTransferRate() { return mPlayer.getLastDownloadTransferRate(); } @Override public float getDroppedFramesPerSecond() { return mPlayer.getDroppedFramesPerSecond(); } @Override public float getBufferPercentage() { return mPlayer.getBufferPercentage(); } @Override public int getCurrentQualityIndex() { return mPlayer.getCurrentQualityIndex(); } @Override public void hardSwitchAudioTrack(int newAudioIndex) { mPlayer.hardSwitchAudioTrack(newAudioIndex); } @Override public void softSwitchAudioTrack(int newAudioIndex) { mPlayer.softSwitchAudioTrack(newAudioIndex); } @Override public void switchTextTrack(int newIndex) { mPlayer.switchTextTrack(newIndex); } @Override public void switchToLive() { mPlayer.goToLive(); } ///////////////////////////////////////////////////////// // // HlsPlayerSDK Listeners // //////////////////////////////////////////////////////// @Override public boolean onStateChanged(PlayerStates state) { com.kaltura.playersdk.types.PlayerStates kState; switch (state) { case START: kState = com.kaltura.playersdk.types.PlayerStates.START; break; case LOAD: kState = com.kaltura.playersdk.types.PlayerStates.LOAD; break; case PLAY: kState = com.kaltura.playersdk.types.PlayerStates.PLAY; break; case PAUSE: kState = com.kaltura.playersdk.types.PlayerStates.PAUSE; break; case END: kState = com.kaltura.playersdk.types.PlayerStates.END; break; case SEEKING: kState = com.kaltura.playersdk.types.PlayerStates.SEEKING; break; case SEEKED: kState = com.kaltura.playersdk.types.PlayerStates.SEEKED; break; default: kState = com.kaltura.playersdk.types.PlayerStates.START; } mListenerExecutor.executeOnStateChanged(kState); return false; } @Override public void onPlayheadUpdated(int msec) { mListenerExecutor.executeOnPlayheadUpdated(msec); } @Override public void onProgressUpdate(int progress) { mListenerExecutor.executeOnProgressUpdate(progress); } @Override public void OnQualityTracksList(List<com.kaltura.hlsplayersdk.QualityTrack> list, int defaultTrackIndex) { List<QualityTrack> newList = new ArrayList<QualityTrack>(); for ( int i=0; i < list.size(); i++ ) { com.kaltura.hlsplayersdk.QualityTrack currentTrack = list.get(i); QualityTrack newTrack = new QualityTrack(); newTrack.bitrate = currentTrack.bitrate; newTrack.height = currentTrack.height; newTrack.width = currentTrack.width; newTrack.trackId = currentTrack.trackId; newTrack.type = currentTrack.type == com.kaltura.hlsplayersdk.types.TrackType.VIDEO ? TrackType.VIDEO: TrackType.AUDIO; newList.add(newTrack); } mListenerExecutor.executeOnQualityTracksList(newList,defaultTrackIndex); } @Override public void onError(int errorCode, String errorMessage) { Log.e(TAG, "HLS Error Occurred - error code: " + errorCode + " " + "msg: " + errorMessage); } @Override public void onFatalError(int errorCode, String errorMessage) { mListenerExecutor.executeOnError(errorCode,errorMessage); } @Override protected List<Listener.EventType> getCompatibleListenersList() { List<Listener.EventType> list = super.getCompatibleListenersList(); list.add(Listener.EventType.AUDIO_TRACK_SWITCH_LISTENER_TYPE); list.add(Listener.EventType.AUDIO_TRACKS_LIST_LISTENER_TYPE); list.add(Listener.EventType.QUALITY_SWITCHING_LISTENER_TYPE); list.add(Listener.EventType.QUALITY_TRACKS_LIST_LISTENER_TYPE); list.add(Listener.EventType.DURATION_CHANGED_LISTENER_TYPE); return list; } @Override public void removeListener(Listener.EventType eventType) { super.removeListener(eventType); registerHLSListener(eventType, false); } @Override public void registerListener(Listener listener){ super.registerListener(listener); if (listener != null) { registerHLSListener(listener.getEventType(), true); } } // TODO: discuss this issue with dp so they will change their player listeners scheme private void registerHLSListener(Listener.EventType eventType, boolean shouldRegister){ switch(eventType){ case JS_CALLBACK_READY_LISTENER_TYPE: break; case AUDIO_TRACKS_LIST_LISTENER_TYPE: mPlayer.registerAudioTracksList(shouldRegister ? this : null); break; case AUDIO_TRACK_SWITCH_LISTENER_TYPE: mPlayer.registerAudioSwitchingChange(shouldRegister ? this : null); break; case CAST_DEVICE_CHANGE_LISTENER_TYPE: break; case CAST_ROUTE_DETECTED_LISTENER_TYPE: break; case ERROR_LISTENER_TYPE: mPlayer.registerError(shouldRegister ? this : null); break; case PLAYER_STATE_CHANGE_LISTENER_TYPE: mPlayer.registerPlayerStateChange(shouldRegister ? this : null); break; case PLAYHEAD_UPDATE_LISTENER_TYPE: mPlayer.registerPlayheadUpdate(shouldRegister ? this : null); break; case PROGRESS_UPDATE_LISTENER_TYPE: mPlayer.registerProgressUpdate(shouldRegister ? this : null); break; case QUALITY_SWITCHING_LISTENER_TYPE: mPlayer.registerQualitySwitchingChange(shouldRegister ? this : null); break; case QUALITY_TRACKS_LIST_LISTENER_TYPE: mPlayer.registerQualityTracksList(shouldRegister ? this : null); break; case TEXT_TRACK_CHANGE_LISTENER_TYPE: break; case TEXT_TRACK_LIST_LISTENER_TYPE: break; case TEXT_TRACK_TEXT_LISTENER_TYPE: break; case TOGGLE_FULLSCREEN_LISTENER_TYPE: break; case WEB_VIEW_MINIMIZE_LISTENER_TYPE: break; case KPLAYER_EVENT_LISTENER_TYPE: break; case DURATION_CHANGED_LISTENER_TYPE: mPlayer.registerDurationChanged(shouldRegister ? this : null); } } @Override public void onAudioSwitchingStart(int oldTrackIndex, int newTrackIndex) { mListenerExecutor.executeOnAudioSwitchingStart(oldTrackIndex, newTrackIndex); } @Override public void onAudioSwitchingEnd(int newTrackIndex) { mListenerExecutor.executeonAudioSwitchingEnd(newTrackIndex); } @Override public void OnAudioTracksList(List<String> list, int defaultTrackIndex) { mListenerExecutor.executeOnAudioTracksList(list,defaultTrackIndex); } @Override public void onQualitySwitchingStart(int oldTrackIndex, int newTrackIndex) { } @Override public void onQualitySwitchingEnd(int newTrackIndex) { } @Override public void onDurationChanged(int msec) { mListenerExecutor.executeOnDurationChanged(msec); } }
minor
playerSDK/src/main/java/com/kaltura/playersdk/players/HLSPlayer.java
minor
<ide><path>layerSDK/src/main/java/com/kaltura/playersdk/players/HLSPlayer.java <ide> } <ide> <ide> @Override <add> public void onAudioSwitchingStart(int oldTrackIndex, int newTrackIndex) { <add> mListenerExecutor.executeOnAudioSwitchingStart(oldTrackIndex, newTrackIndex); <add> } <add> <add> @Override <add> public void onAudioSwitchingEnd(int newTrackIndex) { <add> mListenerExecutor.executeonAudioSwitchingEnd(newTrackIndex); <add> } <add> <add> @Override <add> public void OnAudioTracksList(List<String> list, int defaultTrackIndex) { <add> mListenerExecutor.executeOnAudioTracksList(list,defaultTrackIndex); <add> } <add> <add> @Override <add> public void onQualitySwitchingStart(int oldTrackIndex, int newTrackIndex) { <add> <add> } <add> <add> @Override <add> public void onQualitySwitchingEnd(int newTrackIndex) { <add> <add> } <add> <add> @Override <add> public void onDurationChanged(int msec) { <add> mListenerExecutor.executeOnDurationChanged(msec); <add> } <add> <add> @Override <ide> protected List<Listener.EventType> getCompatibleListenersList() { <ide> List<Listener.EventType> list = super.getCompatibleListenersList(); <ide> list.add(Listener.EventType.AUDIO_TRACK_SWITCH_LISTENER_TYPE); <ide> mPlayer.registerDurationChanged(shouldRegister ? this : null); <ide> } <ide> } <del> <del> <del> @Override <del> public void onAudioSwitchingStart(int oldTrackIndex, int newTrackIndex) { <del> mListenerExecutor.executeOnAudioSwitchingStart(oldTrackIndex, newTrackIndex); <del> } <del> <del> @Override <del> public void onAudioSwitchingEnd(int newTrackIndex) { <del> mListenerExecutor.executeonAudioSwitchingEnd(newTrackIndex); <del> } <del> <del> @Override <del> public void OnAudioTracksList(List<String> list, int defaultTrackIndex) { <del> mListenerExecutor.executeOnAudioTracksList(list,defaultTrackIndex); <del> } <del> <del> @Override <del> public void onQualitySwitchingStart(int oldTrackIndex, int newTrackIndex) { <del> <del> } <del> <del> @Override <del> public void onQualitySwitchingEnd(int newTrackIndex) { <del> <del> } <del> <del> @Override <del> public void onDurationChanged(int msec) { <del> mListenerExecutor.executeOnDurationChanged(msec); <del> } <del> <del> <ide> }
JavaScript
unlicense
a5363f0c4e8379c464147001517e82cf655447c7
0
twolfson/react-playground
// Load in our dependencies import {expect} from 'chai'; import * as httpUtils from '../utils/http'; // Define our tests describe('A GraphQL query request for `echo` via arguments', function () { httpUtils.graphql({ body: ` query { echo(content: "hi") } `, expectedStatusCode: 200 }); it('reuses input as output', function () { expect(this.json).to.deep.equal({data: {echo: 'hi'}}); }); }); describe.only('A GraphQL query request for `echo` via variables', function () { httpUtils.graphql({ body: JSON.stringify({ query: ` query ($content: String) { echo(content: $content) } `, variables: { content: 'hi' } }), expectedStatusCode: 200 }); it('reuses input as output', function () { console.log('wat', this.json); expect(this.json).to.deep.equal({data: {echo: 'hi'}}); }); });
test/server/graphql/query-echo.js
// Load in our dependencies import {expect} from 'chai'; import * as httpUtils from '../utils/http'; // Define our tests describe('A GraphQL query request for `echo`', function () { httpUtils.graphql({ body: ` query { echo(content: "hi") } `, expectedStatusCode: 200 }); it('reuses input as output', function () { expect(this.json).to.deep.equal({data: {echo: 'hi'}}); }); });
Attempting to get variables working with GraphQL
test/server/graphql/query-echo.js
Attempting to get variables working with GraphQL
<ide><path>est/server/graphql/query-echo.js <ide> import * as httpUtils from '../utils/http'; <ide> <ide> // Define our tests <del>describe('A GraphQL query request for `echo`', function () { <add>describe('A GraphQL query request for `echo` via arguments', function () { <ide> httpUtils.graphql({ <ide> body: ` <ide> query { <ide> expect(this.json).to.deep.equal({data: {echo: 'hi'}}); <ide> }); <ide> }); <add> <add>describe.only('A GraphQL query request for `echo` via variables', function () { <add> httpUtils.graphql({ <add> body: JSON.stringify({ <add> query: ` <add> query ($content: String) { <add> echo(content: $content) <add> } <add> `, <add> variables: { <add> content: 'hi' <add> } <add> }), <add> expectedStatusCode: 200 <add> }); <add> <add> it('reuses input as output', function () { <add> console.log('wat', this.json); <add> expect(this.json).to.deep.equal({data: {echo: 'hi'}}); <add> }); <add>});
Java
apache-2.0
0bdf4a86e7ce404cd21876911353e0b03b64b80f
0
Amutheezan/product-das,nirandaperera/product-bam,keizer619/product-bam,nirandaperera/product-bam,Amutheezan/product-das,madusankapremaratne/product-das,madusankapremaratne/product-das,nirmal070125/product-bam,liurl3/product-bam,thiliA/product-das,wso2/product-bam,nirandaperera/product-bam,nirmal070125/product-bam,wso2/product-das,liurl3/product-bam,sajithshn/product-das,mohanvive/product-das,wso2/product-das,wso2/product-bam,wso2/product-bam,thiliA/product-das,swsachith/product-bam,Amutheezan/product-das,thiliA/product-das,sajithshn/product-das,wso2/product-das,wso2/product-das,sajithshn/product-das,madusankapremaratne/product-das,mohanvive/product-das,keizer619/product-bam,swsachith/product-bam,nirmal070125/product-bam,wso2/product-bam,liurl3/product-bam,swsachith/product-bam,swsachith/product-bam,liurl3/product-bam,nirandaperera/product-bam,nirandaperera/product-bam,keizer619/product-bam,madusankapremaratne/product-das,keizer619/product-bam,nirmal070125/product-bam,Amutheezan/product-das,thiliA/product-das,wso2/product-bam,mohanvive/product-das,mohanvive/product-das,swsachith/product-bam,madusankapremaratne/product-das,nirmal070125/product-bam,sajithshn/product-das,liurl3/product-bam
/* * 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. */ package org.wso2.das.integration.tests.messageconsole; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.analytics.messageconsole.stub.beans.PermissionBean; import org.wso2.carbon.analytics.messageconsole.stub.beans.ScheduleTaskInfo; import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable; import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord; import org.wso2.carbon.analytics.webservice.stub.beans.StreamDefAttributeBean; import org.wso2.carbon.analytics.webservice.stub.beans.StreamDefinitionBean; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import org.wso2.carbon.automation.test.utils.common.FileManager; import org.wso2.carbon.databridge.commons.Event; import org.wso2.das.integration.common.clients.AnalyticsWebServiceClient; import org.wso2.das.integration.common.clients.DataPublisherClient; import org.wso2.das.integration.common.clients.EventStreamPersistenceClient; import org.wso2.das.integration.common.clients.MessageConsoleClient; import org.wso2.das.integration.common.utils.DASIntegrationTest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MessageConsoleTestCase extends DASIntegrationTest { private static final String TABLE1 = "integration.test.messageconsole.table1"; private static final String STREAM_VERSION_1 = "1.0.0"; private MessageConsoleClient messageConsoleClient; private AnalyticsWebServiceClient webServiceClient; private EventStreamPersistenceClient persistenceClient; @BeforeClass(alwaysRun = true) protected void init() throws Exception { super.init(); String session = getSessionCookie(); messageConsoleClient = new MessageConsoleClient(backendURL, session); webServiceClient = new AnalyticsWebServiceClient(backendURL, session); persistenceClient = new EventStreamPersistenceClient(backendURL, session); } @AfterClass(alwaysRun = true) public void cleanup() throws Exception { messageConsoleClient.scheduleDataPurgingTask(TABLE1.replace('.', '_'), null, 0); } @Test(groups = "wso2.das", description = "Adding script with task") public void scheduleTask() throws Exception { StreamDefinitionBean streamDefTable1Version1 = getEventStreamBeanTable1Version1(); webServiceClient.addStreamDefinition(streamDefTable1Version1); AnalyticsTable table1Version1 = getAnalyticsTable1Version1(); persistenceClient.addAnalyticsTable(table1Version1); deployEventReceivers(); Thread.sleep(15000); List<Event> events = new ArrayList<>(100); for (int i = 0; i < 100; i++) { Event event = new Event(null, System.currentTimeMillis(), new Object[0], new Object[0], new Object[]{(long) i, String.valueOf(i)}); events.add(event); } publishEvents(events); int timer = 0; while (true) { long count = webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis() + 1L); if (timer == 30 || count == 100) { break; } else { Thread.sleep(2000L); timer++; } } Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis() + 1L), 100, "Record count is invalid"); messageConsoleClient.scheduleDataPurgingTask(TABLE1.replace('.', '_'), "30 * * * * ?", -1); Thread.sleep(90000); Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis()), 0, "Record count is invalid"); } @Test(groups = "wso2.das", description = "Get purging task information", dependsOnMethods = "scheduleTask") public void getDataPurgingDetails() throws Exception { ScheduleTaskInfo dataPurgingDetails = messageConsoleClient.getDataPurgingDetails(TABLE1.replace('.', '_')); Assert.assertEquals(dataPurgingDetails.getCronString(), "30 * * * * ?", "Cron expression wrong"); Assert.assertEquals(dataPurgingDetails.getRetentionPeriod(), -1, "Retention period is wrong"); } @Test(groups = "wso2.das", description = "Test permissions", dependsOnMethods = "getDataPurgingDetails") public void getAvailablePermissions() throws Exception { PermissionBean permissions = messageConsoleClient.getAvailablePermissions(); Assert.assertTrue(permissions.getListRecord(), "Returning invalid result."); Assert.assertTrue(permissions.getListTable(), "Returning invalid result."); Assert.assertTrue(permissions.getDeleteRecord(), "Returning invalid result."); Assert.assertTrue(permissions.getSearchRecord(), "Returning invalid result."); System.out.println("permissions.toString() = " + permissions.toString()); } private void publishEvents(List<Event> events) throws Exception { DataPublisherClient dataPublisherClient = new DataPublisherClient(); dataPublisherClient.publish(TABLE1, STREAM_VERSION_1, events); Thread.sleep(10000); dataPublisherClient.shutdown(); } private StreamDefinitionBean getEventStreamBeanTable1Version1() { StreamDefinitionBean definitionBean = new StreamDefinitionBean(); definitionBean.setName(TABLE1); definitionBean.setVersion(STREAM_VERSION_1); StreamDefAttributeBean[] attributeBeans = new StreamDefAttributeBean[2]; StreamDefAttributeBean uuid = new StreamDefAttributeBean(); uuid.setName("uuid"); uuid.setType("LONG"); attributeBeans[0] = uuid; StreamDefAttributeBean name = new StreamDefAttributeBean(); name.setName("name"); name.setType("STRING"); attributeBeans[1] = name; definitionBean.setPayloadData(attributeBeans); return definitionBean; } private AnalyticsTable getAnalyticsTable1Version1() { AnalyticsTable table = new AnalyticsTable(); table.setPersist(true); table.setTableName(TABLE1); table.setStreamVersion(STREAM_VERSION_1); AnalyticsTableRecord[] records = new AnalyticsTableRecord[2]; AnalyticsTableRecord uuid = new AnalyticsTableRecord(); uuid.setPersist(true); uuid.setPrimaryKey(true); uuid.setIndexed(true); uuid.setColumnName("uuid"); uuid.setColumnType("LONG"); uuid.setScoreParam(false); records[0] = uuid; AnalyticsTableRecord name = new AnalyticsTableRecord(); name.setPersist(true); name.setPrimaryKey(false); name.setIndexed(false); name.setColumnName("name"); name.setColumnType("STRING"); name.setScoreParam(false); records[1] = name; table.setAnalyticsTableRecords(records); return table; } private void deployEventReceivers() throws IOException { String streamResourceDir = FrameworkPathUtil.getSystemResourceLocation() + "messageconsole" + File.separator; String streamsLocation = FrameworkPathUtil.getCarbonHome() + File.separator + "repository" + File.separator + "deployment" + File.separator + "server" + File.separator + "eventreceivers" + File.separator; FileManager.copyResourceToFileSystem(streamResourceDir + "messageconsole.table1.xml", streamsLocation, "messageconsole.table1.xml"); } }
modules/integration/tests-integration/src/test/java/org/wso2/das/integration/tests/messageconsole/MessageConsoleTestCase.java
/* * 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. */ package org.wso2.das.integration.tests.messageconsole; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.wso2.carbon.analytics.messageconsole.stub.beans.PermissionBean; import org.wso2.carbon.analytics.messageconsole.stub.beans.ScheduleTaskInfo; import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTable; import org.wso2.carbon.analytics.stream.persistence.stub.dto.AnalyticsTableRecord; import org.wso2.carbon.analytics.webservice.stub.beans.StreamDefAttributeBean; import org.wso2.carbon.analytics.webservice.stub.beans.StreamDefinitionBean; import org.wso2.carbon.automation.engine.frameworkutils.FrameworkPathUtil; import org.wso2.carbon.automation.test.utils.common.FileManager; import org.wso2.carbon.databridge.commons.Event; import org.wso2.das.integration.common.clients.AnalyticsWebServiceClient; import org.wso2.das.integration.common.clients.DataPublisherClient; import org.wso2.das.integration.common.clients.EventStreamPersistenceClient; import org.wso2.das.integration.common.clients.MessageConsoleClient; import org.wso2.das.integration.common.utils.DASIntegrationTest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class MessageConsoleTestCase extends DASIntegrationTest { private static final String TABLE1 = "integration.test.messageconsole.table1"; private static final String STREAM_VERSION_1 = "1.0.0"; private MessageConsoleClient messageConsoleClient; private AnalyticsWebServiceClient webServiceClient; private EventStreamPersistenceClient persistenceClient; @BeforeClass(alwaysRun = true) protected void init() throws Exception { super.init(); String session = getSessionCookie(); messageConsoleClient = new MessageConsoleClient(backendURL, session); webServiceClient = new AnalyticsWebServiceClient(backendURL, session); persistenceClient = new EventStreamPersistenceClient(backendURL, session); } @AfterClass(alwaysRun = true) public void cleanup() throws Exception { messageConsoleClient.scheduleDataPurgingTask(TABLE1.replace('.', '_'), null, 0); } @Test(groups = "wso2.das", description = "Adding script with task") public void scheduleTask() throws Exception { StreamDefinitionBean streamDefTable1Version1 = getEventStreamBeanTable1Version1(); webServiceClient.addStreamDefinition(streamDefTable1Version1); AnalyticsTable table1Version1 = getAnalyticsTable1Version1(); persistenceClient.addAnalyticsTable(table1Version1); deployEventReceivers(); Thread.sleep(15000); List<Event> events = new ArrayList<>(100); for (int i = 0; i < 100; i++) { Event event = new Event(null, System.currentTimeMillis()-100000L, new Object[0], new Object[0], new Object[]{(long) i, String.valueOf(i)}); events.add(event); } publishEvents(events); Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis()), 100, "Record count is invalid"); messageConsoleClient.scheduleDataPurgingTask(TABLE1.replace('.', '_'), "30 * * * * ?", -1); Thread.sleep(90000); Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis()), 0, "Record count is invalid"); } @Test(groups = "wso2.das", description = "Get purging task information", dependsOnMethods = "scheduleTask") public void getDataPurgingDetails() throws Exception { ScheduleTaskInfo dataPurgingDetails = messageConsoleClient.getDataPurgingDetails(TABLE1.replace('.', '_')); Assert.assertEquals(dataPurgingDetails.getCronString(), "30 * * * * ?", "Cron expression wrong"); Assert.assertEquals(dataPurgingDetails.getRetentionPeriod(), -1, "Retention period is wrong"); } @Test(groups = "wso2.das", description = "Test permissions", dependsOnMethods = "getDataPurgingDetails") public void getAvailablePermissions() throws Exception { PermissionBean permissions = messageConsoleClient.getAvailablePermissions(); Assert.assertTrue(permissions.getListRecord(), "Returning invalid result."); Assert.assertTrue(permissions.getListTable(), "Returning invalid result."); Assert.assertTrue(permissions.getDeleteRecord(), "Returning invalid result."); Assert.assertTrue(permissions.getSearchRecord(), "Returning invalid result."); System.out.println("permissions.toString() = " + permissions.toString()); } private void publishEvents(List<Event> events) throws Exception { DataPublisherClient dataPublisherClient = new DataPublisherClient(); dataPublisherClient.publish(TABLE1, STREAM_VERSION_1, events); Thread.sleep(10000); dataPublisherClient.shutdown(); } private StreamDefinitionBean getEventStreamBeanTable1Version1() { StreamDefinitionBean definitionBean = new StreamDefinitionBean(); definitionBean.setName(TABLE1); definitionBean.setVersion(STREAM_VERSION_1); StreamDefAttributeBean[] attributeBeans = new StreamDefAttributeBean[2]; StreamDefAttributeBean uuid = new StreamDefAttributeBean(); uuid.setName("uuid"); uuid.setType("LONG"); attributeBeans[0] = uuid; StreamDefAttributeBean name = new StreamDefAttributeBean(); name.setName("name"); name.setType("STRING"); attributeBeans[1] = name; definitionBean.setPayloadData(attributeBeans); return definitionBean; } private AnalyticsTable getAnalyticsTable1Version1() { AnalyticsTable table = new AnalyticsTable(); table.setPersist(true); table.setTableName(TABLE1); table.setStreamVersion(STREAM_VERSION_1); AnalyticsTableRecord[] records = new AnalyticsTableRecord[2]; AnalyticsTableRecord uuid = new AnalyticsTableRecord(); uuid.setPersist(true); uuid.setPrimaryKey(true); uuid.setIndexed(true); uuid.setColumnName("uuid"); uuid.setColumnType("LONG"); uuid.setScoreParam(false); records[0] = uuid; AnalyticsTableRecord name = new AnalyticsTableRecord(); name.setPersist(true); name.setPrimaryKey(false); name.setIndexed(false); name.setColumnName("name"); name.setColumnType("STRING"); name.setScoreParam(false); records[1] = name; table.setAnalyticsTableRecords(records); return table; } private void deployEventReceivers() throws IOException { String streamResourceDir = FrameworkPathUtil.getSystemResourceLocation() + "messageconsole" + File.separator; String streamsLocation = FrameworkPathUtil.getCarbonHome() + File.separator + "repository" + File.separator + "deployment" + File.separator + "server" + File.separator + "eventreceivers" + File.separator; FileManager.copyResourceToFileSystem(streamResourceDir + "messageconsole.table1.xml", streamsLocation, "messageconsole.table1.xml"); } }
Fixing intermittent integration test failure on builder
modules/integration/tests-integration/src/test/java/org/wso2/das/integration/tests/messageconsole/MessageConsoleTestCase.java
Fixing intermittent integration test failure on builder
<ide><path>odules/integration/tests-integration/src/test/java/org/wso2/das/integration/tests/messageconsole/MessageConsoleTestCase.java <ide> Thread.sleep(15000); <ide> List<Event> events = new ArrayList<>(100); <ide> for (int i = 0; i < 100; i++) { <del> Event event = new Event(null, System.currentTimeMillis()-100000L, <del> new Object[0], new Object[0], new Object[]{(long) i, String.valueOf(i)}); <add> Event event = new Event(null, System.currentTimeMillis(), <add> new Object[0], new Object[0], new Object[]{(long) i, String.valueOf(i)}); <ide> events.add(event); <ide> } <ide> publishEvents(events); <del> Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis()), <del> 100, "Record count is invalid"); <add> <add> int timer = 0; <add> while (true) { <add> long count = webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis() + 1L); <add> if (timer == 30 || count == 100) { <add> break; <add> } else { <add> Thread.sleep(2000L); <add> timer++; <add> } <add> } <add> Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis() + 1L), <add> 100, "Record count is invalid"); <ide> messageConsoleClient.scheduleDataPurgingTask(TABLE1.replace('.', '_'), "30 * * * * ?", -1); <ide> Thread.sleep(90000); <ide> Assert.assertEquals(webServiceClient.getRecordCount(TABLE1.replace('.', '_'), 0, System.currentTimeMillis()), <del> 0, "Record count is invalid"); <add> 0, "Record count is invalid"); <ide> } <ide> <ide> @Test(groups = "wso2.das", description = "Get purging task information", dependsOnMethods = "scheduleTask") <ide> private void deployEventReceivers() throws IOException { <ide> String streamResourceDir = FrameworkPathUtil.getSystemResourceLocation() + "messageconsole" + File.separator; <ide> String streamsLocation = FrameworkPathUtil.getCarbonHome() + File.separator + "repository" <del> + File.separator + "deployment" + File.separator + "server" + File.separator + "eventreceivers" + File.separator; <add> + File.separator + "deployment" + File.separator + "server" + File.separator + "eventreceivers" + File.separator; <ide> FileManager.copyResourceToFileSystem(streamResourceDir + "messageconsole.table1.xml", streamsLocation, "messageconsole.table1.xml"); <ide> } <ide> }
Java
mpl-2.0
bb818e8cb875e64675628a1af8ecd5bb56f46be8
0
GreenDelta/olca-modules,GreenDelta/olca-modules,GreenDelta/olca-modules
package org.openlca.core.matrix.cache; import java.util.List; import org.openlca.core.database.IDatabase; import org.openlca.core.matrix.CalcAllocationFactor; import org.openlca.core.matrix.CalcCostEntry; import org.openlca.core.matrix.CalcExchange; import org.openlca.core.matrix.CalcImpactFactor; import com.google.common.cache.LoadingCache; public final class MatrixCache { private IDatabase database; private FlowTypeTable flowTypeTable; private ConversionTable conversionTable; private ProcessTable processTable; private LoadingCache<Long, List<CalcAllocationFactor>> allocationCache; private LoadingCache<Long, List<CalcImpactFactor>> impactCache; private LoadingCache<Long, List<CalcExchange>> exchangeCache; private LoadingCache<Long, List<CalcCostEntry>> costCache; public static MatrixCache create(IDatabase database) { return new MatrixCache(database); } private MatrixCache(IDatabase database) { this.database = database; flowTypeTable = FlowTypeTable.create(database); conversionTable = ConversionTable.create(database); processTable = ProcessTable.create(database); exchangeCache = ExchangeCache.create(database, conversionTable, flowTypeTable); allocationCache = AllocationCache.create(database); impactCache = ImpactFactorCache.create(database, conversionTable); costCache = CostEntryCache.create(database); } public void evictAll() { flowTypeTable.reload(); conversionTable.reload(); processTable.reload(); exchangeCache.invalidateAll(); allocationCache.invalidateAll(); impactCache.invalidateAll(); costCache.invalidateAll(); } /** * Drops the vectors for the process with the given ID from the cache. */ public void evictProcess(Long id) { if (id == null) return; processTable.reload(); exchangeCache.invalidate(id); allocationCache.invalidate(id); costCache.invalidate(id); } public IDatabase getDatabase() { return database; } public ProcessTable getProcessTable() { return processTable; } public LoadingCache<Long, List<CalcAllocationFactor>> getAllocationCache() { return allocationCache; } public LoadingCache<Long, List<CalcImpactFactor>> getImpactCache() { return impactCache; } public LoadingCache<Long, List<CalcExchange>> getExchangeCache() { return exchangeCache; } public LoadingCache<Long, List<CalcCostEntry>> getCostCache() { return costCache; } }
olca-core/src/main/java/org/openlca/core/matrix/cache/MatrixCache.java
package org.openlca.core.matrix.cache; import java.util.List; import org.openlca.core.database.IDatabase; import org.openlca.core.matrix.CalcAllocationFactor; import org.openlca.core.matrix.CalcCostEntry; import org.openlca.core.matrix.CalcExchange; import org.openlca.core.matrix.CalcImpactFactor; import com.google.common.cache.LoadingCache; public final class MatrixCache { private IDatabase database; private FlowTypeTable flowTypeTable; private ConversionTable conversionTable; private ProcessTable processTable; private LoadingCache<Long, List<CalcAllocationFactor>> allocationCache; private LoadingCache<Long, List<CalcImpactFactor>> impactCache; private LoadingCache<Long, List<CalcExchange>> exchangeCache; private LoadingCache<Long, List<CalcCostEntry>> costCache; public static MatrixCache create(IDatabase database) { return new MatrixCache(database); } private MatrixCache(IDatabase database) { this.database = database; flowTypeTable = FlowTypeTable.create(database); conversionTable = ConversionTable.create(database); processTable = ProcessTable.create(database); exchangeCache = ExchangeCache.create(database, conversionTable, flowTypeTable); allocationCache = AllocationCache.create(database); impactCache = ImpactFactorCache.create(database, conversionTable); costCache = CostEntryCache.create(database); } public IDatabase getDatabase() { return database; } public ProcessTable getProcessTable() { return processTable; } public LoadingCache<Long, List<CalcAllocationFactor>> getAllocationCache() { return allocationCache; } public LoadingCache<Long, List<CalcImpactFactor>> getImpactCache() { return impactCache; } public LoadingCache<Long, List<CalcExchange>> getExchangeCache() { return exchangeCache; } public LoadingCache<Long, List<CalcCostEntry>> getCostCache() { return costCache; } }
added 'evict' functions to matrix cache
olca-core/src/main/java/org/openlca/core/matrix/cache/MatrixCache.java
added 'evict' functions to matrix cache
<ide><path>lca-core/src/main/java/org/openlca/core/matrix/cache/MatrixCache.java <ide> costCache = CostEntryCache.create(database); <ide> } <ide> <add> public void evictAll() { <add> flowTypeTable.reload(); <add> conversionTable.reload(); <add> processTable.reload(); <add> exchangeCache.invalidateAll(); <add> allocationCache.invalidateAll(); <add> impactCache.invalidateAll(); <add> costCache.invalidateAll(); <add> } <add> <add> /** <add> * Drops the vectors for the process with the given ID from the cache. <add> */ <add> public void evictProcess(Long id) { <add> if (id == null) <add> return; <add> processTable.reload(); <add> exchangeCache.invalidate(id); <add> allocationCache.invalidate(id); <add> costCache.invalidate(id); <add> } <add> <ide> public IDatabase getDatabase() { <ide> return database; <ide> }
JavaScript
mit
f75daea693a582dc4066bdad6d7a1847ea672912
0
camsjams/puremvc-js-util-statemachine-demo-locks
/** * @author Cameron Manavian * * @class ViewEvents */ puremvc.define({ name: 'lockApp.view.event.ViewEvents' }, {}, // INSTANCE MEMBERS { // Add event listener using jQuery.bind() addEventListener: function (object, eventName, listener) { object.bind(eventName, {self: listener}, listener.handleEvent); }, // Dispatch event using jQuery.trigger() dispatchEvent: function (object, eventName, data) { object.trigger(eventName, data); } });
js/view/events/ViewEvents.js
/** * @author Cameron Manavian * * @class ViewEvents */ puremvc.define({ name: 'lockApp.view.event.ViewEvents' }, {}, // INSTANCE MEMBERS { // Add event listener addEventListener: function (object, eventName, listener) { object.bind(eventName, {self: listener}, listener.handleEvent); }, // Dispatch event dispatchEvent: function (object, eventName, data) { object.trigger(eventName, data); }, });
Update ViewEvents.js fixed comments and removed trailing comma
js/view/events/ViewEvents.js
Update ViewEvents.js
<ide><path>s/view/events/ViewEvents.js <ide> // INSTANCE MEMBERS <ide> { <ide> <del> // Add event listener <add>// Add event listener using jQuery.bind() <ide> addEventListener: function (object, eventName, listener) { <ide> object.bind(eventName, {self: listener}, listener.handleEvent); <ide> }, <ide> <del> // Dispatch event <add> // Dispatch event using jQuery.trigger() <ide> dispatchEvent: function (object, eventName, data) { <ide> object.trigger(eventName, data); <del> }, <add> } <ide> });
Java
apache-2.0
f4d1591a2c3165605c73dbabddbeb7b3f19cdafd
0
HaStr/kieker,leadwire-apm/leadwire-javaagent,HaStr/kieker,HaStr/kieker,HaStr/kieker,kieker-monitoring/kieker,kieker-monitoring/kieker,HaStr/kieker,kieker-monitoring/kieker,leadwire-apm/leadwire-javaagent,kieker-monitoring/kieker,kieker-monitoring/kieker
/*************************************************************************** * Copyright 2013 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.common.logging; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Queue; import java.util.TimeZone; import java.util.concurrent.ArrayBlockingQueue; /** * This is a simple logger for the Kieker WebGUI. It stores the log messages within a buffer of a static size. If the buffer is full, the oldest entry will be * removed for new entries. As the entries have to be accessible from outside, the queues are stored statically. * * @author Jan Waller, Nils Christian Ehmke * * @since 1.6 */ public final class LogImplWebguiLogging implements Log { private static final int MAX_ENTRIES = 100; private static final Map<String, Queue<String>> QUEUES = new HashMap<String, Queue<String>>(); // NOPMD (sync needed) private final DateFormat date; private final String name; /** * Creates a new instance of this class. * * @param name * The name of the logger. */ protected LogImplWebguiLogging(final String name) { this.name = name; this.date = new SimpleDateFormat("yyyyMMdd'-'HHmmssSSS", Locale.US); this.date.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * {@inheritDoc} */ public boolean isDebugEnabled() { return false; } /** * {@inheritDoc} */ public void debug(final String message) { // Ignore } /** * {@inheritDoc} */ public void debug(final String message, final Throwable t) { // Ignore } /** * {@inheritDoc} */ public void info(final String message) { this.addMessage(message, "[Info]", null); } /** * {@inheritDoc} */ public void info(final String message, final Throwable t) { this.addMessage(message, "[Info]", t); } /** * {@inheritDoc} */ public void warn(final String message) { this.addMessage(message, "[Warn]", null); } /** * {@inheritDoc} */ public void warn(final String message, final Throwable t) { this.addMessage(message, "[Warn]", t); } /** * {@inheritDoc} */ public void error(final String message) { this.addMessage(message, "[Crit]", null); } /** * {@inheritDoc} */ public void error(final String message, final Throwable t) { this.addMessage(message, "[Crit]", t); } private void addMessage(final String message, final String severity, final Throwable throwable) { Queue<String> queue; synchronized (LogImplWebguiLogging.QUEUES) { // Get the right queue and create it if necessary. queue = LogImplWebguiLogging.QUEUES.get(this.name); if (queue == null) { queue = new ArrayBlockingQueue<String>(MAX_ENTRIES); LogImplWebguiLogging.QUEUES.put(this.name, queue); } } synchronized (queue) { // Is the queue full? if (queue.size() >= MAX_ENTRIES) { // Yes, remove the oldest entry. queue.poll(); // NOFB (ignore the return value) } final StringBuilder sb = new StringBuilder(255); sb.append(this.date.format(new java.util.Date())); // this has to be within synchronized sb.append(": "); sb.append(severity); sb.append(' '); sb.append(message); if (null != throwable) { sb.append('\n'); sb.append(throwable.toString()); } queue.add(sb.toString()); } } /** * Clears the saved entries within this logger. */ public void clear() { synchronized (LogImplWebguiLogging.QUEUES) { LogImplWebguiLogging.QUEUES.clear(); } } /** * Delivers an array with the names of all used loggers. * * @return The available log names. */ public static String[] getAvailableLogs() { synchronized (LogImplWebguiLogging.QUEUES) { return QUEUES.keySet().toArray(new String[QUEUES.size()]); } } /** * Delivers an array with all entries of the logger with the given name. * * @param name * The name of the logger. * @return The stored entries of the logger. If a logger with the given name doesn't exist, an empty array will be returned. */ public static String[] getEntries(final String name) { final Queue<String> queue; synchronized (LogImplWebguiLogging.QUEUES) { // Get the right queue queue = LogImplWebguiLogging.QUEUES.get(name); if (queue == null) { return new String[0]; } } synchronized (queue) { return queue.toArray(new String[queue.size()]); } } }
src/common/kieker/common/logging/LogImplWebguiLogging.java
/*************************************************************************** * Copyright 2013 Kieker Project (http://kieker-monitoring.net) * * 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 kieker.common.logging; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.Queue; import java.util.TimeZone; import java.util.concurrent.ArrayBlockingQueue; /** * This is a simple logger for the Kieker WebGUI. It stores the log messages within a buffer of a static size. If the buffer is full, the oldest entry will be * removed for new entries. As the entries have to be accessible from outside, the queues are stored statically. * * @author Jan Waller, Nils Christian Ehmke * * @since 1.6 */ public final class LogImplWebguiLogging implements Log { private static final int MAX_ENTRIES = 100; private static final Map<String, Queue<String>> QUEUES = new HashMap<String, Queue<String>>(); // NOPMD (sync needed) private final DateFormat date; private final String name; /** * Creates a new instance of this class. * * @param name * The name of the logger. */ protected LogImplWebguiLogging(final String name) { this.name = name; this.date = new SimpleDateFormat("yyyyMMdd'-'HHmmssSSS", Locale.US); this.date.setTimeZone(TimeZone.getTimeZone("UTC")); } /** * {@inheritDoc} */ public boolean isDebugEnabled() { return false; } /** * {@inheritDoc} */ public void debug(final String message) { // Ignore } /** * {@inheritDoc} */ public void debug(final String message, final Throwable t) { // Ignore } /** * {@inheritDoc} */ public void info(final String message) { this.addMessage(message, "[Info]", null); } /** * {@inheritDoc} */ public void info(final String message, final Throwable t) { this.addMessage(message, "[Info]", t); } /** * {@inheritDoc} */ public void warn(final String message) { this.addMessage(message, "[Warn]", null); } /** * {@inheritDoc} */ public void warn(final String message, final Throwable t) { this.addMessage(message, "[Warn]", t); } /** * {@inheritDoc} */ public void error(final String message) { this.addMessage(message, "[Crit]", null); } /** * {@inheritDoc} */ public void error(final String message, final Throwable t) { this.addMessage(message, "[Crit]", t); } private void addMessage(final String message, final String severity, final Throwable throwable) { Queue<String> queue; synchronized (LogImplWebguiLogging.QUEUES) { // Get the right queue and create it if necessary. queue = LogImplWebguiLogging.QUEUES.get(this.name); if (queue == null) { queue = new ArrayBlockingQueue<String>(MAX_ENTRIES); LogImplWebguiLogging.QUEUES.put(this.name, queue); } } synchronized (queue) { // Is the queue full? if (queue.size() >= MAX_ENTRIES) { // Yes, remove the oldest entry. queue.poll(); // NOFB (ignore the return value) } final StringBuilder sb = new StringBuilder(255); sb.append(this.date.format(new java.util.Date())); // this has to be within synchronized sb.append(": "); sb.append(severity); sb.append(' '); sb.append(message); if (null != throwable) { sb.append('\n'); sb.append(throwable.toString()); } queue.add(sb.toString()); } } /** * Clears the saved entries within this logger. */ public void clear() { synchronized (LogImplWebguiLogging.QUEUES) { LogImplWebguiLogging.QUEUES.clear(); } } /** * Delivers an array with all entries of the logger with the given name. * * @param name * The name of the logger. * @return The stored entries of the logger. If a logger with the given name doesn't exist, an empty array will be returned. */ public static String[] getEntries(final String name) { final Queue<String> queue; synchronized (LogImplWebguiLogging.QUEUES) { // Get the right queue queue = LogImplWebguiLogging.QUEUES.get(name); if (queue == null) { return new String[0]; } } synchronized (queue) { return queue.toArray(new String[queue.size()]); } } }
Added a method to LogImplWebguiLogging to receive the names of all logs.
src/common/kieker/common/logging/LogImplWebguiLogging.java
Added a method to LogImplWebguiLogging to receive the names of all logs.
<ide><path>rc/common/kieker/common/logging/LogImplWebguiLogging.java <ide> } <ide> <ide> /** <add> * Delivers an array with the names of all used loggers. <add> * <add> * @return The available log names. <add> */ <add> public static String[] getAvailableLogs() { <add> synchronized (LogImplWebguiLogging.QUEUES) { <add> return QUEUES.keySet().toArray(new String[QUEUES.size()]); <add> } <add> } <add> <add> /** <ide> * Delivers an array with all entries of the logger with the given name. <ide> * <ide> * @param name
Java
bsd-3-clause
fbe7848a24383189abe588e2eac0ec020b481e98
0
bdezonia/zorbage,bdezonia/zorbage
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2019 Barry DeZonia * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package nom.bdezonia.zorbage.algorithm; import static org.junit.Assert.assertEquals; import org.junit.Test; import nom.bdezonia.zorbage.algebras.G; import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class TestEstimateErf { @Test public void test1() { // Note: all decimal numbers below taken from wolframalpha.com on 11-28-19 Float64Member input = G.DBL.construct(); Float64Member result = G.DBL.construct(); input.setV(3); EstimateErf.compute(G.DBL, 32, input, result); assertEquals(0.999977, result.v(), 0.000001); input.setV(0.9); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.796908, result.v(), 0.000001); input.setV(0.7); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.677801, result.v(), 0.000001); input.setV(0.5); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.520500, result.v(), 0.000001); input.setV(0.3); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.328627, result.v(), 0.000001); input.setV(0.1); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.112463, result.v(), 0.000001); input.setV(0); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0, result.v(), 0.000001); input.setV(-0.1); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.112463, result.v(), 0.000001); input.setV(-0.3); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.328627, result.v(), 0.000001); input.setV(-0.5); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.520500, result.v(), 0.000001); input.setV(-0.7); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.677801, result.v(), 0.000001); input.setV(-0.9); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.796908, result.v(), 0.000001); input.setV(-3); EstimateErf.compute(G.DBL, 32, input, result); assertEquals(-0.999977, result.v(), 0.000001); // Do a complex valued erf() test ComplexFloat64Member x = G.CDBL.construct(); ComplexFloat64Member res = G.CDBL.construct(); x.setR(1); x.setI(2); EstimateErf.compute(G.CDBL, 21, x, res); assertEquals(-0.53664356577, res.r(), 0.000001); assertEquals(-5.04914370344, res.i(), 0.000001); } }
src/test/java/nom/bdezonia/zorbage/algorithm/TestEstimateErf.java
/* * Zorbage: an algebraic data hierarchy for use in numeric processing. * * Copyright (C) 2016-2019 Barry DeZonia * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package nom.bdezonia.zorbage.algorithm; import static org.junit.Assert.assertEquals; import org.junit.Test; import nom.bdezonia.zorbage.algebras.G; import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; /** * * @author Barry DeZonia * */ public class TestEstimateErf { @Test public void test1() { // Note: all decimal numbers below taken from wolframalpha.com on 11-28-19 Float64Member input = G.DBL.construct(); Float64Member result = G.DBL.construct(); input.setV(3); EstimateErf.compute(G.DBL, 32, input, result); assertEquals(0.999977, result.v(), 0.000001); input.setV(0.9); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.796908, result.v(), 0.000001); input.setV(0.7); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.677801, result.v(), 0.000001); input.setV(0.5); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.520500, result.v(), 0.000001); input.setV(0.3); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.328627, result.v(), 0.000001); input.setV(0.1); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0.112463, result.v(), 0.000001); input.setV(0); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(0, result.v(), 0.000001); input.setV(-0.1); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.112463, result.v(), 0.000001); input.setV(-0.3); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.328627, result.v(), 0.000001); input.setV(-0.5); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.520500, result.v(), 0.000001); input.setV(-0.7); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.677801, result.v(), 0.000001); input.setV(-0.9); EstimateErf.compute(G.DBL, 8, input, result); assertEquals(-0.796908, result.v(), 0.000001); input.setV(-3); EstimateErf.compute(G.DBL, 32, input, result); assertEquals(-0.999977, result.v(), 0.000001); } }
Test the complex number capability of the EstimateErf algorithm
src/test/java/nom/bdezonia/zorbage/algorithm/TestEstimateErf.java
Test the complex number capability of the EstimateErf algorithm
<ide><path>rc/test/java/nom/bdezonia/zorbage/algorithm/TestEstimateErf.java <ide> import org.junit.Test; <ide> <ide> import nom.bdezonia.zorbage.algebras.G; <add>import nom.bdezonia.zorbage.type.data.float64.complex.ComplexFloat64Member; <ide> import nom.bdezonia.zorbage.type.data.float64.real.Float64Member; <ide> <ide> /** <ide> input.setV(-3); <ide> EstimateErf.compute(G.DBL, 32, input, result); <ide> assertEquals(-0.999977, result.v(), 0.000001); <add> <add> // Do a complex valued erf() test <add> <add> ComplexFloat64Member x = G.CDBL.construct(); <add> ComplexFloat64Member res = G.CDBL.construct(); <add> x.setR(1); <add> x.setI(2); <add> EstimateErf.compute(G.CDBL, 21, x, res); <add> assertEquals(-0.53664356577, res.r(), 0.000001); <add> assertEquals(-5.04914370344, res.i(), 0.000001); <ide> } <ide> }
Java
bsd-3-clause
error: pathspec 'src/xal/tools/LinearInterpolator.java' did not match any file(s) known to git
5c8c21314acefa2c7f5f54baa8f7ab12c666fe50
1
EuropeanSpallationSource/openxal,openxal/openxal,luxiaohan/openxal-csns-luxh,EuropeanSpallationSource/openxal,openxal/openxal,EuropeanSpallationSource/openxal,openxal/openxal,luxiaohan/openxal-csns-luxh,EuropeanSpallationSource/openxal,luxiaohan/openxal-csns-luxh,EuropeanSpallationSource/openxal,luxiaohan/openxal-csns-luxh,openxal/openxal,openxal/openxal
/* * LinearInterpolator.java * * Created on August 11, 2003, 4:10 PM * * Copyright 2003, Spallation Neutron Source * Oak Ridge National Laboratory * Oak Ridge, TN 37830 */ package xal.tools; /** * LinearInterpolator calculates the linear interpolated value at at any point * within the bounds of an array of values. * * @author tap */ final public class LinearInterpolator { /** epsilonWeight is the fraction resolution of the step. */ static final private double epsilonWeight = 1.0e-6; final protected double[] _values; final protected double _start; final protected double _step; /** * Creates a new instance of Interpolator. * @param values is the array of values at fixed intervals. * @param start is the start of the domain of points and corresponds to the first array element * @param step is the step in the domain for each successive element in the array */ public LinearInterpolator( final double[] values, final double start, double step ) { _values = values; _start = start; _step = step; } /** * Calculate the interpolated value at the specified point in the domain. The point must * reside within the domain of points from <code>start</code> to <code>start + step * values.length</code>. * @param point The point in the domain for which we should interpolate the value. * @return The interpolated value. * @throws java.lang.ArrayIndexOutOfBoundsException if the point does not fall int the accepted domain */ public double calcValueAt( final double point ) throws ArrayIndexOutOfBoundsException { final double element = (point - _start) / _step; final double weight = element - Math.floor(element); final int index = (int)element; return (weight < epsilonWeight) ? _values[index] : (1-weight) * _values[index] + weight * _values[index+1]; } }
src/xal/tools/LinearInterpolator.java
-n Port the Linear Interpolator from XAL to Open XAL.
src/xal/tools/LinearInterpolator.java
-n Port the Linear Interpolator from XAL to Open XAL.
<ide><path>rc/xal/tools/LinearInterpolator.java <add>/* <add> * LinearInterpolator.java <add> * <add> * Created on August 11, 2003, 4:10 PM <add> * <add> * Copyright 2003, Spallation Neutron Source <add> * Oak Ridge National Laboratory <add> * Oak Ridge, TN 37830 <add> */ <add> <add>package xal.tools; <add> <add>/** <add> * LinearInterpolator calculates the linear interpolated value at at any point <add> * within the bounds of an array of values. <add> * <add> * @author tap <add> */ <add>final public class LinearInterpolator { <add> /** epsilonWeight is the fraction resolution of the step. */ <add> static final private double epsilonWeight = 1.0e-6; <add> <add> final protected double[] _values; <add> final protected double _start; <add> final protected double _step; <add> <add> <add> /** <add> * Creates a new instance of Interpolator. <add> * @param values is the array of values at fixed intervals. <add> * @param start is the start of the domain of points and corresponds to the first array element <add> * @param step is the step in the domain for each successive element in the array <add> */ <add> public LinearInterpolator( final double[] values, final double start, double step ) { <add> _values = values; <add> _start = start; <add> _step = step; <add> } <add> <add> <add> /** <add> * Calculate the interpolated value at the specified point in the domain. The point must <add> * reside within the domain of points from <code>start</code> to <code>start + step * values.length</code>. <add> * @param point The point in the domain for which we should interpolate the value. <add> * @return The interpolated value. <add> * @throws java.lang.ArrayIndexOutOfBoundsException if the point does not fall int the accepted domain <add> */ <add> public double calcValueAt( final double point ) throws ArrayIndexOutOfBoundsException { <add> final double element = (point - _start) / _step; <add> final double weight = element - Math.floor(element); <add> final int index = (int)element; <add> <add> return (weight < epsilonWeight) ? _values[index] : (1-weight) * _values[index] + weight * _values[index+1]; <add> } <add>}
Java
mit
83bf6d79ccb1cd6be4b75180bbc38c532a3ca73d
0
ollie314/args4j,chambas/args4j,ChartBoost/args4j,NickVolynkin/args4j,ChartBoost/args4j,ollie314/args4j,ollie314/args4j,chambas/args4j,kohsuke/args4j,sannies/args4j,chambas/args4j,kohsuke/args4j,sannies/args4j,NickVolynkin/args4j,sannies/args4j,ChartBoost/args4j,kohsuke/args4j,NickVolynkin/args4j
package org.kohsuke.args4j; import java.io.File; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.logging.Logger; import org.kohsuke.args4j.MetadataParser.Pair; import org.kohsuke.args4j.spi.BooleanOptionHandler; import org.kohsuke.args4j.spi.ByteOptionHandler; import org.kohsuke.args4j.spi.CharOptionHandler; import org.kohsuke.args4j.spi.ClassParser; import org.kohsuke.args4j.spi.DoubleOptionHandler; import org.kohsuke.args4j.spi.EnumOptionHandler; import org.kohsuke.args4j.spi.FileOptionHandler; import org.kohsuke.args4j.spi.FloatOptionHandler; import org.kohsuke.args4j.spi.IntOptionHandler; import org.kohsuke.args4j.spi.LongOptionHandler; import org.kohsuke.args4j.spi.MapOptionHandler; import org.kohsuke.args4j.spi.OptionHandler; import org.kohsuke.args4j.spi.Parameters; import org.kohsuke.args4j.spi.Setter; import org.kohsuke.args4j.spi.ShortOptionHandler; import org.kohsuke.args4j.spi.StringOptionHandler; import org.kohsuke.args4j.spi.URIOptionHandler; import org.kohsuke.args4j.spi.URLOptionHandler; import org.kohsuke.args4j.spi.XmlParser; /** * Command line argument owner. * * <p> * For a typical usage, see <a href="https://args4j.dev.java.net/source/browse/args4j/args4j/examples/SampleMain.java?view=markup">this example</a>. * * @author * Kohsuke Kawaguchi ([email protected]) */ public class CmdLineParser { /** * Discovered {@link OptionHandler}s for options. */ private final List<OptionHandler> options = new ArrayList<OptionHandler>(); /** * Discovered {@link OptionHandler}s for arguments. */ private final List<OptionHandler> arguments = new ArrayList<OptionHandler>(); private boolean parsingOptions = true; private OptionHandler currentOptionHandler = null; /** * The length of a usage line. * If the usage message is longer than this value, the parser * wraps the line. Defaults to 80. */ private int usageWidth = 80; /** * Stack of registered metadata parsers. * The first parser on the stack which can work ({@link MetadataParser#canWorkFor(Object)}) * gets the job. */ private static Stack<MetadataParser> metadataParsers = new Stack<MetadataParser>(); static { registerMetadataParser(new ClassParser()); registerMetadataParser(new XmlParser()); } /** * Registers a new metadata parser. * @param parser the new parser */ public static void registerMetadataParser(MetadataParser parser) { metadataParsers.add(parser); } /** * Creates a new command line owner that * parses arguments/options and set them into * the given object. * * @param bean * instance of a class annotated by {@link Option} and {@link Argument}. * this object will receive values. * * @throws IllegalAnnotationError * if the option bean class is using args4j annotations incorrectly. */ public CmdLineParser(Object bean) { // Find a metadata parser which will scan the metadata. MetadataParser parser = null; Stack<MetadataParser> registeredParsers = (Stack<MetadataParser>) metadataParsers.clone(); while (!registeredParsers.isEmpty() && parser == null) { MetadataParser p = registeredParsers.pop(); if (p.canWorkFor(bean)) { parser = p; } } LOGGER.fine("Use " + parser + " as metadata parser."); // Parse the metadata and create the setters parser.parse(bean); for(Pair pair : parser.getAnnotations()) { Setter setter; if (pair.getMethodOrField() instanceof Method) { // Annotation is on a method Method method = (Method) pair.getMethodOrField(); setter = new MethodSetter(this, bean, method); } else { // Annotation is on a field Field field = (Field) pair.getMethodOrField(); setter = createFieldSetter(field,bean); } if (pair.getArgumentOrOption() instanceof Option) { // @Option annotation addOption(setter, (Option) pair.getArgumentOrOption()); } else { // @Argument annotation addArgument(setter, (Argument) pair.getArgumentOrOption()); } } // for display purposes, we like the arguments in argument order, but the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } private Setter createFieldSetter(Field f, Object bean) { if(List.class.isAssignableFrom(f.getType())) return new MultiValueFieldSetter(bean,f); else if(Map.class.isAssignableFrom(f.getType())) return new MapSetter(bean,f); else return new FieldSetter(bean,f); } /** * Add the object for parsing an argument. * Usually this is called while parsing the business class. * @param setter the setter for the type * @param a the Argument */ public void addArgument(Setter setter, Argument a) { OptionHandler h = createOptionHandler(new OptionDef(a,setter.isMultiValued()),setter); int index = a.index(); // make sure the argument will fit in the list while (index >= arguments.size()) { arguments.add(null); } if(arguments.get(index)!=null) { throw new IllegalAnnotationError("Argument with index "+index+" is used more than once"); } arguments.set(index,h); } /** * Add the object for parsing an option. * Usually this is called while parsing the business class. * @param setter the setter for the type * @param o the Option */ public void addOption(Setter setter, Option o) { checkOptionNotInMap(o.name()); for (String alias : o.aliases()) { checkOptionNotInMap(alias); } options.add(createOptionHandler(new NamedOptionDef(o, setter.isMultiValued()), setter)); } private void checkOptionNotInMap(String name) throws IllegalAnnotationError { if(findOptionByName(name)!=null) { throw new IllegalAnnotationError("Option name "+name+" is used more than once"); } } /** * Creates an {@link OptionHandler} that handles the given {@link Option} annotation * and the {@link Setter} instance. */ @SuppressWarnings("unchecked") protected OptionHandler createOptionHandler(OptionDef o, Setter setter) { Constructor<? extends OptionHandler> handlerType; Class<? extends OptionHandler> h = o.handler(); if(h==OptionHandler.class) { // infer the type // enum is the special case Class t = setter.getType(); if(Enum.class.isAssignableFrom(t)) return new EnumOptionHandler(this,o,setter,t); handlerType = handlerClasses.get(t); if(handlerType==null) throw new IllegalAnnotationError("No OptionHandler is registered to handle "+t); } else { handlerType = getConstructor(h); } try { return handlerType.newInstance(this,o,setter); } catch (InstantiationException e) { throw new IllegalAnnotationError(e); } catch (IllegalAccessException e) { throw new IllegalAnnotationError(e); } catch (InvocationTargetException e) { throw new IllegalAnnotationError(e); } } /** * Formats a command line example into a string. * * See {@link #printExample(ExampleMode, ResourceBundle)} for more details. * * @param mode * must not be null. * @return * always non-null. */ public String printExample(ExampleMode mode) { return printExample(mode,null); } /** * Formats a command line example into a string. * * <p> * This method produces a string like " -d &lt;dir> -v -b", * which is useful for printing a command line example, perhaps * as a part of the usage screen. * * * @param mode * One of the {@link ExampleMode} constants. Must not be null. * This determines what option should be a part of the returned string. * @param rb * If non-null, meta variables (&lt;dir> in the above example) * is treated as a key to this resource bundle, and the associated * value is printed. See {@link Option#metaVar()}. This is to support * localization. * * Passing <tt>null</tt> would print {@link Option#metaVar()} directly. * @return * always non-null. If there's no option, this method returns * just the empty string "". Otherwise, this method returns a * string that contains a space at the beginning (but not at the end.) * This allows you to do something like: * * <pre>System.err.println("java -jar my.jar"+parser.printExample(REQUIRED)+" arg1 arg2");</pre> */ public String printExample(ExampleMode mode,ResourceBundle rb) { StringBuilder buf = new StringBuilder(); for (OptionHandler h : options) { OptionDef option = h.option; if(option.usage().length()==0) continue; // ignore if(!mode.print(option)) continue; buf.append(' '); buf.append(h.getNameAndMeta(rb)); } return buf.toString(); } /** * Prints the list of options and their usages to the screen. * * <p> * This is a convenience method for calling {@code printUsage(new OutputStreamWriter(out),null)} * so that you can do {@code printUsage(System.err)}. */ public void printUsage(OutputStream out) { printUsage(new OutputStreamWriter(out),null); } /** * Prints the list of options and their usages to the screen. * * @param rb * if this is non-null, {@link Option#usage()} is treated * as a key to obtain the actual message from this resource bundle. */ public void printUsage(Writer out, ResourceBundle rb) { PrintWriter w = new PrintWriter(out); // determine the length of the option + metavar first int len = 0; for (OptionHandler h : arguments) { int curLen = getPrefixLen(h, rb); len = Math.max(len,curLen); } for (OptionHandler h: options) { int curLen = getPrefixLen(h, rb); len = Math.max(len,curLen); } // then print for (OptionHandler h : arguments) { printOption(w, h, len, rb); } for (OptionHandler h : options) { printOption(w, h, len, rb); } w.flush(); } /** * Prints the usage information for a given option. * @param out Writer to write into * @param handler handler where to receive the informations * @param len Maximum length of metadata column * @param rb ResourceBundle for I18N */ private void printOption(PrintWriter out, OptionHandler handler, int len, ResourceBundle rb) { // Hiding options without usage information if (handler.option.usage() == null || handler.option.usage().length() == 0) { return; } // What is the width of the two data columns int widthMetadata = Math.min(len, (usageWidth - 4) / 2); int widthUsage = usageWidth - 4 - widthMetadata; // Line wrapping List<String> namesAndMetas = wrapLines(handler.getNameAndMeta(rb), widthMetadata); List<String> usages = wrapLines(localize(handler.option.usage(),rb), widthUsage); // Output for(int i=0; i<Math.max(namesAndMetas.size(), usages.size()); i++) { String nameAndMeta = (i >= namesAndMetas.size()) ? "" : namesAndMetas.get(i); String usage = (i >= usages.size()) ? "" : usages.get(i); String format = (nameAndMeta.length() > 0) ? " %1$-" + widthMetadata + "s : %2$-1s" : " %1$-" + widthMetadata + "s %2$-1s"; String output = String.format(format, nameAndMeta, usage); out.println(output); } } private String localize(String s, ResourceBundle rb) { if(rb!=null) return rb.getString(s); return s; } /** * Wraps a line so that the resulting parts are not longer than a given maximum length. * @param line Line to wrap * @param maxLength maximum length for the resulting parts * @return list of all wrapped parts */ private List<String> wrapLines(String line, final int maxLength) { List<String> rv = new ArrayList<String>(); for (String restOfLine : line.split("\\n")) { while (restOfLine.length() > maxLength) { // try to wrap at space, but don't try too hard as some languages don't even have whitespaces. int lineLength; String candidate = restOfLine.substring(0, maxLength); int sp=candidate.lastIndexOf(' '); if(sp>maxLength*3/4) lineLength=sp; else lineLength=maxLength; rv.add(restOfLine.substring(0, lineLength)); restOfLine = restOfLine.substring(lineLength).trim(); } rv.add(restOfLine); } return rv; } private int getPrefixLen(OptionHandler h, ResourceBundle rb) { if(h.option.usage().length()==0) return 0; return h.getNameAndMeta(rb).length(); } /** * Essentially a pointer over a {@link String} array. * Can move forward, can look ahead. */ private class CmdLineImpl implements Parameters { private final String[] args; private int pos; CmdLineImpl( String[] args ) { this.args = args; pos = 0; } protected boolean hasMore() { return pos<args.length; } protected String getCurrentToken() { return args[pos]; } private void proceed( int n ) { pos += n; } public String getParameter(int idx) throws CmdLineException { if( pos+idx>=args.length ) throw new CmdLineException(CmdLineParser.this, Messages.MISSING_OPERAND.format(getOptionName())); return args[pos+idx]; } public int size() { return args.length-pos; } } private String getOptionName() { return currentOptionHandler.option.toString(); } /** * Parses the command line arguments and set them to the option bean * given in the constructor. * * @param args arguments to parse * * @throws CmdLineException * if there's any error parsing arguments, or if * {@link Option#required() required} option was not given. */ public void parseArgument(final String... args) throws CmdLineException { CmdLineImpl cmdLine = new CmdLineImpl(args); Set<OptionHandler> present = new HashSet<OptionHandler>(); int argIndex = 0; while( cmdLine.hasMore() ) { String arg = cmdLine.getCurrentToken(); if( isOption(arg) ) { boolean isKeyValuePair = arg.indexOf('=')!=-1; // parse this as an option. currentOptionHandler = isKeyValuePair ? findOptionHandler(arg) : findOptionByName(arg); if(currentOptionHandler==null) { // TODO: insert dynamic handler processing throw new CmdLineException(this, Messages.UNDEFINED_OPTION.format(arg)); } // known option; skip its name cmdLine.proceed(1); } else { if (argIndex >= arguments.size()) { Messages msg = arguments.size() == 0 ? Messages.NO_ARGUMENT_ALLOWED : Messages.TOO_MANY_ARGUMENTS; throw new CmdLineException(this, msg.format(arg)); } // known argument currentOptionHandler = arguments.get(argIndex); if (!currentOptionHandler.option.isMultiValued()) argIndex++; } int diff = currentOptionHandler.parseArguments(cmdLine); cmdLine.proceed(diff); present.add(currentOptionHandler); } // make sure that all mandatory options are present for (OptionHandler handler : options) if(handler.option.required() && !present.contains(handler)) throw new CmdLineException(this, Messages.REQUIRED_OPTION_MISSING.format(handler.option.toString())); // make sure that all mandatory arguments are present for (OptionHandler handler : arguments) if(handler.option.required() && !present.contains(handler)) throw new CmdLineException(this, Messages.REQUIRED_ARGUMENT_MISSING.format(handler.option.toString())); } private OptionHandler findOptionHandler(String name) { OptionHandler handler = findOptionByName(name); if (handler==null) { // Have not found by its name, maybe its a property? // Search for parts of the name (=prefix) - most specific first for (int i=name.length(); i>1; i--) { String prefix = name.substring(0, i); Map<String,OptionHandler> possibleHandlers = filter(options, prefix); handler = possibleHandlers.get(prefix); if (handler!=null) return handler; } } return handler; } /** * Finds a registered OptionHandler by its name or its alias. * @param name name * @return the OptionHandler or <tt>null</tt> */ private OptionHandler findOptionByName(String name) { for (OptionHandler h : options) { NamedOptionDef option = (NamedOptionDef)h.option; if (name.equals(option.name())) { return h; } for (String alias : option.aliases()) { if (name.equals(alias)) { return h; } } } return null; } private Map<String,OptionHandler> filter(List<OptionHandler> opt, String keyFilter) { Map<String,OptionHandler> rv = new TreeMap<String,OptionHandler>(); for (OptionHandler h : opt) { if (opt.toString().startsWith(keyFilter)) rv.put(opt.toString(), h); } return rv; } /** * Returns true if the given token is an option * (as opposed to an argument.) */ protected boolean isOption(String arg) { return parsingOptions && arg.startsWith("-"); } /** * All {@link OptionHandler}s known to the {@link CmdLineParser}. * * Constructors of {@link OptionHandler}-derived class keyed by their supported types. */ private static final Map<Class,Constructor<? extends OptionHandler>> handlerClasses = Collections.synchronizedMap(new HashMap<Class,Constructor<? extends OptionHandler>>()); /** * Registers a user-defined {@link OptionHandler} class with args4j. * * <p> * This method allows users to extend the behavior of args4j by writing * their own {@link OptionHandler} implementation. * * @param valueType * The specified handler is used when the field/method annotated by {@link Option} * is of this type. * @param handlerClass * This class must have the constructor that has the same signature as * {@link OptionHandler#OptionHandler(CmdLineParser, OptionDef, Setter)} */ public static void registerHandler( Class valueType, Class<? extends OptionHandler> handlerClass ) { if(valueType==null || handlerClass==null) throw new IllegalArgumentException(); if(!OptionHandler.class.isAssignableFrom(handlerClass)) throw new IllegalArgumentException("Not an OptionHandler class"); Constructor<? extends OptionHandler> c = getConstructor(handlerClass); handlerClasses.put(valueType,c); } private static Constructor<? extends OptionHandler> getConstructor(Class<? extends OptionHandler> handlerClass) { try { return handlerClass.getConstructor(CmdLineParser.class, OptionDef.class, Setter.class); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(handlerClass+" does not have the proper constructor"); } } static { registerHandler(Boolean.class,BooleanOptionHandler.class); registerHandler(boolean.class,BooleanOptionHandler.class); registerHandler(File.class,FileOptionHandler.class); registerHandler(URL.class, URLOptionHandler.class); registerHandler(URI.class, URIOptionHandler.class); registerHandler(Integer.class,IntOptionHandler.class); registerHandler(int.class,IntOptionHandler.class); registerHandler(Double.class, DoubleOptionHandler.class); registerHandler(double.class,DoubleOptionHandler.class); registerHandler(String.class,StringOptionHandler.class); registerHandler(Byte.class, ByteOptionHandler.class); registerHandler(byte.class, ByteOptionHandler.class); registerHandler(Character.class, CharOptionHandler.class); registerHandler(char.class, CharOptionHandler.class); registerHandler(Float.class, FloatOptionHandler.class); registerHandler(float.class, FloatOptionHandler.class); registerHandler(Long.class, LongOptionHandler.class); registerHandler(long.class, LongOptionHandler.class); registerHandler(Short.class, ShortOptionHandler.class); registerHandler(short.class, ShortOptionHandler.class); // enum is a special case registerHandler(Map.class,MapOptionHandler.class); } public void setUsageWidth(int usageWidth) { this.usageWidth = usageWidth; } public void stopOptionParsing() { parsingOptions = false; } /** * Prints a single-line usage to the screen. * * <p> * This is a convenience method for calling {@code printUsage(new OutputStreamWriter(out),null)} * so that you can do {@code printUsage(System.err)}. */ public void printSingleLineUsage(OutputStream out) { printSingleLineUsage(new OutputStreamWriter(out),null); } /** * Prints a single-line usage to the screen. * * @param rb * if this is non-null, {@link Option#usage()} is treated * as a key to obtain the actual message from this resource bundle. */ public void printSingleLineUsage(Writer w, ResourceBundle rb) { PrintWriter pw = new PrintWriter(w); for (OptionHandler h : arguments) { printSingleLineOption(pw, h, rb); } for (OptionHandler h : options) { printSingleLineOption(pw, h, rb); } pw.flush(); } private void printSingleLineOption(PrintWriter pw, OptionHandler h, ResourceBundle rb) { pw.print(' '); if (!h.option.required()) pw.print('['); pw.print(h.getNameAndMeta(rb)); if (h.option.isMultiValued()) { pw.print(" ..."); } if (!h.option.required()) pw.print(']'); } private static final Logger LOGGER = Logger.getLogger(CmdLineParser.class.getName()); }
args4j/src/org/kohsuke/args4j/CmdLineParser.java
package org.kohsuke.args4j; import java.io.File; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Writer; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.ResourceBundle; import java.util.Set; import java.util.Stack; import java.util.TreeMap; import java.util.logging.Logger; import org.kohsuke.args4j.MetadataParser.Pair; import org.kohsuke.args4j.spi.BooleanOptionHandler; import org.kohsuke.args4j.spi.ByteOptionHandler; import org.kohsuke.args4j.spi.CharOptionHandler; import org.kohsuke.args4j.spi.ClassParser; import org.kohsuke.args4j.spi.DoubleOptionHandler; import org.kohsuke.args4j.spi.EnumOptionHandler; import org.kohsuke.args4j.spi.FileOptionHandler; import org.kohsuke.args4j.spi.FloatOptionHandler; import org.kohsuke.args4j.spi.IntOptionHandler; import org.kohsuke.args4j.spi.LongOptionHandler; import org.kohsuke.args4j.spi.MapOptionHandler; import org.kohsuke.args4j.spi.OptionHandler; import org.kohsuke.args4j.spi.Parameters; import org.kohsuke.args4j.spi.Setter; import org.kohsuke.args4j.spi.ShortOptionHandler; import org.kohsuke.args4j.spi.StringOptionHandler; import org.kohsuke.args4j.spi.URIOptionHandler; import org.kohsuke.args4j.spi.URLOptionHandler; import org.kohsuke.args4j.spi.XmlParser; /** * Command line argument owner. * * <p> * For a typical usage, see <a href="https://args4j.dev.java.net/source/browse/args4j/args4j/examples/SampleMain.java?view=markup">this example</a>. * * @author * Kohsuke Kawaguchi ([email protected]) */ public class CmdLineParser { /** * Option bean instance. */ private final Object bean; /** * Discovered {@link OptionHandler}s for options. */ private final List<OptionHandler> options = new ArrayList<OptionHandler>(); /** * Discovered {@link OptionHandler}s for arguments. */ private final List<OptionHandler> arguments = new ArrayList<OptionHandler>(); private boolean parsingOptions = true; private OptionHandler currentOptionHandler = null; /** * The length of a usage line. * If the usage message is longer than this value, the parser * wraps the line. Defaults to 80. */ private int usageWidth = 80; /** * Stack of registered metadata parsers. * The first parser on the stack which can work ({@link MetadataParser#canWorkFor(Object)}) * gets the job. */ private static Stack<MetadataParser> metadataParsers = new Stack<MetadataParser>(); static { registerMetadataParser(new ClassParser()); registerMetadataParser(new XmlParser()); } /** * Registers a new metadata parser. * @param parser the new parser */ public static void registerMetadataParser(MetadataParser parser) { metadataParsers.add(parser); } /** * Creates a new command line owner that * parses arguments/options and set them into * the given object. * * @param bean * instance of a class annotated by {@link Option} and {@link Argument}. * this object will receive values. * * @throws IllegalAnnotationError * if the option bean class is using args4j annotations incorrectly. */ public CmdLineParser(Object bean) { this.bean = bean; // Find a metadata parser which will scan the metadata. MetadataParser parser = null; Stack<MetadataParser> registeredParsers = (Stack<MetadataParser>) metadataParsers.clone(); while (!registeredParsers.isEmpty() && parser == null) { MetadataParser p = registeredParsers.pop(); if (p.canWorkFor(bean)) { parser = p; } } LOGGER.fine("Use " + parser + " as metadata parser."); // Parse the metadata and create the setters parser.parse(bean); for(Pair pair : parser.getAnnotations()) { Setter setter = null; if (pair.getMethodOrField() instanceof Method) { // Annotation is on a method Method method = (Method) pair.getMethodOrField(); setter = new MethodSetter(this, bean, method); if (pair.getArgumentOrOption() instanceof Option) { // @Option annotation addOption(setter, (Option) pair.getArgumentOrOption()); } else { // @Argument annotation addArgument(setter, (Argument) pair.getArgumentOrOption()); } } else { // Annotation is on a field Field field = (Field) pair.getMethodOrField(); if (pair.getArgumentOrOption() instanceof Option) { // @Option annotation Option o = (Option) pair.getArgumentOrOption(); addOption(createFieldSetter(field), (Option) pair.getArgumentOrOption()); } else { // @Argument annotation addArgument(createFieldSetter(field), (Argument) pair.getArgumentOrOption()); } } } // for display purposes, we like the arguments in argument order, but the options in alphabetical order Collections.sort(options, new Comparator<OptionHandler>() { public int compare(OptionHandler o1, OptionHandler o2) { return o1.option.toString().compareTo(o2.option.toString()); } }); } private Setter createFieldSetter(Field f) { if(List.class.isAssignableFrom(f.getType())) return new MultiValueFieldSetter(bean,f); else if(Map.class.isAssignableFrom(f.getType())) return new MapSetter(bean,f); else return new FieldSetter(bean,f); } /** * Add the object for parsing an argument. * Usually this is called while parsing the business class. * @param setter the setter for the type * @param a the Argument */ public void addArgument(Setter setter, Argument a) { OptionHandler h = createOptionHandler(new OptionDef(a,setter.isMultiValued()),setter); int index = a.index(); // make sure the argument will fit in the list while (index >= arguments.size()) { arguments.add(null); } if(arguments.get(index)!=null) { throw new IllegalAnnotationError("Argument with index "+index+" is used more than once"); } arguments.set(index,h); } /** * Add the object for parsing an option. * Usually this is called while parsing the business class. * @param setter the setter for the type * @param o the Option */ public void addOption(Setter setter, Option o) { checkOptionNotInMap(o.name()); for (String alias : o.aliases()) { checkOptionNotInMap(alias); } options.add(createOptionHandler(new NamedOptionDef(o, setter.isMultiValued()), setter)); } private void checkOptionNotInMap(String name) throws IllegalAnnotationError { if(findOptionByName(name)!=null) { throw new IllegalAnnotationError("Option name "+name+" is used more than once"); } } /** * Creates an {@link OptionHandler} that handles the given {@link Option} annotation * and the {@link Setter} instance. */ @SuppressWarnings("unchecked") protected OptionHandler createOptionHandler(OptionDef o, Setter setter) { Constructor<? extends OptionHandler> handlerType; Class<? extends OptionHandler> h = o.handler(); if(h==OptionHandler.class) { // infer the type // enum is the special case Class t = setter.getType(); if(Enum.class.isAssignableFrom(t)) return new EnumOptionHandler(this,o,setter,t); handlerType = handlerClasses.get(t); if(handlerType==null) throw new IllegalAnnotationError("No OptionHandler is registered to handle "+t); } else { handlerType = getConstructor(h); } try { return handlerType.newInstance(this,o,setter); } catch (InstantiationException e) { throw new IllegalAnnotationError(e); } catch (IllegalAccessException e) { throw new IllegalAnnotationError(e); } catch (InvocationTargetException e) { throw new IllegalAnnotationError(e); } } /** * Formats a command line example into a string. * * See {@link #printExample(ExampleMode, ResourceBundle)} for more details. * * @param mode * must not be null. * @return * always non-null. */ public String printExample(ExampleMode mode) { return printExample(mode,null); } /** * Formats a command line example into a string. * * <p> * This method produces a string like " -d &lt;dir> -v -b", * which is useful for printing a command line example, perhaps * as a part of the usage screen. * * * @param mode * One of the {@link ExampleMode} constants. Must not be null. * This determines what option should be a part of the returned string. * @param rb * If non-null, meta variables (&lt;dir> in the above example) * is treated as a key to this resource bundle, and the associated * value is printed. See {@link Option#metaVar()}. This is to support * localization. * * Passing <tt>null</tt> would print {@link Option#metaVar()} directly. * @return * always non-null. If there's no option, this method returns * just the empty string "". Otherwise, this method returns a * string that contains a space at the beginning (but not at the end.) * This allows you to do something like: * * <pre>System.err.println("java -jar my.jar"+parser.printExample(REQUIRED)+" arg1 arg2");</pre> */ public String printExample(ExampleMode mode,ResourceBundle rb) { StringBuilder buf = new StringBuilder(); for (OptionHandler h : options) { OptionDef option = h.option; if(option.usage().length()==0) continue; // ignore if(!mode.print(option)) continue; buf.append(' '); buf.append(h.getNameAndMeta(rb)); } return buf.toString(); } /** * Prints the list of options and their usages to the screen. * * <p> * This is a convenience method for calling {@code printUsage(new OutputStreamWriter(out),null)} * so that you can do {@code printUsage(System.err)}. */ public void printUsage(OutputStream out) { printUsage(new OutputStreamWriter(out),null); } /** * Prints the list of options and their usages to the screen. * * @param rb * if this is non-null, {@link Option#usage()} is treated * as a key to obtain the actual message from this resource bundle. */ public void printUsage(Writer out, ResourceBundle rb) { PrintWriter w = new PrintWriter(out); // determine the length of the option + metavar first int len = 0; for (OptionHandler h : arguments) { int curLen = getPrefixLen(h, rb); len = Math.max(len,curLen); } for (OptionHandler h: options) { int curLen = getPrefixLen(h, rb); len = Math.max(len,curLen); } // then print for (OptionHandler h : arguments) { printOption(w, h, len, rb); } for (OptionHandler h : options) { printOption(w, h, len, rb); } w.flush(); } /** * Prints the usage information for a given option. * @param out Writer to write into * @param handler handler where to receive the informations * @param len Maximum length of metadata column * @param rb ResourceBundle for I18N */ private void printOption(PrintWriter out, OptionHandler handler, int len, ResourceBundle rb) { // Hiding options without usage information if (handler.option.usage() == null || handler.option.usage().length() == 0) { return; } // What is the width of the two data columns int widthMetadata = Math.min(len, (usageWidth - 4) / 2); int widthUsage = usageWidth - 4 - widthMetadata; // Line wrapping List<String> namesAndMetas = wrapLines(handler.getNameAndMeta(rb), widthMetadata); List<String> usages = wrapLines(localize(handler.option.usage(),rb), widthUsage); // Output for(int i=0; i<Math.max(namesAndMetas.size(), usages.size()); i++) { String nameAndMeta = (i >= namesAndMetas.size()) ? "" : namesAndMetas.get(i); String usage = (i >= usages.size()) ? "" : usages.get(i); String format = (nameAndMeta.length() > 0) ? " %1$-" + widthMetadata + "s : %2$-1s" : " %1$-" + widthMetadata + "s %2$-1s"; String output = String.format(format, nameAndMeta, usage); out.println(output); } } private String localize(String s, ResourceBundle rb) { if(rb!=null) return rb.getString(s); return s; } /** * Wraps a line so that the resulting parts are not longer than a given maximum length. * @param line Line to wrap * @param maxLength maximum length for the resulting parts * @return list of all wrapped parts */ private List<String> wrapLines(String line, final int maxLength) { List<String> rv = new ArrayList<String>(); for (String restOfLine : line.split("\\n")) { while (restOfLine.length() > maxLength) { // try to wrap at space, but don't try too hard as some languages don't even have whitespaces. int lineLength; String candidate = restOfLine.substring(0, maxLength); int sp=candidate.lastIndexOf(' '); if(sp>maxLength*3/4) lineLength=sp; else lineLength=maxLength; rv.add(restOfLine.substring(0, lineLength)); restOfLine = restOfLine.substring(lineLength).trim(); } rv.add(restOfLine); } return rv; } private int getPrefixLen(OptionHandler h, ResourceBundle rb) { if(h.option.usage().length()==0) return 0; return h.getNameAndMeta(rb).length(); } /** * Essentially a pointer over a {@link String} array. * Can move forward, can look ahead. */ private class CmdLineImpl implements Parameters { private final String[] args; private int pos; CmdLineImpl( String[] args ) { this.args = args; pos = 0; } protected boolean hasMore() { return pos<args.length; } protected String getCurrentToken() { return args[pos]; } private void proceed( int n ) { pos += n; } public String getParameter(int idx) throws CmdLineException { if( pos+idx>=args.length ) throw new CmdLineException(CmdLineParser.this, Messages.MISSING_OPERAND.format(getOptionName())); return args[pos+idx]; } public int size() { return args.length-pos; } } private String getOptionName() { return currentOptionHandler.option.toString(); } /** * Parses the command line arguments and set them to the option bean * given in the constructor. * * @param args arguments to parse * * @throws CmdLineException * if there's any error parsing arguments, or if * {@link Option#required() required} option was not given. */ public void parseArgument(final String... args) throws CmdLineException { CmdLineImpl cmdLine = new CmdLineImpl(args); Set<OptionHandler> present = new HashSet<OptionHandler>(); int argIndex = 0; while( cmdLine.hasMore() ) { String arg = cmdLine.getCurrentToken(); if( isOption(arg) ) { boolean isKeyValuePair = arg.indexOf('=')!=-1; // parse this as an option. currentOptionHandler = isKeyValuePair ? findOptionHandler(arg) : findOptionByName(arg); if(currentOptionHandler==null) { // TODO: insert dynamic handler processing throw new CmdLineException(this, Messages.UNDEFINED_OPTION.format(arg)); } // known option; skip its name cmdLine.proceed(1); } else { if (argIndex >= arguments.size()) { Messages msg = arguments.size() == 0 ? Messages.NO_ARGUMENT_ALLOWED : Messages.TOO_MANY_ARGUMENTS; throw new CmdLineException(this, msg.format(arg)); } // known argument currentOptionHandler = arguments.get(argIndex); if (!currentOptionHandler.option.isMultiValued()) argIndex++; } int diff = currentOptionHandler.parseArguments(cmdLine); cmdLine.proceed(diff); present.add(currentOptionHandler); } // make sure that all mandatory options are present for (OptionHandler handler : options) if(handler.option.required() && !present.contains(handler)) throw new CmdLineException(this, Messages.REQUIRED_OPTION_MISSING.format(handler.option.toString())); // make sure that all mandatory arguments are present for (OptionHandler handler : arguments) if(handler.option.required() && !present.contains(handler)) throw new CmdLineException(this, Messages.REQUIRED_ARGUMENT_MISSING.format(handler.option.toString())); } private OptionHandler findOptionHandler(String name) { OptionHandler handler = findOptionByName(name); if (handler==null) { // Have not found by its name, maybe its a property? // Search for parts of the name (=prefix) - most specific first for (int i=name.length(); i>1; i--) { String prefix = name.substring(0, i); Map<String,OptionHandler> possibleHandlers = filter(options, prefix); handler = possibleHandlers.get(prefix); if (handler!=null) return handler; } } return handler; } /** * Finds a registered OptionHandler by its name or its alias. * @param name name * @return the OptionHandler or <tt>null</tt> */ private OptionHandler findOptionByName(String name) { for (OptionHandler h : options) { NamedOptionDef option = (NamedOptionDef)h.option; if (name.equals(option.name())) { return h; } for (String alias : option.aliases()) { if (name.equals(alias)) { return h; } } } return null; } private Map<String,OptionHandler> filter(List<OptionHandler> opt, String keyFilter) { Map<String,OptionHandler> rv = new TreeMap<String,OptionHandler>(); for (OptionHandler h : opt) { if (opt.toString().startsWith(keyFilter)) rv.put(opt.toString(), h); } return rv; } /** * Returns true if the given token is an option * (as opposed to an argument.) */ protected boolean isOption(String arg) { return parsingOptions && arg.startsWith("-"); } /** * All {@link OptionHandler}s known to the {@link CmdLineParser}. * * Constructors of {@link OptionHandler}-derived class keyed by their supported types. */ private static final Map<Class,Constructor<? extends OptionHandler>> handlerClasses = Collections.synchronizedMap(new HashMap<Class,Constructor<? extends OptionHandler>>()); /** * Registers a user-defined {@link OptionHandler} class with args4j. * * <p> * This method allows users to extend the behavior of args4j by writing * their own {@link OptionHandler} implementation. * * @param valueType * The specified handler is used when the field/method annotated by {@link Option} * is of this type. * @param handlerClass * This class must have the constructor that has the same signature as * {@link OptionHandler#OptionHandler(CmdLineParser, OptionDef, Setter)} */ public static void registerHandler( Class valueType, Class<? extends OptionHandler> handlerClass ) { if(valueType==null || handlerClass==null) throw new IllegalArgumentException(); if(!OptionHandler.class.isAssignableFrom(handlerClass)) throw new IllegalArgumentException("Not an OptionHandler class"); Constructor<? extends OptionHandler> c = getConstructor(handlerClass); handlerClasses.put(valueType,c); } private static Constructor<? extends OptionHandler> getConstructor(Class<? extends OptionHandler> handlerClass) { try { return handlerClass.getConstructor(CmdLineParser.class, OptionDef.class, Setter.class); } catch (NoSuchMethodException e) { throw new IllegalArgumentException(handlerClass+" does not have the proper constructor"); } } static { registerHandler(Boolean.class,BooleanOptionHandler.class); registerHandler(boolean.class,BooleanOptionHandler.class); registerHandler(File.class,FileOptionHandler.class); registerHandler(URL.class, URLOptionHandler.class); registerHandler(URI.class, URIOptionHandler.class); registerHandler(Integer.class,IntOptionHandler.class); registerHandler(int.class,IntOptionHandler.class); registerHandler(Double.class, DoubleOptionHandler.class); registerHandler(double.class,DoubleOptionHandler.class); registerHandler(String.class,StringOptionHandler.class); registerHandler(Byte.class, ByteOptionHandler.class); registerHandler(byte.class, ByteOptionHandler.class); registerHandler(Character.class, CharOptionHandler.class); registerHandler(char.class, CharOptionHandler.class); registerHandler(Float.class, FloatOptionHandler.class); registerHandler(float.class, FloatOptionHandler.class); registerHandler(Long.class, LongOptionHandler.class); registerHandler(long.class, LongOptionHandler.class); registerHandler(Short.class, ShortOptionHandler.class); registerHandler(short.class, ShortOptionHandler.class); // enum is a special case registerHandler(Map.class,MapOptionHandler.class); } public void setUsageWidth(int usageWidth) { this.usageWidth = usageWidth; } public void stopOptionParsing() { parsingOptions = false; } /** * Prints a single-line usage to the screen. * * <p> * This is a convenience method for calling {@code printUsage(new OutputStreamWriter(out),null)} * so that you can do {@code printUsage(System.err)}. */ public void printSingleLineUsage(OutputStream out) { printSingleLineUsage(new OutputStreamWriter(out),null); } /** * Prints a single-line usage to the screen. * * @param rb * if this is non-null, {@link Option#usage()} is treated * as a key to obtain the actual message from this resource bundle. */ public void printSingleLineUsage(Writer w, ResourceBundle rb) { PrintWriter pw = new PrintWriter(w); for (OptionHandler h : arguments) { printSingleLineOption(pw, h, rb); } for (OptionHandler h : options) { printSingleLineOption(pw, h, rb); } pw.flush(); } private void printSingleLineOption(PrintWriter pw, OptionHandler h, ResourceBundle rb) { pw.print(' '); if (!h.option.required()) pw.print('['); pw.print(h.getNameAndMeta(rb)); if (h.option.isMultiValued()) { pw.print(" ..."); } if (!h.option.required()) pw.print(']'); } private static final Logger LOGGER = Logger.getLogger(CmdLineParser.class.getName()); }
- removed dupliation. - removed the bean field to make room for multi-bean binding.
args4j/src/org/kohsuke/args4j/CmdLineParser.java
- removed dupliation. - removed the bean field to make room for multi-bean binding.
<ide><path>rgs4j/src/org/kohsuke/args4j/CmdLineParser.java <ide> */ <ide> public class CmdLineParser { <ide> /** <del> * Option bean instance. <del> */ <del> private final Object bean; <del> <del> /** <ide> * Discovered {@link OptionHandler}s for options. <ide> */ <ide> private final List<OptionHandler> options = new ArrayList<OptionHandler>(); <ide> * if the option bean class is using args4j annotations incorrectly. <ide> */ <ide> public CmdLineParser(Object bean) { <del> this.bean = bean; <del> <ide> // Find a metadata parser which will scan the metadata. <ide> MetadataParser parser = null; <ide> Stack<MetadataParser> registeredParsers = (Stack<MetadataParser>) metadataParsers.clone(); <ide> // Parse the metadata and create the setters <ide> parser.parse(bean); <ide> for(Pair pair : parser.getAnnotations()) { <del> Setter setter = null; <add> Setter setter; <ide> if (pair.getMethodOrField() instanceof Method) { <ide> // Annotation is on a method <ide> Method method = (Method) pair.getMethodOrField(); <ide> setter = new MethodSetter(this, bean, method); <del> if (pair.getArgumentOrOption() instanceof Option) { <del> // @Option annotation <del> addOption(setter, (Option) pair.getArgumentOrOption()); <del> } else { <del> // @Argument annotation <del> addArgument(setter, (Argument) pair.getArgumentOrOption()); <del> } <ide> } else { <ide> // Annotation is on a field <ide> Field field = (Field) pair.getMethodOrField(); <del> if (pair.getArgumentOrOption() instanceof Option) { <del> // @Option annotation <del> Option o = (Option) pair.getArgumentOrOption(); <del> addOption(createFieldSetter(field), (Option) pair.getArgumentOrOption()); <del> } else { <del> // @Argument annotation <del> addArgument(createFieldSetter(field), (Argument) pair.getArgumentOrOption()); <del> } <add> setter = createFieldSetter(field,bean); <ide> } <add> if (pair.getArgumentOrOption() instanceof Option) { <add> // @Option annotation <add> addOption(setter, (Option) pair.getArgumentOrOption()); <add> } else { <add> // @Argument annotation <add> addArgument(setter, (Argument) pair.getArgumentOrOption()); <add> } <ide> } <ide> <ide> // for display purposes, we like the arguments in argument order, but the options in alphabetical order <ide> }); <ide> } <ide> <del> private Setter createFieldSetter(Field f) { <add> private Setter createFieldSetter(Field f, Object bean) { <ide> if(List.class.isAssignableFrom(f.getType())) <ide> return new MultiValueFieldSetter(bean,f); <ide> else if(Map.class.isAssignableFrom(f.getType()))
Java
apache-2.0
fffb68f84d4e80cab4ecdcf1fbcc6a24729b43c8
0
MichaelNedzelsky/intellij-community,da1z/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,fitermay/intellij-community,retomerz/intellij-community,tmpgit/intellij-community,holmes/intellij-community,gnuhub/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,akosyakov/intellij-community,Distrotech/intellij-community,suncycheng/intellij-community,FHannes/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,amith01994/intellij-community,fitermay/intellij-community,kool79/intellij-community,amith01994/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,michaelgallacher/intellij-community,lucafavatella/intellij-community,orekyuu/intellij-community,wreckJ/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,signed/intellij-community,alphafoobar/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,izonder/intellij-community,diorcety/intellij-community,ibinti/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,retomerz/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,supersven/intellij-community,MichaelNedzelsky/intellij-community,nicolargo/intellij-community,caot/intellij-community,izonder/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,consulo/consulo,kdwink/intellij-community,semonte/intellij-community,semonte/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,diorcety/intellij-community,apixandru/intellij-community,dslomov/intellij-community,retomerz/intellij-community,ol-loginov/intellij-community,kool79/intellij-community,caot/intellij-community,retomerz/intellij-community,FHannes/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,vvv1559/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,kool79/intellij-community,asedunov/intellij-community,allotria/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,lucafavatella/intellij-community,Distrotech/intellij-community,diorcety/intellij-community,ibinti/intellij-community,salguarnieri/intellij-community,pwoodworth/intellij-community,fnouama/intellij-community,kdwink/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,semonte/intellij-community,consulo/consulo,da1z/intellij-community,da1z/intellij-community,supersven/intellij-community,Lekanich/intellij-community,pwoodworth/intellij-community,semonte/intellij-community,signed/intellij-community,ivan-fedorov/intellij-community,hurricup/intellij-community,samthor/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,da1z/intellij-community,nicolargo/intellij-community,kool79/intellij-community,robovm/robovm-studio,blademainer/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,samthor/intellij-community,adedayo/intellij-community,petteyg/intellij-community,allotria/intellij-community,pwoodworth/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,apixandru/intellij-community,samthor/intellij-community,ivan-fedorov/intellij-community,ftomassetti/intellij-community,ahb0327/intellij-community,ibinti/intellij-community,holmes/intellij-community,hurricup/intellij-community,dslomov/intellij-community,idea4bsd/idea4bsd,wreckJ/intellij-community,ahb0327/intellij-community,consulo/consulo,supersven/intellij-community,clumsy/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,caot/intellij-community,ftomassetti/intellij-community,gnuhub/intellij-community,salguarnieri/intellij-community,clumsy/intellij-community,holmes/intellij-community,supersven/intellij-community,nicolargo/intellij-community,amith01994/intellij-community,signed/intellij-community,nicolargo/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,clumsy/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,ibinti/intellij-community,amith01994/intellij-community,MichaelNedzelsky/intellij-community,slisson/intellij-community,slisson/intellij-community,izonder/intellij-community,apixandru/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,petteyg/intellij-community,izonder/intellij-community,Distrotech/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,kdwink/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,asedunov/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,fitermay/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,slisson/intellij-community,da1z/intellij-community,adedayo/intellij-community,kool79/intellij-community,izonder/intellij-community,hurricup/intellij-community,vladmm/intellij-community,amith01994/intellij-community,ivan-fedorov/intellij-community,wreckJ/intellij-community,fengbaicanhe/intellij-community,allotria/intellij-community,semonte/intellij-community,samthor/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,nicolargo/intellij-community,ibinti/intellij-community,ibinti/intellij-community,holmes/intellij-community,caot/intellij-community,izonder/intellij-community,retomerz/intellij-community,ivan-fedorov/intellij-community,blademainer/intellij-community,slisson/intellij-community,xfournet/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,signed/intellij-community,Distrotech/intellij-community,ftomassetti/intellij-community,diorcety/intellij-community,consulo/consulo,lucafavatella/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,da1z/intellij-community,vladmm/intellij-community,kool79/intellij-community,dslomov/intellij-community,supersven/intellij-community,salguarnieri/intellij-community,lucafavatella/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,mglukhikh/intellij-community,akosyakov/intellij-community,suncycheng/intellij-community,Distrotech/intellij-community,idea4bsd/idea4bsd,idea4bsd/idea4bsd,retomerz/intellij-community,retomerz/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,SerCeMan/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,Lekanich/intellij-community,fitermay/intellij-community,petteyg/intellij-community,holmes/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,youdonghai/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,muntasirsyed/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,diorcety/intellij-community,signed/intellij-community,ftomassetti/intellij-community,suncycheng/intellij-community,SerCeMan/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,SerCeMan/intellij-community,FHannes/intellij-community,ryano144/intellij-community,holmes/intellij-community,Lekanich/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,fnouama/intellij-community,suncycheng/intellij-community,fnouama/intellij-community,kool79/intellij-community,ernestp/consulo,akosyakov/intellij-community,nicolargo/intellij-community,hurricup/intellij-community,nicolargo/intellij-community,retomerz/intellij-community,apixandru/intellij-community,diorcety/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,asedunov/intellij-community,ryano144/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,jagguli/intellij-community,xfournet/intellij-community,da1z/intellij-community,MER-GROUP/intellij-community,MER-GROUP/intellij-community,michaelgallacher/intellij-community,robovm/robovm-studio,xfournet/intellij-community,ol-loginov/intellij-community,blademainer/intellij-community,robovm/robovm-studio,adedayo/intellij-community,FHannes/intellij-community,fnouama/intellij-community,signed/intellij-community,fnouama/intellij-community,wreckJ/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,clumsy/intellij-community,supersven/intellij-community,ibinti/intellij-community,SerCeMan/intellij-community,supersven/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,petteyg/intellij-community,consulo/consulo,hurricup/intellij-community,mglukhikh/intellij-community,diorcety/intellij-community,amith01994/intellij-community,lucafavatella/intellij-community,akosyakov/intellij-community,jagguli/intellij-community,youdonghai/intellij-community,youdonghai/intellij-community,allotria/intellij-community,lucafavatella/intellij-community,vladmm/intellij-community,consulo/consulo,salguarnieri/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,fnouama/intellij-community,tmpgit/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,salguarnieri/intellij-community,vvv1559/intellij-community,gnuhub/intellij-community,izonder/intellij-community,suncycheng/intellij-community,hurricup/intellij-community,hurricup/intellij-community,ftomassetti/intellij-community,MER-GROUP/intellij-community,fitermay/intellij-community,kool79/intellij-community,hurricup/intellij-community,apixandru/intellij-community,fengbaicanhe/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,orekyuu/intellij-community,kdwink/intellij-community,dslomov/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,signed/intellij-community,dslomov/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,MichaelNedzelsky/intellij-community,amith01994/intellij-community,allotria/intellij-community,amith01994/intellij-community,jagguli/intellij-community,apixandru/intellij-community,ryano144/intellij-community,nicolargo/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,kool79/intellij-community,ThiagoGarciaAlves/intellij-community,clumsy/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,semonte/intellij-community,akosyakov/intellij-community,blademainer/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,alphafoobar/intellij-community,caot/intellij-community,akosyakov/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,mglukhikh/intellij-community,SerCeMan/intellij-community,izonder/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,orekyuu/intellij-community,SerCeMan/intellij-community,kool79/intellij-community,michaelgallacher/intellij-community,petteyg/intellij-community,holmes/intellij-community,pwoodworth/intellij-community,ernestp/consulo,fitermay/intellij-community,ol-loginov/intellij-community,TangHao1987/intellij-community,MER-GROUP/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,asedunov/intellij-community,retomerz/intellij-community,ftomassetti/intellij-community,vladmm/intellij-community,ivan-fedorov/intellij-community,caot/intellij-community,MER-GROUP/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,asedunov/intellij-community,ryano144/intellij-community,SerCeMan/intellij-community,vvv1559/intellij-community,orekyuu/intellij-community,vladmm/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,blademainer/intellij-community,supersven/intellij-community,idea4bsd/idea4bsd,tmpgit/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,fnouama/intellij-community,izonder/intellij-community,gnuhub/intellij-community,asedunov/intellij-community,gnuhub/intellij-community,akosyakov/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,hurricup/intellij-community,akosyakov/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,diorcety/intellij-community,salguarnieri/intellij-community,dslomov/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,fnouama/intellij-community,MichaelNedzelsky/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,vvv1559/intellij-community,amith01994/intellij-community,SerCeMan/intellij-community,apixandru/intellij-community,fnouama/intellij-community,asedunov/intellij-community,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,slisson/intellij-community,pwoodworth/intellij-community,vladmm/intellij-community,samthor/intellij-community,jagguli/intellij-community,ahb0327/intellij-community,ThiagoGarciaAlves/intellij-community,apixandru/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,mglukhikh/intellij-community,gnuhub/intellij-community,diorcety/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,wreckJ/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,orekyuu/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,samthor/intellij-community,robovm/robovm-studio,MER-GROUP/intellij-community,pwoodworth/intellij-community,clumsy/intellij-community,hurricup/intellij-community,xfournet/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,slisson/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,ahb0327/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,muntasirsyed/intellij-community,gnuhub/intellij-community,dslomov/intellij-community,fnouama/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,semonte/intellij-community,petteyg/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,slisson/intellij-community,ryano144/intellij-community,robovm/robovm-studio,ivan-fedorov/intellij-community,muntasirsyed/intellij-community,petteyg/intellij-community,SerCeMan/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ahb0327/intellij-community,gnuhub/intellij-community,vvv1559/intellij-community,wreckJ/intellij-community,ryano144/intellij-community,caot/intellij-community,muntasirsyed/intellij-community,slisson/intellij-community,muntasirsyed/intellij-community,ivan-fedorov/intellij-community,asedunov/intellij-community,MER-GROUP/intellij-community,fnouama/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,slisson/intellij-community,youdonghai/intellij-community,retomerz/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,xfournet/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,ol-loginov/intellij-community,Distrotech/intellij-community,orekyuu/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,supersven/intellij-community,orekyuu/intellij-community,salguarnieri/intellij-community,izonder/intellij-community,holmes/intellij-community,signed/intellij-community,ahb0327/intellij-community,tmpgit/intellij-community,semonte/intellij-community,vvv1559/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,fitermay/intellij-community,lucafavatella/intellij-community,tmpgit/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,dslomov/intellij-community,allotria/intellij-community,Distrotech/intellij-community,clumsy/intellij-community,ftomassetti/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,suncycheng/intellij-community,blademainer/intellij-community,dslomov/intellij-community,ivan-fedorov/intellij-community,clumsy/intellij-community,alphafoobar/intellij-community,asedunov/intellij-community,ernestp/consulo,clumsy/intellij-community,caot/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,robovm/robovm-studio,fengbaicanhe/intellij-community,ThiagoGarciaAlves/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,muntasirsyed/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,ahb0327/intellij-community,fengbaicanhe/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,caot/intellij-community,adedayo/intellij-community,da1z/intellij-community,muntasirsyed/intellij-community,lucafavatella/intellij-community,petteyg/intellij-community,adedayo/intellij-community,SerCeMan/intellij-community,akosyakov/intellij-community,mglukhikh/intellij-community,clumsy/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,tmpgit/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,MichaelNedzelsky/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fengbaicanhe/intellij-community,vladmm/intellij-community,orekyuu/intellij-community,blademainer/intellij-community,kool79/intellij-community,ryano144/intellij-community,robovm/robovm-studio,fitermay/intellij-community,adedayo/intellij-community,gnuhub/intellij-community,pwoodworth/intellij-community,blademainer/intellij-community,youdonghai/intellij-community,holmes/intellij-community,hurricup/intellij-community,fengbaicanhe/intellij-community,fitermay/intellij-community,vladmm/intellij-community,xfournet/intellij-community,ryano144/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,michaelgallacher/intellij-community,TangHao1987/intellij-community,blademainer/intellij-community,amith01994/intellij-community,asedunov/intellij-community,nicolargo/intellij-community,Lekanich/intellij-community,diorcety/intellij-community,xfournet/intellij-community,ryano144/intellij-community,slisson/intellij-community,gnuhub/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,ol-loginov/intellij-community,ahb0327/intellij-community,akosyakov/intellij-community,samthor/intellij-community,semonte/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,ftomassetti/intellij-community,da1z/intellij-community,fnouama/intellij-community,asedunov/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,MER-GROUP/intellij-community,ernestp/consulo,Lekanich/intellij-community,allotria/intellij-community,dslomov/intellij-community,TangHao1987/intellij-community,allotria/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,salguarnieri/intellij-community,vladmm/intellij-community,fengbaicanhe/intellij-community,amith01994/intellij-community,kdwink/intellij-community,robovm/robovm-studio,nicolargo/intellij-community,tmpgit/intellij-community,izonder/intellij-community,muntasirsyed/intellij-community,hurricup/intellij-community,jagguli/intellij-community,lucafavatella/intellij-community,adedayo/intellij-community,vladmm/intellij-community,pwoodworth/intellij-community,FHannes/intellij-community,jagguli/intellij-community,wreckJ/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,ryano144/intellij-community,ibinti/intellij-community,slisson/intellij-community,izonder/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,gnuhub/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,Lekanich/intellij-community,kdwink/intellij-community,signed/intellij-community,Distrotech/intellij-community,alphafoobar/intellij-community,caot/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,xfournet/intellij-community,ivan-fedorov/intellij-community,ernestp/consulo,ryano144/intellij-community,FHannes/intellij-community,robovm/robovm-studio,kdwink/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,ernestp/consulo,supersven/intellij-community,da1z/intellij-community,FHannes/intellij-community,tmpgit/intellij-community,ol-loginov/intellij-community,alphafoobar/intellij-community,samthor/intellij-community,clumsy/intellij-community,tmpgit/intellij-community
/* * Copyright 2000-2012 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.codeInsight; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.DefaultJDOMExternalizer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizableStringList; import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.PsiModifierListOwner; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * User: anna * Date: 1/25/11 */ public class NullableNotNullManager implements PersistentStateComponent<Element> { private static final Logger LOG = Logger.getInstance("#" + NullableNotNullManager.class.getName()); public String myDefaultNullable = AnnotationUtil.NULLABLE; public String myDefaultNotNull = AnnotationUtil.NOT_NULL; public final JDOMExternalizableStringList myNullables = new JDOMExternalizableStringList(); public final JDOMExternalizableStringList myNotNulls = new JDOMExternalizableStringList(); public static final String[] DEFAULT_NULLABLES = {AnnotationUtil.NULLABLE, "javax.annotation.Nullable", "edu.umd.cs.findbugs.annotations.Nullable"}; public static final String[] DEFAULT_NOT_NULLS = {AnnotationUtil.NOT_NULL, "javax.annotation.Nonnull", "edu.umd.cs.findbugs.annotations.NonNull"}; public NullableNotNullManager() { Collections.addAll(myNotNulls, DEFAULT_NOT_NULLS); Collections.addAll(myNullables, DEFAULT_NULLABLES); } public static NullableNotNullManager getInstance(Project project) { return ServiceManager.getService(project, NullableNotNullManager.class); } public Collection<String> getAllAnnotations() { final List<String> all = new ArrayList<String>(getNullables()); all.addAll(getNotNulls()); return all; } private static void addAllIfNotPresent(Collection<String> collection, String... annotations) { for (String annotation : annotations) { LOG.assertTrue(annotation != null); if (!collection.contains(annotation)) { collection.add(annotation); } } } public void setNotNulls(String... annotations) { myNotNulls.clear(); addAllIfNotPresent(myNotNulls, DEFAULT_NOT_NULLS); addAllIfNotPresent(myNotNulls, annotations); } public void setNullables(String... annotations) { myNullables.clear(); addAllIfNotPresent(myNullables, DEFAULT_NULLABLES); addAllIfNotPresent(myNullables, annotations); } public String getDefaultNullable() { return myDefaultNullable; } @Nullable public String getNullable(PsiModifierListOwner owner) { for (String nullable : getNullables()) { if (AnnotationUtil.isAnnotated(owner, nullable, false, false)) return nullable; } return null; } public void setDefaultNullable(@NotNull String defaultNullable) { LOG.assertTrue(getNullables().contains(defaultNullable)); myDefaultNullable = defaultNullable; } public String getDefaultNotNull() { return myDefaultNotNull; } @Nullable public String getNotNull(PsiModifierListOwner owner) { for (String notNull : getNotNulls()) { if (AnnotationUtil.isAnnotated(owner, notNull, false, false)) return notNull; } return null; } public void setDefaultNotNull(@NotNull String defaultNotNull) { LOG.assertTrue(getNotNulls().contains(defaultNotNull)); myDefaultNotNull = defaultNotNull; } public boolean isNullable(PsiModifierListOwner owner, boolean checkBases) { return AnnotationUtil.isAnnotated(owner, getNullables(), checkBases, false); } public boolean isNotNull(PsiModifierListOwner owner, boolean checkBases) { return AnnotationUtil.isAnnotated(owner, getNotNulls(), checkBases, false); } public List<String> getNullables() { return myNullables; } public List<String> getNotNulls() { return myNotNulls; } public boolean hasDefaultValues() { if (DEFAULT_NULLABLES.length != getNullables().size() || DEFAULT_NOT_NULLS.length != getNotNulls().size()) { return false; } if (myDefaultNotNull != AnnotationUtil.NOT_NULL || myDefaultNullable != AnnotationUtil.NULLABLE) { return false; } for (int i = 0; i < DEFAULT_NULLABLES.length; i++) { if (!getNullables().get(i).equals(DEFAULT_NULLABLES[i])) { return false; } } for (int i = 0; i < DEFAULT_NOT_NULLS.length; i++) { if (!getNotNulls().get(i).equals(DEFAULT_NOT_NULLS[i])) { return false; } } return true; } @Override public Element getState() { final Element component = new Element("component"); if (hasDefaultValues()) { return component; } try { DefaultJDOMExternalizer.writeExternal(this, component); } catch (WriteExternalException e) { LOG.error(e); } return component; } @Override public void loadState(Element state) { try { DefaultJDOMExternalizer.readExternal(this, state); if (myNullables.isEmpty()) { Collections.addAll(myNullables, DEFAULT_NULLABLES); } if (myNotNulls.isEmpty()) { Collections.addAll(myNotNulls, DEFAULT_NOT_NULLS); } } catch (InvalidDataException e) { LOG.error(e); } } public static boolean isNullable(@NotNull PsiModifierListOwner owner) { return !isNotNull(owner) && getInstance(owner.getProject()).isNullable(owner, true); } public static boolean isNotNull(@NotNull PsiModifierListOwner owner) { return getInstance(owner.getProject()).isNotNull(owner, true); } }
java/java-psi-api/src/com/intellij/codeInsight/NullableNotNullManager.java
/* * Copyright 2000-2012 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.codeInsight; import com.intellij.openapi.components.*; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.DefaultJDOMExternalizer; import com.intellij.openapi.util.InvalidDataException; import com.intellij.openapi.util.JDOMExternalizableStringList; import com.intellij.openapi.util.WriteExternalException; import com.intellij.psi.PsiModifierListOwner; import org.jdom.Element; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * User: anna * Date: 1/25/11 */ public class NullableNotNullManager implements PersistentStateComponent<Element> { private static final Logger LOG = Logger.getInstance("#" + NullableNotNullManager.class.getName()); public String myDefaultNullable = AnnotationUtil.NULLABLE; public String myDefaultNotNull = AnnotationUtil.NOT_NULL; public final JDOMExternalizableStringList myNullables = new JDOMExternalizableStringList(); public final JDOMExternalizableStringList myNotNulls = new JDOMExternalizableStringList(); public static final String[] DEFAULT_NULLABLES = {AnnotationUtil.NULLABLE, "javax.annotation.Nullable", "edu.umd.cs.findbugs.annotations.Nullable"}; public static final String[] DEFAULT_NOT_NULLS = {AnnotationUtil.NOT_NULL, "javax.annotation.Nonnull", "edu.umd.cs.findbugs.annotations.NonNull"}; public static NullableNotNullManager getInstance(Project project) { return ServiceManager.getService(project, NullableNotNullManager.class); } public Collection<String> getAllAnnotations() { final List<String> all = new ArrayList<String>(getNullables()); all.addAll(getNotNulls()); return all; } private static void addAllIfNotPresent(Collection<String> collection, String... annotations) { for (String annotation : annotations) { LOG.assertTrue(annotation != null); if (!collection.contains(annotation)) { collection.add(annotation); } } } public void setNotNulls(String... annotations) { myNotNulls.clear(); addAllIfNotPresent(myNotNulls, DEFAULT_NOT_NULLS); addAllIfNotPresent(myNotNulls, annotations); } public void setNullables(String... annotations) { myNullables.clear(); addAllIfNotPresent(myNullables, DEFAULT_NULLABLES); addAllIfNotPresent(myNullables, annotations); } public String getDefaultNullable() { return myDefaultNullable; } @Nullable public String getNullable(PsiModifierListOwner owner) { for (String nullable : getNullables()) { if (AnnotationUtil.isAnnotated(owner, nullable, false, false)) return nullable; } return null; } public void setDefaultNullable(@NotNull String defaultNullable) { LOG.assertTrue(getNullables().contains(defaultNullable)); myDefaultNullable = defaultNullable; } public String getDefaultNotNull() { return myDefaultNotNull; } @Nullable public String getNotNull(PsiModifierListOwner owner) { for (String notNull : getNotNulls()) { if (AnnotationUtil.isAnnotated(owner, notNull, false, false)) return notNull; } return null; } public void setDefaultNotNull(@NotNull String defaultNotNull) { LOG.assertTrue(getNotNulls().contains(defaultNotNull)); myDefaultNotNull = defaultNotNull; } public boolean isNullable(PsiModifierListOwner owner, boolean checkBases) { return AnnotationUtil.isAnnotated(owner, getNullables(), checkBases, false); } public boolean isNotNull(PsiModifierListOwner owner, boolean checkBases) { return AnnotationUtil.isAnnotated(owner, getNotNulls(), checkBases, false); } public List<String> getNullables() { return myNullables; } public List<String> getNotNulls() { return myNotNulls; } public boolean hasDefaultValues() { if (DEFAULT_NULLABLES.length != getNullables().size() || DEFAULT_NOT_NULLS.length != getNotNulls().size()) { return false; } if (myDefaultNotNull != AnnotationUtil.NOT_NULL || myDefaultNullable != AnnotationUtil.NULLABLE) { return false; } for (int i = 0; i < DEFAULT_NULLABLES.length; i++) { if (!getNullables().get(i).equals(DEFAULT_NULLABLES[i])) { return false; } } for (int i = 0; i < DEFAULT_NOT_NULLS.length; i++) { if (!getNotNulls().get(i).equals(DEFAULT_NOT_NULLS[i])) { return false; } } return true; } @Override public Element getState() { final Element component = new Element("component"); if (hasDefaultValues()) { return component; } try { DefaultJDOMExternalizer.writeExternal(this, component); } catch (WriteExternalException e) { LOG.error(e); } return component; } @Override public void loadState(Element state) { try { DefaultJDOMExternalizer.readExternal(this, state); if (myNullables.isEmpty()) { Collections.addAll(myNullables, DEFAULT_NULLABLES); } if (myNotNulls.isEmpty()) { Collections.addAll(myNotNulls, DEFAULT_NOT_NULLS); } } catch (InvalidDataException e) { LOG.error(e); } } public static boolean isNullable(@NotNull PsiModifierListOwner owner) { return !isNotNull(owner) && getInstance(owner.getProject()).isNullable(owner, true); } public static boolean isNotNull(@NotNull PsiModifierListOwner owner) { return getInstance(owner.getProject()).isNotNull(owner, true); } }
init with default values in case read external was not called
java/java-psi-api/src/com/intellij/codeInsight/NullableNotNullManager.java
init with default values in case read external was not called
<ide><path>ava/java-psi-api/src/com/intellij/codeInsight/NullableNotNullManager.java <ide> <ide> public static final String[] DEFAULT_NULLABLES = {AnnotationUtil.NULLABLE, "javax.annotation.Nullable", "edu.umd.cs.findbugs.annotations.Nullable"}; <ide> public static final String[] DEFAULT_NOT_NULLS = {AnnotationUtil.NOT_NULL, "javax.annotation.Nonnull", "edu.umd.cs.findbugs.annotations.NonNull"}; <add> <add> public NullableNotNullManager() { <add> Collections.addAll(myNotNulls, DEFAULT_NOT_NULLS); <add> Collections.addAll(myNullables, DEFAULT_NULLABLES); <add> } <ide> <ide> public static NullableNotNullManager getInstance(Project project) { <ide> return ServiceManager.getService(project, NullableNotNullManager.class);
Java
agpl-3.0
c5b3bed1f8ef9bdba1a912bae853760cf6e35479
0
imCodePartnerAB/imcms,imCodePartnerAB/imcms,imCodePartnerAB/imcms
package com.imcode.imcms.model; import lombok.NoArgsConstructor; import java.io.Serializable; @NoArgsConstructor public abstract class CategoryType implements Serializable { private static final long serialVersionUID = 6975350692159491957L; protected CategoryType(CategoryType from) { setId(from.getId()); setName(from.getName()); setMultiSelect(from.isMultiSelect()); setInherited(from.isInherited()); } public abstract boolean isMultiSelect(); public abstract void setMultiSelect(boolean multiSelect); public abstract boolean isInherited(); public abstract void setInherited(boolean isInherited); public abstract boolean isImageArchive(); public abstract void setImageArchive(boolean imageArchive); public abstract Integer getId(); public abstract void setId(Integer id); public abstract String getName(); public abstract void setName(String name); }
src/main/java/com/imcode/imcms/model/CategoryType.java
package com.imcode.imcms.model; import lombok.NoArgsConstructor; import java.io.Serializable; @NoArgsConstructor public abstract class CategoryType implements Serializable { private static final long serialVersionUID = 6975350692159491957L; protected CategoryType(CategoryType from) { setId(from.getId()); setName(from.getName()); setMultiSelect(from.isMultiSelect()); } public abstract boolean isMultiSelect(); public abstract void setMultiSelect(boolean multiSelect); public abstract boolean isInherited(); public abstract void setInherited(boolean isInherited); public abstract boolean isImageArchive(); public abstract void setImageArchive(boolean imageArchive); public abstract Integer getId(); public abstract void setId(Integer id); public abstract String getName(); public abstract void setName(String name); }
Issue IMCMS-335: New design to super admin page: categories tab - Improve constructor category type;
src/main/java/com/imcode/imcms/model/CategoryType.java
Issue IMCMS-335: New design to super admin page: categories tab - Improve constructor category type;
<ide><path>rc/main/java/com/imcode/imcms/model/CategoryType.java <ide> setId(from.getId()); <ide> setName(from.getName()); <ide> setMultiSelect(from.isMultiSelect()); <add> setInherited(from.isInherited()); <ide> } <ide> <ide> public abstract boolean isMultiSelect();
Java
agpl-3.0
1470255b45dca7f7add02eb089107af07bf3630f
0
telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus,telefonicaid/fiware-cygnus
/** * Copyright 2014-2017 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-cygnus (FIWARE project). * * fiware-cygnus 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. * fiware-cygnus 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 fiware-cygnus. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es */ package com.telefonica.iot.cygnus.sinks; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import org.apache.flume.Context; import com.telefonica.iot.cygnus.backends.mysql.MySQLBackendImpl; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement; import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration; import com.telefonica.iot.cygnus.errors.CygnusBadContextData; import com.telefonica.iot.cygnus.errors.CygnusCappingError; import com.telefonica.iot.cygnus.errors.CygnusExpiratingError; import com.telefonica.iot.cygnus.errors.CygnusPersistenceError; import com.telefonica.iot.cygnus.errors.CygnusRuntimeError; import com.telefonica.iot.cygnus.interceptors.NGSIEvent; import com.telefonica.iot.cygnus.log.CygnusLogger; import com.telefonica.iot.cygnus.utils.CommonConstants; import com.telefonica.iot.cygnus.utils.CommonUtils; import com.telefonica.iot.cygnus.utils.NGSICharsets; import com.telefonica.iot.cygnus.utils.NGSIConstants; import com.telefonica.iot.cygnus.utils.NGSIUtils; /** * * @author frb * * Detailed documentation can be found at: * https://github.com/telefonicaid/fiware-cygnus/blob/master/doc/flume_extensions_catalogue/ngsi_mysql_sink.md */ public class NGSIMySQLSink extends NGSISink { private static final String DEFAULT_ROW_ATTR_PERSISTENCE = "row"; private static final String DEFAULT_PASSWORD = ""; private static final String DEFAULT_PORT = "3306"; private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_USER_NAME = "root"; private static final int DEFAULT_MAX_POOL_SIZE = 3; private static final String DEFAULT_ATTR_NATIVE_TYPES = "false"; private static final CygnusLogger LOGGER = new CygnusLogger(NGSIMySQLSink.class); private String mysqlHost; private String mysqlPort; private String mysqlUsername; private String mysqlPassword; private int maxPoolSize; private boolean rowAttrPersistence; private MySQLBackendImpl persistenceBackend; private boolean attrNativeTypes; /** * Constructor. */ public NGSIMySQLSink() { super(); } // NGSIMySQLSink /** * Gets the MySQL host. It is protected due to it is only required for testing purposes. * @return The MySQL host */ protected String getMySQLHost() { return mysqlHost; } // getMySQLHost /** * Gets the MySQL port. It is protected due to it is only required for testing purposes. * @return The MySQL port */ protected String getMySQLPort() { return mysqlPort; } // getMySQLPort /** * Gets the MySQL username. It is protected due to it is only required for testing purposes. * @return The MySQL username */ protected String getMySQLUsername() { return mysqlUsername; } // getMySQLUsername /** * Gets the MySQL password. It is protected due to it is only required for testing purposes. * @return The MySQL password */ protected String getMySQLPassword() { return mysqlPassword; } // getMySQLPassword /** * Returns if the attribute persistence is row-based. It is protected due to it is only required for testing * purposes. * @return True if the attribute persistence is row-based, false otherwise */ protected boolean getRowAttrPersistence() { return rowAttrPersistence; } // getRowAttrPersistence /** * Returns the persistence backend. It is protected due to it is only required for testing purposes. * @return The persistence backend */ protected MySQLBackendImpl getPersistenceBackend() { return persistenceBackend; } // getPersistenceBackend /** * Sets the persistence backend. It is protected due to it is only required for testing purposes. * @param persistenceBackend */ protected void setPersistenceBackend(MySQLBackendImpl persistenceBackend) { this.persistenceBackend = persistenceBackend; } // setPersistenceBackend /** * Returns if the attribute value will be native or stringfy. It will be stringfy due to backward compatibility * purposes. * @return True if the attribute value will be native, false otherwise */ protected boolean getNativeAttrTypes() { return attrNativeTypes; } // attrNativeTypes @Override public void configure(Context context) { mysqlHost = context.getString("mysql_host", DEFAULT_HOST); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_host=" + mysqlHost + ")"); mysqlPort = context.getString("mysql_port", DEFAULT_PORT); int intPort = Integer.parseInt(mysqlPort); if ((intPort <= 0) || (intPort > 65535)) { invalidConfiguration = true; LOGGER.warn("[" + this.getName() + "] Invalid configuration (mysql_port=" + mysqlPort + ") " + "must be between 0 and 65535"); } else { LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_port=" + mysqlPort + ")"); } // if else mysqlUsername = context.getString("mysql_username", DEFAULT_USER_NAME); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_username=" + mysqlUsername + ")"); // FIXME: mysqlPassword should be read encrypted and decoded here mysqlPassword = context.getString("mysql_password", DEFAULT_PASSWORD); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_password=" + mysqlPassword + ")"); maxPoolSize = context.getInteger("mysql_maxPoolSize", DEFAULT_MAX_POOL_SIZE); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_maxPoolSize=" + maxPoolSize + ")"); rowAttrPersistence = context.getString("attr_persistence", DEFAULT_ROW_ATTR_PERSISTENCE).equals("row"); String persistence = context.getString("attr_persistence", DEFAULT_ROW_ATTR_PERSISTENCE); if (persistence.equals("row") || persistence.equals("column")) { LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_persistence=" + persistence + ")"); } else { invalidConfiguration = true; LOGGER.warn("[" + this.getName() + "] Invalid configuration (attr_persistence=" + persistence + ") must be 'row' or 'column'"); } // if else String attrNativeTypesStr = context.getString("attr_native_types", DEFAULT_ATTR_NATIVE_TYPES); if (attrNativeTypesStr.equals("true") || attrNativeTypesStr.equals("false")) { attrNativeTypes = Boolean.valueOf(attrNativeTypesStr); LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_native_types=" + attrNativeTypesStr + ")"); } else { invalidConfiguration = true; LOGGER.debug("[" + this.getName() + "] Invalid configuration (attr_native_types=" + attrNativeTypesStr + ") -- Must be 'true' or 'false'"); } // if else super.configure(context); } // configure @Override public void start() { try { persistenceBackend = new MySQLBackendImpl(mysqlHost, mysqlPort, mysqlUsername, mysqlPassword, maxPoolSize); LOGGER.debug("[" + this.getName() + "] MySQL persistence backend created"); } catch (Exception e) { LOGGER.error("Error while creating the MySQL persistence backend. Details=" + e.getMessage()); } // try catch super.start(); } // start @Override public void stop() { super.stop(); if (persistenceBackend != null) persistenceBackend.close(); } // stop @Override void persistBatch(NGSIBatch batch) throws CygnusBadConfiguration, CygnusPersistenceError, CygnusRuntimeError, CygnusBadContextData { if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // if // Iterate on the destinations batch.startIterator(); while (batch.hasNext()) { String destination = batch.getNextDestination(); LOGGER.debug("[" + this.getName() + "] Processing sub-batch regarding the " + destination + " destination"); // Get the events within the current sub-batch ArrayList<NGSIEvent> events = batch.getNextEvents(); // Get an aggregator for this destination and initialize it MySQLAggregator aggregator = getAggregator(rowAttrPersistence); aggregator.initialize(events.get(0)); for (NGSIEvent event : events) { aggregator.aggregate(event); } // for // Persist the aggregation persistAggregation(aggregator); batch.setNextPersisted(true); } // for } // persistBatch @Override public void capRecords(NGSIBatch batch, long maxRecords) throws CygnusCappingError { if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // if // Iterate on the destinations batch.startIterator(); while (batch.hasNext()) { // Get the events within the current sub-batch ArrayList<NGSIEvent> events = batch.getNextEvents(); // Get a representative from the current destination sub-batch NGSIEvent event = events.get(0); // Do the capping String service = event.getServiceForNaming(enableNameMappings); String servicePathForNaming = event.getServicePathForNaming(enableGrouping, enableNameMappings); String entity = event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding); String entityType = event.getEntityTypeForNaming(enableGrouping, enableNameMappings); String attribute = event.getAttributeForNaming(enableNameMappings); try { String dbName = buildDbName(service); String tableName = buildTableName(servicePathForNaming, entity, entityType, attribute); LOGGER.debug("[" + this.getName() + "] Capping resource (maxRecords=" + maxRecords + ",dbName=" + dbName + ", tableName=" + tableName + ")"); persistenceBackend.capRecords(dbName, tableName, maxRecords); } catch (CygnusBadConfiguration e) { throw new CygnusCappingError("Data capping error", "CygnusBadConfiguration", e.getMessage()); } catch (CygnusRuntimeError e) { throw new CygnusCappingError("Data capping error", "CygnusRuntimeError", e.getMessage()); } catch (CygnusPersistenceError e) { throw new CygnusCappingError("Data capping error", "CygnusPersistenceError", e.getMessage()); } // try catch } // while } // capRecords @Override public void expirateRecords(long expirationTime) throws CygnusExpiratingError { LOGGER.debug("[" + this.getName() + "] Expirating records (time=" + expirationTime + ")"); try { persistenceBackend.expirateRecordsCache(expirationTime); } catch (CygnusRuntimeError e) { throw new CygnusExpiratingError("Data expiration error", "CygnusRuntimeError", e.getMessage()); } catch (CygnusPersistenceError e) { throw new CygnusExpiratingError("Data expiration error", "CygnusPersistenceError", e.getMessage()); } // try catch } // expirateRecords /** * Class for aggregating. */ private abstract class MySQLAggregator { // object containing the aggregted data private LinkedHashMap<String, ArrayList<String>> aggregation; private String service; private String servicePathForData; private String servicePathForNaming; private String entityForNaming; private String entityType; private String attribute; private String dbName; private String tableName; MySQLAggregator() { aggregation = new LinkedHashMap<>(); } // MySQLAggregator protected LinkedHashMap<String, ArrayList<String>> getAggregation() { return aggregation; } //getAggregation @SuppressWarnings("unused") protected void setAggregation(LinkedHashMap<String, ArrayList<String>> aggregation) { this.aggregation = aggregation; } //setAggregation @SuppressWarnings("unused") protected String getService() { return service; } //getService @SuppressWarnings("unused") protected void setService(String service) { this.service = service; } //setService protected String getServicePathForData() { return servicePathForData; } //getServicePathForData @SuppressWarnings("unused") protected void setServicePathForData(String servicePathForData) { this.servicePathForData = servicePathForData; } //setServicePathForData @SuppressWarnings("unused") protected String getServicePathForNaming() { return servicePathForNaming; } //getServicePathForNaming @SuppressWarnings("unused") protected void setServicePathForNaming(String servicePathForNaming) { this.servicePathForNaming = servicePathForNaming; } //setServicePathForNaming @SuppressWarnings("unused") protected String getTableName() { return tableName; } //getTableName @SuppressWarnings("unused") protected void setTableName(String tableName) { this.tableName = tableName; } //setTableName public String getDbName(boolean enableLowercase) { if (enableLowercase) { return dbName.toLowerCase(); } else { return dbName; } // if else } // getDbName public String getTableName(boolean enableLowercase) { if (enableLowercase) { return tableName.toLowerCase(); } else { return tableName; } // if else } // getTableName public String getValuesForInsert() { String valuesForInsert = ""; int numEvents = aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).size(); for (int i = 0; i < numEvents; i++) { if (i == 0) { valuesForInsert += "("; } else { valuesForInsert += ",("; } // if else boolean first = true; Iterator<String> it = aggregation.keySet().iterator(); while (it.hasNext()) { ArrayList<String> values = (ArrayList<String>) aggregation.get((String) it.next()); String value = values.get(i); if (attrNativeTypes) { if (value == null) { // TBD check also if value == "" ? value = "NULL"; } else { String valueType = (String) it.next(); if ( (valueType != null) && (!valueType.equals("Number")) ) { value = "'" + value + "'"; } else { value = "" + value + ""; // redundant ? } LOGGER.debug("[" + getName() + "] value type = " + valueType ); } LOGGER.debug("[" + getName() + "] native value = " + value ); } else { value = "'" + value + "'"; } if (first) { valuesForInsert += value; first = false; } else { valuesForInsert += "," + value; } // if else } // while valuesForInsert += ")"; } // for return valuesForInsert; } // getValuesForInsert public String getFieldsForCreate() { String fieldsForCreate = "("; boolean first = true; Iterator<String> it = aggregation.keySet().iterator(); while (it.hasNext()) { if (first) { fieldsForCreate += (String) it.next() + " text"; first = false; } else { fieldsForCreate += "," + (String) it.next() + " text"; } // if else } // while return fieldsForCreate + ")"; } // getFieldsForCreate public String getFieldsForInsert() { String fieldsForInsert = "("; boolean first = true; Iterator<String> it = aggregation.keySet().iterator(); while (it.hasNext()) { if (first) { fieldsForInsert += (String) it.next(); first = false; } else { fieldsForInsert += "," + (String) it.next(); } // if else } // while return fieldsForInsert + ")"; } // getFieldsForInsert public void initialize(NGSIEvent event) throws CygnusBadConfiguration { service = event.getServiceForNaming(enableNameMappings); servicePathForData = event.getServicePathForData(); servicePathForNaming = event.getServicePathForNaming(enableGrouping, enableNameMappings); entityForNaming = event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding); entityType = event.getEntityTypeForNaming(enableGrouping, enableNameMappings); attribute = event.getAttributeForNaming(enableNameMappings); dbName = buildDbName(service); tableName = buildTableName(servicePathForNaming, entityForNaming, entityType, attribute); } // initialize public abstract void aggregate(NGSIEvent cygnusEvent); } // MySQLAggregator /** * Class for aggregating batches in row mode. */ private class RowAggregator extends MySQLAggregator { @Override public void initialize(NGSIEvent cygnusEvent) throws CygnusBadConfiguration { super.initialize(cygnusEvent); LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.put(NGSIConstants.RECV_TIME_TS, new ArrayList<String>()); aggregation.put(NGSIConstants.RECV_TIME, new ArrayList<String>()); aggregation.put(NGSIConstants.FIWARE_SERVICE_PATH, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_ID, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_TYPE, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_NAME, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_TYPE, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_VALUE, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_MD, new ArrayList<String>()); } // initialize @Override public void aggregate(NGSIEvent event) { // get the getRecvTimeTs headers long recvTimeTs = event.getRecvTimeTs(); String recvTime = CommonUtils.getHumanReadable(recvTimeTs, false); // get the getRecvTimeTs body ContextElement contextElement = event.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // aggregate the attribute information LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.get(NGSIConstants.RECV_TIME_TS).add(Long.toString(recvTimeTs)); aggregation.get(NGSIConstants.RECV_TIME).add(recvTime); aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).add(getServicePathForData()); aggregation.get(NGSIConstants.ENTITY_ID).add(entityId); aggregation.get(NGSIConstants.ENTITY_TYPE).add(entityType); aggregation.get(NGSIConstants.ATTR_NAME).add(attrName); aggregation.get(NGSIConstants.ATTR_TYPE).add(attrType); aggregation.get(NGSIConstants.ATTR_VALUE).add(attrValue); aggregation.get(NGSIConstants.ATTR_MD).add(attrMetadata); } // for } // aggregate } // RowAggregator /** * Class for aggregating batches in column mode. */ private class ColumnAggregator extends MySQLAggregator { @Override public void initialize(NGSIEvent cygnusEvent) throws CygnusBadConfiguration { super.initialize(cygnusEvent); // particular initialization LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.put(NGSIConstants.RECV_TIME, new ArrayList<String>()); aggregation.put(NGSIConstants.FIWARE_SERVICE_PATH, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_ID, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_TYPE, new ArrayList<String>()); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); aggregation.put(attrName, new ArrayList<String>()); aggregation.put(attrName + "_md", new ArrayList<String>()); } // for } // initialize @Override public void aggregate(NGSIEvent event) { // Number of previous values int numPreviousValues = getAggregation().get(NGSIConstants.FIWARE_SERVICE_PATH).size(); // Get the event headers long recvTimeTs = event.getRecvTimeTs(); String recvTime = CommonUtils.getHumanReadable(recvTimeTs, false); // get the event body ContextElement contextElement = event.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // Iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.get(NGSIConstants.RECV_TIME).add(recvTime); aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).add(getServicePathForData()); aggregation.get(NGSIConstants.ENTITY_ID).add(entityId); aggregation.get(NGSIConstants.ENTITY_TYPE).add(entityType); for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // Check if the attribute already exists in the form of 2 columns (one for metadata); if not existing, // add an empty value for all previous rows if (aggregation.containsKey(attrName)) { aggregation.get(attrName).add(attrValue); aggregation.get(attrName + "_md").add(attrMetadata); } else { ArrayList<String> values = new ArrayList<>(Collections.nCopies(numPreviousValues, "")); values.add(attrValue); aggregation.put(attrName, values); ArrayList<String> valuesMd = new ArrayList<>(Collections.nCopies(numPreviousValues, "")); valuesMd.add(attrMetadata); aggregation.put(attrName + "_md", valuesMd); } // if else } // for // Iterate on all the aggregations, checking for not updated attributes; add an empty value if missing for (String key : aggregation.keySet()) { ArrayList<String> values = aggregation.get(key); if (values.size() == numPreviousValues) { values.add(""); } // if } // for } // aggregate } // ColumnAggregator private MySQLAggregator getAggregator(boolean rowAttrPersistence) { if (rowAttrPersistence) { return new RowAggregator(); } else { return new ColumnAggregator(); } // if else } // getAggregator private void persistAggregation(MySQLAggregator aggregator) throws CygnusPersistenceError, CygnusRuntimeError, CygnusBadContextData { String fieldsForCreate = aggregator.getFieldsForCreate(); String fieldsForInsert = aggregator.getFieldsForInsert(); String valuesForInsert = aggregator.getValuesForInsert(); String dbName = aggregator.getDbName(enableLowercase); String tableName = aggregator.getTableName(enableLowercase); LOGGER.info("[" + this.getName() + "] Persisting data at NGSIMySQLSink. Database (" + dbName + "), Table (" + tableName + "), Fields (" + fieldsForInsert + "), Values (" + valuesForInsert + ")"); // creating the database and the table has only sense if working in row mode, in column node // everything must be provisioned in advance if (aggregator instanceof RowAggregator) { persistenceBackend.createDatabase(dbName); persistenceBackend.createTable(dbName, tableName, fieldsForCreate); } // if if (valuesForInsert.equals("")) { LOGGER.debug("[" + this.getName() + "] no values for insert"); } else { persistenceBackend.insertContextData(dbName, tableName, fieldsForInsert, valuesForInsert); } } // persistAggregation /** * Creates a MySQL DB name given the FIWARE service. * @param service * @return The MySQL DB name * @throws CygnusBadConfiguration */ protected String buildDbName(String service) throws CygnusBadConfiguration { String name; if (enableEncoding) { name = NGSICharsets.encodeMySQL(service); } else { name = NGSIUtils.encode(service, false, true); } // if else if (name.length() > NGSIConstants.MYSQL_MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building database name '" + name + "' and its length is greater than " + NGSIConstants.MYSQL_MAX_NAME_LEN); } // if return name; } // buildDbName /** * Creates a MySQL table name given the FIWARE service path, the entity and the attribute. * @param servicePath * @param entity * @param attribute * @return The MySQL table name * @throws CygnusBadConfiguration */ protected String buildTableName(String servicePath, String entity, String entityType, String attribute) throws CygnusBadConfiguration { String name; if (enableEncoding) { switch (dataModel) { case DMBYSERVICEPATH: name = NGSICharsets.encodeMySQL(servicePath); break; case DMBYENTITY: name = NGSICharsets.encodeMySQL(servicePath) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(entity); break; case DMBYENTITYTYPE: name = NGSICharsets.encodeMySQL(servicePath) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(entityType); break; case DMBYATTRIBUTE: name = NGSICharsets.encodeMySQL(servicePath) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(entity) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(attribute); break; default: throw new CygnusBadConfiguration("Unknown data model '" + dataModel.toString() + "'. Please, use dm-by-service-path, dm-by-entity or dm-by-attribute"); } // switch } else { switch (dataModel) { case DMBYSERVICEPATH: if (servicePath.equals("/")) { throw new CygnusBadConfiguration("Default service path '/' cannot be used with " + "dm-by-service-path data model"); } // if name = NGSIUtils.encode(servicePath, true, false); break; case DMBYENTITY: String truncatedServicePath = NGSIUtils.encode(servicePath, true, false); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encode(entity, false, true); break; case DMBYENTITYTYPE: truncatedServicePath = NGSIUtils.encode(servicePath, true, false); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encode(entityType, false, true); break; case DMBYATTRIBUTE: truncatedServicePath = NGSIUtils.encode(servicePath, true, false); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encode(entity, false, true) + '_' + NGSIUtils.encode(attribute, false, true); break; default: throw new CygnusBadConfiguration("Unknown data model '" + dataModel.toString() + "'. Please, use DMBYSERVICEPATH, DMBYENTITY, DMBYENTITYTYPE or DMBYATTRIBUTE"); } // switch } // if else if (name.length() > NGSIConstants.MYSQL_MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building table name '" + name + "' and its length is greater than " + NGSIConstants.MYSQL_MAX_NAME_LEN); } // if return name; } // buildTableName } // NGSIMySQLSink
cygnus-ngsi/src/main/java/com/telefonica/iot/cygnus/sinks/NGSIMySQLSink.java
/** * Copyright 2014-2017 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-cygnus (FIWARE project). * * fiware-cygnus 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. * fiware-cygnus 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 fiware-cygnus. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with iot_support at tid dot es */ package com.telefonica.iot.cygnus.sinks; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import org.apache.flume.Context; import com.telefonica.iot.cygnus.backends.mysql.MySQLBackendImpl; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextAttribute; import com.telefonica.iot.cygnus.containers.NotifyContextRequest.ContextElement; import com.telefonica.iot.cygnus.errors.CygnusBadConfiguration; import com.telefonica.iot.cygnus.errors.CygnusBadContextData; import com.telefonica.iot.cygnus.errors.CygnusCappingError; import com.telefonica.iot.cygnus.errors.CygnusExpiratingError; import com.telefonica.iot.cygnus.errors.CygnusPersistenceError; import com.telefonica.iot.cygnus.errors.CygnusRuntimeError; import com.telefonica.iot.cygnus.interceptors.NGSIEvent; import com.telefonica.iot.cygnus.log.CygnusLogger; import com.telefonica.iot.cygnus.utils.CommonConstants; import com.telefonica.iot.cygnus.utils.CommonUtils; import com.telefonica.iot.cygnus.utils.NGSICharsets; import com.telefonica.iot.cygnus.utils.NGSIConstants; import com.telefonica.iot.cygnus.utils.NGSIUtils; /** * * @author frb * * Detailed documentation can be found at: * https://github.com/telefonicaid/fiware-cygnus/blob/master/doc/flume_extensions_catalogue/ngsi_mysql_sink.md */ public class NGSIMySQLSink extends NGSISink { private static final String DEFAULT_ROW_ATTR_PERSISTENCE = "row"; private static final String DEFAULT_PASSWORD = ""; private static final String DEFAULT_PORT = "3306"; private static final String DEFAULT_HOST = "localhost"; private static final String DEFAULT_USER_NAME = "root"; private static final int DEFAULT_MAX_POOL_SIZE = 3; private static final String DEFAULT_ATTR_NATIVE_TYPES = "false"; private static final CygnusLogger LOGGER = new CygnusLogger(NGSIMySQLSink.class); private String mysqlHost; private String mysqlPort; private String mysqlUsername; private String mysqlPassword; private int maxPoolSize; private boolean rowAttrPersistence; private MySQLBackendImpl persistenceBackend; private boolean attrNativeTypes; /** * Constructor. */ public NGSIMySQLSink() { super(); } // NGSIMySQLSink /** * Gets the MySQL host. It is protected due to it is only required for testing purposes. * @return The MySQL host */ protected String getMySQLHost() { return mysqlHost; } // getMySQLHost /** * Gets the MySQL port. It is protected due to it is only required for testing purposes. * @return The MySQL port */ protected String getMySQLPort() { return mysqlPort; } // getMySQLPort /** * Gets the MySQL username. It is protected due to it is only required for testing purposes. * @return The MySQL username */ protected String getMySQLUsername() { return mysqlUsername; } // getMySQLUsername /** * Gets the MySQL password. It is protected due to it is only required for testing purposes. * @return The MySQL password */ protected String getMySQLPassword() { return mysqlPassword; } // getMySQLPassword /** * Returns if the attribute persistence is row-based. It is protected due to it is only required for testing * purposes. * @return True if the attribute persistence is row-based, false otherwise */ protected boolean getRowAttrPersistence() { return rowAttrPersistence; } // getRowAttrPersistence /** * Returns the persistence backend. It is protected due to it is only required for testing purposes. * @return The persistence backend */ protected MySQLBackendImpl getPersistenceBackend() { return persistenceBackend; } // getPersistenceBackend /** * Sets the persistence backend. It is protected due to it is only required for testing purposes. * @param persistenceBackend */ protected void setPersistenceBackend(MySQLBackendImpl persistenceBackend) { this.persistenceBackend = persistenceBackend; } // setPersistenceBackend /** * Returns if the attribute value will be native or stringfy. It will be stringfy due to backward compatibility * purposes. * @return True if the attribute value will be native, false otherwise */ protected boolean getNativeAttrTypes() { return attrNativeTypes; } // attrNativeTypes @Override public void configure(Context context) { mysqlHost = context.getString("mysql_host", DEFAULT_HOST); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_host=" + mysqlHost + ")"); mysqlPort = context.getString("mysql_port", DEFAULT_PORT); int intPort = Integer.parseInt(mysqlPort); if ((intPort <= 0) || (intPort > 65535)) { invalidConfiguration = true; LOGGER.warn("[" + this.getName() + "] Invalid configuration (mysql_port=" + mysqlPort + ") " + "must be between 0 and 65535"); } else { LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_port=" + mysqlPort + ")"); } // if else mysqlUsername = context.getString("mysql_username", DEFAULT_USER_NAME); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_username=" + mysqlUsername + ")"); // FIXME: mysqlPassword should be read encrypted and decoded here mysqlPassword = context.getString("mysql_password", DEFAULT_PASSWORD); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_password=" + mysqlPassword + ")"); maxPoolSize = context.getInteger("mysql_maxPoolSize", DEFAULT_MAX_POOL_SIZE); LOGGER.debug("[" + this.getName() + "] Reading configuration (mysql_maxPoolSize=" + maxPoolSize + ")"); rowAttrPersistence = context.getString("attr_persistence", DEFAULT_ROW_ATTR_PERSISTENCE).equals("row"); String persistence = context.getString("attr_persistence", DEFAULT_ROW_ATTR_PERSISTENCE); if (persistence.equals("row") || persistence.equals("column")) { LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_persistence=" + persistence + ")"); } else { invalidConfiguration = true; LOGGER.warn("[" + this.getName() + "] Invalid configuration (attr_persistence=" + persistence + ") must be 'row' or 'column'"); } // if else String attrNativeTypesStr = context.getString("attr_native_types", DEFAULT_ATTR_NATIVE_TYPES); if (attrNativeTypesStr.equals("true") || attrNativeTypesStr.equals("false")) { attrNativeTypes = Boolean.valueOf(attrNativeTypesStr); LOGGER.debug("[" + this.getName() + "] Reading configuration (attr_native_types=" + attrNativeTypesStr + ")"); } else { invalidConfiguration = true; LOGGER.debug("[" + this.getName() + "] Invalid configuration (attr_native_types=" + attrNativeTypesStr + ") -- Must be 'true' or 'false'"); } // if else super.configure(context); } // configure @Override public void start() { try { persistenceBackend = new MySQLBackendImpl(mysqlHost, mysqlPort, mysqlUsername, mysqlPassword, maxPoolSize); LOGGER.debug("[" + this.getName() + "] MySQL persistence backend created"); } catch (Exception e) { LOGGER.error("Error while creating the MySQL persistence backend. Details=" + e.getMessage()); } // try catch super.start(); } // start @Override public void stop() { super.stop(); if (persistenceBackend != null) persistenceBackend.close(); } // stop @Override void persistBatch(NGSIBatch batch) throws CygnusBadConfiguration, CygnusPersistenceError, CygnusRuntimeError, CygnusBadContextData { if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // if // Iterate on the destinations batch.startIterator(); while (batch.hasNext()) { String destination = batch.getNextDestination(); LOGGER.debug("[" + this.getName() + "] Processing sub-batch regarding the " + destination + " destination"); // Get the events within the current sub-batch ArrayList<NGSIEvent> events = batch.getNextEvents(); // Get an aggregator for this destination and initialize it MySQLAggregator aggregator = getAggregator(rowAttrPersistence); aggregator.initialize(events.get(0)); for (NGSIEvent event : events) { aggregator.aggregate(event); } // for // Persist the aggregation persistAggregation(aggregator); batch.setNextPersisted(true); } // for } // persistBatch @Override public void capRecords(NGSIBatch batch, long maxRecords) throws CygnusCappingError { if (batch == null) { LOGGER.debug("[" + this.getName() + "] Null batch, nothing to do"); return; } // if // Iterate on the destinations batch.startIterator(); while (batch.hasNext()) { // Get the events within the current sub-batch ArrayList<NGSIEvent> events = batch.getNextEvents(); // Get a representative from the current destination sub-batch NGSIEvent event = events.get(0); // Do the capping String service = event.getServiceForNaming(enableNameMappings); String servicePathForNaming = event.getServicePathForNaming(enableGrouping, enableNameMappings); String entity = event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding); String entityType = event.getEntityTypeForNaming(enableGrouping, enableNameMappings); String attribute = event.getAttributeForNaming(enableNameMappings); try { String dbName = buildDbName(service); String tableName = buildTableName(servicePathForNaming, entity, entityType, attribute); LOGGER.debug("[" + this.getName() + "] Capping resource (maxRecords=" + maxRecords + ",dbName=" + dbName + ", tableName=" + tableName + ")"); persistenceBackend.capRecords(dbName, tableName, maxRecords); } catch (CygnusBadConfiguration e) { throw new CygnusCappingError("Data capping error", "CygnusBadConfiguration", e.getMessage()); } catch (CygnusRuntimeError e) { throw new CygnusCappingError("Data capping error", "CygnusRuntimeError", e.getMessage()); } catch (CygnusPersistenceError e) { throw new CygnusCappingError("Data capping error", "CygnusPersistenceError", e.getMessage()); } // try catch } // while } // capRecords @Override public void expirateRecords(long expirationTime) throws CygnusExpiratingError { LOGGER.debug("[" + this.getName() + "] Expirating records (time=" + expirationTime + ")"); try { persistenceBackend.expirateRecordsCache(expirationTime); } catch (CygnusRuntimeError e) { throw new CygnusExpiratingError("Data expiration error", "CygnusRuntimeError", e.getMessage()); } catch (CygnusPersistenceError e) { throw new CygnusExpiratingError("Data expiration error", "CygnusPersistenceError", e.getMessage()); } // try catch } // expirateRecords /** * Class for aggregating. */ private abstract class MySQLAggregator { // object containing the aggregted data private LinkedHashMap<String, ArrayList<String>> aggregation; private String service; private String servicePathForData; private String servicePathForNaming; private String entityForNaming; private String entityType; private String attribute; private String dbName; private String tableName; MySQLAggregator() { aggregation = new LinkedHashMap<>(); } // MySQLAggregator protected LinkedHashMap<String, ArrayList<String>> getAggregation() { return aggregation; } //getAggregation @SuppressWarnings("unused") protected void setAggregation(LinkedHashMap<String, ArrayList<String>> aggregation) { this.aggregation = aggregation; } //setAggregation @SuppressWarnings("unused") protected String getService() { return service; } //getService @SuppressWarnings("unused") protected void setService(String service) { this.service = service; } //setService protected String getServicePathForData() { return servicePathForData; } //getServicePathForData @SuppressWarnings("unused") protected void setServicePathForData(String servicePathForData) { this.servicePathForData = servicePathForData; } //setServicePathForData @SuppressWarnings("unused") protected String getServicePathForNaming() { return servicePathForNaming; } //getServicePathForNaming @SuppressWarnings("unused") protected void setServicePathForNaming(String servicePathForNaming) { this.servicePathForNaming = servicePathForNaming; } //setServicePathForNaming @SuppressWarnings("unused") protected String getTableName() { return tableName; } //getTableName @SuppressWarnings("unused") protected void setTableName(String tableName) { this.tableName = tableName; } //setTableName public String getDbName(boolean enableLowercase) { if (enableLowercase) { return dbName.toLowerCase(); } else { return dbName; } // if else } // getDbName public String getTableName(boolean enableLowercase) { if (enableLowercase) { return tableName.toLowerCase(); } else { return tableName; } // if else } // getTableName public String getValuesForInsert() { String valuesForInsert = ""; int numEvents = aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).size(); for (int i = 0; i < numEvents; i++) { if (i == 0) { valuesForInsert += "("; } else { valuesForInsert += ",("; } // if else boolean first = true; Iterator<String> it = aggregation.keySet().iterator(); while (it.hasNext()) { ArrayList<String> values = (ArrayList<String>) aggregation.get((String) it.next()); String value = values.get(i); if (attrNativeTypes) { if (value == null) { // TBD check also if value == "" ? value = "NULL"; } else { String valueType = (String) it.next(); if ( (valueType != null) && (!valueType.equals("Number")) ) { value = "'" + value + "'"; } else { value = "" + value + ""; // redundant ? } LOGGER.debug("[" getName() + "] value type = " + valueType ); } LOGGER.debug("[" getName() + "] native value = " + value ); } else { value = "'" + value + "'"; } if (first) { valuesForInsert += value; first = false; } else { valuesForInsert += "," + value; } // if else } // while valuesForInsert += ")"; } // for return valuesForInsert; } // getValuesForInsert public String getFieldsForCreate() { String fieldsForCreate = "("; boolean first = true; Iterator<String> it = aggregation.keySet().iterator(); while (it.hasNext()) { if (first) { fieldsForCreate += (String) it.next() + " text"; first = false; } else { fieldsForCreate += "," + (String) it.next() + " text"; } // if else } // while return fieldsForCreate + ")"; } // getFieldsForCreate public String getFieldsForInsert() { String fieldsForInsert = "("; boolean first = true; Iterator<String> it = aggregation.keySet().iterator(); while (it.hasNext()) { if (first) { fieldsForInsert += (String) it.next(); first = false; } else { fieldsForInsert += "," + (String) it.next(); } // if else } // while return fieldsForInsert + ")"; } // getFieldsForInsert public void initialize(NGSIEvent event) throws CygnusBadConfiguration { service = event.getServiceForNaming(enableNameMappings); servicePathForData = event.getServicePathForData(); servicePathForNaming = event.getServicePathForNaming(enableGrouping, enableNameMappings); entityForNaming = event.getEntityForNaming(enableGrouping, enableNameMappings, enableEncoding); entityType = event.getEntityTypeForNaming(enableGrouping, enableNameMappings); attribute = event.getAttributeForNaming(enableNameMappings); dbName = buildDbName(service); tableName = buildTableName(servicePathForNaming, entityForNaming, entityType, attribute); } // initialize public abstract void aggregate(NGSIEvent cygnusEvent); } // MySQLAggregator /** * Class for aggregating batches in row mode. */ private class RowAggregator extends MySQLAggregator { @Override public void initialize(NGSIEvent cygnusEvent) throws CygnusBadConfiguration { super.initialize(cygnusEvent); LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.put(NGSIConstants.RECV_TIME_TS, new ArrayList<String>()); aggregation.put(NGSIConstants.RECV_TIME, new ArrayList<String>()); aggregation.put(NGSIConstants.FIWARE_SERVICE_PATH, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_ID, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_TYPE, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_NAME, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_TYPE, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_VALUE, new ArrayList<String>()); aggregation.put(NGSIConstants.ATTR_MD, new ArrayList<String>()); } // initialize @Override public void aggregate(NGSIEvent event) { // get the getRecvTimeTs headers long recvTimeTs = event.getRecvTimeTs(); String recvTime = CommonUtils.getHumanReadable(recvTimeTs, false); // get the getRecvTimeTs body ContextElement contextElement = event.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // aggregate the attribute information LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.get(NGSIConstants.RECV_TIME_TS).add(Long.toString(recvTimeTs)); aggregation.get(NGSIConstants.RECV_TIME).add(recvTime); aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).add(getServicePathForData()); aggregation.get(NGSIConstants.ENTITY_ID).add(entityId); aggregation.get(NGSIConstants.ENTITY_TYPE).add(entityType); aggregation.get(NGSIConstants.ATTR_NAME).add(attrName); aggregation.get(NGSIConstants.ATTR_TYPE).add(attrType); aggregation.get(NGSIConstants.ATTR_VALUE).add(attrValue); aggregation.get(NGSIConstants.ATTR_MD).add(attrMetadata); } // for } // aggregate } // RowAggregator /** * Class for aggregating batches in column mode. */ private class ColumnAggregator extends MySQLAggregator { @Override public void initialize(NGSIEvent cygnusEvent) throws CygnusBadConfiguration { super.initialize(cygnusEvent); // particular initialization LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.put(NGSIConstants.RECV_TIME, new ArrayList<String>()); aggregation.put(NGSIConstants.FIWARE_SERVICE_PATH, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_ID, new ArrayList<String>()); aggregation.put(NGSIConstants.ENTITY_TYPE, new ArrayList<String>()); // iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = cygnusEvent.getContextElement().getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { return; } // if for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); aggregation.put(attrName, new ArrayList<String>()); aggregation.put(attrName + "_md", new ArrayList<String>()); } // for } // initialize @Override public void aggregate(NGSIEvent event) { // Number of previous values int numPreviousValues = getAggregation().get(NGSIConstants.FIWARE_SERVICE_PATH).size(); // Get the event headers long recvTimeTs = event.getRecvTimeTs(); String recvTime = CommonUtils.getHumanReadable(recvTimeTs, false); // get the event body ContextElement contextElement = event.getContextElement(); String entityId = contextElement.getId(); String entityType = contextElement.getType(); LOGGER.debug("[" + getName() + "] Processing context element (id=" + entityId + ", type=" + entityType + ")"); // Iterate on all this context element attributes, if there are attributes ArrayList<ContextAttribute> contextAttributes = contextElement.getAttributes(); if (contextAttributes == null || contextAttributes.isEmpty()) { LOGGER.warn("No attributes within the notified entity, nothing is done (id=" + entityId + ", type=" + entityType + ")"); return; } // if LinkedHashMap<String, ArrayList<String>> aggregation = getAggregation(); aggregation.get(NGSIConstants.RECV_TIME).add(recvTime); aggregation.get(NGSIConstants.FIWARE_SERVICE_PATH).add(getServicePathForData()); aggregation.get(NGSIConstants.ENTITY_ID).add(entityId); aggregation.get(NGSIConstants.ENTITY_TYPE).add(entityType); for (ContextAttribute contextAttribute : contextAttributes) { String attrName = contextAttribute.getName(); String attrType = contextAttribute.getType(); String attrValue = contextAttribute.getContextValue(false); String attrMetadata = contextAttribute.getContextMetadata(); LOGGER.debug("[" + getName() + "] Processing context attribute (name=" + attrName + ", type=" + attrType + ")"); // Check if the attribute already exists in the form of 2 columns (one for metadata); if not existing, // add an empty value for all previous rows if (aggregation.containsKey(attrName)) { aggregation.get(attrName).add(attrValue); aggregation.get(attrName + "_md").add(attrMetadata); } else { ArrayList<String> values = new ArrayList<>(Collections.nCopies(numPreviousValues, "")); values.add(attrValue); aggregation.put(attrName, values); ArrayList<String> valuesMd = new ArrayList<>(Collections.nCopies(numPreviousValues, "")); valuesMd.add(attrMetadata); aggregation.put(attrName + "_md", valuesMd); } // if else } // for // Iterate on all the aggregations, checking for not updated attributes; add an empty value if missing for (String key : aggregation.keySet()) { ArrayList<String> values = aggregation.get(key); if (values.size() == numPreviousValues) { values.add(""); } // if } // for } // aggregate } // ColumnAggregator private MySQLAggregator getAggregator(boolean rowAttrPersistence) { if (rowAttrPersistence) { return new RowAggregator(); } else { return new ColumnAggregator(); } // if else } // getAggregator private void persistAggregation(MySQLAggregator aggregator) throws CygnusPersistenceError, CygnusRuntimeError, CygnusBadContextData { String fieldsForCreate = aggregator.getFieldsForCreate(); String fieldsForInsert = aggregator.getFieldsForInsert(); String valuesForInsert = aggregator.getValuesForInsert(); String dbName = aggregator.getDbName(enableLowercase); String tableName = aggregator.getTableName(enableLowercase); LOGGER.info("[" + this.getName() + "] Persisting data at NGSIMySQLSink. Database (" + dbName + "), Table (" + tableName + "), Fields (" + fieldsForInsert + "), Values (" + valuesForInsert + ")"); // creating the database and the table has only sense if working in row mode, in column node // everything must be provisioned in advance if (aggregator instanceof RowAggregator) { persistenceBackend.createDatabase(dbName); persistenceBackend.createTable(dbName, tableName, fieldsForCreate); } // if if (valuesForInsert.equals("")) { LOGGER.debug("[" + this.getName() + "] no values for insert"); } else { persistenceBackend.insertContextData(dbName, tableName, fieldsForInsert, valuesForInsert); } } // persistAggregation /** * Creates a MySQL DB name given the FIWARE service. * @param service * @return The MySQL DB name * @throws CygnusBadConfiguration */ protected String buildDbName(String service) throws CygnusBadConfiguration { String name; if (enableEncoding) { name = NGSICharsets.encodeMySQL(service); } else { name = NGSIUtils.encode(service, false, true); } // if else if (name.length() > NGSIConstants.MYSQL_MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building database name '" + name + "' and its length is greater than " + NGSIConstants.MYSQL_MAX_NAME_LEN); } // if return name; } // buildDbName /** * Creates a MySQL table name given the FIWARE service path, the entity and the attribute. * @param servicePath * @param entity * @param attribute * @return The MySQL table name * @throws CygnusBadConfiguration */ protected String buildTableName(String servicePath, String entity, String entityType, String attribute) throws CygnusBadConfiguration { String name; if (enableEncoding) { switch (dataModel) { case DMBYSERVICEPATH: name = NGSICharsets.encodeMySQL(servicePath); break; case DMBYENTITY: name = NGSICharsets.encodeMySQL(servicePath) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(entity); break; case DMBYENTITYTYPE: name = NGSICharsets.encodeMySQL(servicePath) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(entityType); break; case DMBYATTRIBUTE: name = NGSICharsets.encodeMySQL(servicePath) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(entity) + CommonConstants.CONCATENATOR + NGSICharsets.encodeMySQL(attribute); break; default: throw new CygnusBadConfiguration("Unknown data model '" + dataModel.toString() + "'. Please, use dm-by-service-path, dm-by-entity or dm-by-attribute"); } // switch } else { switch (dataModel) { case DMBYSERVICEPATH: if (servicePath.equals("/")) { throw new CygnusBadConfiguration("Default service path '/' cannot be used with " + "dm-by-service-path data model"); } // if name = NGSIUtils.encode(servicePath, true, false); break; case DMBYENTITY: String truncatedServicePath = NGSIUtils.encode(servicePath, true, false); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encode(entity, false, true); break; case DMBYENTITYTYPE: truncatedServicePath = NGSIUtils.encode(servicePath, true, false); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encode(entityType, false, true); break; case DMBYATTRIBUTE: truncatedServicePath = NGSIUtils.encode(servicePath, true, false); name = (truncatedServicePath.isEmpty() ? "" : truncatedServicePath + '_') + NGSIUtils.encode(entity, false, true) + '_' + NGSIUtils.encode(attribute, false, true); break; default: throw new CygnusBadConfiguration("Unknown data model '" + dataModel.toString() + "'. Please, use DMBYSERVICEPATH, DMBYENTITY, DMBYENTITYTYPE or DMBYATTRIBUTE"); } // switch } // if else if (name.length() > NGSIConstants.MYSQL_MAX_NAME_LEN) { throw new CygnusBadConfiguration("Building table name '" + name + "' and its length is greater than " + NGSIConstants.MYSQL_MAX_NAME_LEN); } // if return name; } // buildTableName } // NGSIMySQLSink
log native types mysql
cygnus-ngsi/src/main/java/com/telefonica/iot/cygnus/sinks/NGSIMySQLSink.java
log native types mysql
<ide><path>ygnus-ngsi/src/main/java/com/telefonica/iot/cygnus/sinks/NGSIMySQLSink.java <ide> } else { <ide> value = "" + value + ""; // redundant ? <ide> } <del> LOGGER.debug("[" getName() + "] value type = " + valueType ); <add> LOGGER.debug("[" + getName() + "] value type = " + valueType ); <ide> } <del> LOGGER.debug("[" getName() + "] native value = " + value ); <add> LOGGER.debug("[" + getName() + "] native value = " + value ); <ide> } else { <ide> value = "'" + value + "'"; <ide> }
Java
mit
cdcfb56b59ee72d83b360497c2cf711f77327161
0
classgraph/classgraph,lukehutch/fast-classpath-scanner,lukehutch/fast-classpath-scanner
/* * This file is part of ClassGraph. * * Author: Luke Hutchison * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2018 Luke Hutchison * * 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. */ package io.github.classgraph.issues.issue238; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import javax.persistence.Entity; import org.junit.Test; import io.github.classgraph.ClassGraph; @Entity public class Issue238Test { public static class B extends D { } public static class C { } public static class D extends C { } public static class E extends F { } public static class A extends G { } public static class G extends B { } public static class F extends A { } @Test public void testSuperclassInheritanceOrder() throws Exception { final List<String> classNames = new ClassGraph() .whitelistPackages(Issue238Test.class.getPackage().getName()).enableAllInfo().scan().getAllClasses() .get(E.class.getName()).getSuperclasses().getNames(); assertThat(classNames).containsExactly(F.class.getName(), A.class.getName(), G.class.getName(), B.class.getName(), D.class.getName(), C.class.getName()); } }
src/test/java/io/github/classgraph/issues/issue238/Issue238Test.java
/* * This file is part of ClassGraph. * * Author: Luke Hutchison * * Hosted at: https://github.com/lukehutch/fast-classpath-scanner * * -- * * The MIT License (MIT) * * Copyright (c) 2018 Luke Hutchison * * 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. */ package io.github.classgraph.issues.issue238; import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import javax.persistence.Entity; import org.junit.Test; import io.github.classgraph.ClassGraph; @Entity public class Issue238Test { public static class B extends D { } public static class C { } public static class D extends C { } public static class E extends F { } public static class A extends G { } public static class G extends B { } public static class F extends A { } @Test public void testSuperclassInheritanceOrder() throws Exception { final List<String> classNames = new ClassGraph() .whitelistPackages(Issue238Test.class.getPackage().getName()).enableAllInfo().scan().getAllClasses() .get(E.class.getName()).getSuperclasses().getNames(); System.out.println(classNames); assertThat(classNames).containsExactly(F.class.getName(), A.class.getName(), G.class.getName(), B.class.getName(), D.class.getName(), C.class.getName()); } }
Remove println
src/test/java/io/github/classgraph/issues/issue238/Issue238Test.java
Remove println
<ide><path>rc/test/java/io/github/classgraph/issues/issue238/Issue238Test.java <ide> final List<String> classNames = new ClassGraph() <ide> .whitelistPackages(Issue238Test.class.getPackage().getName()).enableAllInfo().scan().getAllClasses() <ide> .get(E.class.getName()).getSuperclasses().getNames(); <del> System.out.println(classNames); <ide> assertThat(classNames).containsExactly(F.class.getName(), A.class.getName(), G.class.getName(), <ide> B.class.getName(), D.class.getName(), C.class.getName()); <ide> }
Java
mit
8a7bc41d4ec357a6718b89c86616d243bcc2beee
0
isi-nlp/tac-kbp-eal,isi-nlp/tac-kbp-eal,BBN-E/tac-kbp-eal,BBN-E/tac-kbp-eal,rgabbard-bbn/kbp-2014-event-arguments,rgabbard-bbn/kbp-2014-event-arguments
package com.bbn.kbp.events2014.assessmentDiff.observers; import com.bbn.bue.common.symbols.Symbol; import com.bbn.kbp.events2014.Response; import com.bbn.kbp.events2014.ResponseAssessment; import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver; public class AETObserver extends ConfusionMatrixAssessmentPairObserver { @Override protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) { return left.justificationSupportsEventType().isPresent() && right.justificationSupportsEventType().isPresent(); } @Override protected Symbol toKey(ResponseAssessment assessment) { return Symbol.from(assessment.justificationSupportsEventType().get().toString()); } }
kbp-events2014-scorer/src/main/java/com/bbn/kbp/events2014/assessmentDiff/observers/AETObserver.java
package com.bbn.kbp.events2014.assessmentDiff.observers; import com.bbn.bue.common.symbols.Symbol; import com.bbn.kbp.events2014.Response; import com.bbn.kbp.events2014.ResponseAssessment; import com.bbn.kbp.events2014.assessmentDiff.observers.ConfusionMatrixAssessmentPairObserver; public class AETObserver extends ConfusionMatrixAssessmentPairObserver { @Override protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) { return true; } @Override protected Symbol toKey(ResponseAssessment assessment) { return Symbol.from(assessment.justificationSupportsEventType().toString()); } }
Update AET diff observer for possibility AET is absent
kbp-events2014-scorer/src/main/java/com/bbn/kbp/events2014/assessmentDiff/observers/AETObserver.java
Update AET diff observer for possibility AET is absent
<ide><path>bp-events2014-scorer/src/main/java/com/bbn/kbp/events2014/assessmentDiff/observers/AETObserver.java <ide> <ide> @Override <ide> protected boolean filter(Response response, ResponseAssessment left, ResponseAssessment right) { <del> return true; <add> return left.justificationSupportsEventType().isPresent() && right.justificationSupportsEventType().isPresent(); <ide> } <ide> <ide> @Override <ide> protected Symbol toKey(ResponseAssessment assessment) { <del> return Symbol.from(assessment.justificationSupportsEventType().toString()); <add> return Symbol.from(assessment.justificationSupportsEventType().get().toString()); <ide> } <ide> }
Java
apache-2.0
07ba1c50b34235f12d0f6e58e4bb6e623bc3bcb8
0
SpineEventEngine/gae-java,SpineEventEngine/gae-java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.storage.datastore; import com.google.cloud.datastore.EntityQuery; import com.google.common.base.Suppliers; import com.google.common.collect.Streams; import com.google.protobuf.Any; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import io.spine.core.Event; import io.spine.core.Version; import io.spine.protobuf.AnyPacker; import io.spine.server.BoundedContext; import io.spine.server.aggregate.Aggregate; import io.spine.server.aggregate.AggregateEventRecord; import io.spine.server.aggregate.AggregateHistory; import io.spine.server.aggregate.AggregateReadRequest; import io.spine.server.aggregate.AggregateStorage; import io.spine.server.aggregate.AggregateStorageTest; import io.spine.server.aggregate.Snapshot; import io.spine.server.aggregate.given.repo.ProjectAggregate; import io.spine.server.entity.Entity; import io.spine.server.storage.datastore.given.aggregate.ProjectAggregateRepository; import io.spine.server.type.CommandEnvelope; import io.spine.test.aggregate.Project; import io.spine.test.aggregate.ProjectId; import io.spine.test.aggregate.command.AggAddTask; import io.spine.test.storage.StateImported; import io.spine.testdata.Sample; import io.spine.testing.client.TestActorRequestFactory; import io.spine.testing.server.TestEventFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.Optional; import static io.spine.base.Time.currentTime; import static io.spine.core.Versions.increment; import static io.spine.core.Versions.zero; import static io.spine.server.aggregate.given.Given.CommandMessage.addTask; import static io.spine.server.storage.datastore.DatastoreWrapper.MAX_ENTITIES_PER_WRITE_REQUEST; import static io.spine.server.storage.datastore.TestDatastoreStorageFactory.defaultInstance; import static io.spine.server.storage.datastore.given.DsRecordStorageTestEnv.datastoreFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @DisplayName("DsAggregateStorage should") class DsAggregateStorageTest extends AggregateStorageTest { private static final TestDatastoreStorageFactory datastoreFactory = defaultInstance(); @BeforeAll static void setUpClass() { datastoreFactory.setUp(); } @AfterEach void tearDownTest() { datastoreFactory.clear(); } @AfterAll static void tearDownClass() { datastoreFactory.tearDown(); } @Override protected AggregateStorage<ProjectId> newStorage(Class<? extends Entity<?, ?>> cls) { @SuppressWarnings("unchecked") // Logically checked; OK for test purposes. Class<? extends Aggregate<ProjectId, ?, ?>> aggCls = (Class<? extends Aggregate<ProjectId, ?, ?>>) cls; return datastoreFactory.createAggregateStorage(aggCls); } @Override protected <I> AggregateStorage<I> newStorage(Class<? extends I> idClass, Class<? extends Aggregate<I, ?, ?>> aggregateClass) { return datastoreFactory.createAggregateStorage(aggregateClass); } @SuppressWarnings("DuplicateStringLiteralInspection") // OK for tests. @Test @DisplayName("provide access to DatastoreWrapper for extensibility") void testAccessDatastoreWrapper() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); DatastoreWrapper datastore = storage.datastore(); assertNotNull(datastore); } @SuppressWarnings("DuplicateStringLiteralInspection") // OK for tests. @Test @DisplayName("provide access to PropertyStorage for extensibility") void testAccessPropertyStorage() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); DsPropertyStorage propertyStorage = storage.getPropertyStorage(); assertNotNull(propertyStorage); } @Test @DisplayName("fail to write invalid record") void testFailOnInvalidRecord() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); assertThrows(IllegalArgumentException.class, () -> storage.writeRecord(Sample.messageOfType(ProjectId.class), AggregateEventRecord.getDefaultInstance())); } @Test @DisplayName("not set limit for history backward query") void testHistoryQueryLimit() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); int batchSize = 10; AggregateReadRequest<ProjectId> request = new AggregateReadRequest<>(newId(), batchSize); EntityQuery historyBackwardQuery = storage.historyBackwardQuery(request); Integer queryLimit = historyBackwardQuery.getLimit(); assertNull(queryLimit); } @Test @DisplayName("not overwrite the snapshot when saving a new one") void notOverwriteSnapshot() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); ProjectId id = newId(); writeSnapshotWithTimestamp(id, Timestamps.fromMillis(15)); writeSnapshotWithTimestamp(id, Timestamps.fromMillis(15000)); int batchSize = 10; AggregateReadRequest<ProjectId> request = new AggregateReadRequest<>(id, batchSize); Iterator<AggregateEventRecord> records = storage.historyBackward(request); long snapshotCount = Streams.stream(records) .count(); assertEquals(2, snapshotCount); } @Nested @DisplayName("truncate efficiently") class TruncateEfficiently { private DsAggregateStorage<ProjectId> storage; @BeforeEach void setUp() { SpyStorageFactory.injectWrapper(datastoreFactory().datastore()); SpyStorageFactory storageFactory = new SpyStorageFactory(); storage = (DsAggregateStorage<ProjectId>) storageFactory.createAggregateStorage(ProjectAggregate.class); } @Test @DisplayName("when having bulk of records stored") void withBulkOfRecords() { ProjectId id = newId(); AggregateHistory.Builder history = AggregateHistory.newBuilder(); Version version = zero(); Any state = AnyPacker.pack(Project.getDefaultInstance()); // Store *max entities per delete request* + 1 events. TestEventFactory factory = TestEventFactory.newInstance(DsAggregateStorageTest.class); int eventCount = MAX_ENTITIES_PER_WRITE_REQUEST + 1; StateImported eventMessage = StateImported .newBuilder() .setState(state) .vBuild(); for (int i = 0; i < eventCount; i++) { version = increment(version); Event event = factory.createEvent(eventMessage, version, currentTime()); history.addEvent(event); } storage.write(id, history.build()); // Store the snapshot after events. version = increment(version); Snapshot latestSnapshot = Snapshot .newBuilder() .setState(state) .setVersion(version) .setTimestamp(currentTime()) .vBuild(); Event latestEvent = factory.createEvent(eventMessage, increment(version), currentTime()); AggregateHistory historyAfterSnapshot = AggregateHistory .newBuilder() .setSnapshot(latestSnapshot) .addEvent(latestEvent) .vBuild(); storage.write(id, historyAfterSnapshot); // Order removal of all records before the snapshot. storage.truncateOlderThan(0); // Check that the number of operations is minimum possible. int expectedOperationCount = eventCount / MAX_ENTITIES_PER_WRITE_REQUEST + 1; verify(storage.datastore(), times(expectedOperationCount)).deleteEntities(any()); } } @Nested class DynamicSnapshotTrigger { private ProjectAggregateRepository repository; private TestActorRequestFactory factory; private ProjectId id; @BeforeEach void setUp() { BoundedContext boundedContext = BoundedContext.newBuilder() .setName(DsAggregateStorageTest.class.getName()) .setStorageFactorySupplier(Suppliers.ofInstance(datastoreFactory)) .build(); repository = new ProjectAggregateRepository(); boundedContext.register(repository); factory = new TestActorRequestFactory(DsAggregateStorageTest.class); id = newId(); } @Test @DisplayName("still load aggregates properly after snapshot trigger decrease at runtime") void testLoadHistoryAfterSnapshotTriggerChange() { int initialSnapshotTrigger = 10; // To restore an aggregate using a snapshot and events. int tasksCount = initialSnapshotTrigger * 2 - 1; repository.setSnapshotTrigger(initialSnapshotTrigger); for (int i = 0; i < tasksCount; i++) { AggAddTask command = addTask(id); CommandEnvelope envelope = CommandEnvelope.of(factory.createCommand(command)); ProjectId target = repository.dispatch(envelope); assertEquals(id, target); } int minimalSnapshotTrigger = 1; repository.setSnapshotTrigger(minimalSnapshotTrigger); Optional<ProjectAggregate> optional = repository.find(id); assertTrue(optional.isPresent()); ProjectAggregate aggregate = optional.get(); assertEquals(tasksCount, aggregate.state() .getTaskCount()); } } private void writeSnapshotWithTimestamp(ProjectId id, Timestamp timestamp) { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); Snapshot snapshot = Snapshot .newBuilder() .setTimestamp(timestamp) .vBuild(); AggregateEventRecord record = AggregateEventRecord .newBuilder() .setSnapshot(snapshot) .vBuild(); storage.writeRecord(id, record); } }
datastore/src/test/java/io/spine/server/storage/datastore/DsAggregateStorageTest.java
/* * Copyright 2019, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.server.storage.datastore; import com.google.cloud.datastore.EntityQuery; import com.google.common.base.Suppliers; import com.google.common.collect.Streams; import com.google.protobuf.Any; import com.google.protobuf.Timestamp; import com.google.protobuf.util.Timestamps; import io.spine.core.Event; import io.spine.core.Version; import io.spine.protobuf.AnyPacker; import io.spine.server.BoundedContext; import io.spine.server.aggregate.Aggregate; import io.spine.server.aggregate.AggregateEventRecord; import io.spine.server.aggregate.AggregateHistory; import io.spine.server.aggregate.AggregateReadRequest; import io.spine.server.aggregate.AggregateStorage; import io.spine.server.aggregate.AggregateStorageTest; import io.spine.server.aggregate.Snapshot; import io.spine.server.aggregate.given.repo.ProjectAggregate; import io.spine.server.entity.Entity; import io.spine.server.storage.datastore.given.aggregate.ProjectAggregateRepository; import io.spine.server.type.CommandEnvelope; import io.spine.test.aggregate.Project; import io.spine.test.aggregate.ProjectId; import io.spine.test.aggregate.command.AggAddTask; import io.spine.test.storage.StateImported; import io.spine.testdata.Sample; import io.spine.testing.client.TestActorRequestFactory; import io.spine.testing.server.TestEventFactory; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import java.util.Iterator; import java.util.Optional; import static io.spine.base.Time.currentTime; import static io.spine.core.Versions.increment; import static io.spine.core.Versions.zero; import static io.spine.server.aggregate.given.Given.CommandMessage.addTask; import static io.spine.server.storage.datastore.DatastoreWrapper.MAX_ENTITIES_PER_WRITE_REQUEST; import static io.spine.server.storage.datastore.TestDatastoreStorageFactory.defaultInstance; import static io.spine.server.storage.datastore.given.DsRecordStorageTestEnv.datastoreFactory; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @DisplayName("DsAggregateStorage should") class DsAggregateStorageTest extends AggregateStorageTest { private static final TestDatastoreStorageFactory datastoreFactory = defaultInstance(); @BeforeAll static void setUpClass() { datastoreFactory.setUp(); } @AfterEach void tearDownTest() { datastoreFactory.clear(); } @AfterAll static void tearDownClass() { datastoreFactory.tearDown(); } @Override protected AggregateStorage<ProjectId> newStorage(Class<? extends Entity<?, ?>> cls) { @SuppressWarnings("unchecked") // Logically checked; OK for test purposes. Class<? extends Aggregate<ProjectId, ?, ?>> aggCls = (Class<? extends Aggregate<ProjectId, ?, ?>>) cls; return datastoreFactory.createAggregateStorage(aggCls); } @Override protected <I> AggregateStorage<I> newStorage(Class<? extends I> idClass, Class<? extends Aggregate<I, ?, ?>> aggregateClass) { return datastoreFactory.createAggregateStorage(aggregateClass); } @SuppressWarnings("DuplicateStringLiteralInspection") // OK for tests. @Test @DisplayName("provide access to DatastoreWrapper for extensibility") void testAccessDatastoreWrapper() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); DatastoreWrapper datastore = storage.datastore(); assertNotNull(datastore); } @SuppressWarnings("DuplicateStringLiteralInspection") // OK for tests. @Test @DisplayName("provide access to PropertyStorage for extensibility") void testAccessPropertyStorage() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); DsPropertyStorage propertyStorage = storage.getPropertyStorage(); assertNotNull(propertyStorage); } @Test @DisplayName("fail to write invalid record") void testFailOnInvalidRecord() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); assertThrows(IllegalArgumentException.class, () -> storage.writeRecord(Sample.messageOfType(ProjectId.class), AggregateEventRecord.getDefaultInstance())); } @Test @DisplayName("not set limit for history backward query") void testHistoryQueryLimit() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); int batchSize = 10; AggregateReadRequest<ProjectId> request = new AggregateReadRequest<>(newId(), batchSize); EntityQuery historyBackwardQuery = storage.historyBackwardQuery(request); Integer queryLimit = historyBackwardQuery.getLimit(); assertNull(queryLimit); } @Test @DisplayName("not overwrite the snapshot when saving a new one") void notOverwriteSnapshot() { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); ProjectId id = newId(); writeSnapshotWithTimestamp(id, Timestamps.fromMillis(15)); writeSnapshotWithTimestamp(id, Timestamps.fromMillis(15000)); int batchSize = 10; AggregateReadRequest<ProjectId> request = new AggregateReadRequest<>(id, batchSize); Iterator<AggregateEventRecord> records = storage.historyBackward(request); long snapshotCount = Streams.stream(records) .count(); assertEquals(2, snapshotCount); } @Nested @DisplayName("truncate efficiently") class TruncateEfficiently { private DsAggregateStorage<ProjectId> storage; @BeforeEach void setUp() { SpyStorageFactory.injectWrapper(datastoreFactory().datastore()); SpyStorageFactory storageFactory = new SpyStorageFactory(); storage = (DsAggregateStorage<ProjectId>) storageFactory.createAggregateStorage(ProjectAggregate.class); } @Test @DisplayName("when having bulk of records stored") void withBulkOfRecords() { ProjectId id = newId(); AggregateHistory.Builder history = AggregateHistory.newBuilder(); Version version = zero(); Any state = AnyPacker.pack(Project.getDefaultInstance()); // Store *max entities per delete request* + 1 events. TestEventFactory factory = TestEventFactory.newInstance(DsAggregateStorageTest.class); int eventCount = MAX_ENTITIES_PER_WRITE_REQUEST + 1; StateImported eventMessage = StateImported .newBuilder() .setState(state) .vBuild(); for (int i = 0; i < eventCount; i++) { version = increment(version); Event event = factory.createEvent(eventMessage, version, currentTime()); history.addEvent(event); } storage.write(id, history.build()); // Store the snapshot after events. version = increment(version); Snapshot latestSnapshot = Snapshot .newBuilder() .setState(state) .setVersion(version) .setTimestamp(currentTime()) .vBuild(); Event latestEvent = factory.createEvent(eventMessage, increment(version), currentTime()); AggregateHistory historyAfterSnapshot = AggregateHistory .newBuilder() .setSnapshot(latestSnapshot) .addEvent(latestEvent) .vBuild(); storage.write(id, historyAfterSnapshot); // Order removal of all records before the snapshot. storage.truncateOlderThan(0); // Check that the number of operations is minimum possible. int expectedOperationCount = eventCount / MAX_ENTITIES_PER_WRITE_REQUEST + 1; verify(storage.datastore(), times(expectedOperationCount)).deleteEntities(any()); } } @Nested class DynamicSnapshotTrigger { private ProjectAggregateRepository repository; private TestActorRequestFactory factory; private ProjectId id; @BeforeEach void setUp() { BoundedContext boundedContext = BoundedContext.newBuilder() .setName(DsAggregateStorageTest.class.getName()) .setStorageFactorySupplier(Suppliers.ofInstance(datastoreFactory)) .build(); repository = new ProjectAggregateRepository(); boundedContext.register(repository); factory = new TestActorRequestFactory(DsAggregateStorageTest.class); id = newId(); } @Test @DisplayName("still load aggregates properly after snapshot trigger decrease at runtime") void testLoadHistoryAfterSnapshotTriggerChange() { int initialSnapshotTrigger = 10; // To restore an aggregate using a snapshot and events. int tasksCount = initialSnapshotTrigger * 2 - 1; repository.setSnapshotTrigger(initialSnapshotTrigger); for (int i = 0; i < tasksCount; i++) { AggAddTask command = addTask(id); CommandEnvelope envelope = CommandEnvelope.of(factory.createCommand(command)); ProjectId target = repository.dispatch(envelope); assertEquals(id, target); } int minimalSnapshotTrigger = 1; repository.setSnapshotTrigger(minimalSnapshotTrigger); Optional<ProjectAggregate> optional = repository.find(id); assertTrue(optional.isPresent()); ProjectAggregate aggregate = optional.get(); assertEquals(tasksCount, aggregate.state() .getTaskCount()); } } private void writeSnapshotWithTimestamp(ProjectId id, Timestamp timestamp) { DsAggregateStorage<ProjectId> storage = (DsAggregateStorage<ProjectId>) storage(); Snapshot snapshot = Snapshot .newBuilder() .setTimestamp(timestamp) .vBuild(); AggregateEventRecord record = AggregateEventRecord .newBuilder() .setSnapshot(snapshot) .vBuild(); storage.writeRecord(id, record); } }
Fix formatting
datastore/src/test/java/io/spine/server/storage/datastore/DsAggregateStorageTest.java
Fix formatting
<ide><path>atastore/src/test/java/io/spine/server/storage/datastore/DsAggregateStorageTest.java <ide> } <ide> <ide> @Override <del> protected AggregateStorage<ProjectId> <del> newStorage(Class<? extends Entity<?, ?>> cls) { <add> protected AggregateStorage<ProjectId> newStorage(Class<? extends Entity<?, ?>> cls) { <ide> @SuppressWarnings("unchecked") // Logically checked; OK for test purposes. <ide> Class<? extends Aggregate<ProjectId, ?, ?>> aggCls = <ide> (Class<? extends Aggregate<ProjectId, ?, ?>>) cls;
Java
apache-2.0
f2478939558f9d1a014660a0813adeea5baa3b26
0
manstis/drools,jomarko/drools,lanceleverich/drools,winklerm/drools,sotty/drools,sutaakar/drools,winklerm/drools,sotty/drools,reynoldsm88/drools,reynoldsm88/drools,ngs-mtech/drools,jomarko/drools,lanceleverich/drools,ngs-mtech/drools,manstis/drools,reynoldsm88/drools,romartin/drools,romartin/drools,winklerm/drools,droolsjbpm/drools,jomarko/drools,droolsjbpm/drools,droolsjbpm/drools,romartin/drools,sutaakar/drools,sutaakar/drools,manstis/drools,lanceleverich/drools,sotty/drools,sotty/drools,jomarko/drools,sutaakar/drools,reynoldsm88/drools,sotty/drools,droolsjbpm/drools,ngs-mtech/drools,manstis/drools,ngs-mtech/drools,winklerm/drools,winklerm/drools,romartin/drools,manstis/drools,reynoldsm88/drools,ngs-mtech/drools,droolsjbpm/drools,romartin/drools,lanceleverich/drools,sutaakar/drools,lanceleverich/drools,jomarko/drools
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.core.util; import org.kie.internal.assembler.KieAssemblerService; import org.kie.internal.assembler.KieAssemblers; import org.kie.internal.runtime.KieRuntimeService; import org.kie.internal.runtime.KieRuntimes; import org.kie.internal.runtime.beliefs.KieBeliefService; import org.kie.internal.runtime.beliefs.KieBeliefs; import org.kie.internal.utils.KieService; import org.kie.internal.utils.ServiceDiscovery; import org.kie.internal.utils.ServiceRegistry; import org.kie.internal.utils.ServiceRegistryImpl; import org.kie.internal.weaver.KieWeaverService; import org.kie.internal.weaver.KieWeavers; import org.mvel2.MVEL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.Enumeration; import java.util.List; import java.util.Map; public class ServiceDiscoveryImpl implements ServiceDiscovery { private static final Logger log = LoggerFactory.getLogger( ServiceDiscovery.class ); public void discoverFactories(Enumeration<URL> confResources, ServiceRegistry serviceRegistry) { // iterate urls, then for each url split the service key and attempt to register each service while ( confResources.hasMoreElements() ) { URL url = confResources.nextElement(); java.io.InputStream is = null; try { is = url.openStream(); log.info( "Discovered kie.conf url={} ", url ); processKieConf( is, serviceRegistry ); } catch ( Exception exc ) { throw new RuntimeException( "Unable to build kie service url = " + url.toExternalForm(), exc ); } finally { try { if ( is != null ) { is.close(); } else { log.error( "Unable to build kie service url={}\n", url.toExternalForm() ); } } catch (IOException e1) { log.warn( "Unable to close Stream for url={} reason={}\n", url, e1.getMessage() ); } } } } public static void processKieConf(InputStream is, ServiceRegistry serviceRegistry) throws IOException { String conf = readFileAsString( new InputStreamReader( is )); processKieConf( conf, serviceRegistry ); } public static void processKieConf(String conf, ServiceRegistry serviceRegistry) { Map<String, List> map = ( Map<String, List> ) MVEL.eval( conf ); processKieConf(map, serviceRegistry); } public static void processKieConf(Map<String, List> map, ServiceRegistry serviceRegistry) { processKieServices(map, serviceRegistry); processKieAssemblers(map, serviceRegistry); processKieWeavers(map, serviceRegistry); processKieBeliefs(map, serviceRegistry); processRuntimes(map, serviceRegistry); } private static void processRuntimes(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieRuntimeService> runtimeList = map.get( "runtimes" ); if ( runtimeList != null && runtimeList.size() > 0 ) { KieRuntimes runtimes = serviceRegistry.get(KieRuntimes.class); for ( KieRuntimeService runtime : runtimeList ) { log.info("Adding Runtime {}\n", runtime.getServiceInterface().getName()); runtimes.getRuntimes().put( runtime.getServiceInterface().getName(), runtime); } } } private static void processKieAssemblers(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieAssemblerService> assemblerList = map.get( "assemblers" ); if ( assemblerList != null && assemblerList.size() > 0 ) { KieAssemblers assemblers = serviceRegistry.get(KieAssemblers.class); for ( KieAssemblerService assemblerFactory : assemblerList ) { log.info( "Adding Assembler {}\n", assemblerFactory.getClass().getName() ); assemblers.getAssemblers().put(assemblerFactory.getResourceType(), assemblerFactory); } } } private static void processKieWeavers(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieWeaverService> weaverList = map.get( "weavers" ); if ( weaverList != null && weaverList.size() > 0 ) { KieWeavers weavers = serviceRegistry.get(KieWeavers.class); for ( KieWeaverService weaver : weaverList ) { log.info("Adding Weaver {}\n", weavers.getClass().getName()); weavers.getWeavers().put( weaver.getResourceType(), weaver ); } } } private static void processKieBeliefs(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieBeliefService> beliefsList = map.get( "beliefs" ); if ( beliefsList != null && beliefsList.size() > 0 ) { KieBeliefs beliefs = serviceRegistry.get(KieBeliefs.class); for ( KieBeliefService belief : beliefsList ) { log.info("Adding Belief {}\n", beliefs.getClass().getName()); beliefs.getBeliefs().put( belief.getBeliefType(), belief ); } } } private static void processKieServices(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieService> servicesList = map.get( "services" ); if ( servicesList != null && servicesList.size() > 0 ) { for ( KieService service : servicesList ) { log.info( "Adding Service {}\n", service.getClass().getName() ); serviceRegistry.registerLocator(service.getServiceInterface(), new ServiceRegistryImpl.ReturnInstance(service)); } } } public static String readFileAsString(Reader reader) { try { StringBuilder fileData = new StringBuilder( 1000 ); char[] buf = new char[1024]; int numRead; while ( (numRead = reader.read( buf )) != -1 ) { String readData = String.valueOf( buf, 0, numRead ); fileData.append( readData ); buf = new char[1024]; } reader.close(); return fileData.toString(); } catch ( IOException e ) { throw new RuntimeException( e ); } } }
drools-core/src/main/java/org/drools/core/util/ServiceDiscoveryImpl.java
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.drools.core.util; import org.kie.internal.assembler.KieAssemblerService; import org.kie.internal.assembler.KieAssemblers; import org.kie.internal.runtime.KieRuntimeService; import org.kie.internal.runtime.KieRuntimes; import org.kie.internal.runtime.beliefs.KieBeliefService; import org.kie.internal.runtime.beliefs.KieBeliefs; import org.kie.internal.utils.KieService; import org.kie.internal.utils.ServiceDiscovery; import org.kie.internal.utils.ServiceRegistry; import org.kie.internal.utils.ServiceRegistryImpl; import org.kie.internal.weaver.KieWeaverService; import org.kie.internal.weaver.KieWeavers; import org.mvel2.MVEL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.util.Enumeration; import java.util.List; import java.util.Map; public class ServiceDiscoveryImpl implements ServiceDiscovery { private static final Logger log = LoggerFactory.getLogger( ServiceDiscovery.class ); public void discoverFactories(Enumeration<URL> confResources, ServiceRegistry serviceRegistry) { // iterate urls, then for each url split the service key and attempt to register each service while ( confResources.hasMoreElements() ) { URL url = confResources.nextElement(); java.io.InputStream is = null; try { is = url.openStream(); log.info( "Discovered kie.conf url={} ", url ); processKieConf( is, serviceRegistry ); } catch ( Exception exc ) { throw new RuntimeException( "Unable to build kie service url = " + url.toExternalForm(), exc ); } finally { try { if ( is != null ) { is.close(); } else { log.error( "Unable to build kie service url={}\n", url.toExternalForm() ); } } catch (IOException e1) { log.warn( "Unable to close Stream for url={} reason={}", url, e1.getMessage() ); } } } } public static void processKieConf(InputStream is, ServiceRegistry serviceRegistry) throws IOException { String conf = readFileAsString( new InputStreamReader( is )); processKieConf( conf, serviceRegistry ); } public static void processKieConf(String conf, ServiceRegistry serviceRegistry) { Map<String, List> map = ( Map<String, List> ) MVEL.eval( conf ); processKieConf(map, serviceRegistry); } public static void processKieConf(Map<String, List> map, ServiceRegistry serviceRegistry) { processKieServices(map, serviceRegistry); processKieAssemblers(map, serviceRegistry); processKieWeavers(map, serviceRegistry); processKieBeliefs(map, serviceRegistry); processRuntimes(map, serviceRegistry); } private static void processRuntimes(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieRuntimeService> runtimeList = map.get( "runtimes" ); if ( runtimeList != null && runtimeList.size() > 0 ) { KieRuntimes runtimes = serviceRegistry.get(KieRuntimes.class); for ( KieRuntimeService runtime : runtimeList ) { log.info("Adding Runtime {} ", runtime.getServiceInterface().getName()); runtimes.getRuntimes().put( runtime.getServiceInterface().getName(), runtime); } } } private static void processKieAssemblers(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieAssemblerService> assemblerList = map.get( "assemblers" ); if ( assemblerList != null && assemblerList.size() > 0 ) { KieAssemblers assemblers = serviceRegistry.get(KieAssemblers.class); for ( KieAssemblerService assemblerFactory : assemblerList ) { log.info( "Adding Assembler {} ", assemblerFactory.getClass().getName() ); assemblers.getAssemblers().put(assemblerFactory.getResourceType(), assemblerFactory); } } } private static void processKieWeavers(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieWeaverService> weaverList = map.get( "weavers" ); if ( weaverList != null && weaverList.size() > 0 ) { KieWeavers weavers = serviceRegistry.get(KieWeavers.class); for ( KieWeaverService weaver : weaverList ) { log.info("Adding Weaver {} ", weavers.getClass().getName()); weavers.getWeavers().put( weaver.getResourceType(), weaver ); } } } private static void processKieBeliefs(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieBeliefService> beliefsList = map.get( "beliefs" ); if ( beliefsList != null && beliefsList.size() > 0 ) { KieBeliefs beliefs = serviceRegistry.get(KieBeliefs.class); for ( KieBeliefService belief : beliefsList ) { log.info("Adding Belief {} ", beliefs.getClass().getName()); beliefs.getBeliefs().put( belief.getBeliefType(), belief ); } } } private static void processKieServices(Map<String, List> map, ServiceRegistry serviceRegistry) { List<KieService> servicesList = map.get( "services" ); if ( servicesList != null && servicesList.size() > 0 ) { for ( KieService service : servicesList ) { log.info( "Adding Service {} ", service.getClass().getName() ); serviceRegistry.registerLocator(service.getServiceInterface(), new ServiceRegistryImpl.ReturnInstance(service)); } } } public static String readFileAsString(Reader reader) { try { StringBuilder fileData = new StringBuilder( 1000 ); char[] buf = new char[1024]; int numRead; while ( (numRead = reader.read( buf )) != -1 ) { String readData = String.valueOf( buf, 0, numRead ); fileData.append( readData ); buf = new char[1024]; } reader.close(); return fileData.toString(); } catch ( IOException e ) { throw new RuntimeException( e ); } } }
Fixing log formatting
drools-core/src/main/java/org/drools/core/util/ServiceDiscoveryImpl.java
Fixing log formatting
<ide><path>rools-core/src/main/java/org/drools/core/util/ServiceDiscoveryImpl.java <ide> log.error( "Unable to build kie service url={}\n", url.toExternalForm() ); <ide> } <ide> } catch (IOException e1) { <del> log.warn( "Unable to close Stream for url={} reason={}", url, e1.getMessage() ); <add> log.warn( "Unable to close Stream for url={} reason={}\n", url, e1.getMessage() ); <ide> } <ide> } <ide> } <ide> KieRuntimes runtimes = serviceRegistry.get(KieRuntimes.class); <ide> <ide> for ( KieRuntimeService runtime : runtimeList ) { <del> log.info("Adding Runtime {} ", runtime.getServiceInterface().getName()); <add> log.info("Adding Runtime {}\n", runtime.getServiceInterface().getName()); <ide> runtimes.getRuntimes().put( runtime.getServiceInterface().getName(), <ide> runtime); <ide> } <ide> if ( assemblerList != null && assemblerList.size() > 0 ) { <ide> KieAssemblers assemblers = serviceRegistry.get(KieAssemblers.class); <ide> for ( KieAssemblerService assemblerFactory : assemblerList ) { <del> log.info( "Adding Assembler {} ", assemblerFactory.getClass().getName() ); <add> log.info( "Adding Assembler {}\n", assemblerFactory.getClass().getName() ); <ide> assemblers.getAssemblers().put(assemblerFactory.getResourceType(), <ide> assemblerFactory); <ide> } <ide> if ( weaverList != null && weaverList.size() > 0 ) { <ide> KieWeavers weavers = serviceRegistry.get(KieWeavers.class); <ide> for ( KieWeaverService weaver : weaverList ) { <del> log.info("Adding Weaver {} ", weavers.getClass().getName()); <add> log.info("Adding Weaver {}\n", weavers.getClass().getName()); <ide> weavers.getWeavers().put( weaver.getResourceType(), <ide> weaver ); <ide> } <ide> if ( beliefsList != null && beliefsList.size() > 0 ) { <ide> KieBeliefs beliefs = serviceRegistry.get(KieBeliefs.class); <ide> for ( KieBeliefService belief : beliefsList ) { <del> log.info("Adding Belief {} ", beliefs.getClass().getName()); <add> log.info("Adding Belief {}\n", beliefs.getClass().getName()); <ide> beliefs.getBeliefs().put( belief.getBeliefType(), <ide> belief ); <ide> } <ide> List<KieService> servicesList = map.get( "services" ); <ide> if ( servicesList != null && servicesList.size() > 0 ) { <ide> for ( KieService service : servicesList ) { <del> log.info( "Adding Service {} ", service.getClass().getName() ); <add> log.info( "Adding Service {}\n", service.getClass().getName() ); <ide> serviceRegistry.registerLocator(service.getServiceInterface(), new ServiceRegistryImpl.ReturnInstance(service)); <ide> } <ide> }