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 | bsd-3-clause | b32636af4601dc944550966acb72fe0a38d2aa31 | 0 | alwalker/duty-hours | var express = require('express');
var pg = require('pg');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.get('/', function(request, response) {
response.send('Woooo!');
});
app.get('/api/users', function (request, response) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
if (err)
{ console.error(err); response.send("Error " + err); }
client.query('SELECT * FROM users', function(err, result) {
done();
if (err)
{ console.error(err); response.send("Error " + err); }
else
{ response.send({results: result.rows}); }
});
});
});
app.put('/api/:user/shift', function(request, response) {
findUser(
request.params.user,
function() {response.send("Couldn't find user!");},
function() {response.send("Found user!")})
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
function findUser(user, not_found_func, found_func) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
if (err) {
console.error(err);
not_found_func();
return;
}
client.query('SELECT * FROM users', function(err, result) {
done();
if (err) {
console.error(err);
not_found_func();
return;
}
else {
var found = false;
for(var row in result.rows) {
if(results.rows[row]['email'] === user) {
found = true;
break;
}
}
if(found) {
console.log('found them!');
found_func();
}
else {
console.log('not found!');
not_found_func();
}
}
});
});
}
| index.js | var express = require('express');
var pg = require('pg');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.get('/', function(request, response) {
response.send('Woooo!');
});
app.get('/api/users', function (request, response) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
if (err)
{ console.error(err); response.send("Error " + err); }
client.query('SELECT * FROM users', function(err, result) {
done();
if (err)
{ console.error(err); response.send("Error " + err); }
else
{ response.send({results: result.rows}); }
});
});
});
app.put('/api/:user/shift', function(request, response) {
findUser(
request.params.user,
function() {response.send("Couldn't find user!");},
function() {response.send("Found user!")})
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
function findUser(user, not_found_func, found_func) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
if (err) {
console.error(err);
not_found_func();
return;
}
client.query('SELECT * FROM users', function(err, result) {
done();
if (err) {
console.error(err);
not_found_func();
return;
}
else {
var found = false;
for(var row in result.rows) {
console.log('comparing ' + user + ' to ' + row['email']);
if(row['email'] === user) {
found = true;
break;
}
}
if(found) {
console.log('found them!');
found_func();
}
else {
console.log('not found!');
not_found_func();
}
}
});
});
}
| learned how for loops work
| index.js | learned how for loops work | <ide><path>ndex.js
<ide> else {
<ide> var found = false;
<ide> for(var row in result.rows) {
<del> console.log('comparing ' + user + ' to ' + row['email']);
<del> if(row['email'] === user) {
<add> if(results.rows[row]['email'] === user) {
<ide> found = true;
<ide> break;
<ide> } |
|
Java | apache-2.0 | f14cfba258532d57ae29f14d318dfb4be5ee0608 | 0 | signed/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,allotria/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,allotria/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,ibinti/intellij-community,signed/intellij-community,semonte/intellij-community,vvv1559/intellij-community,signed/intellij-community,youdonghai/intellij-community,semonte/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,signed/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,FHannes/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,ThiagoGarciaAlves/intellij-community,da1z/intellij-community,semonte/intellij-community,ibinti/intellij-community,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,ibinti/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,asedunov/intellij-community,asedunov/intellij-community,da1z/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,signed/intellij-community,suncycheng/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,allotria/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,vvv1559/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,ibinti/intellij-community,apixandru/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,da1z/intellij-community,suncycheng/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,da1z/intellij-community,signed/intellij-community,apixandru/intellij-community,signed/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,allotria/intellij-community,apixandru/intellij-community,ibinti/intellij-community,ibinti/intellij-community,FHannes/intellij-community,ibinti/intellij-community,signed/intellij-community,FHannes/intellij-community,allotria/intellij-community,FHannes/intellij-community,apixandru/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,apixandru/intellij-community,youdonghai/intellij-community,allotria/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,allotria/intellij-community,semonte/intellij-community,semonte/intellij-community,signed/intellij-community,signed/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,asedunov/intellij-community,ibinti/intellij-community,signed/intellij-community,suncycheng/intellij-community,asedunov/intellij-community,da1z/intellij-community,semonte/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,da1z/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,da1z/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,apixandru/intellij-community,ibinti/intellij-community,apixandru/intellij-community,FHannes/intellij-community,asedunov/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,mglukhikh/intellij-community,FHannes/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,da1z/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,semonte/intellij-community,idea4bsd/idea4bsd,FHannes/intellij-community,vvv1559/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,youdonghai/intellij-community,semonte/intellij-community,asedunov/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,apixandru/intellij-community,allotria/intellij-community | /*
* Copyright 2000-2016 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.ui.popup.list;
import com.intellij.openapi.ui.popup.ListItemDescriptor;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.ErrorLabel;
import com.intellij.ui.GroupedElementsRenderer;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import java.awt.*;
public class GroupedItemsListRenderer<E> extends GroupedElementsRenderer.List implements ListCellRenderer<E> {
protected ListItemDescriptor<E> myDescriptor;
protected JLabel myNextStepLabel;
public JLabel getNextStepLabel() {
return myNextStepLabel;
}
public GroupedItemsListRenderer(ListItemDescriptor<E> descriptor) {
myDescriptor = descriptor;
}
@Override
public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
String caption = myDescriptor.getCaptionAboveOf(value);
boolean hasSeparator = myDescriptor.hasSeparatorAboveOf(value);
if (index == 0 && StringUtil.isEmptyOrSpaces(caption)) hasSeparator = false;
Icon icon = myDescriptor.getIconFor(value);
final JComponent result = configureComponent(myDescriptor.getTextFor(value), myDescriptor.getTooltipFor(value),
icon, icon, isSelected, hasSeparator,
caption, -1);
customizeComponent(list, value, isSelected);
return result;
}
@Override
protected JComponent createItemComponent() {
createLabel();
return layoutComponent(myTextLabel);
}
protected void createLabel() {
myTextLabel = new ErrorLabel();
myTextLabel.setBorder(JBUI.Borders.emptyBottom(1));
myTextLabel.setOpaque(true);
}
protected final JComponent layoutComponent(JComponent middleItemComponent) {
myNextStepLabel = new JLabel();
myNextStepLabel.setOpaque(true);
return JBUI.Panels.simplePanel(middleItemComponent)
.addToRight(myNextStepLabel)
.withBorder(getDefaultItemComponentBorder());
}
protected void customizeComponent(JList list, Object value, boolean isSelected) {
}
}
| platform/platform-impl/src/com/intellij/ui/popup/list/GroupedItemsListRenderer.java | /*
* Copyright 2000-2016 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.ui.popup.list;
import com.intellij.openapi.ui.popup.ListItemDescriptor;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.ui.ErrorLabel;
import com.intellij.ui.GroupedElementsRenderer;
import com.intellij.util.ui.JBUI;
import javax.swing.*;
import java.awt.*;
public class GroupedItemsListRenderer extends GroupedElementsRenderer.List implements ListCellRenderer {
protected ListItemDescriptor myDescriptor;
protected JLabel myNextStepLabel;
public JLabel getNextStepLabel() {
return myNextStepLabel;
}
public GroupedItemsListRenderer(ListItemDescriptor descriptor) {
myDescriptor = descriptor;
}
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String caption = myDescriptor.getCaptionAboveOf(value);
boolean hasSeparator = myDescriptor.hasSeparatorAboveOf(value);
if (index == 0 && StringUtil.isEmptyOrSpaces(caption)) hasSeparator = false;
Icon icon = myDescriptor.getIconFor(value);
final JComponent result = configureComponent(myDescriptor.getTextFor(value), myDescriptor.getTooltipFor(value),
icon, icon, isSelected, hasSeparator,
caption, -1);
customizeComponent(list, value, isSelected);
return result;
}
@Override
protected JComponent createItemComponent() {
createLabel();
return layoutComponent(myTextLabel);
}
protected void createLabel() {
myTextLabel = new ErrorLabel();
myTextLabel.setBorder(JBUI.Borders.emptyBottom(1));
myTextLabel.setOpaque(true);
}
protected final JComponent layoutComponent(JComponent middleItemComponent) {
myNextStepLabel = new JLabel();
myNextStepLabel.setOpaque(true);
return JBUI.Panels.simplePanel(middleItemComponent)
.addToRight(myNextStepLabel)
.withBorder(getDefaultItemComponentBorder());
}
protected void customizeComponent(JList list, Object value, boolean isSelected) {
}
}
| GroupedItemsListRenderer generified
| platform/platform-impl/src/com/intellij/ui/popup/list/GroupedItemsListRenderer.java | GroupedItemsListRenderer generified | <ide><path>latform/platform-impl/src/com/intellij/ui/popup/list/GroupedItemsListRenderer.java
<ide> import javax.swing.*;
<ide> import java.awt.*;
<ide>
<del>public class GroupedItemsListRenderer extends GroupedElementsRenderer.List implements ListCellRenderer {
<del> protected ListItemDescriptor myDescriptor;
<add>public class GroupedItemsListRenderer<E> extends GroupedElementsRenderer.List implements ListCellRenderer<E> {
<add> protected ListItemDescriptor<E> myDescriptor;
<ide>
<ide> protected JLabel myNextStepLabel;
<ide>
<ide> }
<ide>
<ide>
<del> public GroupedItemsListRenderer(ListItemDescriptor descriptor) {
<add> public GroupedItemsListRenderer(ListItemDescriptor<E> descriptor) {
<ide> myDescriptor = descriptor;
<ide> }
<ide>
<ide> @Override
<del> public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
<add> public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
<ide> String caption = myDescriptor.getCaptionAboveOf(value);
<ide> boolean hasSeparator = myDescriptor.hasSeparatorAboveOf(value);
<ide> if (index == 0 && StringUtil.isEmptyOrSpaces(caption)) hasSeparator = false; |
|
Java | agpl-3.0 | 91dd64a46cca49d58d05a567ea413f51ce376458 | 0 | conwetlab/fiware-rss,conwetlab/fiware-rss,Fiware/apps.Rss,Fiware/apps.Rss,Fiware/apps.Rss,Fiware/apps.Rss,conwetlab/fiware-rss,conwetlab/fiware-rss | /**
* Revenue Settlement and Sharing System GE
* Copyright (C) 2011-2014, Javier Lucio - [email protected]
* Telefonica Investigacion y Desarrollo, S.A.
*
* Copyright (C) 2015, CoNWeT Lab., Universidad Politécnica de Madrid
*
* 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 es.tid.fiware.rss.ws;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import es.tid.fiware.rss.model.RSSModel;
import es.tid.fiware.rss.service.RSSModelsManager;
import es.tid.fiware.rss.exception.RSSException;
import es.tid.fiware.rss.exception.UNICAExceptionType;
import es.tid.fiware.rss.model.RSUser;
import es.tid.fiware.rss.service.UserManager;
/**
*
*
*/
@WebService(serviceName = "RSSModelService", name = "RSSModelService")
@Produces("application/json")
@Consumes("application/json")
@Path("/")
public class RSSModelService {
/**
* Variable to print the trace.
*/
private static Logger logger = LoggerFactory.getLogger(RSSModelService.class);
/**
*
*/
public static final String RESOURCE = "/rssModelManagement";
@Autowired
private RSSModelsManager rssModelsManager;
/**
* Oauth manager.
*/
@Autowired
private UserManager userManager;
/**
* Get Rss Models.
*
* @param appProvider
* @param productClass
* @param aggregatorId
* @return
* @throws Exception
*/
@WebMethod
@GET
@Path("/")
public Response getRssModels(@QueryParam("appProviderId") String appProvider,
@QueryParam("productClass") String productClass,
@QueryParam("aggregatorId") String aggregatorId)
throws Exception {
RSSModelService.logger.debug("Into getRssModels()");
RSUser user = userManager.getCurrentUser();
String effectiveAggregator;
if (userManager.isAdmin()) {
effectiveAggregator = aggregatorId;
} else if (null == aggregatorId || aggregatorId.equals(user.getEmail())){
effectiveAggregator = user.getEmail();
} else {
String[] args = {"You are not allowed to retrieve RS models for the given aggregator"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
List<RSSModel> rssModels = rssModelsManager.getRssModels(effectiveAggregator, appProvider, productClass);
// Response
ResponseBuilder rb = Response.status(Response.Status.OK.getStatusCode());
rb.entity(rssModels);
return rb.build();
}
/**
* Create Rss Model
*
* @param rssModel
* @return
* @throws Exception
*/
@WebMethod
@POST
@Path("/")
@Consumes("application/json")
public Response createRSSModel(RSSModel rssModel) throws Exception {
RSSModelService.logger.debug("Into createRSSModel method");
// check security
RSUser user = userManager.getCurrentUser();
// Validate that the user can create a RS model for the given aggregator
if (!userManager.isAdmin() &&
!rssModel.getAggregatorId().equals(user.getEmail())) {
String[] args = {"You are not allowed to create a RS model for the given aggregatorId"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
RSSModel model = rssModelsManager.createRssModel(rssModel);
// Building response
ResponseBuilder rb = Response.status(Response.Status.CREATED.getStatusCode());
rb.entity(model);
return rb.build();
}
/**
* Update Rss model
*
* @param rssModel
* @return
* @throws Exception
*/
@WebMethod
@PUT
@Path("/")
@Consumes("application/json")
public Response modifyRSSModel(RSSModel rssModel) throws Exception {
RSSModelService.logger.debug("Into modifyRSSModel method");
RSUser user = userManager.getCurrentUser();
// Validate that the user can modify a RS model for the given aggregator
if (!userManager.isAdmin() &&
!rssModel.getAggregatorId().equals(user.getEmail())) {
String[] args = {"You are not allowed to create a RS model for the given aggregatorId"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
RSSModel model = rssModelsManager.updateRssModel(rssModel);
// Building response
ResponseBuilder rb = Response.status(Response.Status.CREATED.getStatusCode());
rb.entity(model);
return rb.build();
}
/**
* Delete Rss Models.
*
* @param aggregatorId
* @param appProvider
* @param productClass
* @return
* @throws Exception
*/
@WebMethod
@DELETE
@Path("/")
@Consumes("application/json")
public Response deleteRSSModel(
@QueryParam("aggregatorId") String aggregatorId,
@QueryParam("appProviderId") String appProvider,
@QueryParam("productClass") String productClass) throws Exception {
RSSModelService.logger.debug("Into deleteRSSModel method");
// check security
RSUser user = userManager.getCurrentUser();
String effectiveAggregator;
if (userManager.isAdmin()) {
effectiveAggregator = aggregatorId;
} else if (null == aggregatorId || aggregatorId.equals(user.getEmail())){
effectiveAggregator = user.getEmail();
} else {
String[] args = {"You are not allowed to remove RS Models for the given aggregator"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
rssModelsManager.deleteRssModel(effectiveAggregator, appProvider, productClass);
// Building response
ResponseBuilder rb = Response.status(Response.Status.OK.getStatusCode());
return rb.build();
}
}
| fiware-rss/src/main/java/es/tid/fiware/rss/ws/RSSModelService.java | /**
* Revenue Settlement and Sharing System GE
* Copyright (C) 2011-2014, Javier Lucio - [email protected]
* Telefonica Investigacion y Desarrollo, S.A.
*
* Copyright (C) 2015, CoNWeT Lab., Universidad Politécnica de Madrid
*
* 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 es.tid.fiware.rss.ws;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.ResponseBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import es.tid.fiware.rss.model.RSSModel;
import es.tid.fiware.rss.service.RSSModelsManager;
import es.tid.fiware.rss.exception.RSSException;
import es.tid.fiware.rss.exception.UNICAExceptionType;
import es.tid.fiware.rss.model.RSUser;
import es.tid.fiware.rss.service.UserManager;
/**
*
*
*/
@WebService(serviceName = "RSSModelService", name = "RSSModelService")
@Produces("application/json")
@Consumes("application/json")
@Path("/")
public class RSSModelService {
/**
* Variable to print the trace.
*/
private static Logger logger = LoggerFactory.getLogger(RSSModelService.class);
/**
*
*/
public static final String RESOURCE = "/rssModelManagement";
@Autowired
private RSSModelsManager rssModelsManager;
/**
* Oauth manager.
*/
@Autowired
private UserManager userManager;
/**
* Get Rss Models.
*
* @param appProvider
* @param productClass
* @param aggregatorId
* @return
* @throws Exception
*/
@WebMethod
@GET
@Path("/")
public Response getRssModels(@QueryParam("appProviderId") String appProvider,
@QueryParam("productClass") String productClass,
@QueryParam("aggregatorId") String aggregatorId)
throws Exception {
RSSModelService.logger.debug("Into getRssModels()");
RSUser user = userManager.getCurrentUser();
String effectiveAggregator;
if (userManager.isAdmin()) {
effectiveAggregator = aggregatorId;
} else if (null == aggregatorId || aggregatorId.equals(user.getEmail())){
effectiveAggregator = user.getEmail();
} else {
String[] args = {"You are not allowed to retrieve RS models for the given aggregator"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
List<RSSModel> rssModels = rssModelsManager.getRssModels(effectiveAggregator, appProvider, productClass);
// Response
ResponseBuilder rb = Response.status(Response.Status.OK.getStatusCode());
rb.entity(rssModels);
return rb.build();
}
/**
* Create Rss Model
*
* @param rssModel
* @return
* @throws Exception
*/
@WebMethod
@POST
@Path("/")
@Consumes("application/json")
public Response createRSSModel(RSSModel rssModel) throws Exception {
RSSModelService.logger.debug("Into createRSSModel method");
// check security
RSUser user = userManager.getCurrentUser();
// Validate that the user can create a RS model for the given aggregator
if (!userManager.isAdmin() &&
!rssModel.getAggregatorId().equals(user.getEmail())) {
String[] args = {"You are not allowed to create a RS model for the given aggregatorId"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
RSSModel model = rssModelsManager.createRssModel(rssModel);
// Building response
ResponseBuilder rb = Response.status(Response.Status.CREATED.getStatusCode());
rb.entity(model);
return rb.build();
}
/**
* Update Rss model
*
* @param rssModel
* @return
* @throws Exception
*/
@WebMethod
@PUT
@Path("/")
@Consumes("application/json")
public Response modifyRSSModel(RSSModel rssModel) throws Exception {
RSSModelService.logger.debug("Into modifyRSSModel method");
RSUser user = userManager.getCurrentUser();
// Validate that the user can modify a RS model for the given aggregator
if (!userManager.isAdmin() &&
!rssModel.getAggregatorId().equals(user.getEmail())) {
String[] args = {"You are not allowed to create a RS model for the given aggregatorId"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
RSSModel model = rssModelsManager.updateRssModel(rssModel);
// Building response
ResponseBuilder rb = Response.status(Response.Status.CREATED.getStatusCode());
rb.entity(model);
return rb.build();
}
/**
* Delete Rss Models.
*
* @param aggregatorId
* @param appProvider
* @param productClass
* @return
* @throws Exception
*/
@WebMethod
@DELETE
@Path("/")
@Consumes("application/json")
public Response deleteRSSModel(
@QueryParam("aggregatorId") String aggregatorId,
@QueryParam("appProviderId") String appProvider,
@QueryParam("productClass") String productClass) throws Exception {
RSSModelService.logger.debug("Into deleteRSSModel method");
// check security
RSUser user = userManager.getCurrentUser();
String effectiveAggregator;
if (userManager.isAdmin()) {
effectiveAggregator = aggregatorId;
} else if (null == aggregatorId || aggregatorId.equals(user.getEmail())){
effectiveAggregator = user.getEmail();
} else {
String[] args = {"You are not allowed to remove RS Models for the given aggregator"};
throw new RSSException(UNICAExceptionType.NON_ALLOWED_OPERATION, args);
}
// Call service
rssModelsManager.deleteRssModel(effectiveAggregator, appProvider, productClass);
// Building response
ResponseBuilder rb = Response.status(Response.Status.OK.getStatusCode());
return rb.build();
}
}
| Remove unused import
| fiware-rss/src/main/java/es/tid/fiware/rss/ws/RSSModelService.java | Remove unused import | <ide><path>iware-rss/src/main/java/es/tid/fiware/rss/ws/RSSModelService.java
<ide> import javax.ws.rs.Consumes;
<ide> import javax.ws.rs.DELETE;
<ide> import javax.ws.rs.GET;
<del>import javax.ws.rs.HeaderParam;
<ide> import javax.ws.rs.POST;
<ide> import javax.ws.rs.PUT;
<ide> import javax.ws.rs.Path; |
|
Java | apache-2.0 | 0f52a8018a6671df97ce23133348d397a1a88167 | 0 | apache/batik,apache/batik,apache/batik,apache/batik | /*
Copyright 2003, 2006 The Apache Software Foundation
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.apache.batik.util;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.ref.PhantomReference;
/**
* One line Class Desc
*
* Complete Class Desc
*
* @author <a href="mailto:[email protected]">l449433</a>
* @version $Id$
*/
public class CleanerThread extends Thread {
static volatile ReferenceQueue queue = null;
static CleanerThread thread = null;
public static ReferenceQueue getReferenceQueue() {
if ( queue == null ) {
synchronized (CleanerThread.class) {
queue = new ReferenceQueue();
thread = new CleanerThread();
}
}
return queue;
}
/**
* If objects registered with the reference queue associated with
* this class implement this interface then the 'cleared' method
* will be called when the reference is queued.
*/
public static interface ReferenceCleared {
/* Called when the reference is cleared */
void cleared();
}
/**
* A SoftReference subclass that automatically registers with
* the cleaner ReferenceQueue.
*/
public static abstract class SoftReferenceCleared extends SoftReference
implements ReferenceCleared {
public SoftReferenceCleared(Object o) {
super (o, CleanerThread.getReferenceQueue());
}
}
/**
* A WeakReference subclass that automatically registers with
* the cleaner ReferenceQueue.
*/
public static abstract class WeakReferenceCleared extends WeakReference
implements ReferenceCleared {
public WeakReferenceCleared(Object o) {
super (o, CleanerThread.getReferenceQueue());
}
}
/**
* A PhantomReference subclass that automatically registers with
* the cleaner ReferenceQueue.
*/
public static abstract class PhantomReferenceCleared
extends PhantomReference
implements ReferenceCleared {
public PhantomReferenceCleared(Object o) {
super (o, CleanerThread.getReferenceQueue());
}
}
protected CleanerThread() {
setDaemon(true);
start();
}
public void run() {
while(true) {
try {
Reference ref;
try {
ref = queue.remove();
// System.err.println("Cleaned: " + ref);
} catch (InterruptedException ie) {
continue;
}
if (ref instanceof ReferenceCleared) {
ReferenceCleared rc = (ReferenceCleared)ref;
rc.cleared();
}
} catch (ThreadDeath td) {
throw td;
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
| sources/org/apache/batik/util/CleanerThread.java | /*
Copyright 2003 The Apache Software Foundation
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.apache.batik.util;
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.ref.PhantomReference;
/**
* One line Class Desc
*
* Complete Class Desc
*
* @author <a href="mailto:[email protected]">l449433</a>
* @version $Id$
*/
public class CleanerThread extends Thread {
static ReferenceQueue queue = null;
static CleanerThread thread = null;
public static ReferenceQueue getReferenceQueue() {
if (queue != null)
return queue;
queue = new ReferenceQueue();
thread = new CleanerThread();
return queue;
}
/**
* If objects registered with the reference queue associated with
* this class implement this interface then the 'cleared' method
* will be called when the reference is queued.
*/
public static interface ReferenceCleared {
/* Called when the reference is cleared */
public void cleared();
}
/**
* A SoftReference subclass that automatically registers with
* the cleaner ReferenceQueue.
*/
public static abstract class SoftReferenceCleared extends SoftReference
implements ReferenceCleared {
public SoftReferenceCleared(Object o) {
super (o, CleanerThread.getReferenceQueue());
}
}
/**
* A WeakReference subclass that automatically registers with
* the cleaner ReferenceQueue.
*/
public static abstract class WeakReferenceCleared extends WeakReference
implements ReferenceCleared {
public WeakReferenceCleared(Object o) {
super (o, CleanerThread.getReferenceQueue());
}
}
/**
* A PhantomReference subclass that automatically registers with
* the cleaner ReferenceQueue.
*/
public static abstract class PhantomReferenceCleared
extends PhantomReference
implements ReferenceCleared {
public PhantomReferenceCleared(Object o) {
super (o, CleanerThread.getReferenceQueue());
}
}
protected CleanerThread() {
setDaemon(true);
start();
}
public void run() {
while(true) {
try {
Reference ref;
try {
ref = queue.remove();
// System.err.println("Cleaned: " + ref);
} catch (InterruptedException ie) {
continue;
}
if (ref instanceof ReferenceCleared) {
ReferenceCleared rc = (ReferenceCleared)ref;
rc.cleared();
}
} catch (ThreadDeath td) {
throw td;
} catch (Throwable t) {
t.printStackTrace();
}
}
}
}
| proper thread-safe initialization of queue
git-svn-id: e944db0f7b5c8f0ae3e1ad43ca99b026751ef0c2@428323 13f79535-47bb-0310-9956-ffa450edef68
| sources/org/apache/batik/util/CleanerThread.java | proper thread-safe initialization of queue | <ide><path>ources/org/apache/batik/util/CleanerThread.java
<ide> /*
<ide>
<del> Copyright 2003 The Apache Software Foundation
<add> Copyright 2003, 2006 The Apache Software Foundation
<ide>
<ide> Licensed under the Apache License, Version 2.0 (the "License");
<ide> you may not use this file except in compliance with the License.
<ide> */
<ide> public class CleanerThread extends Thread {
<ide>
<del> static ReferenceQueue queue = null;
<add> static volatile ReferenceQueue queue = null;
<ide> static CleanerThread thread = null;
<ide>
<del> public static ReferenceQueue getReferenceQueue() {
<del> if (queue != null)
<del> return queue;
<del>
<del> queue = new ReferenceQueue();
<del> thread = new CleanerThread();
<del> return queue;
<add> public static ReferenceQueue getReferenceQueue() {
<add>
<add> if ( queue == null ) {
<add> synchronized (CleanerThread.class) {
<add> queue = new ReferenceQueue();
<add> thread = new CleanerThread();
<add> }
<add> }
<add> return queue;
<ide> }
<ide>
<ide> /**
<ide> */
<ide> public static interface ReferenceCleared {
<ide> /* Called when the reference is cleared */
<del> public void cleared();
<add> void cleared();
<ide> }
<ide>
<ide> /**
<del> * A SoftReference subclass that automatically registers with
<add> * A SoftReference subclass that automatically registers with
<ide> * the cleaner ReferenceQueue.
<ide> */
<del> public static abstract class SoftReferenceCleared extends SoftReference
<add> public static abstract class SoftReferenceCleared extends SoftReference
<ide> implements ReferenceCleared {
<ide> public SoftReferenceCleared(Object o) {
<ide> super (o, CleanerThread.getReferenceQueue());
<ide> }
<ide>
<ide> /**
<del> * A WeakReference subclass that automatically registers with
<add> * A WeakReference subclass that automatically registers with
<ide> * the cleaner ReferenceQueue.
<ide> */
<del> public static abstract class WeakReferenceCleared extends WeakReference
<add> public static abstract class WeakReferenceCleared extends WeakReference
<ide> implements ReferenceCleared {
<ide> public WeakReferenceCleared(Object o) {
<ide> super (o, CleanerThread.getReferenceQueue());
<ide> }
<ide>
<ide> /**
<del> * A PhantomReference subclass that automatically registers with
<add> * A PhantomReference subclass that automatically registers with
<ide> * the cleaner ReferenceQueue.
<ide> */
<del> public static abstract class PhantomReferenceCleared
<del> extends PhantomReference
<add> public static abstract class PhantomReferenceCleared
<add> extends PhantomReference
<ide> implements ReferenceCleared {
<ide> public PhantomReferenceCleared(Object o) {
<ide> super (o, CleanerThread.getReferenceQueue());
<ide> }
<ide> }
<del>
<add>
<ide> protected CleanerThread() {
<ide> setDaemon(true);
<ide> start(); |
|
Java | apache-2.0 | d5afd9622c30fa06f27cbe4b1d94cb90b25e2f89 | 0 | miniway/presto,hgschmie/presto,facebook/presto,stewartpark/presto,zzhao0/presto,twitter-forks/presto,raghavsethi/presto,Yaliang/presto,treasure-data/presto,prateek1306/presto,arhimondr/presto,yuananf/presto,treasure-data/presto,haozhun/presto,mandusm/presto,wagnermarkd/presto,facebook/presto,svstanev/presto,zzhao0/presto,svstanev/presto,electrum/presto,nezihyigitbasi/presto,jxiang/presto,damiencarol/presto,geraint0923/presto,martint/presto,mvp/presto,svstanev/presto,Yaliang/presto,elonazoulay/presto,11xor6/presto,prateek1306/presto,erichwang/presto,geraint0923/presto,dain/presto,dain/presto,ptkool/presto,miniway/presto,damiencarol/presto,nezihyigitbasi/presto,aleph-zero/presto,jiangyifangh/presto,treasure-data/presto,RobinUS2/presto,losipiuk/presto,prateek1306/presto,ocono-tech/presto,smartnews/presto,raghavsethi/presto,wyukawa/presto,arhimondr/presto,zzhao0/presto,facebook/presto,losipiuk/presto,RobinUS2/presto,mbeitchman/presto,wyukawa/presto,EvilMcJerkface/presto,ocono-tech/presto,arhimondr/presto,ocono-tech/presto,miniway/presto,twitter-forks/presto,dain/presto,EvilMcJerkface/presto,aglne/presto,elonazoulay/presto,Praveen2112/presto,haozhun/presto,Teradata/presto,twitter-forks/presto,aglne/presto,ebyhr/presto,treasure-data/presto,wagnermarkd/presto,erichwang/presto,wagnermarkd/presto,Praveen2112/presto,dain/presto,jxiang/presto,gh351135612/presto,electrum/presto,prestodb/presto,martint/presto,troels/nz-presto,bloomberg/presto,wagnermarkd/presto,gh351135612/presto,treasure-data/presto,sopel39/presto,sumitkgec/presto,svstanev/presto,mbeitchman/presto,aglne/presto,gh351135612/presto,nezihyigitbasi/presto,haozhun/presto,zzhao0/presto,prestodb/presto,Praveen2112/presto,youngwookim/presto,jxiang/presto,bloomberg/presto,prestodb/presto,mandusm/presto,Yaliang/presto,mbeitchman/presto,11xor6/presto,jiangyifangh/presto,jiangyifangh/presto,aramesh117/presto,nezihyigitbasi/presto,raghavsethi/presto,troels/nz-presto,troels/nz-presto,smartnews/presto,Teradata/presto,ptkool/presto,shixuan-fan/presto,ocono-tech/presto,mbeitchman/presto,troels/nz-presto,ebyhr/presto,sumitkgec/presto,elonazoulay/presto,11xor6/presto,aleph-zero/presto,Praveen2112/presto,arhimondr/presto,youngwookim/presto,aleph-zero/presto,shixuan-fan/presto,RobinUS2/presto,bloomberg/presto,smartnews/presto,arhimondr/presto,Yaliang/presto,elonazoulay/presto,mandusm/presto,aramesh117/presto,mandusm/presto,geraint0923/presto,hgschmie/presto,treasure-data/presto,wyukawa/presto,shixuan-fan/presto,wagnermarkd/presto,martint/presto,sopel39/presto,bloomberg/presto,mandusm/presto,ptkool/presto,geraint0923/presto,stewartpark/presto,11xor6/presto,Yaliang/presto,EvilMcJerkface/presto,yuananf/presto,ptkool/presto,hgschmie/presto,mvp/presto,aramesh117/presto,sopel39/presto,11xor6/presto,yuananf/presto,haozhun/presto,smartnews/presto,aramesh117/presto,youngwookim/presto,shixuan-fan/presto,miniway/presto,gh351135612/presto,Teradata/presto,troels/nz-presto,damiencarol/presto,mvp/presto,shixuan-fan/presto,prateek1306/presto,electrum/presto,EvilMcJerkface/presto,aramesh117/presto,aleph-zero/presto,jiangyifangh/presto,damiencarol/presto,erichwang/presto,aleph-zero/presto,erichwang/presto,raghavsethi/presto,Teradata/presto,haozhun/presto,mvp/presto,bloomberg/presto,yuananf/presto,hgschmie/presto,ebyhr/presto,sopel39/presto,losipiuk/presto,prestodb/presto,zzhao0/presto,youngwookim/presto,wyukawa/presto,raghavsethi/presto,miniway/presto,elonazoulay/presto,Praveen2112/presto,jiangyifangh/presto,ocono-tech/presto,youngwookim/presto,prestodb/presto,sopel39/presto,RobinUS2/presto,electrum/presto,gh351135612/presto,hgschmie/presto,mvp/presto,prateek1306/presto,Teradata/presto,wyukawa/presto,jxiang/presto,stewartpark/presto,sumitkgec/presto,dain/presto,aglne/presto,twitter-forks/presto,sumitkgec/presto,yuananf/presto,mbeitchman/presto,electrum/presto,stewartpark/presto,nezihyigitbasi/presto,losipiuk/presto,prestodb/presto,RobinUS2/presto,EvilMcJerkface/presto,stewartpark/presto,jxiang/presto,martint/presto,facebook/presto,damiencarol/presto,aglne/presto,twitter-forks/presto,erichwang/presto,ebyhr/presto,facebook/presto,geraint0923/presto,svstanev/presto,losipiuk/presto,martint/presto,ebyhr/presto,ptkool/presto,smartnews/presto,sumitkgec/presto | /*
* 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.presto.server;
import com.facebook.presto.GroupByHashPageIndexerFactory;
import com.facebook.presto.PagesIndexPageSorter;
import com.facebook.presto.SystemSessionProperties;
import com.facebook.presto.block.BlockEncodingManager;
import com.facebook.presto.block.BlockJsonSerde;
import com.facebook.presto.client.NodeVersion;
import com.facebook.presto.client.ServerInfo;
import com.facebook.presto.connector.ConnectorManager;
import com.facebook.presto.connector.system.SystemConnectorModule;
import com.facebook.presto.event.query.QueryMonitor;
import com.facebook.presto.event.query.QueryMonitorConfig;
import com.facebook.presto.execution.LocationFactory;
import com.facebook.presto.execution.NodeTaskMap;
import com.facebook.presto.execution.QueryManager;
import com.facebook.presto.execution.QueryManagerConfig;
import com.facebook.presto.execution.QueryPerformanceFetcher;
import com.facebook.presto.execution.QueryPerformanceFetcherProvider;
import com.facebook.presto.execution.SqlTaskManager;
import com.facebook.presto.execution.StageInfo;
import com.facebook.presto.execution.TaskExecutor;
import com.facebook.presto.execution.TaskInfo;
import com.facebook.presto.execution.TaskManager;
import com.facebook.presto.execution.TaskManagerConfig;
import com.facebook.presto.execution.TaskStatus;
import com.facebook.presto.execution.resourceGroups.NoOpResourceGroupManager;
import com.facebook.presto.execution.resourceGroups.ResourceGroupManager;
import com.facebook.presto.execution.scheduler.FlatNetworkTopology;
import com.facebook.presto.execution.scheduler.LegacyNetworkTopology;
import com.facebook.presto.execution.scheduler.NetworkTopology;
import com.facebook.presto.execution.scheduler.NodeScheduler;
import com.facebook.presto.execution.scheduler.NodeSchedulerConfig;
import com.facebook.presto.execution.scheduler.NodeSchedulerExporter;
import com.facebook.presto.failureDetector.FailureDetector;
import com.facebook.presto.failureDetector.FailureDetectorModule;
import com.facebook.presto.index.IndexManager;
import com.facebook.presto.memory.LocalMemoryManager;
import com.facebook.presto.memory.LocalMemoryManagerExporter;
import com.facebook.presto.memory.MemoryInfo;
import com.facebook.presto.memory.MemoryManagerConfig;
import com.facebook.presto.memory.MemoryPoolAssignmentsRequest;
import com.facebook.presto.memory.MemoryResource;
import com.facebook.presto.memory.NodeMemoryConfig;
import com.facebook.presto.memory.ReservedSystemMemoryConfig;
import com.facebook.presto.metadata.CatalogManager;
import com.facebook.presto.metadata.DiscoveryNodeManager;
import com.facebook.presto.metadata.ForNodeManager;
import com.facebook.presto.metadata.HandleJsonModule;
import com.facebook.presto.metadata.InternalNodeManager;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.SchemaPropertyManager;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.metadata.StaticCatalogStore;
import com.facebook.presto.metadata.StaticCatalogStoreConfig;
import com.facebook.presto.metadata.TablePropertyManager;
import com.facebook.presto.metadata.ViewDefinition;
import com.facebook.presto.operator.ExchangeClientConfig;
import com.facebook.presto.operator.ExchangeClientFactory;
import com.facebook.presto.operator.ExchangeClientSupplier;
import com.facebook.presto.operator.ForExchange;
import com.facebook.presto.operator.LookupJoinOperators;
import com.facebook.presto.operator.PagesIndex;
import com.facebook.presto.operator.index.IndexJoinLookupStats;
import com.facebook.presto.server.remotetask.HttpLocationFactory;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.PageIndexerFactory;
import com.facebook.presto.spi.PageSorter;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockEncodingFactory;
import com.facebook.presto.spi.block.BlockEncodingSerde;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spiller.BinarySpillerFactory;
import com.facebook.presto.spiller.SpillerFactory;
import com.facebook.presto.split.PageSinkManager;
import com.facebook.presto.split.PageSinkProvider;
import com.facebook.presto.split.PageSourceManager;
import com.facebook.presto.split.PageSourceProvider;
import com.facebook.presto.split.SplitManager;
import com.facebook.presto.sql.Serialization.ExpressionDeserializer;
import com.facebook.presto.sql.Serialization.ExpressionSerializer;
import com.facebook.presto.sql.Serialization.FunctionCallDeserializer;
import com.facebook.presto.sql.analyzer.FeaturesConfig;
import com.facebook.presto.sql.gen.ExpressionCompiler;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.sql.gen.JoinFilterFunctionCompiler;
import com.facebook.presto.sql.gen.JoinProbeCompiler;
import com.facebook.presto.sql.gen.OrderingCompiler;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.parser.SqlParserOptions;
import com.facebook.presto.sql.planner.CompilerConfig;
import com.facebook.presto.sql.planner.LocalExecutionPlanner;
import com.facebook.presto.sql.planner.NodePartitioningManager;
import com.facebook.presto.sql.planner.PlanOptimizers;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.transaction.ForTransactionManager;
import com.facebook.presto.transaction.TransactionManager;
import com.facebook.presto.transaction.TransactionManagerConfig;
import com.facebook.presto.type.TypeDeserializer;
import com.facebook.presto.type.TypeRegistry;
import com.facebook.presto.util.FinalizerService;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import io.airlift.concurrent.BoundedExecutor;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import io.airlift.discovery.client.ServiceDescriptor;
import io.airlift.node.NodeInfo;
import io.airlift.slice.Slice;
import io.airlift.stats.PauseMeter;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import javax.inject.Singleton;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import static com.facebook.presto.execution.scheduler.NodeSchedulerConfig.NetworkTopologyType.FLAT;
import static com.facebook.presto.execution.scheduler.NodeSchedulerConfig.NetworkTopologyType.LEGACY;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.reflect.Reflection.newProxy;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.airlift.configuration.ConditionalModule.installModuleIf;
import static io.airlift.configuration.ConfigBinder.configBinder;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonBinder.jsonBinder;
import static io.airlift.json.JsonCodecBinder.jsonCodecBinder;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.weakref.jmx.guice.ExportBinder.newExporter;
public class ServerMainModule
extends AbstractConfigurationAwareModule
{
private final SqlParserOptions sqlParserOptions;
public ServerMainModule(SqlParserOptions sqlParserOptions)
{
this.sqlParserOptions = requireNonNull(sqlParserOptions, "sqlParserOptions is null");
}
@Override
protected void setup(Binder binder)
{
ServerConfig serverConfig = buildConfigObject(ServerConfig.class);
if (serverConfig.isCoordinator()) {
install(new CoordinatorModule());
binder.bind(new TypeLiteral<Optional<QueryPerformanceFetcher>>(){}).toProvider(QueryPerformanceFetcherProvider.class).in(Scopes.SINGLETON);
}
else {
binder.bind(new TypeLiteral<Optional<QueryPerformanceFetcher>>(){}).toInstance(Optional.empty());
// Install no-op resource group manager on workers, since only coordinators manage resource groups.
binder.bind(ResourceGroupManager.class).to(NoOpResourceGroupManager.class).in(Scopes.SINGLETON);
// HACK: this binding is needed by SystemConnectorModule, but will only be used on the coordinator
binder.bind(QueryManager.class).toInstance(newProxy(QueryManager.class, (proxy, method, args) -> {
throw new UnsupportedOperationException();
}));
}
configBinder(binder).bindConfig(FeaturesConfig.class);
binder.bind(SqlParser.class).in(Scopes.SINGLETON);
binder.bind(SqlParserOptions.class).toInstance(sqlParserOptions);
bindFailureDetector(binder, serverConfig.isCoordinator());
jaxrsBinder(binder).bind(ThrowableMapper.class);
configBinder(binder).bindConfig(QueryManagerConfig.class);
jsonCodecBinder(binder).bindJsonCodec(ViewDefinition.class);
// session properties
binder.bind(SessionPropertyManager.class).in(Scopes.SINGLETON);
binder.bind(SystemSessionProperties.class).in(Scopes.SINGLETON);
// schema properties
binder.bind(SchemaPropertyManager.class).in(Scopes.SINGLETON);
// table properties
binder.bind(TablePropertyManager.class).in(Scopes.SINGLETON);
// node manager
discoveryBinder(binder).bindSelector("presto");
binder.bind(DiscoveryNodeManager.class).in(Scopes.SINGLETON);
binder.bind(InternalNodeManager.class).to(DiscoveryNodeManager.class).in(Scopes.SINGLETON);
newExporter(binder).export(DiscoveryNodeManager.class).withGeneratedName();
httpClientBinder(binder).bindHttpClient("node-manager", ForNodeManager.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
});
// node scheduler
// TODO: remove from NodePartitioningManager and move to CoordinatorModule
configBinder(binder).bindConfig(NodeSchedulerConfig.class);
binder.bind(NodeScheduler.class).in(Scopes.SINGLETON);
binder.bind(NodeSchedulerExporter.class).in(Scopes.SINGLETON);
binder.bind(NodeTaskMap.class).in(Scopes.SINGLETON);
newExporter(binder).export(NodeScheduler.class).withGeneratedName();
// network topology
// TODO: move to CoordinatorModule when NodeScheduler is moved
install(installModuleIf(
NodeSchedulerConfig.class,
config -> LEGACY.equalsIgnoreCase(config.getNetworkTopology()),
moduleBinder -> moduleBinder.bind(NetworkTopology.class).to(LegacyNetworkTopology.class).in(Scopes.SINGLETON)));
install(installModuleIf(
NodeSchedulerConfig.class,
config -> FLAT.equalsIgnoreCase(config.getNetworkTopology()),
moduleBinder -> moduleBinder.bind(NetworkTopology.class).to(FlatNetworkTopology.class).in(Scopes.SINGLETON)));
// task execution
jaxrsBinder(binder).bind(TaskResource.class);
newExporter(binder).export(TaskResource.class).withGeneratedName();
binder.bind(TaskManager.class).to(SqlTaskManager.class).in(Scopes.SINGLETON);
// workaround for CodeCache GC issue
if (JavaVersion.current().getMajor() == 8) {
configBinder(binder).bindConfig(CodeCacheGcConfig.class);
binder.bind(CodeCacheGcTrigger.class).in(Scopes.SINGLETON);
}
// Add monitoring for JVM pauses
binder.bind(PauseMeter.class).in(Scopes.SINGLETON);
newExporter(binder).export(PauseMeter.class).withGeneratedName();
configBinder(binder).bindConfig(MemoryManagerConfig.class);
configBinder(binder).bindConfig(NodeMemoryConfig.class);
configBinder(binder).bindConfig(ReservedSystemMemoryConfig.class);
binder.bind(LocalMemoryManager.class).in(Scopes.SINGLETON);
binder.bind(LocalMemoryManagerExporter.class).in(Scopes.SINGLETON);
newExporter(binder).export(TaskManager.class).withGeneratedName();
binder.bind(TaskExecutor.class).in(Scopes.SINGLETON);
newExporter(binder).export(TaskExecutor.class).withGeneratedName();
binder.bind(LocalExecutionPlanner.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(CompilerConfig.class);
binder.bind(ExpressionCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(ExpressionCompiler.class).withGeneratedName();
configBinder(binder).bindConfig(TaskManagerConfig.class);
binder.bind(IndexJoinLookupStats.class).in(Scopes.SINGLETON);
newExporter(binder).export(IndexJoinLookupStats.class).withGeneratedName();
binder.bind(AsyncHttpExecutionMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(AsyncHttpExecutionMBean.class).withGeneratedName();
binder.bind(JoinFilterFunctionCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(JoinFilterFunctionCompiler.class).withGeneratedName();
binder.bind(JoinCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(JoinCompiler.class).withGeneratedName();
binder.bind(OrderingCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(OrderingCompiler.class).withGeneratedName();
binder.bind(PagesIndex.Factory.class).to(PagesIndex.DefaultFactory.class);
binder.bind(JoinProbeCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(JoinProbeCompiler.class).withGeneratedName();
binder.bind(LookupJoinOperators.class).in(Scopes.SINGLETON);
jsonCodecBinder(binder).bindJsonCodec(TaskStatus.class);
jsonCodecBinder(binder).bindJsonCodec(StageInfo.class);
jsonCodecBinder(binder).bindJsonCodec(TaskInfo.class);
jaxrsBinder(binder).bind(PagesResponseWriter.class);
// exchange client
binder.bind(new TypeLiteral<ExchangeClientSupplier>() {}).to(ExchangeClientFactory.class).in(Scopes.SINGLETON);
httpClientBinder(binder).bindHttpClient("exchange", ForExchange.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
config.setMaxConnectionsPerServer(250);
config.setMaxContentLength(new DataSize(32, MEGABYTE));
});
configBinder(binder).bindConfig(ExchangeClientConfig.class);
binder.bind(ExchangeExecutionMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(ExchangeExecutionMBean.class).withGeneratedName();
// execution
binder.bind(LocationFactory.class).to(HttpLocationFactory.class).in(Scopes.SINGLETON);
// memory manager
jaxrsBinder(binder).bind(MemoryResource.class);
jsonCodecBinder(binder).bindJsonCodec(MemoryInfo.class);
jsonCodecBinder(binder).bindJsonCodec(MemoryPoolAssignmentsRequest.class);
// transaction manager
configBinder(binder).bindConfig(TransactionManagerConfig.class);
// data stream provider
binder.bind(PageSourceManager.class).in(Scopes.SINGLETON);
binder.bind(PageSourceProvider.class).to(PageSourceManager.class).in(Scopes.SINGLETON);
// page sink provider
binder.bind(PageSinkManager.class).in(Scopes.SINGLETON);
binder.bind(PageSinkProvider.class).to(PageSinkManager.class).in(Scopes.SINGLETON);
// metadata
binder.bind(StaticCatalogStore.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(StaticCatalogStoreConfig.class);
binder.bind(MetadataManager.class).in(Scopes.SINGLETON);
binder.bind(Metadata.class).to(MetadataManager.class).in(Scopes.SINGLETON);
// type
binder.bind(TypeRegistry.class).in(Scopes.SINGLETON);
binder.bind(TypeManager.class).to(TypeRegistry.class).in(Scopes.SINGLETON);
jsonBinder(binder).addDeserializerBinding(Type.class).to(TypeDeserializer.class);
newSetBinder(binder, Type.class);
// split manager
binder.bind(SplitManager.class).in(Scopes.SINGLETON);
// node partitioning manager
binder.bind(NodePartitioningManager.class).in(Scopes.SINGLETON);
// index manager
binder.bind(IndexManager.class).in(Scopes.SINGLETON);
// handle resolver
binder.install(new HandleJsonModule());
// connector
binder.bind(ConnectorManager.class).in(Scopes.SINGLETON);
// system connector
binder.install(new SystemConnectorModule());
// splits
jsonCodecBinder(binder).bindJsonCodec(TaskUpdateRequest.class);
jsonCodecBinder(binder).bindJsonCodec(ConnectorSplit.class);
jsonBinder(binder).addSerializerBinding(Slice.class).to(SliceSerializer.class);
jsonBinder(binder).addDeserializerBinding(Slice.class).to(SliceDeserializer.class);
jsonBinder(binder).addSerializerBinding(Expression.class).to(ExpressionSerializer.class);
jsonBinder(binder).addDeserializerBinding(Expression.class).to(ExpressionDeserializer.class);
jsonBinder(binder).addDeserializerBinding(FunctionCall.class).to(FunctionCallDeserializer.class);
// query monitor
configBinder(binder).bindConfig(QueryMonitorConfig.class);
binder.bind(QueryMonitor.class).in(Scopes.SINGLETON);
// Determine the NodeVersion
String prestoVersion = serverConfig.getPrestoVersion();
if (prestoVersion == null) {
prestoVersion = getClass().getPackage().getImplementationVersion();
}
checkState(prestoVersion != null, "presto.version must be provided when it cannot be automatically determined");
NodeVersion nodeVersion = new NodeVersion(prestoVersion);
binder.bind(NodeVersion.class).toInstance(nodeVersion);
// presto announcement
discoveryBinder(binder).bindHttpAnnouncement("presto")
.addProperty("node_version", nodeVersion.toString())
.addProperty("coordinator", String.valueOf(serverConfig.isCoordinator()))
.addProperty("connectorIds", nullToEmpty(serverConfig.getDataSources()));
// server info resource
jaxrsBinder(binder).bind(ServerInfoResource.class);
// plugin manager
binder.bind(PluginManager.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(PluginManagerConfig.class);
binder.bind(CatalogManager.class).in(Scopes.SINGLETON);
// optimizers
binder.bind(PlanOptimizers.class).in(Scopes.SINGLETON);
// block encodings
binder.bind(BlockEncodingManager.class).in(Scopes.SINGLETON);
binder.bind(BlockEncodingSerde.class).to(BlockEncodingManager.class).in(Scopes.SINGLETON);
newSetBinder(binder, new TypeLiteral<BlockEncodingFactory<?>>() {});
jsonBinder(binder).addSerializerBinding(Block.class).to(BlockJsonSerde.Serializer.class);
jsonBinder(binder).addDeserializerBinding(Block.class).to(BlockJsonSerde.Deserializer.class);
// thread visualizer
jaxrsBinder(binder).bind(ThreadResource.class);
// PageSorter
binder.bind(PageSorter.class).to(PagesIndexPageSorter.class).in(Scopes.SINGLETON);
// PageIndexer
binder.bind(PageIndexerFactory.class).to(GroupByHashPageIndexerFactory.class).in(Scopes.SINGLETON);
// Finalizer
binder.bind(FinalizerService.class).in(Scopes.SINGLETON);
// Spiller
binder.bind(SpillerFactory.class).to(BinarySpillerFactory.class).in(Scopes.SINGLETON);
newExporter(binder).export(SpillerFactory.class).withGeneratedName();
}
@Provides
@Singleton
public static ServerInfo createServerInfo(NodeVersion nodeVersion, NodeInfo nodeInfo, ServerConfig serverConfig)
{
return new ServerInfo(nodeVersion, nodeInfo.getEnvironment(), serverConfig.isCoordinator());
}
@Provides
@Singleton
@ForExchange
public static ScheduledExecutorService createExchangeExecutor(ExchangeClientConfig config)
{
return newScheduledThreadPool(config.getClientThreads(), daemonThreadsNamed("exchange-client-%s"));
}
@Provides
@Singleton
@ForAsyncHttp
public static ExecutorService createAsyncHttpResponseCoreExecutor()
{
return newCachedThreadPool(daemonThreadsNamed("async-http-response-%s"));
}
@Provides
@Singleton
@ForAsyncHttp
public static BoundedExecutor createAsyncHttpResponseExecutor(@ForAsyncHttp ExecutorService coreExecutor, TaskManagerConfig config)
{
return new BoundedExecutor(coreExecutor, config.getHttpResponseThreads());
}
@Provides
@Singleton
@ForAsyncHttp
public static ScheduledExecutorService createAsyncHttpTimeoutExecutor(TaskManagerConfig config)
{
return newScheduledThreadPool(config.getHttpTimeoutThreads(), daemonThreadsNamed("async-http-timeout-%s"));
}
@Provides
@Singleton
@ForTransactionManager
public static ScheduledExecutorService createTransactionIdleCheckExecutor()
{
return newSingleThreadScheduledExecutor(daemonThreadsNamed("transaction-idle-check"));
}
@Provides
@Singleton
@ForTransactionManager
public static ExecutorService createTransactionFinishingExecutor()
{
return newCachedThreadPool(daemonThreadsNamed("transaction-finishing-%s"));
}
@Provides
@Singleton
public static TransactionManager createTransactionManager(
TransactionManagerConfig config,
CatalogManager catalogManager,
@ForTransactionManager ScheduledExecutorService idleCheckExecutor,
@ForTransactionManager ExecutorService finishingExecutor)
{
return TransactionManager.create(config, idleCheckExecutor, catalogManager, finishingExecutor);
}
private static void bindFailureDetector(Binder binder, boolean coordinator)
{
// TODO: this is a hack until the coordinator module works correctly
if (coordinator) {
binder.install(new FailureDetectorModule());
jaxrsBinder(binder).bind(NodeResource.class);
}
else {
binder.bind(FailureDetector.class).toInstance(new FailureDetector()
{
@Override
public Set<ServiceDescriptor> getFailed()
{
return ImmutableSet.of();
}
});
}
}
}
| presto-main/src/main/java/com/facebook/presto/server/ServerMainModule.java | /*
* 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.presto.server;
import com.facebook.presto.GroupByHashPageIndexerFactory;
import com.facebook.presto.PagesIndexPageSorter;
import com.facebook.presto.SystemSessionProperties;
import com.facebook.presto.block.BlockEncodingManager;
import com.facebook.presto.block.BlockJsonSerde;
import com.facebook.presto.client.NodeVersion;
import com.facebook.presto.client.ServerInfo;
import com.facebook.presto.connector.ConnectorManager;
import com.facebook.presto.connector.system.SystemConnectorModule;
import com.facebook.presto.event.query.QueryMonitor;
import com.facebook.presto.event.query.QueryMonitorConfig;
import com.facebook.presto.execution.LocationFactory;
import com.facebook.presto.execution.NodeTaskMap;
import com.facebook.presto.execution.QueryManager;
import com.facebook.presto.execution.QueryManagerConfig;
import com.facebook.presto.execution.QueryPerformanceFetcher;
import com.facebook.presto.execution.QueryPerformanceFetcherProvider;
import com.facebook.presto.execution.SqlTaskManager;
import com.facebook.presto.execution.StageInfo;
import com.facebook.presto.execution.TaskExecutor;
import com.facebook.presto.execution.TaskInfo;
import com.facebook.presto.execution.TaskManager;
import com.facebook.presto.execution.TaskManagerConfig;
import com.facebook.presto.execution.TaskStatus;
import com.facebook.presto.execution.resourceGroups.NoOpResourceGroupManager;
import com.facebook.presto.execution.resourceGroups.ResourceGroupManager;
import com.facebook.presto.execution.scheduler.FlatNetworkTopology;
import com.facebook.presto.execution.scheduler.LegacyNetworkTopology;
import com.facebook.presto.execution.scheduler.NetworkTopology;
import com.facebook.presto.execution.scheduler.NodeScheduler;
import com.facebook.presto.execution.scheduler.NodeSchedulerConfig;
import com.facebook.presto.execution.scheduler.NodeSchedulerExporter;
import com.facebook.presto.failureDetector.FailureDetector;
import com.facebook.presto.failureDetector.FailureDetectorModule;
import com.facebook.presto.index.IndexManager;
import com.facebook.presto.memory.LocalMemoryManager;
import com.facebook.presto.memory.LocalMemoryManagerExporter;
import com.facebook.presto.memory.MemoryInfo;
import com.facebook.presto.memory.MemoryManagerConfig;
import com.facebook.presto.memory.MemoryPoolAssignmentsRequest;
import com.facebook.presto.memory.MemoryResource;
import com.facebook.presto.memory.NodeMemoryConfig;
import com.facebook.presto.memory.ReservedSystemMemoryConfig;
import com.facebook.presto.metadata.CatalogManager;
import com.facebook.presto.metadata.DiscoveryNodeManager;
import com.facebook.presto.metadata.ForNodeManager;
import com.facebook.presto.metadata.HandleJsonModule;
import com.facebook.presto.metadata.InternalNodeManager;
import com.facebook.presto.metadata.Metadata;
import com.facebook.presto.metadata.MetadataManager;
import com.facebook.presto.metadata.SchemaPropertyManager;
import com.facebook.presto.metadata.SessionPropertyManager;
import com.facebook.presto.metadata.StaticCatalogStore;
import com.facebook.presto.metadata.StaticCatalogStoreConfig;
import com.facebook.presto.metadata.TablePropertyManager;
import com.facebook.presto.metadata.ViewDefinition;
import com.facebook.presto.operator.ExchangeClientConfig;
import com.facebook.presto.operator.ExchangeClientFactory;
import com.facebook.presto.operator.ExchangeClientSupplier;
import com.facebook.presto.operator.ForExchange;
import com.facebook.presto.operator.LookupJoinOperators;
import com.facebook.presto.operator.PagesIndex;
import com.facebook.presto.operator.index.IndexJoinLookupStats;
import com.facebook.presto.server.remotetask.HttpLocationFactory;
import com.facebook.presto.spi.ConnectorSplit;
import com.facebook.presto.spi.PageIndexerFactory;
import com.facebook.presto.spi.PageSorter;
import com.facebook.presto.spi.block.Block;
import com.facebook.presto.spi.block.BlockEncodingFactory;
import com.facebook.presto.spi.block.BlockEncodingSerde;
import com.facebook.presto.spi.type.Type;
import com.facebook.presto.spi.type.TypeManager;
import com.facebook.presto.spiller.BinarySpillerFactory;
import com.facebook.presto.spiller.SpillerFactory;
import com.facebook.presto.split.PageSinkManager;
import com.facebook.presto.split.PageSinkProvider;
import com.facebook.presto.split.PageSourceManager;
import com.facebook.presto.split.PageSourceProvider;
import com.facebook.presto.split.SplitManager;
import com.facebook.presto.sql.Serialization.ExpressionDeserializer;
import com.facebook.presto.sql.Serialization.ExpressionSerializer;
import com.facebook.presto.sql.Serialization.FunctionCallDeserializer;
import com.facebook.presto.sql.analyzer.FeaturesConfig;
import com.facebook.presto.sql.gen.ExpressionCompiler;
import com.facebook.presto.sql.gen.JoinCompiler;
import com.facebook.presto.sql.gen.JoinFilterFunctionCompiler;
import com.facebook.presto.sql.gen.JoinProbeCompiler;
import com.facebook.presto.sql.gen.OrderingCompiler;
import com.facebook.presto.sql.parser.SqlParser;
import com.facebook.presto.sql.parser.SqlParserOptions;
import com.facebook.presto.sql.planner.CompilerConfig;
import com.facebook.presto.sql.planner.LocalExecutionPlanner;
import com.facebook.presto.sql.planner.NodePartitioningManager;
import com.facebook.presto.sql.planner.PlanOptimizers;
import com.facebook.presto.sql.tree.Expression;
import com.facebook.presto.sql.tree.FunctionCall;
import com.facebook.presto.transaction.ForTransactionManager;
import com.facebook.presto.transaction.TransactionManager;
import com.facebook.presto.transaction.TransactionManagerConfig;
import com.facebook.presto.type.TypeDeserializer;
import com.facebook.presto.type.TypeRegistry;
import com.facebook.presto.util.FinalizerService;
import com.google.common.collect.ImmutableSet;
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.Scopes;
import com.google.inject.TypeLiteral;
import io.airlift.concurrent.BoundedExecutor;
import io.airlift.configuration.AbstractConfigurationAwareModule;
import io.airlift.discovery.client.ServiceDescriptor;
import io.airlift.node.NodeInfo;
import io.airlift.slice.Slice;
import io.airlift.stats.PauseMeter;
import io.airlift.units.Duration;
import javax.inject.Singleton;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ScheduledExecutorService;
import static com.facebook.presto.execution.scheduler.NodeSchedulerConfig.NetworkTopologyType.FLAT;
import static com.facebook.presto.execution.scheduler.NodeSchedulerConfig.NetworkTopologyType.LEGACY;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.base.Strings.nullToEmpty;
import static com.google.common.reflect.Reflection.newProxy;
import static com.google.inject.multibindings.Multibinder.newSetBinder;
import static io.airlift.concurrent.Threads.daemonThreadsNamed;
import static io.airlift.configuration.ConditionalModule.installModuleIf;
import static io.airlift.configuration.ConfigBinder.configBinder;
import static io.airlift.discovery.client.DiscoveryBinder.discoveryBinder;
import static io.airlift.http.client.HttpClientBinder.httpClientBinder;
import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
import static io.airlift.json.JsonBinder.jsonBinder;
import static io.airlift.json.JsonCodecBinder.jsonCodecBinder;
import static java.util.Objects.requireNonNull;
import static java.util.concurrent.Executors.newCachedThreadPool;
import static java.util.concurrent.Executors.newScheduledThreadPool;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.weakref.jmx.guice.ExportBinder.newExporter;
public class ServerMainModule
extends AbstractConfigurationAwareModule
{
private final SqlParserOptions sqlParserOptions;
public ServerMainModule(SqlParserOptions sqlParserOptions)
{
this.sqlParserOptions = requireNonNull(sqlParserOptions, "sqlParserOptions is null");
}
@Override
protected void setup(Binder binder)
{
ServerConfig serverConfig = buildConfigObject(ServerConfig.class);
if (serverConfig.isCoordinator()) {
install(new CoordinatorModule());
binder.bind(new TypeLiteral<Optional<QueryPerformanceFetcher>>(){}).toProvider(QueryPerformanceFetcherProvider.class).in(Scopes.SINGLETON);
}
else {
binder.bind(new TypeLiteral<Optional<QueryPerformanceFetcher>>(){}).toInstance(Optional.empty());
// Install no-op resource group manager on workers, since only coordinators manage resource groups.
binder.bind(ResourceGroupManager.class).to(NoOpResourceGroupManager.class).in(Scopes.SINGLETON);
// HACK: this binding is needed by SystemConnectorModule, but will only be used on the coordinator
binder.bind(QueryManager.class).toInstance(newProxy(QueryManager.class, (proxy, method, args) -> {
throw new UnsupportedOperationException();
}));
}
configBinder(binder).bindConfig(FeaturesConfig.class);
binder.bind(SqlParser.class).in(Scopes.SINGLETON);
binder.bind(SqlParserOptions.class).toInstance(sqlParserOptions);
bindFailureDetector(binder, serverConfig.isCoordinator());
jaxrsBinder(binder).bind(ThrowableMapper.class);
configBinder(binder).bindConfig(QueryManagerConfig.class);
jsonCodecBinder(binder).bindJsonCodec(ViewDefinition.class);
// session properties
binder.bind(SessionPropertyManager.class).in(Scopes.SINGLETON);
binder.bind(SystemSessionProperties.class).in(Scopes.SINGLETON);
// schema properties
binder.bind(SchemaPropertyManager.class).in(Scopes.SINGLETON);
// table properties
binder.bind(TablePropertyManager.class).in(Scopes.SINGLETON);
// node manager
discoveryBinder(binder).bindSelector("presto");
binder.bind(DiscoveryNodeManager.class).in(Scopes.SINGLETON);
binder.bind(InternalNodeManager.class).to(DiscoveryNodeManager.class).in(Scopes.SINGLETON);
newExporter(binder).export(DiscoveryNodeManager.class).withGeneratedName();
httpClientBinder(binder).bindHttpClient("node-manager", ForNodeManager.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
});
// node scheduler
// TODO: remove from NodePartitioningManager and move to CoordinatorModule
configBinder(binder).bindConfig(NodeSchedulerConfig.class);
binder.bind(NodeScheduler.class).in(Scopes.SINGLETON);
binder.bind(NodeSchedulerExporter.class).in(Scopes.SINGLETON);
binder.bind(NodeTaskMap.class).in(Scopes.SINGLETON);
newExporter(binder).export(NodeScheduler.class).withGeneratedName();
// network topology
// TODO: move to CoordinatorModule when NodeScheduler is moved
install(installModuleIf(
NodeSchedulerConfig.class,
config -> LEGACY.equalsIgnoreCase(config.getNetworkTopology()),
moduleBinder -> moduleBinder.bind(NetworkTopology.class).to(LegacyNetworkTopology.class).in(Scopes.SINGLETON)));
install(installModuleIf(
NodeSchedulerConfig.class,
config -> FLAT.equalsIgnoreCase(config.getNetworkTopology()),
moduleBinder -> moduleBinder.bind(NetworkTopology.class).to(FlatNetworkTopology.class).in(Scopes.SINGLETON)));
// task execution
jaxrsBinder(binder).bind(TaskResource.class);
newExporter(binder).export(TaskResource.class).withGeneratedName();
binder.bind(TaskManager.class).to(SqlTaskManager.class).in(Scopes.SINGLETON);
// workaround for CodeCache GC issue
if (JavaVersion.current().getMajor() == 8) {
configBinder(binder).bindConfig(CodeCacheGcConfig.class);
binder.bind(CodeCacheGcTrigger.class).in(Scopes.SINGLETON);
}
// Add monitoring for JVM pauses
binder.bind(PauseMeter.class).in(Scopes.SINGLETON);
newExporter(binder).export(PauseMeter.class).withGeneratedName();
configBinder(binder).bindConfig(MemoryManagerConfig.class);
configBinder(binder).bindConfig(NodeMemoryConfig.class);
configBinder(binder).bindConfig(ReservedSystemMemoryConfig.class);
binder.bind(LocalMemoryManager.class).in(Scopes.SINGLETON);
binder.bind(LocalMemoryManagerExporter.class).in(Scopes.SINGLETON);
newExporter(binder).export(TaskManager.class).withGeneratedName();
binder.bind(TaskExecutor.class).in(Scopes.SINGLETON);
newExporter(binder).export(TaskExecutor.class).withGeneratedName();
binder.bind(LocalExecutionPlanner.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(CompilerConfig.class);
binder.bind(ExpressionCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(ExpressionCompiler.class).withGeneratedName();
configBinder(binder).bindConfig(TaskManagerConfig.class);
binder.bind(IndexJoinLookupStats.class).in(Scopes.SINGLETON);
newExporter(binder).export(IndexJoinLookupStats.class).withGeneratedName();
binder.bind(AsyncHttpExecutionMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(AsyncHttpExecutionMBean.class).withGeneratedName();
binder.bind(JoinFilterFunctionCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(JoinFilterFunctionCompiler.class).withGeneratedName();
binder.bind(JoinCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(JoinCompiler.class).withGeneratedName();
binder.bind(OrderingCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(OrderingCompiler.class).withGeneratedName();
binder.bind(PagesIndex.Factory.class).to(PagesIndex.DefaultFactory.class);
binder.bind(JoinProbeCompiler.class).in(Scopes.SINGLETON);
newExporter(binder).export(JoinProbeCompiler.class).withGeneratedName();
binder.bind(LookupJoinOperators.class).in(Scopes.SINGLETON);
jsonCodecBinder(binder).bindJsonCodec(TaskStatus.class);
jsonCodecBinder(binder).bindJsonCodec(StageInfo.class);
jsonCodecBinder(binder).bindJsonCodec(TaskInfo.class);
jaxrsBinder(binder).bind(PagesResponseWriter.class);
// exchange client
binder.bind(new TypeLiteral<ExchangeClientSupplier>() {}).to(ExchangeClientFactory.class).in(Scopes.SINGLETON);
httpClientBinder(binder).bindHttpClient("exchange", ForExchange.class)
.withTracing()
.withConfigDefaults(config -> {
config.setIdleTimeout(new Duration(30, SECONDS));
config.setRequestTimeout(new Duration(10, SECONDS));
config.setMaxConnectionsPerServer(250);
});
configBinder(binder).bindConfig(ExchangeClientConfig.class);
binder.bind(ExchangeExecutionMBean.class).in(Scopes.SINGLETON);
newExporter(binder).export(ExchangeExecutionMBean.class).withGeneratedName();
// execution
binder.bind(LocationFactory.class).to(HttpLocationFactory.class).in(Scopes.SINGLETON);
// memory manager
jaxrsBinder(binder).bind(MemoryResource.class);
jsonCodecBinder(binder).bindJsonCodec(MemoryInfo.class);
jsonCodecBinder(binder).bindJsonCodec(MemoryPoolAssignmentsRequest.class);
// transaction manager
configBinder(binder).bindConfig(TransactionManagerConfig.class);
// data stream provider
binder.bind(PageSourceManager.class).in(Scopes.SINGLETON);
binder.bind(PageSourceProvider.class).to(PageSourceManager.class).in(Scopes.SINGLETON);
// page sink provider
binder.bind(PageSinkManager.class).in(Scopes.SINGLETON);
binder.bind(PageSinkProvider.class).to(PageSinkManager.class).in(Scopes.SINGLETON);
// metadata
binder.bind(StaticCatalogStore.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(StaticCatalogStoreConfig.class);
binder.bind(MetadataManager.class).in(Scopes.SINGLETON);
binder.bind(Metadata.class).to(MetadataManager.class).in(Scopes.SINGLETON);
// type
binder.bind(TypeRegistry.class).in(Scopes.SINGLETON);
binder.bind(TypeManager.class).to(TypeRegistry.class).in(Scopes.SINGLETON);
jsonBinder(binder).addDeserializerBinding(Type.class).to(TypeDeserializer.class);
newSetBinder(binder, Type.class);
// split manager
binder.bind(SplitManager.class).in(Scopes.SINGLETON);
// node partitioning manager
binder.bind(NodePartitioningManager.class).in(Scopes.SINGLETON);
// index manager
binder.bind(IndexManager.class).in(Scopes.SINGLETON);
// handle resolver
binder.install(new HandleJsonModule());
// connector
binder.bind(ConnectorManager.class).in(Scopes.SINGLETON);
// system connector
binder.install(new SystemConnectorModule());
// splits
jsonCodecBinder(binder).bindJsonCodec(TaskUpdateRequest.class);
jsonCodecBinder(binder).bindJsonCodec(ConnectorSplit.class);
jsonBinder(binder).addSerializerBinding(Slice.class).to(SliceSerializer.class);
jsonBinder(binder).addDeserializerBinding(Slice.class).to(SliceDeserializer.class);
jsonBinder(binder).addSerializerBinding(Expression.class).to(ExpressionSerializer.class);
jsonBinder(binder).addDeserializerBinding(Expression.class).to(ExpressionDeserializer.class);
jsonBinder(binder).addDeserializerBinding(FunctionCall.class).to(FunctionCallDeserializer.class);
// query monitor
configBinder(binder).bindConfig(QueryMonitorConfig.class);
binder.bind(QueryMonitor.class).in(Scopes.SINGLETON);
// Determine the NodeVersion
String prestoVersion = serverConfig.getPrestoVersion();
if (prestoVersion == null) {
prestoVersion = getClass().getPackage().getImplementationVersion();
}
checkState(prestoVersion != null, "presto.version must be provided when it cannot be automatically determined");
NodeVersion nodeVersion = new NodeVersion(prestoVersion);
binder.bind(NodeVersion.class).toInstance(nodeVersion);
// presto announcement
discoveryBinder(binder).bindHttpAnnouncement("presto")
.addProperty("node_version", nodeVersion.toString())
.addProperty("coordinator", String.valueOf(serverConfig.isCoordinator()))
.addProperty("connectorIds", nullToEmpty(serverConfig.getDataSources()));
// server info resource
jaxrsBinder(binder).bind(ServerInfoResource.class);
// plugin manager
binder.bind(PluginManager.class).in(Scopes.SINGLETON);
configBinder(binder).bindConfig(PluginManagerConfig.class);
binder.bind(CatalogManager.class).in(Scopes.SINGLETON);
// optimizers
binder.bind(PlanOptimizers.class).in(Scopes.SINGLETON);
// block encodings
binder.bind(BlockEncodingManager.class).in(Scopes.SINGLETON);
binder.bind(BlockEncodingSerde.class).to(BlockEncodingManager.class).in(Scopes.SINGLETON);
newSetBinder(binder, new TypeLiteral<BlockEncodingFactory<?>>() {});
jsonBinder(binder).addSerializerBinding(Block.class).to(BlockJsonSerde.Serializer.class);
jsonBinder(binder).addDeserializerBinding(Block.class).to(BlockJsonSerde.Deserializer.class);
// thread visualizer
jaxrsBinder(binder).bind(ThreadResource.class);
// PageSorter
binder.bind(PageSorter.class).to(PagesIndexPageSorter.class).in(Scopes.SINGLETON);
// PageIndexer
binder.bind(PageIndexerFactory.class).to(GroupByHashPageIndexerFactory.class).in(Scopes.SINGLETON);
// Finalizer
binder.bind(FinalizerService.class).in(Scopes.SINGLETON);
// Spiller
binder.bind(SpillerFactory.class).to(BinarySpillerFactory.class).in(Scopes.SINGLETON);
newExporter(binder).export(SpillerFactory.class).withGeneratedName();
}
@Provides
@Singleton
public static ServerInfo createServerInfo(NodeVersion nodeVersion, NodeInfo nodeInfo, ServerConfig serverConfig)
{
return new ServerInfo(nodeVersion, nodeInfo.getEnvironment(), serverConfig.isCoordinator());
}
@Provides
@Singleton
@ForExchange
public static ScheduledExecutorService createExchangeExecutor(ExchangeClientConfig config)
{
return newScheduledThreadPool(config.getClientThreads(), daemonThreadsNamed("exchange-client-%s"));
}
@Provides
@Singleton
@ForAsyncHttp
public static ExecutorService createAsyncHttpResponseCoreExecutor()
{
return newCachedThreadPool(daemonThreadsNamed("async-http-response-%s"));
}
@Provides
@Singleton
@ForAsyncHttp
public static BoundedExecutor createAsyncHttpResponseExecutor(@ForAsyncHttp ExecutorService coreExecutor, TaskManagerConfig config)
{
return new BoundedExecutor(coreExecutor, config.getHttpResponseThreads());
}
@Provides
@Singleton
@ForAsyncHttp
public static ScheduledExecutorService createAsyncHttpTimeoutExecutor(TaskManagerConfig config)
{
return newScheduledThreadPool(config.getHttpTimeoutThreads(), daemonThreadsNamed("async-http-timeout-%s"));
}
@Provides
@Singleton
@ForTransactionManager
public static ScheduledExecutorService createTransactionIdleCheckExecutor()
{
return newSingleThreadScheduledExecutor(daemonThreadsNamed("transaction-idle-check"));
}
@Provides
@Singleton
@ForTransactionManager
public static ExecutorService createTransactionFinishingExecutor()
{
return newCachedThreadPool(daemonThreadsNamed("transaction-finishing-%s"));
}
@Provides
@Singleton
public static TransactionManager createTransactionManager(
TransactionManagerConfig config,
CatalogManager catalogManager,
@ForTransactionManager ScheduledExecutorService idleCheckExecutor,
@ForTransactionManager ExecutorService finishingExecutor)
{
return TransactionManager.create(config, idleCheckExecutor, catalogManager, finishingExecutor);
}
private static void bindFailureDetector(Binder binder, boolean coordinator)
{
// TODO: this is a hack until the coordinator module works correctly
if (coordinator) {
binder.install(new FailureDetectorModule());
jaxrsBinder(binder).bind(NodeResource.class);
}
else {
binder.bind(FailureDetector.class).toInstance(new FailureDetector()
{
@Override
public Set<ServiceDescriptor> getFailed()
{
return ImmutableSet.of();
}
});
}
}
}
| Increase default exchange HTTP max content length to 32MB
| presto-main/src/main/java/com/facebook/presto/server/ServerMainModule.java | Increase default exchange HTTP max content length to 32MB | <ide><path>resto-main/src/main/java/com/facebook/presto/server/ServerMainModule.java
<ide> import io.airlift.node.NodeInfo;
<ide> import io.airlift.slice.Slice;
<ide> import io.airlift.stats.PauseMeter;
<add>import io.airlift.units.DataSize;
<ide> import io.airlift.units.Duration;
<ide>
<ide> import javax.inject.Singleton;
<ide> import static io.airlift.jaxrs.JaxrsBinder.jaxrsBinder;
<ide> import static io.airlift.json.JsonBinder.jsonBinder;
<ide> import static io.airlift.json.JsonCodecBinder.jsonCodecBinder;
<add>import static io.airlift.units.DataSize.Unit.MEGABYTE;
<ide> import static java.util.Objects.requireNonNull;
<ide> import static java.util.concurrent.Executors.newCachedThreadPool;
<ide> import static java.util.concurrent.Executors.newScheduledThreadPool;
<ide> config.setIdleTimeout(new Duration(30, SECONDS));
<ide> config.setRequestTimeout(new Duration(10, SECONDS));
<ide> config.setMaxConnectionsPerServer(250);
<add> config.setMaxContentLength(new DataSize(32, MEGABYTE));
<ide> });
<ide>
<ide> configBinder(binder).bindConfig(ExchangeClientConfig.class); |
|
Java | bsd-2-clause | 275bf37287f80a4b1d3b69b925bf7f24023b4563 | 0 | 7u83/SeSim,7u83/SeSim | /*
* Copyright (c) 2017, 7u83 <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * 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 HOLDER 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 gui.orderbook;
import gui.Globals;
import gui.Globals.CfgListener;
import gui.tools.NummericCellRenderer;
import java.awt.Component;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import sesim.Exchange;
import sesim.Exchange.Order;
import sesim.Exchange.OrderType;
/**
*
* @author 7u83 <[email protected]>
*/
public class OrderBook extends javax.swing.JPanel implements Exchange.BookReceiver, CfgListener {
DefaultTableModel model;
TableColumn trader_column = null;
class Renderer extends DefaultTableCellRenderer {
private final DecimalFormat formatter = new DecimalFormat("#.0000");
Renderer() {
super();
this.setHorizontalAlignment(RIGHT);
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
// First format the cell value as required
value = formatter.format((Number) value);
// And pass it on to parent class
return super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
}
}
OrderType type = OrderType.BUYLIMIT;
int depth = 40;
public void setGodMode(boolean on) {
TableColumnModel tcm = list.getColumnModel();
if (on) {
if (list.getColumnCount() == 3) {
return;
}
tcm.addColumn(trader_column);
tcm.moveColumn(2, 0);
} else {
if (list.getColumnCount() == 2) {
return;
}
tcm.removeColumn(tcm.getColumn(0));
}
}
/**
* Bla
*/
@Override
public final void cfgChanged() {
boolean gm = Globals.prefs.get(Globals.CfgStrings.GODMODE, "false").equals("true");
setGodMode(gm);
list.invalidate();
list.repaint();
}
public void setType(OrderType type) {
this.type = type;
Globals.se.addBookReceiver(type, this);
}
/**
* Creates new form OrderBookNew
*/
public OrderBook() {
initComponents();
if (Globals.se == null) {
return;
}
model = (DefaultTableModel) this.list.getModel();
trader_column = list.getColumnModel().getColumn(0);
list.getColumnModel().getColumn(1).setCellRenderer(new NummericCellRenderer(3));
list.getColumnModel().getColumn(2).setCellRenderer(new NummericCellRenderer(0));
cfgChanged();
// Globals.se.addBookReceiver(Exchange.OrderType.BUYLIMIT, this);
Globals.addCfgListener(this);
}
boolean oupdate = false;
boolean new_oupdate = false;
void oupdater() {
ArrayList<Order> ob = Globals.se.getOrderBook(type, depth);
model.setRowCount(ob.size());
int row = 0;
for (Order ob1 : ob) {
model.setValueAt(ob1.getAccount().getOwner().getName(), row, 0);
model.setValueAt(ob1.getLimit(), row, 1);
model.setValueAt(ob1.getVolume(), row, 2);
row++;
}
oupdate = false;
}
@Override
public synchronized void UpdateOrderBook() {
if (oupdate) {
new_oupdate=true;
return;
}
oupdate = true;
SwingUtilities.invokeLater(() -> {
oupdater();
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
list = new javax.swing.JTable();
list.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Trader", "Price", "Volume"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Double.class, java.lang.Double.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(list);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable list;
// End of variables declaration//GEN-END:variables
}
| src/main/java/gui/orderbook/OrderBook.java | /*
* Copyright (c) 2017, 7u83 <[email protected]>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * 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 HOLDER 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 gui.orderbook;
import gui.Globals;
import gui.Globals.CfgListener;
import java.awt.Component;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import sesim.Exchange;
import sesim.Exchange.Order;
import sesim.Exchange.OrderType;
/**
*
* @author 7u83 <[email protected]>
*/
public class OrderBook extends javax.swing.JPanel implements Exchange.BookReceiver, CfgListener {
DefaultTableModel model;
TableColumn trader_column = null;
class Renderer extends DefaultTableCellRenderer {
private final DecimalFormat formatter = new DecimalFormat("#.0000");
Renderer() {
super();
this.setHorizontalAlignment(RIGHT);
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
// First format the cell value as required
value = formatter.format((Number) value);
// And pass it on to parent class
return super.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
}
}
OrderType type = OrderType.BUYLIMIT;
int depth = 40;
public void setGodMode(boolean on) {
TableColumnModel tcm = list.getColumnModel();
if (on) {
if (list.getColumnCount() == 3) {
return;
}
tcm.addColumn(trader_column);
tcm.moveColumn(2, 0);
} else {
if (list.getColumnCount() == 2) {
return;
}
tcm.removeColumn(tcm.getColumn(0));
}
}
/**
* Bla
*/
@Override
public final void cfgChanged() {
boolean gm = Globals.prefs.get(Globals.CfgStrings.GODMODE, "false").equals("true");
setGodMode(gm);
list.invalidate();
list.repaint();
}
public void setType(OrderType type) {
this.type = type;
Globals.se.addBookReceiver(type, this);
}
/**
* Creates new form OrderBookNew
*/
public OrderBook() {
initComponents();
if (Globals.se == null) {
return;
}
model = (DefaultTableModel) this.list.getModel();
trader_column = list.getColumnModel().getColumn(0);
list.getColumnModel().getColumn(1).setCellRenderer(new Renderer());
cfgChanged();
// Globals.se.addBookReceiver(Exchange.OrderType.BUYLIMIT, this);
Globals.addCfgListener(this);
}
boolean oupdate = false;
boolean new_oupdate = false;
void oupdater() {
ArrayList<Order> ob = Globals.se.getOrderBook(type, depth);
model.setRowCount(ob.size());
int row = 0;
for (Order ob1 : ob) {
model.setValueAt(ob1.getAccount().getOwner().getName(), row, 0);
model.setValueAt(ob1.getLimit(), row, 1);
model.setValueAt(ob1.getVolume(), row, 2);
row++;
}
oupdate = false;
}
@Override
public synchronized void UpdateOrderBook() {
if (oupdate) {
new_oupdate=true;
return;
}
oupdate = true;
SwingUtilities.invokeLater(() -> {
oupdater();
});
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jScrollPane1 = new javax.swing.JScrollPane();
list = new javax.swing.JTable();
list.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Trader", "Price", "Volume"
}
) {
Class[] types = new Class [] {
java.lang.String.class, java.lang.Double.class, java.lang.Double.class
};
boolean[] canEdit = new boolean [] {
false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
jScrollPane1.setViewportView(list);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 389, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 284, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable list;
// End of variables declaration//GEN-END:variables
}
| Uses NummericCellRenderer | src/main/java/gui/orderbook/OrderBook.java | Uses NummericCellRenderer | <ide><path>rc/main/java/gui/orderbook/OrderBook.java
<ide>
<ide> import gui.Globals;
<ide> import gui.Globals.CfgListener;
<add>import gui.tools.NummericCellRenderer;
<ide> import java.awt.Component;
<ide> import java.text.DecimalFormat;
<ide> import java.util.ArrayList;
<ide> }
<ide> model = (DefaultTableModel) this.list.getModel();
<ide> trader_column = list.getColumnModel().getColumn(0);
<del> list.getColumnModel().getColumn(1).setCellRenderer(new Renderer());
<add> list.getColumnModel().getColumn(1).setCellRenderer(new NummericCellRenderer(3));
<add> list.getColumnModel().getColumn(2).setCellRenderer(new NummericCellRenderer(0));
<ide> cfgChanged();
<ide> // Globals.se.addBookReceiver(Exchange.OrderType.BUYLIMIT, this);
<ide> Globals.addCfgListener(this); |
|
Java | apache-2.0 | 68942691fc20efafaa0b36825fd0b593ba118e32 | 0 | consulo/consulo-java,consulo/consulo-java,consulo/consulo-java,consulo/consulo-java | /*
* Copyright 2000-2009 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.
*/
/**
* class FilteredRequestorImpl
* @author Jeka
*/
package com.intellij.debugger.ui.breakpoints;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.debugger.InstanceFilter;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.PsiElement;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.xdebugger.impl.XDebuggerHistoryManager;
import com.intellij.xdebugger.impl.breakpoints.ui.DefaultConditionComboBoxPanel;
import consulo.internal.com.sun.jdi.event.LocatableEvent;
/*
* Not used any more, since move to xBreakpoints
*/
public class FilteredRequestorImpl implements JDOMExternalizable, FilteredRequestor
{
public String SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
public boolean SUSPEND = true;
public boolean COUNT_FILTER_ENABLED = false;
public int COUNT_FILTER = 0;
public boolean CONDITION_ENABLED = false;
private TextWithImports myCondition;
public boolean CLASS_FILTERS_ENABLED = false;
private ClassFilter[] myClassFilters = ClassFilter.EMPTY_ARRAY;
private ClassFilter[] myClassExclusionFilters = ClassFilter.EMPTY_ARRAY;
public boolean INSTANCE_FILTERS_ENABLED = false;
private InstanceFilter[] myInstanceFilters = InstanceFilter.EMPTY_ARRAY;
@NonNls
private static final String FILTER_OPTION_NAME = "filter";
@NonNls
private static final String EXCLUSION_FILTER_OPTION_NAME = "exclusion_filter";
@NonNls
private static final String INSTANCE_ID_OPTION_NAME = "instance_id";
@NonNls
private static final String CONDITION_OPTION_NAME = "CONDITION";
protected final Project myProject;
public FilteredRequestorImpl(@NotNull Project project)
{
myProject = project;
myCondition = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "");
}
@Override
public InstanceFilter[] getInstanceFilters()
{
return myInstanceFilters;
}
public void setInstanceFilters(InstanceFilter[] instanceFilters)
{
myInstanceFilters = instanceFilters != null ? instanceFilters : InstanceFilter.EMPTY_ARRAY;
}
@Override
public String getSuspendPolicy()
{
return SUSPEND ? SUSPEND_POLICY : DebuggerSettings.SUSPEND_NONE;
}
/**
* @return true if the ID was added or false otherwise
*/
private boolean hasObjectID(long id)
{
for(InstanceFilter instanceFilter : myInstanceFilters)
{
if(instanceFilter.getId() == id)
{
return true;
}
}
return false;
}
protected void addInstanceFilter(long l)
{
final InstanceFilter[] filters = new InstanceFilter[myInstanceFilters.length + 1];
System.arraycopy(myInstanceFilters, 0, filters, 0, myInstanceFilters.length);
filters[myInstanceFilters.length] = InstanceFilter.create(String.valueOf(l));
myInstanceFilters = filters;
}
@Override
public final ClassFilter[] getClassFilters()
{
return myClassFilters;
}
public final void setClassFilters(ClassFilter[] classFilters)
{
myClassFilters = classFilters != null ? classFilters : ClassFilter.EMPTY_ARRAY;
}
@Override
public ClassFilter[] getClassExclusionFilters()
{
return myClassExclusionFilters;
}
public void setClassExclusionFilters(ClassFilter[] classExclusionFilters)
{
myClassExclusionFilters = classExclusionFilters != null ? classExclusionFilters : ClassFilter.EMPTY_ARRAY;
}
public void readTo(Element parentNode, Breakpoint breakpoint) throws InvalidDataException
{
readExternal(parentNode);
if(SUSPEND)
{
breakpoint.setSuspendPolicy(SUSPEND_POLICY);
}
else
{
breakpoint.setSuspendPolicy(DebuggerSettings.SUSPEND_NONE);
}
breakpoint.setCountFilterEnabled(COUNT_FILTER_ENABLED);
breakpoint.setCountFilter(COUNT_FILTER);
breakpoint.setCondition(CONDITION_ENABLED ? myCondition : null);
if(myCondition != null && !myCondition.isEmpty())
{
XDebuggerHistoryManager.getInstance(myProject).addRecentExpression(DefaultConditionComboBoxPanel.HISTORY_KEY,
TextWithImportsImpl.toXExpression(myCondition));
}
breakpoint.setClassFiltersEnabled(CLASS_FILTERS_ENABLED);
breakpoint.setClassFilters(getClassFilters());
breakpoint.setClassExclusionFilters(getClassExclusionFilters());
breakpoint.setInstanceFiltersEnabled(INSTANCE_FILTERS_ENABLED);
breakpoint.setInstanceFilters(getInstanceFilters());
}
@Override
public void readExternal(Element parentNode) throws InvalidDataException
{
DefaultJDOMExternalizer.readExternal(this, parentNode);
if(DebuggerSettings.SUSPEND_NONE.equals(SUSPEND_POLICY))
{ // compatibility with older format
SUSPEND = false;
SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
}
String condition = JDOMExternalizerUtil.readField(parentNode, CONDITION_OPTION_NAME);
if(condition != null)
{
setCondition(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition));
}
myClassFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(FILTER_OPTION_NAME));
myClassExclusionFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(EXCLUSION_FILTER_OPTION_NAME));
final ClassFilter[] instanceFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(INSTANCE_ID_OPTION_NAME));
final List<InstanceFilter> iFilters = new ArrayList<InstanceFilter>(instanceFilters.length);
for(ClassFilter instanceFilter : instanceFilters)
{
try
{
iFilters.add(InstanceFilter.create(instanceFilter));
}
catch(Exception e)
{
}
}
myInstanceFilters = iFilters.isEmpty() ? InstanceFilter.EMPTY_ARRAY : iFilters.toArray(new InstanceFilter[iFilters.size()]);
}
@Override
public void writeExternal(Element parentNode) throws WriteExternalException
{
DefaultJDOMExternalizer.writeExternal(this, parentNode);
JDOMExternalizerUtil.writeField(parentNode, CONDITION_OPTION_NAME, getCondition().toExternalForm());
DebuggerUtilsEx.writeFilters(parentNode, FILTER_OPTION_NAME, myClassFilters);
DebuggerUtilsEx.writeFilters(parentNode, EXCLUSION_FILTER_OPTION_NAME, myClassExclusionFilters);
DebuggerUtilsEx.writeFilters(parentNode, INSTANCE_ID_OPTION_NAME, InstanceFilter.createClassFilters(myInstanceFilters));
}
protected String calculateEventClass(EvaluationContextImpl context, LocatableEvent event) throws EvaluateException
{
return event.location().declaringType().name();
}
private boolean typeMatchesClassFilters(@Nullable String typeName)
{
if(typeName == null)
{
return true;
}
boolean matches = false, hasEnabled = false;
for(ClassFilter classFilter : getClassFilters())
{
if(classFilter.isEnabled())
{
hasEnabled = true;
if(classFilter.matches(typeName))
{
matches = true;
break;
}
}
}
if(hasEnabled && !matches)
{
return false;
}
for(ClassFilter classFilter : getClassExclusionFilters())
{
if(classFilter.isEnabled() && classFilter.matches(typeName))
{
return false;
}
}
return true;
}
public PsiElement getEvaluationElement()
{
return null;
}
public TextWithImports getCondition()
{
return myCondition;
}
public void setCondition(TextWithImports condition)
{
myCondition = condition;
}
public Project getProject()
{
return myProject;
}
@Override
public boolean isCountFilterEnabled()
{
return COUNT_FILTER_ENABLED;
}
@Override
public int getCountFilter()
{
return COUNT_FILTER;
}
@Override
public boolean isClassFiltersEnabled()
{
return CLASS_FILTERS_ENABLED;
}
@Override
public boolean isInstanceFiltersEnabled()
{
return INSTANCE_FILTERS_ENABLED;
}
@Override
public boolean processLocatableEvent(SuspendContextCommandImpl action, LocatableEvent event) throws EventProcessingException
{
return false;
}
}
| java-debugger-impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java | /*
* Copyright 2000-2009 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.
*/
/**
* class FilteredRequestorImpl
* @author Jeka
*/
package com.intellij.debugger.ui.breakpoints;
import java.util.ArrayList;
import java.util.List;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import com.intellij.debugger.InstanceFilter;
import com.intellij.debugger.engine.evaluation.CodeFragmentKind;
import com.intellij.debugger.engine.evaluation.EvaluateException;
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
import com.intellij.debugger.engine.evaluation.TextWithImports;
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl;
import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
import com.intellij.debugger.impl.DebuggerUtilsEx;
import com.intellij.debugger.settings.DebuggerSettings;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.DefaultJDOMExternalizer;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.JDOMExternalizable;
import com.intellij.openapi.util.JDOMExternalizerUtil;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.PsiElement;
import com.intellij.ui.classFilter.ClassFilter;
import com.intellij.xdebugger.impl.XDebuggerHistoryManager;
import com.intellij.xdebugger.impl.breakpoints.ui.DefaultConditionComboBoxPanel;
import consulo.internal.com.sun.jdi.event.LocatableEvent;
/*
* Not used any more, since move to xBreakpoints
*/
public class FilteredRequestorImpl implements JDOMExternalizable, FilteredRequestor
{
public String SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
public boolean SUSPEND = true;
public boolean COUNT_FILTER_ENABLED = false;
public int COUNT_FILTER = 0;
public boolean CONDITION_ENABLED = false;
private TextWithImports myCondition;
public boolean CLASS_FILTERS_ENABLED = false;
private ClassFilter[] myClassFilters = ClassFilter.EMPTY_ARRAY;
private ClassFilter[] myClassExclusionFilters = ClassFilter.EMPTY_ARRAY;
public boolean INSTANCE_FILTERS_ENABLED = false;
private InstanceFilter[] myInstanceFilters = InstanceFilter.EMPTY_ARRAY;
@NonNls
private static final String FILTER_OPTION_NAME = "filter";
@NonNls
private static final String EXCLUSION_FILTER_OPTION_NAME = "exclusion_filter";
@NonNls
private static final String INSTANCE_ID_OPTION_NAME = "instance_id";
@NonNls
private static final String CONDITION_OPTION_NAME = "CONDITION";
protected final Project myProject;
public FilteredRequestorImpl(@NotNull Project project)
{
myProject = project;
myCondition = new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, "");
}
@Override
public InstanceFilter[] getInstanceFilters()
{
return myInstanceFilters;
}
public void setInstanceFilters(InstanceFilter[] instanceFilters)
{
myInstanceFilters = instanceFilters != null ? instanceFilters : InstanceFilter.EMPTY_ARRAY;
}
@Override
public String getSuspendPolicy()
{
return SUSPEND ? SUSPEND_POLICY : DebuggerSettings.SUSPEND_NONE;
}
/**
* @return true if the ID was added or false otherwise
*/
private boolean hasObjectID(long id)
{
for(InstanceFilter instanceFilter : myInstanceFilters)
{
if(instanceFilter.getId() == id)
{
return true;
}
}
return false;
}
protected void addInstanceFilter(long l)
{
final InstanceFilter[] filters = new InstanceFilter[myInstanceFilters.length + 1];
System.arraycopy(myInstanceFilters, 0, filters, 0, myInstanceFilters.length);
filters[myInstanceFilters.length] = InstanceFilter.create(String.valueOf(l));
myInstanceFilters = filters;
}
@Override
public final ClassFilter[] getClassFilters()
{
return myClassFilters;
}
public final void setClassFilters(ClassFilter[] classFilters)
{
myClassFilters = classFilters != null ? classFilters : ClassFilter.EMPTY_ARRAY;
}
@Override
public ClassFilter[] getClassExclusionFilters()
{
return myClassExclusionFilters;
}
public void setClassExclusionFilters(ClassFilter[] classExclusionFilters)
{
myClassExclusionFilters = classExclusionFilters != null ? classExclusionFilters : ClassFilter.EMPTY_ARRAY;
}
public void readTo(Element parentNode, Breakpoint breakpoint) throws InvalidDataException
{
readExternal(parentNode);
if(SUSPEND)
{
breakpoint.setSuspendPolicy(SUSPEND_POLICY);
}
else
{
breakpoint.setSuspendPolicy(DebuggerSettings.SUSPEND_NONE);
}
breakpoint.setCountFilterEnabled(COUNT_FILTER_ENABLED);
breakpoint.setCountFilter(COUNT_FILTER);
breakpoint.setCondition(CONDITION_ENABLED ? myCondition : null);
if(myCondition != null && !myCondition.isEmpty())
{
XDebuggerHistoryManager.getInstance(myProject).addRecentExpression(DefaultConditionComboBoxPanel.HISTORY_KEY, myCondition.getText());
}
breakpoint.setClassFiltersEnabled(CLASS_FILTERS_ENABLED);
breakpoint.setClassFilters(getClassFilters());
breakpoint.setClassExclusionFilters(getClassExclusionFilters());
breakpoint.setInstanceFiltersEnabled(INSTANCE_FILTERS_ENABLED);
breakpoint.setInstanceFilters(getInstanceFilters());
}
@Override
public void readExternal(Element parentNode) throws InvalidDataException
{
DefaultJDOMExternalizer.readExternal(this, parentNode);
if(DebuggerSettings.SUSPEND_NONE.equals(SUSPEND_POLICY))
{ // compatibility with older format
SUSPEND = false;
SUSPEND_POLICY = DebuggerSettings.SUSPEND_ALL;
}
String condition = JDOMExternalizerUtil.readField(parentNode, CONDITION_OPTION_NAME);
if(condition != null)
{
setCondition(new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition));
}
myClassFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(FILTER_OPTION_NAME));
myClassExclusionFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(EXCLUSION_FILTER_OPTION_NAME));
final ClassFilter[] instanceFilters = DebuggerUtilsEx.readFilters(parentNode.getChildren(INSTANCE_ID_OPTION_NAME));
final List<InstanceFilter> iFilters = new ArrayList<InstanceFilter>(instanceFilters.length);
for(ClassFilter instanceFilter : instanceFilters)
{
try
{
iFilters.add(InstanceFilter.create(instanceFilter));
}
catch(Exception e)
{
}
}
myInstanceFilters = iFilters.isEmpty() ? InstanceFilter.EMPTY_ARRAY : iFilters.toArray(new InstanceFilter[iFilters.size()]);
}
@Override
public void writeExternal(Element parentNode) throws WriteExternalException
{
DefaultJDOMExternalizer.writeExternal(this, parentNode);
JDOMExternalizerUtil.writeField(parentNode, CONDITION_OPTION_NAME, getCondition().toExternalForm());
DebuggerUtilsEx.writeFilters(parentNode, FILTER_OPTION_NAME, myClassFilters);
DebuggerUtilsEx.writeFilters(parentNode, EXCLUSION_FILTER_OPTION_NAME, myClassExclusionFilters);
DebuggerUtilsEx.writeFilters(parentNode, INSTANCE_ID_OPTION_NAME, InstanceFilter.createClassFilters(myInstanceFilters));
}
protected String calculateEventClass(EvaluationContextImpl context, LocatableEvent event) throws EvaluateException
{
return event.location().declaringType().name();
}
private boolean typeMatchesClassFilters(@Nullable String typeName)
{
if(typeName == null)
{
return true;
}
boolean matches = false, hasEnabled = false;
for(ClassFilter classFilter : getClassFilters())
{
if(classFilter.isEnabled())
{
hasEnabled = true;
if(classFilter.matches(typeName))
{
matches = true;
break;
}
}
}
if(hasEnabled && !matches)
{
return false;
}
for(ClassFilter classFilter : getClassExclusionFilters())
{
if(classFilter.isEnabled() && classFilter.matches(typeName))
{
return false;
}
}
return true;
}
public PsiElement getEvaluationElement()
{
return null;
}
public TextWithImports getCondition()
{
return myCondition;
}
public void setCondition(TextWithImports condition)
{
myCondition = condition;
}
public Project getProject()
{
return myProject;
}
@Override
public boolean isCountFilterEnabled()
{
return COUNT_FILTER_ENABLED;
}
@Override
public int getCountFilter()
{
return COUNT_FILTER;
}
@Override
public boolean isClassFiltersEnabled()
{
return CLASS_FILTERS_ENABLED;
}
@Override
public boolean isInstanceFiltersEnabled()
{
return INSTANCE_FILTERS_ENABLED;
}
@Override
public boolean processLocatableEvent(SuspendContextCommandImpl action, LocatableEvent event) throws EventProcessingException
{
return false;
}
}
| compilation fixed
| java-debugger-impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java | compilation fixed | <ide><path>ava-debugger-impl/src/com/intellij/debugger/ui/breakpoints/FilteredRequestorImpl.java
<ide> breakpoint.setCondition(CONDITION_ENABLED ? myCondition : null);
<ide> if(myCondition != null && !myCondition.isEmpty())
<ide> {
<del> XDebuggerHistoryManager.getInstance(myProject).addRecentExpression(DefaultConditionComboBoxPanel.HISTORY_KEY, myCondition.getText());
<add> XDebuggerHistoryManager.getInstance(myProject).addRecentExpression(DefaultConditionComboBoxPanel.HISTORY_KEY,
<add> TextWithImportsImpl.toXExpression(myCondition));
<ide> }
<ide>
<ide> breakpoint.setClassFiltersEnabled(CLASS_FILTERS_ENABLED); |
|
Java | apache-2.0 | df96bdb403e13f6696b889b7fb2e55c37105c903 | 0 | Orange-OpenSource/cf-java-client,cloudfoundry/cf-java-client,Orange-OpenSource/cf-java-client,cloudfoundry/cf-java-client,orange-cloudfoundry/cf-java-client,cloudfoundry/cf-java-client,alexander071/cf-java-client,orange-cloudfoundry/cf-java-client,alexander071/cf-java-client | /*
* Copyright 2009-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client.lib.oauth2;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.cloudfoundry.client.lib.CloudCredentials;
import org.cloudfoundry.client.lib.CloudFoundryException;
import org.cloudfoundry.client.lib.util.JsonUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.client.RestTemplate;
/**
* Client that can handle authentication against a UAA instance
*
* @author Dave Syer
* @author Thomas Risberg
*/
public class OauthClient {
private static final String AUTHORIZATION_HEADER_KEY = "Authorization";
private URL authorizationUrl;
private RestTemplate restTemplate;
private OAuth2AccessToken token;
private CloudCredentials credentials;
public OauthClient(URL authorizationUrl, RestTemplate restTemplate) {
this.authorizationUrl = authorizationUrl;
this.restTemplate = restTemplate;
}
public void init(CloudCredentials credentials) {
if (credentials != null) {
this.credentials = credentials;
if (credentials.getToken() != null) {
this.token = credentials.getToken();
} else {
this.token = createToken(credentials.getEmail(), credentials.getPassword(),
credentials.getClientId(), credentials.getClientSecret());
}
}
}
public void clear() {
this.token = null;
this.credentials = null;
}
public OAuth2AccessToken getToken() {
if (token == null) {
return null;
}
if (token.getExpiresIn() < 50) { // 50 seconds before expiration? Then refresh it.
token = refreshToken(token, credentials.getEmail(), credentials.getPassword(),
credentials.getClientId(), credentials.getClientSecret());
}
return token;
}
public String getAuthorizationHeader() {
OAuth2AccessToken accessToken = getToken();
if (accessToken != null) {
return accessToken.getTokenType() + " " + accessToken.getValue();
}
return null;
}
private OAuth2AccessToken createToken(String username, String password, String clientId, String clientSecret) {
OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
AccessTokenRequest request = createAccessTokenRequest(username, password);
ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
try {
return provider.obtainAccessToken(resource, request);
}
catch (OAuth2AccessDeniedException oauthEx) {
HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage());
cfEx.setDescription(oauthEx.getSummary());
throw cfEx;
}
}
private OAuth2AccessToken refreshToken(OAuth2AccessToken currentToken, String username, String password, String clientId, String clientSecret) {
OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
AccessTokenRequest request = createAccessTokenRequest(username, password);
ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
return provider.refreshAccessToken(resource, currentToken.getRefreshToken(), request);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void changePassword(String oldPassword, String newPassword) {
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION_HEADER_KEY, token.getTokenType() + " " + token.getValue());
HttpEntity info = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(authorizationUrl + "/userinfo", HttpMethod.GET, info, String.class);
Map<String, Object> responseMap = JsonUtil.convertJsonToMap(response.getBody());
String userId = (String) responseMap.get("user_id");
Map<String, Object> body = new HashMap<String, Object>();
body.put("schemas", new String[] {"urn:scim:schemas:core:1.0"});
body.put("password", newPassword);
body.put("oldPassword", oldPassword);
HttpEntity<Map> httpEntity = new HttpEntity<Map>(body, headers);
restTemplate.put(authorizationUrl + "/User/{id}/password", httpEntity, userId);
}
protected ResourceOwnerPasswordAccessTokenProvider createResourceOwnerPasswordAccessTokenProvider() {
ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
resourceOwnerPasswordAccessTokenProvider.setRequestFactory(restTemplate.getRequestFactory()); //copy the http proxy along
return resourceOwnerPasswordAccessTokenProvider;
}
private AccessTokenRequest createAccessTokenRequest(String username, String password) {
Map<String, String> parameters = new LinkedHashMap<String, String>();
parameters.put("credentials", String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password));
AccessTokenRequest request = new DefaultAccessTokenRequest();
request.setAll(parameters);
return request;
}
private OAuth2ProtectedResourceDetails getResourceDetails(String username, String password, String clientId, String clientSecret) {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setUsername(username);
resource.setPassword(password);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setId(clientId);
resource.setClientAuthenticationScheme(AuthenticationScheme.header);
resource.setAccessTokenUri(authorizationUrl + "/oauth/token");
return resource;
}
}
| cloudfoundry-client-lib/src/main/java/org/cloudfoundry/client/lib/oauth2/OauthClient.java | /*
* Copyright 2009-2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.cloudfoundry.client.lib.oauth2;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import org.cloudfoundry.client.lib.CloudCredentials;
import org.cloudfoundry.client.lib.CloudFoundryException;
import org.cloudfoundry.client.lib.util.JsonUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.oauth2.client.resource.OAuth2AccessDeniedException;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.client.token.AccessTokenRequest;
import org.springframework.security.oauth2.client.token.DefaultAccessTokenRequest;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordAccessTokenProvider;
import org.springframework.security.oauth2.client.token.grant.password.ResourceOwnerPasswordResourceDetails;
import org.springframework.security.oauth2.common.AuthenticationScheme;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.web.client.RestTemplate;
/**
* Client that can handle authentication against a UAA instance
*
* @author Dave Syer
* @author Thomas Risberg
*/
public class OauthClient {
private static final String AUTHORIZATION_HEADER_KEY = "Authorization";
private URL authorizationUrl;
private RestTemplate restTemplate;
private OAuth2AccessToken token;
private CloudCredentials credentials;
public OauthClient(URL authorizationUrl, RestTemplate restTemplate) {
this.authorizationUrl = authorizationUrl;
this.restTemplate = restTemplate;
}
public void init(CloudCredentials credentials) {
if (credentials != null) {
this.credentials = credentials;
if (credentials.getToken() != null) {
this.token = credentials.getToken();
} else {
this.token = createToken(credentials.getEmail(), credentials.getPassword(),
credentials.getClientId(), credentials.getClientSecret());
}
}
}
public void clear() {
this.token = null;
this.credentials = null;
}
public OAuth2AccessToken getToken() {
if (token == null) {
return null;
}
if (token.getExpiresIn() < 50) { // 50 seconds before expiration? Then refresh it.
token = refreshToken(token, credentials.getEmail(), credentials.getPassword(),
credentials.getClientId(), credentials.getClientSecret());
}
return token;
}
public String getAuthorizationHeader() {
if (token != null) {
return token.getTokenType() + " " + token.getValue();
}
return null;
}
private OAuth2AccessToken createToken(String username, String password, String clientId, String clientSecret) {
OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
AccessTokenRequest request = createAccessTokenRequest(username, password);
ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
try {
return provider.obtainAccessToken(resource, request);
}
catch (OAuth2AccessDeniedException oauthEx) {
HttpStatus status = HttpStatus.valueOf(oauthEx.getHttpErrorCode());
CloudFoundryException cfEx = new CloudFoundryException(status, oauthEx.getMessage());
cfEx.setDescription(oauthEx.getSummary());
throw cfEx;
}
}
private OAuth2AccessToken refreshToken(OAuth2AccessToken currentToken, String username, String password, String clientId, String clientSecret) {
OAuth2ProtectedResourceDetails resource = getResourceDetails(username, password, clientId, clientSecret);
AccessTokenRequest request = createAccessTokenRequest(username, password);
ResourceOwnerPasswordAccessTokenProvider provider = createResourceOwnerPasswordAccessTokenProvider();
return provider.refreshAccessToken(resource, currentToken.getRefreshToken(), request);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public void changePassword(String oldPassword, String newPassword) {
HttpHeaders headers = new HttpHeaders();
headers.add(AUTHORIZATION_HEADER_KEY, token.getTokenType() + " " + token.getValue());
HttpEntity info = new HttpEntity(headers);
ResponseEntity<String> response = restTemplate.exchange(authorizationUrl + "/userinfo", HttpMethod.GET, info, String.class);
Map<String, Object> responseMap = JsonUtil.convertJsonToMap(response.getBody());
String userId = (String) responseMap.get("user_id");
Map<String, Object> body = new HashMap<String, Object>();
body.put("schemas", new String[] {"urn:scim:schemas:core:1.0"});
body.put("password", newPassword);
body.put("oldPassword", oldPassword);
HttpEntity<Map> httpEntity = new HttpEntity<Map>(body, headers);
restTemplate.put(authorizationUrl + "/User/{id}/password", httpEntity, userId);
}
protected ResourceOwnerPasswordAccessTokenProvider createResourceOwnerPasswordAccessTokenProvider() {
ResourceOwnerPasswordAccessTokenProvider resourceOwnerPasswordAccessTokenProvider = new ResourceOwnerPasswordAccessTokenProvider();
resourceOwnerPasswordAccessTokenProvider.setRequestFactory(restTemplate.getRequestFactory()); //copy the http proxy along
return resourceOwnerPasswordAccessTokenProvider;
}
private AccessTokenRequest createAccessTokenRequest(String username, String password) {
Map<String, String> parameters = new LinkedHashMap<String, String>();
parameters.put("credentials", String.format("{\"username\":\"%s\",\"password\":\"%s\"}", username, password));
AccessTokenRequest request = new DefaultAccessTokenRequest();
request.setAll(parameters);
return request;
}
private OAuth2ProtectedResourceDetails getResourceDetails(String username, String password, String clientId, String clientSecret) {
ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();
resource.setUsername(username);
resource.setPassword(password);
resource.setClientId(clientId);
resource.setClientSecret(clientSecret);
resource.setId(clientId);
resource.setClientAuthenticationScheme(AuthenticationScheme.header);
resource.setAccessTokenUri(authorizationUrl + "/oauth/token");
return resource;
}
}
| Fixed refreshing of access token for requests.
| cloudfoundry-client-lib/src/main/java/org/cloudfoundry/client/lib/oauth2/OauthClient.java | Fixed refreshing of access token for requests. | <ide><path>loudfoundry-client-lib/src/main/java/org/cloudfoundry/client/lib/oauth2/OauthClient.java
<ide> }
<ide>
<ide> public String getAuthorizationHeader() {
<del> if (token != null) {
<del> return token.getTokenType() + " " + token.getValue();
<add> OAuth2AccessToken accessToken = getToken();
<add> if (accessToken != null) {
<add> return accessToken.getTokenType() + " " + accessToken.getValue();
<ide> }
<ide> return null;
<ide> } |
|
Java | apache-2.0 | 73103cb6bc8e59f9e6bc4ee6c48119d4dbc17b6f | 0 | testng-team/testng-remote,testng-team/testng-remote,testng-team/testng-remote | package org.testng.remote;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import org.osgi.framework.Version;
import org.testng.CommandLineArgs;
import org.testng.TestNGException;
import org.testng.remote.support.RemoteTestNGFactory;
import org.testng.remote.support.ServiceLoaderHelper;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.Map.Entry;
public class RemoteTestNG {
// The following constants are referenced by the Eclipse plug-in, make sure you
// modify the plug-in as well if you change any of them.
public static final String DEBUG_PORT = "12345";
public static final String DEBUG_SUITE_FILE = "testng-customsuite.xml";
public static final String DEBUG_SUITE_DIRECTORY = System.getProperty("java.io.tmpdir");
public static final String PROPERTY_DEBUG = "testng.eclipse.debug";
public static final String PROPERTY_VERBOSE = "testng.eclipse.verbose";
// End of Eclipse constants.
private static boolean m_debug;
public static void main(String[] args) throws ParameterException {
if (isDebug()) {
dumpRevision();
}
CommandLineArgs cla = new CommandLineArgs();
RemoteArgs ra = new RemoteArgs();
new JCommander(Arrays.asList(cla, ra), args);
Version ver = ra.version;
if (ver == null) {
// no version specified on cli, detect ourself
ver = getTestNGVersion();
}
p("detected TestNG version " + ver);
RemoteTestNGFactory factory;
try {
factory = ServiceLoaderHelper.getFirst(ver);
} catch (TestNGException e) {
throw e;
} catch (Exception e) {
if (isDebug()) {
e.printStackTrace();
}
// for issue #29, give it 2nd try by manually scanning the jars on classpath
factory = ServiceLoaderHelper.getFirstQuietly(ver);
}
IRemoteTestNG remoteTestNg = factory.createRemoteTestNG();
remoteTestNg.dontExit(ra.dontExit);
if (cla.port != null && ra.serPort != null) {
throw new TestNGException("Can only specify one of " + CommandLineArgs.PORT
+ " and " + RemoteArgs.PORT);
}
m_debug = cla.debug;
remoteTestNg.setDebug(cla.debug);
remoteTestNg.setAck(ra.ack);
if (m_debug) {
// while (true) {
initAndRun(remoteTestNg, args, cla, ra);
// }
}
else {
initAndRun(remoteTestNg, args, cla, ra);
}
}
/**
* Get the version of TestNG on classpath.
*
* @return the Version of TestNG
* @throws RuntimeException if can't recognize the TestNG version on classpath.
*/
private static Version getTestNGVersion() {
try {
// use reflection to read org.testng.internal.Version.VERSION for reason of:
// 1. bypass the javac compile time constant substitution
// 2. org.testng.internal.Version is available since version 6.6
@SuppressWarnings("rawtypes")
Class clazz = Class.forName("org.testng.internal.Version");
Field field = clazz.getDeclaredField("VERSION");
String strVer = (String) field.get(null);
// trim the version to leave digital number only
int idx = strVer.indexOf("beta");
if (idx > 0) {
strVer = strVer.substring(0, idx);
}
idx = strVer.indexOf("-SNAPSHOT");
if (idx > 0) {
strVer = strVer.substring(0, idx);
}
return new Version(strVer);
} catch (Exception e) {
if (isDebug()) {
e.printStackTrace();
}
p("now trying to parse the version from pom.properties");
// for testng version < 6.6, since ClassNotFound: org.testng.internal.Version,
// parse the version from 'META-INF/maven/org.testng/testng/pom.properties' of testng jar on classpath
// assume this is the same classLoader loading the TestNG classes
ClassLoader cl = RemoteTestNG.class.getClassLoader();
try {
Enumeration<URL> resources = cl.getResources(
"META-INF/maven/org.testng/testng/pom.properties");
while (resources.hasMoreElements()) {
Properties props = new Properties();
try (InputStream in = resources.nextElement().openStream()) {
props.load(in);
}
return new Version(props.getProperty("version"));
}
} catch (Exception ex) {
if (isDebug()) {
ex.printStackTrace();
}
}
p("No TestNG version found on classpath");
if (isDebug()) {
if (cl instanceof URLClassLoader) {
p(join(((URLClassLoader) cl).getURLs(), ", "));
}
}
}
throw new RuntimeException("Can't recognize the TestNG version on classpath."
+ " Please make sure that there's a supported TestNG version (aka. >= 6.5.1) on your project.");
}
private static void initAndRun(IRemoteTestNG remoteTestNg, String[] args, CommandLineArgs cla, RemoteArgs ra) {
if (m_debug) {
// In debug mode, override the port and the XML file to a fixed location
cla.port = Integer.parseInt(DEBUG_PORT);
ra.serPort = cla.port;
cla.suiteFiles = Arrays.asList(new String[] {
DEBUG_SUITE_DIRECTORY + DEBUG_SUITE_FILE
});
}
remoteTestNg.configure(cla);
remoteTestNg.setHost(cla.host);
remoteTestNg.setSerPort(ra.serPort);
remoteTestNg.setProtocol(ra.protocol);
remoteTestNg.setPort(cla.port);
if (isVerbose()) {
StringBuilder sb = new StringBuilder("Invoked with ");
for (String s : args) {
sb.append(s).append(" ");
}
p(sb.toString());
// remoteTestNg.setVerbose(1);
// } else {
// remoteTestNg.setVerbose(0);
}
AbstractRemoteTestNG.validateCommandLineParameters(cla);
remoteTestNg.run();
// if (m_debug) {
// // Run in a loop if in debug mode so it is possible to run several launches
// // without having to relauch RemoteTestNG.
// while (true) {
// remoteTestNg.run();
// remoteTestNg.configure(cla);
// }
// } else {
// remoteTestNg.run();
// }
}
private static void p(String s) {
if (isVerbose()) {
System.out.println("[RemoteTestNG] " + s);
}
}
private static String join(URL[] urls, String sep) {
StringBuilder sb = new StringBuilder();
for (URL url : urls) {
sb.append(url);
sb.append(sep);
}
return sb.toString();
}
public static boolean isVerbose() {
boolean result = System.getProperty(PROPERTY_VERBOSE) != null || isDebug();
return result;
}
public static boolean isDebug() {
return m_debug || System.getProperty(PROPERTY_DEBUG) != null;
}
public static void dumpRevision() {
ClassLoader cl = RemoteTestNG.class.getClassLoader();
Properties props = new Properties();
try (InputStream in = cl.getResourceAsStream("revision.properties")) {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("[RemoteTestNG] revisions:");
for (Entry<Object, Object> entry : props.entrySet()) {
System.out.println("\t" + entry.getKey() + "=" + entry.getValue());
}
}
}
| remote/src/main/java/org/testng/remote/RemoteTestNG.java | package org.testng.remote;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.ParameterException;
import org.osgi.framework.Version;
import org.testng.CommandLineArgs;
import org.testng.TestNGException;
import org.testng.remote.support.RemoteTestNGFactory;
import org.testng.remote.support.ServiceLoaderHelper;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;
import java.util.Map.Entry;
public class RemoteTestNG {
// The following constants are referenced by the Eclipse plug-in, make sure you
// modify the plug-in as well if you change any of them.
public static final String DEBUG_PORT = "12345";
public static final String DEBUG_SUITE_FILE = "testng-customsuite.xml";
public static final String DEBUG_SUITE_DIRECTORY = System.getProperty("java.io.tmpdir");
public static final String PROPERTY_DEBUG = "testng.eclipse.debug";
public static final String PROPERTY_VERBOSE = "testng.eclipse.verbose";
// End of Eclipse constants.
private static boolean m_debug;
public static void main(String[] args) throws ParameterException {
if (isDebug()) {
dumpRevision();
}
CommandLineArgs cla = new CommandLineArgs();
RemoteArgs ra = new RemoteArgs();
new JCommander(Arrays.asList(cla, ra), args);
Version ver = ra.version;
if (ver == null) {
// no version specified on cli, detect ourself
ver = getTestNGVersion();
}
p("detected TestNG version " + ver);
RemoteTestNGFactory factory;
try {
factory = ServiceLoaderHelper.getFirst(ver);
} catch (TestNGException e) {
throw e;
} catch (Exception e) {
if (isDebug()) {
e.printStackTrace();
}
// for issue #29, give it 2nd try by manually scanning the jars on classpath
factory = ServiceLoaderHelper.getFirstQuietly(ver);
}
IRemoteTestNG remoteTestNg = factory.createRemoteTestNG();
remoteTestNg.dontExit(ra.dontExit);
if (cla.port != null && ra.serPort != null) {
throw new TestNGException("Can only specify one of " + CommandLineArgs.PORT
+ " and " + RemoteArgs.PORT);
}
m_debug = cla.debug;
remoteTestNg.setDebug(cla.debug);
remoteTestNg.setAck(ra.ack);
if (m_debug) {
// while (true) {
initAndRun(remoteTestNg, args, cla, ra);
// }
}
else {
initAndRun(remoteTestNg, args, cla, ra);
}
}
/**
* Get the version of TestNG on classpath.
*
* @return the Version of TestNG
* @throws RuntimeException if can't recognize the TestNG version on classpath.
*/
private static Version getTestNGVersion() {
try {
// use reflection to read org.testng.internal.Version.VERSION for reason of:
// 1. bypass the javac compile time constant substitution
// 2. org.testng.internal.Version is available since version 6.6
@SuppressWarnings("rawtypes")
Class clazz = Class.forName("org.testng.internal.Version");
Field field = clazz.getDeclaredField("VERSION");
String strVer = (String) field.get(null);
// trim the version to leave digital number only
int idx = strVer.indexOf("beta");
if (idx > 0) {
strVer = strVer.substring(0, idx);
}
idx = strVer.indexOf("-SNAPSHOT");
if (idx > 0) {
strVer = strVer.substring(0, idx);
}
return new Version(strVer);
} catch (Exception e) {
if (isDebug()) {
e.printStackTrace();
}
// for testng version < 6.6, since ClassNotFound: org.testng.internal.Version,
// parse the version from 'META-INF/maven/org.testng/testng/pom.properties' of testng jar on classpath
// assume this is the same classLoader loading the TestNG classes
ClassLoader cl = RemoteTestNG.class.getClassLoader();
try {
Enumeration<URL> resources = cl.getResources(
"META-INF/maven/org.testng/testng/pom.properties");
while (resources.hasMoreElements()) {
Properties props = new Properties();
try (InputStream in = resources.nextElement().openStream()) {
props.load(in);
}
return new Version(props.getProperty("version"));
}
} catch (Exception ex) {
if (isDebug()) {
ex.printStackTrace();
}
}
p("No TestNG version found on classpath");
if (isDebug()) {
if (cl instanceof URLClassLoader) {
p(join(((URLClassLoader) cl).getURLs(), ", "));
}
}
}
throw new RuntimeException("Can't recognize the TestNG version on classpath."
+ " Please make sure that there's a supported TestNG version (aka. >= 6.5.1) on your project.");
}
private static void initAndRun(IRemoteTestNG remoteTestNg, String[] args, CommandLineArgs cla, RemoteArgs ra) {
if (m_debug) {
// In debug mode, override the port and the XML file to a fixed location
cla.port = Integer.parseInt(DEBUG_PORT);
ra.serPort = cla.port;
cla.suiteFiles = Arrays.asList(new String[] {
DEBUG_SUITE_DIRECTORY + DEBUG_SUITE_FILE
});
}
remoteTestNg.configure(cla);
remoteTestNg.setHost(cla.host);
remoteTestNg.setSerPort(ra.serPort);
remoteTestNg.setProtocol(ra.protocol);
remoteTestNg.setPort(cla.port);
if (isVerbose()) {
StringBuilder sb = new StringBuilder("Invoked with ");
for (String s : args) {
sb.append(s).append(" ");
}
p(sb.toString());
// remoteTestNg.setVerbose(1);
// } else {
// remoteTestNg.setVerbose(0);
}
AbstractRemoteTestNG.validateCommandLineParameters(cla);
remoteTestNg.run();
// if (m_debug) {
// // Run in a loop if in debug mode so it is possible to run several launches
// // without having to relauch RemoteTestNG.
// while (true) {
// remoteTestNg.run();
// remoteTestNg.configure(cla);
// }
// } else {
// remoteTestNg.run();
// }
}
private static void p(String s) {
if (isVerbose()) {
System.out.println("[RemoteTestNG] " + s);
}
}
private static String join(URL[] urls, String sep) {
StringBuilder sb = new StringBuilder();
for (URL url : urls) {
sb.append(url);
sb.append(sep);
}
return sb.toString();
}
public static boolean isVerbose() {
boolean result = System.getProperty(PROPERTY_VERBOSE) != null || isDebug();
return result;
}
public static boolean isDebug() {
return m_debug || System.getProperty(PROPERTY_DEBUG) != null;
}
public static void dumpRevision() {
ClassLoader cl = RemoteTestNG.class.getClassLoader();
Properties props = new Properties();
try (InputStream in = cl.getResourceAsStream("revision.properties")) {
props.load(in);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("[RemoteTestNG] revisions:");
for (Entry<Object, Object> entry : props.entrySet()) {
System.out.println("\t" + entry.getKey() + "=" + entry.getValue());
}
}
}
| logging if fall into logic of parse the version from pom.properties
| remote/src/main/java/org/testng/remote/RemoteTestNG.java | logging if fall into logic of parse the version from pom.properties | <ide><path>emote/src/main/java/org/testng/remote/RemoteTestNG.java
<ide> if (isDebug()) {
<ide> e.printStackTrace();
<ide> }
<add> p("now trying to parse the version from pom.properties");
<ide>
<ide> // for testng version < 6.6, since ClassNotFound: org.testng.internal.Version,
<ide> // parse the version from 'META-INF/maven/org.testng/testng/pom.properties' of testng jar on classpath |
|
Java | apache-2.0 | 587f87de13561b20f8fbaab9162a436543ed503d | 0 | nikita36078/J2ME-Loader,nikita36078/J2ME-Loader,nikita36078/J2ME-Loader,nikita36078/J2ME-Loader | /*
* Copyright 2018 Nikita Shakarun
* Copyright 2020 Yury Kharchenko
*
* 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 ru.playsoftware.j2meloader.config;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.microedition.shell.MicroActivity;
import javax.microedition.util.ContextHolder;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import androidx.core.widget.TextViewCompat;
import ru.playsoftware.j2meloader.R;
import ru.playsoftware.j2meloader.base.BaseActivity;
import ru.playsoftware.j2meloader.settings.KeyMapperActivity;
import ru.playsoftware.j2meloader.util.FileUtils;
import yuku.ambilwarna.AmbilWarnaDialog;
import static ru.playsoftware.j2meloader.util.Constants.*;
public class ConfigActivity extends BaseActivity implements View.OnClickListener, ShaderTuneAlert.Callback {
private static final String TAG = ConfigActivity.class.getSimpleName();
protected ScrollView rootContainer;
protected EditText tfScreenWidth;
protected EditText tfScreenHeight;
protected AppCompatCheckBox cbLockAspect;
protected EditText tfScreenBack;
protected SeekBar sbScaleRatio;
protected EditText tfScaleRatioValue;
protected Spinner spOrientation;
protected Spinner spScreenGravity;
protected Spinner spScaleType;
protected Checkable cxFilter;
protected Checkable cxImmediate;
protected Spinner spGraphicsMode;
protected Spinner spShader;
protected CompoundButton cxParallel;
protected Checkable cxForceFullscreen;
protected Checkable cxShowFps;
protected EditText tfFpsLimit;
protected EditText tfFontSizeSmall;
protected EditText tfFontSizeMedium;
protected EditText tfFontSizeLarge;
protected Checkable cxFontSizeInSP;
protected Checkable cxFontAA;
protected CompoundButton cxShowKeyboard;
private View rootInputConfig;
private View groupVkConfig;
protected Checkable cxVKFeedback;
protected Checkable cxTouchInput;
protected Spinner spLayout;
private Spinner spButtonsShape;
protected SeekBar sbVKAlpha;
protected Checkable cxVKForceOpacity;
protected EditText tfVKHideDelay;
protected EditText tfVKFore;
protected EditText tfVKBack;
protected EditText tfVKSelFore;
protected EditText tfVKSelBack;
protected EditText tfVKOutline;
protected EditText tfSystemProperties;
protected ArrayList<String> screenPresets = new ArrayList<>();
protected ArrayList<int[]> fontPresetValues = new ArrayList<>();
protected ArrayList<String> fontPresetTitles = new ArrayList<>();
private File keylayoutFile;
private File dataDir;
private ProfileModel params;
private FragmentManager fragmentManager;
private boolean isProfile;
private Display display;
private File configDir;
private String defProfile;
private ArrayAdapter<ShaderInfo> spShaderAdapter;
private View shaderContainer;
private ImageButton btShaderTune;
private String workDir;
private boolean needShow;
@SuppressLint({"StringFormatMatches", "StringFormatInvalid"})
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String action = intent.getAction();
isProfile = ACTION_EDIT_PROFILE.equals(action);
needShow = isProfile || ACTION_EDIT.equals(action);
String path = intent.getDataString();
if (path == null) {
needShow = false;
finish();
return;
}
if (isProfile) {
setResult(RESULT_OK, new Intent().setData(intent.getData()));
configDir = new File(Config.getProfilesDir(), path);
workDir = Config.getEmulatorDir();
setTitle(path);
} else {
setTitle(intent.getStringExtra(KEY_MIDLET_NAME));
File appDir = new File(path);
File convertedDir = appDir.getParentFile();
if (!appDir.isDirectory() || convertedDir == null
|| (workDir = convertedDir.getParent()) == null) {
needShow = false;
String storageName = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE);
if (sm != null) {
StorageVolume storageVolume = sm.getStorageVolume(appDir);
if (storageVolume != null) {
String desc = storageVolume.getDescription(this);
if (desc != null) {
storageName = "\"" + desc + "\" ";
}
}
}
}
new AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(getString(R.string.err_missing_app, storageName))
.setPositiveButton(R.string.exit, (d, w) -> finish())
.setCancelable(false)
.show();
return;
}
dataDir = new File(workDir + Config.MIDLET_DATA_DIR + appDir.getName());
dataDir.mkdirs();
configDir = new File(workDir + Config.MIDLET_CONFIGS_DIR + appDir.getName());
}
configDir.mkdirs();
defProfile = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString(PREF_DEFAULT_PROFILE, null);
loadConfig();
if (!params.isNew && !needShow) {
needShow = false;
startMIDlet();
return;
}
loadKeyLayout();
setContentView(R.layout.activity_config);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
display = getWindowManager().getDefaultDisplay();
fragmentManager = getSupportFragmentManager();
rootContainer = findViewById(R.id.configRoot);
tfScreenWidth = findViewById(R.id.tfScreenWidth);
tfScreenHeight = findViewById(R.id.tfScreenHeight);
cbLockAspect = findViewById(R.id.cbLockAspect);
tfScreenBack = findViewById(R.id.tfScreenBack);
spScreenGravity = findViewById(R.id.spScreenGravity);
spScaleType = findViewById(R.id.spScaleType);
sbScaleRatio = findViewById(R.id.sbScaleRatio);
tfScaleRatioValue = findViewById(R.id.tfScaleRatioValue);
spOrientation = findViewById(R.id.spOrientation);
cxFilter = findViewById(R.id.cxFilter);
cxImmediate = findViewById(R.id.cxImmediate);
spGraphicsMode = findViewById(R.id.spGraphicsMode);
spShader = findViewById(R.id.spShader);
btShaderTune = findViewById(R.id.btShaderTune);
shaderContainer = findViewById(R.id.shaderContainer);
cxParallel = findViewById(R.id.cxParallel);
cxForceFullscreen = findViewById(R.id.cxForceFullscreen);
cxShowFps = findViewById(R.id.cxShowFps);
tfFpsLimit = findViewById(R.id.etFpsLimit);
tfFontSizeSmall = findViewById(R.id.tfFontSizeSmall);
tfFontSizeMedium = findViewById(R.id.tfFontSizeMedium);
tfFontSizeLarge = findViewById(R.id.tfFontSizeLarge);
cxFontSizeInSP = findViewById(R.id.cxFontSizeInSP);
cxFontAA = findViewById(R.id.cxFontAA);
tfSystemProperties = findViewById(R.id.tfSystemProperties);
rootInputConfig = findViewById(R.id.rootInputConfig);
cxTouchInput = findViewById(R.id.cxTouchInput);
cxShowKeyboard = findViewById(R.id.cxIsShowKeyboard);
groupVkConfig = findViewById(R.id.groupVkConfig);
cxVKFeedback = findViewById(R.id.cxVKFeedback);
cxVKForceOpacity = findViewById(R.id.cxVKForceOpacity);
spLayout = findViewById(R.id.spLayout);
spButtonsShape = findViewById(R.id.spButtonsShape);
sbVKAlpha = findViewById(R.id.sbVKAlpha);
tfVKHideDelay = findViewById(R.id.tfVKHideDelay);
tfVKFore = findViewById(R.id.tfVKFore);
tfVKBack = findViewById(R.id.tfVKBack);
tfVKSelFore = findViewById(R.id.tfVKSelFore);
tfVKSelBack = findViewById(R.id.tfVKSelBack);
tfVKOutline = findViewById(R.id.tfVKOutline);
fillScreenSizePresets(display.getWidth(), display.getHeight());
addFontSizePreset("128 x 128", 9, 13, 15);
addFontSizePreset("128 x 160", 13, 15, 20);
addFontSizePreset("176 x 220", 15, 18, 22);
addFontSizePreset("240 x 320", 18, 22, 26);
cbLockAspect.setOnCheckedChangeListener(this::onLockAspectChanged);
findViewById(R.id.cmdScreenSizePresets).setOnClickListener(this::showScreenPresets);
findViewById(R.id.cmdSwapSizes).setOnClickListener(this);
findViewById(R.id.cmdAddToPreset).setOnClickListener(v -> addResolutionToPresets());
findViewById(R.id.cmdFontSizePresets).setOnClickListener(this);
findViewById(R.id.cmdScreenBack).setOnClickListener(this);
findViewById(R.id.cmdKeyMappings).setOnClickListener(this);
findViewById(R.id.cmdVKBack).setOnClickListener(this);
findViewById(R.id.cmdVKFore).setOnClickListener(this);
findViewById(R.id.cmdVKSelBack).setOnClickListener(this);
findViewById(R.id.cmdVKSelFore).setOnClickListener(this);
findViewById(R.id.cmdVKOutline).setOnClickListener(this);
findViewById(R.id.btEncoding).setOnClickListener(this::showCharsetPicker);
btShaderTune.setOnClickListener(this::showShaderSettings);
sbScaleRatio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) tfScaleRatioValue.setText(String.valueOf(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
tfScaleRatioValue.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = s.length();
if (length > 3) {
if (start >= 3) {
tfScaleRatioValue.getText().delete(3, length);
} else {
int st = start + count;
int end = st + (before == 0 ? count : before);
tfScaleRatioValue.getText().delete(st, Math.min(end, length));
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) return;
try {
int progress = Integer.parseInt(s.toString());
if (progress <= 100) {
sbScaleRatio.setProgress(progress);
} else {
s.replace(0, s.length(), "100");
}
} catch (NumberFormatException e) {
s.clear();
}
}
});
spGraphicsMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
case 3:
cxParallel.setVisibility(View.VISIBLE);
shaderContainer.setVisibility(View.GONE);
break;
case 1:
cxParallel.setVisibility(View.GONE);
initShaderSpinner();
break;
case 2:
cxParallel.setVisibility(View.GONE);
shaderContainer.setVisibility(View.GONE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
cxShowKeyboard.setOnClickListener((b) -> {
View.OnLayoutChangeListener onLayoutChangeListener = new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
View focus = rootContainer.findFocus();
if (focus != null) focus.clearFocus();
v.scrollTo(0, rootInputConfig.getTop());
v.removeOnLayoutChangeListener(this);
}
};
rootContainer.addOnLayoutChangeListener(onLayoutChangeListener);
groupVkConfig.setVisibility(cxShowKeyboard.isChecked() ? View.VISIBLE : View.GONE);
});
tfScreenBack.addTextChangedListener(new ColorTextWatcher(tfScreenBack));
tfVKFore.addTextChangedListener(new ColorTextWatcher(tfVKFore));
tfVKBack.addTextChangedListener(new ColorTextWatcher(tfVKBack));
tfVKSelFore.addTextChangedListener(new ColorTextWatcher(tfVKSelFore));
tfVKSelBack.addTextChangedListener(new ColorTextWatcher(tfVKSelBack));
tfVKOutline.addTextChangedListener(new ColorTextWatcher(tfVKOutline));
}
private void onLockAspectChanged(CompoundButton cb, boolean isChecked) {
if (isChecked) {
float w;
try {
w = Integer.parseInt(tfScreenWidth.getText().toString());
} catch (Exception ignored) {
w = 0;
}
if (w <= 0) {
cb.setChecked(false);
return;
}
float h;
try {
h = Integer.parseInt(tfScreenHeight.getText().toString());
} catch (Exception ignored) {
h = 0;
}
if (h <= 0) {
cb.setChecked(false);
return;
}
float finalW = w;
float finalH = h;
tfScreenWidth.setOnFocusChangeListener(new ResolutionAutoFill(tfScreenWidth, tfScreenHeight, finalH / finalW));
tfScreenHeight.setOnFocusChangeListener(new ResolutionAutoFill(tfScreenHeight, tfScreenWidth, finalW / finalH));
} else {
View.OnFocusChangeListener listener = tfScreenWidth.getOnFocusChangeListener();
if (listener != null) {
listener.onFocusChange(tfScreenWidth, false);
tfScreenWidth.setOnFocusChangeListener(null);
}
listener = tfScreenHeight.getOnFocusChangeListener();
if (listener != null) {
listener.onFocusChange(tfScreenHeight, false);
tfScreenHeight.setOnFocusChangeListener(null);
}
}
}
void loadConfig() {
params = ProfilesManager.loadConfig(configDir);
if (params == null && defProfile != null) {
FileUtils.copyFiles(new File(Config.getProfilesDir(), defProfile), configDir, null);
params = ProfilesManager.loadConfig(configDir);
}
if (params == null) {
params = new ProfileModel(configDir);
}
}
private void showShaderSettings(View v) {
ShaderInfo shader = (ShaderInfo) spShader.getSelectedItem();
params.shader = shader;
ShaderTuneAlert.newInstance(shader).show(getSupportFragmentManager(), "ShaderTuning");
}
private void initShaderSpinner() {
if (spShaderAdapter != null) {
shaderContainer.setVisibility(View.VISIBLE);
return;
}
File dir = new File(workDir + Config.SHADERS_DIR);
if (!dir.exists()) {
//noinspection ResultOfMethodCallIgnored
dir.mkdirs();
}
ArrayList<ShaderInfo> infos = new ArrayList<>();
spShaderAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, infos);
spShaderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spShader.setAdapter(spShaderAdapter);
File[] files = dir.listFiles((f) -> f.isFile() && f.getName().toLowerCase().endsWith(".ini"));
if (files != null) {
for (File file : files) {
String text = FileUtils.getText(file.getAbsolutePath());
String[] split = text.split("[\\n\\r]+");
ShaderInfo info = null;
for (String line : split) {
if (line.startsWith("[")) {
if (info != null && info.fragment != null && info.vertex != null) {
infos.add(info);
}
info = new ShaderInfo(line.replaceAll("[\\[\\]]", ""), "unknown");
} else if (info != null) {
try {
info.set(line);
} catch (Exception e) {
Log.e(TAG, "initShaderSpinner: ", e);
}
}
}
if (info != null && info.fragment != null && info.vertex != null) {
infos.add(info);
}
}
Collections.sort(infos);
}
infos.add(0, new ShaderInfo(getString(R.string.identity_filter), "woesss"));
spShaderAdapter.notifyDataSetChanged();
ShaderInfo selected = params.shader;
if (selected != null) {
int position = infos.indexOf(selected);
if (position > 0) {
infos.get(position).values = selected.values;
spShader.setSelection(position);
}
}
shaderContainer.setVisibility(View.VISIBLE);
spShader.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ShaderInfo item = (ShaderInfo) parent.getItemAtPosition(position);
ShaderInfo.Setting[] settings = item.settings;
float[] values = item.values;
if (values == null) {
for (int i = 0; i < 4; i++) {
if (settings[i] != null) {
if (values == null) {
values = new float[4];
}
values[i] = settings[i].def;
}
}
}
if (values == null) {
btShaderTune.setVisibility(View.GONE);
} else {
item.values = values;
btShaderTune.setVisibility(View.VISIBLE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void showCharsetPicker(View v) {
String[] charsets = Charset.availableCharsets().keySet().toArray(new String[0]);
new AlertDialog.Builder(this).setItems(charsets, (d, w) -> {
String enc = "microedition.encoding: " + charsets[w];
String[] props = tfSystemProperties.getText().toString().split("[\\n\\r]+");
int propsLength = props.length;
if (propsLength == 0) {
tfSystemProperties.setText(enc);
return;
}
int i = propsLength - 1;
while (i >= 0) {
if (props[i].startsWith("microedition.encoding")) {
props[i] = enc;
break;
}
i--;
}
if (i < 0) {
tfSystemProperties.append(enc);
return;
}
tfSystemProperties.setText(TextUtils.join("\n", props));
}).setTitle(R.string.pref_encoding_title).show();
}
private void loadKeyLayout() {
File file = new File(configDir, Config.MIDLET_KEY_LAYOUT_FILE);
keylayoutFile = file;
if (isProfile || file.exists()) {
return;
}
if (defProfile == null) {
return;
}
File defaultKeyLayoutFile = new File(Config.getProfilesDir() + defProfile, Config.MIDLET_KEY_LAYOUT_FILE);
if (!defaultKeyLayoutFile.exists()) {
return;
}
try {
FileUtils.copyFileUsingChannel(defaultKeyLayoutFile, file);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onPause() {
if (needShow && configDir != null) {
saveParams();
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (needShow) {
loadParams(true);
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
fillScreenSizePresets(display.getWidth(), display.getHeight());
}
private void fillScreenSizePresets(int w, int h) {
ArrayList<String> screenPresets = this.screenPresets;
screenPresets.clear();
screenPresets.add("128 x 128");
screenPresets.add("128 x 160");
screenPresets.add("132 x 176");
screenPresets.add("176 x 220");
screenPresets.add("240 x 320");
screenPresets.add("352 x 416");
screenPresets.add("640 x 360");
screenPresets.add("800 x 480");
if (w > h) {
screenPresets.add(h * 3 / 4 + " x " + h);
screenPresets.add(h * 4 / 3 + " x " + h);
} else {
screenPresets.add(w + " x " + w * 4 / 3);
screenPresets.add(w + " x " + w * 3 / 4);
}
screenPresets.add(w + " x " + h);
Set<String> preset = PreferenceManager.getDefaultSharedPreferences(this)
.getStringSet("ResolutionsPreset", null);
if (preset != null) {
screenPresets.addAll(preset);
}
Collections.sort(screenPresets, (o1, o2) -> {
int sep1 = o1.indexOf(" x ");
int sep2 = o2.indexOf(" x ");
if (sep1 == -1) {
if (sep2 != -1) return -1;
else return 0;
} else if (sep2 == -1) return 1;
int r = Integer.decode(o1.substring(0, sep1)).compareTo(Integer.decode(o2.substring(0, sep2)));
if (r != 0) return r;
return Integer.decode(o1.substring(sep1 + 3)).compareTo(Integer.decode(o2.substring(sep2 + 3)));
});
String prev = null;
for (Iterator<String> iterator = screenPresets.iterator(); iterator.hasNext(); ) {
String next = iterator.next();
if (next.equals(prev)) iterator.remove();
else prev = next;
}
}
private void addFontSizePreset(String title, int small, int medium, int large) {
fontPresetValues.add(new int[]{small, medium, large});
fontPresetTitles.add(title);
}
private int parseInt(String s) {
return parseInt(s, 10);
}
private int parseInt(String s, int radix) {
int result;
try {
result = Integer.parseInt(s, radix);
} catch (NumberFormatException e) {
result = 0;
}
return result;
}
@SuppressLint("SetTextI18n")
public void loadParams(boolean reloadFromFile) {
if (reloadFromFile) {
loadConfig();
}
int screenWidth = params.screenWidth;
if (screenWidth != 0) {
tfScreenWidth.setText(Integer.toString(screenWidth));
}
int screenHeight = params.screenHeight;
if (screenHeight != 0) {
tfScreenHeight.setText(Integer.toString(screenHeight));
}
tfScreenBack.setText(String.format("%06X", params.screenBackgroundColor));
sbScaleRatio.setProgress(params.screenScaleRatio);
tfScaleRatioValue.setText(Integer.toString(params.screenScaleRatio));
spOrientation.setSelection(params.orientation);
spScaleType.setSelection(params.screenScaleType);
spScreenGravity.setSelection(params.screenGravity);
cxFilter.setChecked(params.screenFilter);
cxImmediate.setChecked(params.immediateMode);
cxParallel.setChecked(params.parallelRedrawScreen);
cxForceFullscreen.setChecked(params.forceFullscreen);
spGraphicsMode.setSelection(params.graphicsMode);
cxShowFps.setChecked(params.showFps);
tfFontSizeSmall.setText(Integer.toString(params.fontSizeSmall));
tfFontSizeMedium.setText(Integer.toString(params.fontSizeMedium));
tfFontSizeLarge.setText(Integer.toString(params.fontSizeLarge));
cxFontSizeInSP.setChecked(params.fontApplyDimensions);
cxFontAA.setChecked(params.fontAA);
boolean showVk = params.showKeyboard;
cxShowKeyboard.setChecked(showVk);
groupVkConfig.setVisibility(showVk ? View.VISIBLE : View.GONE);
cxVKFeedback.setChecked(params.vkFeedback);
cxVKForceOpacity.setChecked(params.vkForceOpacity);
cxTouchInput.setChecked(params.touchInput);
int fpsLimit = params.fpsLimit;
tfFpsLimit.setText(fpsLimit > 0 ? Integer.toString(fpsLimit) : "");
spLayout.setSelection(params.keyCodesLayout);
spButtonsShape.setSelection(params.vkButtonShape);
sbVKAlpha.setProgress(params.vkAlpha);
int vkHideDelay = params.vkHideDelay;
tfVKHideDelay.setText(vkHideDelay > 0 ? Integer.toString(vkHideDelay) : "");
tfVKBack.setText(String.format("%06X", params.vkBgColor));
tfVKFore.setText(String.format("%06X", params.vkFgColor));
tfVKSelBack.setText(String.format("%06X", params.vkBgColorSelected));
tfVKSelFore.setText(String.format("%06X", params.vkFgColorSelected));
tfVKOutline.setText(String.format("%06X", params.vkOutlineColor));
String systemProperties = params.systemProperties;
if (systemProperties == null) {
systemProperties = ContextHolder.getAssetAsString("defaults/system.props");
}
tfSystemProperties.setText(systemProperties);
}
private void saveParams() {
try {
int width = parseInt(tfScreenWidth.getText().toString());
params.screenWidth = width;
int height = parseInt(tfScreenHeight.getText().toString());
params.screenHeight = height;
try {
params.screenBackgroundColor = Integer.parseInt(tfScreenBack.getText().toString(), 16);
} catch (NumberFormatException ignored) {
}
params.screenScaleRatio = sbScaleRatio.getProgress();
params.orientation = spOrientation.getSelectedItemPosition();
params.screenGravity = spScreenGravity.getSelectedItemPosition();
params.screenScaleType = spScaleType.getSelectedItemPosition();
params.screenFilter = cxFilter.isChecked();
params.immediateMode = cxImmediate.isChecked();
int mode = spGraphicsMode.getSelectedItemPosition();
params.graphicsMode = mode;
if (mode == 1) {
if (spShader.getSelectedItemPosition() == 0)
params.shader = null;
else
params.shader = (ShaderInfo) spShader.getSelectedItem();
}
params.parallelRedrawScreen = cxParallel.isChecked();
params.forceFullscreen = cxForceFullscreen.isChecked();
params.showFps = cxShowFps.isChecked();
params.fpsLimit = parseInt(tfFpsLimit.getText().toString());
try {
params.fontSizeSmall = Integer.parseInt(tfFontSizeSmall.getText().toString());
} catch (NumberFormatException e) {
params.fontSizeSmall = 0;
}
try {
params.fontSizeMedium = Integer.parseInt(tfFontSizeMedium.getText().toString());
} catch (NumberFormatException e) {
params.fontSizeMedium = 0;
}
try {
params.fontSizeLarge = Integer.parseInt(tfFontSizeLarge.getText().toString());
} catch (NumberFormatException e) {
params.fontSizeLarge = 0;
}
params.fontApplyDimensions = cxFontSizeInSP.isChecked();
params.fontAA = cxFontAA.isChecked();
params.showKeyboard = cxShowKeyboard.isChecked();
params.vkFeedback = cxVKFeedback.isChecked();
params.vkForceOpacity = cxVKForceOpacity.isChecked();
params.touchInput = cxTouchInput.isChecked();
params.keyCodesLayout = spLayout.getSelectedItemPosition();
params.vkButtonShape = spButtonsShape.getSelectedItemPosition();
params.vkAlpha = sbVKAlpha.getProgress();
params.vkHideDelay = parseInt(tfVKHideDelay.getText().toString());
try {
params.vkBgColor = Integer.parseInt(tfVKBack.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkFgColor = Integer.parseInt(tfVKFore.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkBgColorSelected = Integer.parseInt(tfVKSelBack.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkFgColorSelected = Integer.parseInt(tfVKSelFore.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkOutlineColor = Integer.parseInt(tfVKOutline.getText().toString(), 16);
} catch (Exception ignored) {
}
params.systemProperties = getSystemProperties();
ProfilesManager.saveConfig(params);
} catch (Throwable t) {
t.printStackTrace();
}
}
@NonNull
private String getSystemProperties() {
String s = tfSystemProperties.getText().toString();
String[] lines = s.split("\\n");
StringBuilder sb = new StringBuilder(s.length());
boolean validCharset = false;
for (int i = lines.length - 1; i >= 0; i--) {
String line = lines[i];
if (line.trim().isEmpty()) continue;
if (line.startsWith("microedition.encoding:")) {
if (validCharset) continue;
try {
Charset.forName(line.substring(22).trim());
validCharset = true;
} catch (Exception ignored) {
continue;
}
}
sb.append(line).append('\n');
}
return sb.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.config, menu);
if (isProfile) {
menu.findItem(R.id.action_start).setVisible(false);
menu.findItem(R.id.action_clear_data).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_start) {
startMIDlet();
} else if (itemId == R.id.action_clear_data) {
showClearDataDialog();
} else if (itemId == R.id.action_reset_settings) {
params = new ProfileModel(configDir);
loadParams(false);
} else if (itemId == R.id.action_reset_layout) {//noinspection ResultOfMethodCallIgnored
keylayoutFile.delete();
loadKeyLayout();
} else if (itemId == R.id.action_load_profile) {
LoadProfileAlert.newInstance(keylayoutFile.getParent())
.show(fragmentManager, "load_profile");
} else if (itemId == R.id.action_save_profile) {
saveParams();
SaveProfileAlert.getInstance(keylayoutFile.getParent())
.show(fragmentManager, "save_profile");
} else if (itemId == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void showClearDataDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(android.R.string.dialog_alert_title)
.setMessage(R.string.message_clear_data)
.setPositiveButton(android.R.string.ok, (d, w) -> FileUtils.clearDirectory(dataDir))
.setNegativeButton(android.R.string.cancel, null);
builder.show();
}
private void startMIDlet() {
Intent i = new Intent(this, MicroActivity.class);
i.setData(getIntent().getData());
i.putExtra(KEY_MIDLET_NAME, getIntent().getStringExtra(KEY_MIDLET_NAME));
startActivity(i);
finish();
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.cmdSwapSizes) {
String tmp = tfScreenWidth.getText().toString();
tfScreenWidth.setText(tfScreenHeight.getText().toString());
tfScreenHeight.setText(tmp);
} else if (id == R.id.cmdFontSizePresets) {
new AlertDialog.Builder(this)
.setTitle(getString(R.string.SIZE_PRESETS))
.setItems(fontPresetTitles.toArray(new String[0]),
(dialog, which) -> {
int[] values = fontPresetValues.get(which);
tfFontSizeSmall.setText(Integer.toString(values[0]));
tfFontSizeMedium.setText(Integer.toString(values[1]));
tfFontSizeLarge.setText(Integer.toString(values[2]));
})
.show();
} else if (id == R.id.cmdScreenBack) {
showColorPicker(tfScreenBack);
} else if (id == R.id.cmdVKBack) {
showColorPicker(tfVKBack);
} else if (id == R.id.cmdVKFore) {
showColorPicker(tfVKFore);
} else if (id == R.id.cmdVKSelFore) {
showColorPicker(tfVKSelFore);
} else if (id == R.id.cmdVKSelBack) {
showColorPicker(tfVKSelBack);
} else if (id == R.id.cmdVKOutline) {
showColorPicker(tfVKOutline);
} else if (id == R.id.cmdKeyMappings) {
Intent i = new Intent(getIntent().getAction(), Uri.parse(configDir.getPath()),
this, KeyMapperActivity.class);
startActivity(i);
}
}
private void showScreenPresets(View v) {
PopupMenu popup = new PopupMenu(this, v);
Menu menu = popup.getMenu();
for (String preset : screenPresets) {
menu.add(preset);
}
popup.setOnMenuItemClickListener(item -> {
String string = item.getTitle().toString();
int separator = string.indexOf(" x ");
tfScreenWidth.setText(string.substring(0, separator));
tfScreenHeight.setText(string.substring(separator + 3));
return true;
});
popup.show();
}
private void showColorPicker(EditText et) {
AmbilWarnaDialog.OnAmbilWarnaListener colorListener = new AmbilWarnaDialog.OnAmbilWarnaListener() {
@Override
public void onOk(AmbilWarnaDialog dialog, int color) {
et.setText(String.format("%06X", color & 0xFFFFFF));
ColorDrawable drawable = (ColorDrawable) TextViewCompat.getCompoundDrawablesRelative(et)[2];
drawable.setColor(color);
}
@Override
public void onCancel(AmbilWarnaDialog dialog) {
}
};
int color = parseInt(et.getText().toString().trim(), 16);
new AmbilWarnaDialog(this, color | 0xFF000000, colorListener).show();
}
private void addResolutionToPresets() {
String width = tfScreenWidth.getText().toString();
String height = tfScreenHeight.getText().toString();
if (width.isEmpty()) width = "-1";
if (height.isEmpty()) height = "-1";
int w = parseInt(width);
int h = parseInt(height);
if (w <= 0 || h <= 0) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
return;
}
String preset = width + " x " + height;
if (screenPresets.contains(preset)) {
Toast.makeText(this, R.string.not_saved_exists, Toast.LENGTH_SHORT).show();
return;
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Set<String> set = preferences.getStringSet("ResolutionsPreset", null);
if (set == null) {
set = new HashSet<>(1);
}
if (set.add(preset)) {
preferences.edit().putStringSet("ResolutionsPreset", set).apply();
screenPresets.add(preset);
Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.not_saved_exists, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onTuneComplete(float[] values) {
params.shader.values = values;
}
private static class ColorTextWatcher implements TextWatcher {
private final EditText editText;
private final ColorDrawable drawable;
ColorTextWatcher(EditText editText) {
this.editText = editText;
int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32,
editText.getResources().getDisplayMetrics());
ColorDrawable colorDrawable = new ColorDrawable();
colorDrawable.setBounds(0, 0, size, size);
TextViewCompat.setCompoundDrawablesRelative(editText,null, null, colorDrawable, null);
drawable = colorDrawable;
editText.setFilters(new InputFilter[]{this::filter});
}
private CharSequence filter(CharSequence src, int ss, int se, Spanned dst, int ds, int de) {
StringBuilder sb = new StringBuilder(se - ss);
for (int i = ss; i < se; i++) {
char c = src.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
sb.append(c);
} else if (c >= 'a' && c <= 'f') {
sb.append((char) (c - 32));
}
}
return sb;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 6) {
if (start >= 6) editText.getText().delete(6, s.length());
else {
int st = start + count;
int end = st + (before == 0 ? count : before);
editText.getText().delete(st, Math.min(end, s.length()));
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) return;
try {
int color = Integer.parseInt(s.toString(), 16);
drawable.setColor(color | Color.BLACK);
} catch (NumberFormatException e) {
drawable.setColor(Color.BLACK);
s.clear();
}
}
}
private static class ResolutionAutoFill implements TextWatcher, View.OnFocusChangeListener {
private final EditText src;
private final EditText dst;
private final float aspect;
public ResolutionAutoFill(EditText src, EditText dst, float aspect) {
this.src = src;
this.dst = dst;
this.aspect = aspect;
if (src.hasFocus())
src.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
int size = Integer.parseInt(src.getText().toString());
if (size <= 0) return;
int value = Math.round(size * aspect);
dst.setText(Integer.toString(value));
} catch (NumberFormatException ignored) { }
}
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
src.addTextChangedListener(this);
} else {
src.removeTextChangedListener(this);
}
}
}
}
| app/src/main/java/ru/playsoftware/j2meloader/config/ConfigActivity.java | /*
* Copyright 2018 Nikita Shakarun
* Copyright 2020 Yury Kharchenko
*
* 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 ru.playsoftware.j2meloader.config;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Checkable;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javax.microedition.shell.MicroActivity;
import javax.microedition.util.ContextHolder;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatCheckBox;
import androidx.appcompat.widget.PopupMenu;
import androidx.fragment.app.FragmentManager;
import androidx.preference.PreferenceManager;
import ru.playsoftware.j2meloader.R;
import ru.playsoftware.j2meloader.base.BaseActivity;
import ru.playsoftware.j2meloader.settings.KeyMapperActivity;
import ru.playsoftware.j2meloader.util.FileUtils;
import yuku.ambilwarna.AmbilWarnaDialog;
import static ru.playsoftware.j2meloader.util.Constants.*;
public class ConfigActivity extends BaseActivity implements View.OnClickListener, ShaderTuneAlert.Callback {
private static final String TAG = ConfigActivity.class.getSimpleName();
protected ScrollView rootContainer;
protected EditText tfScreenWidth;
protected EditText tfScreenHeight;
protected AppCompatCheckBox cbLockAspect;
protected EditText tfScreenBack;
protected SeekBar sbScaleRatio;
protected EditText tfScaleRatioValue;
protected Spinner spOrientation;
protected Spinner spScreenGravity;
protected Spinner spScaleType;
protected Checkable cxFilter;
protected Checkable cxImmediate;
protected Spinner spGraphicsMode;
protected Spinner spShader;
protected CompoundButton cxParallel;
protected Checkable cxForceFullscreen;
protected Checkable cxShowFps;
protected EditText tfFpsLimit;
protected EditText tfFontSizeSmall;
protected EditText tfFontSizeMedium;
protected EditText tfFontSizeLarge;
protected Checkable cxFontSizeInSP;
protected Checkable cxFontAA;
protected CompoundButton cxShowKeyboard;
private View rootInputConfig;
private View groupVkConfig;
protected Checkable cxVKFeedback;
protected Checkable cxTouchInput;
protected Spinner spLayout;
private Spinner spButtonsShape;
protected SeekBar sbVKAlpha;
protected Checkable cxVKForceOpacity;
protected EditText tfVKHideDelay;
protected EditText tfVKFore;
protected EditText tfVKBack;
protected EditText tfVKSelFore;
protected EditText tfVKSelBack;
protected EditText tfVKOutline;
protected EditText tfSystemProperties;
protected ArrayList<String> screenPresets = new ArrayList<>();
protected ArrayList<int[]> fontPresetValues = new ArrayList<>();
protected ArrayList<String> fontPresetTitles = new ArrayList<>();
private File keylayoutFile;
private File dataDir;
private ProfileModel params;
private FragmentManager fragmentManager;
private boolean isProfile;
private Display display;
private File configDir;
private String defProfile;
private ArrayAdapter<ShaderInfo> spShaderAdapter;
private View shaderContainer;
private ImageButton btShaderTune;
private String workDir;
private boolean needShow;
@SuppressLint({"StringFormatMatches", "StringFormatInvalid"})
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
String action = intent.getAction();
isProfile = ACTION_EDIT_PROFILE.equals(action);
needShow = isProfile || ACTION_EDIT.equals(action);
String path = intent.getDataString();
if (path == null) {
needShow = false;
finish();
return;
}
if (isProfile) {
setResult(RESULT_OK, new Intent().setData(intent.getData()));
configDir = new File(Config.getProfilesDir(), path);
workDir = Config.getEmulatorDir();
setTitle(path);
} else {
setTitle(intent.getStringExtra(KEY_MIDLET_NAME));
File appDir = new File(path);
File convertedDir = appDir.getParentFile();
if (!appDir.isDirectory() || convertedDir == null
|| (workDir = convertedDir.getParent()) == null) {
needShow = false;
String storageName = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE);
if (sm != null) {
StorageVolume storageVolume = sm.getStorageVolume(appDir);
if (storageVolume != null) {
String desc = storageVolume.getDescription(this);
if (desc != null) {
storageName = "\"" + desc + "\" ";
}
}
}
}
new AlertDialog.Builder(this)
.setTitle(R.string.error)
.setMessage(getString(R.string.err_missing_app, storageName))
.setPositiveButton(R.string.exit, (d, w) -> finish())
.setCancelable(false)
.show();
return;
}
dataDir = new File(workDir + Config.MIDLET_DATA_DIR + appDir.getName());
dataDir.mkdirs();
configDir = new File(workDir + Config.MIDLET_CONFIGS_DIR + appDir.getName());
}
configDir.mkdirs();
defProfile = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
.getString(PREF_DEFAULT_PROFILE, null);
loadConfig();
if (!params.isNew && !needShow) {
needShow = false;
startMIDlet();
return;
}
loadKeyLayout();
setContentView(R.layout.activity_config);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
display = getWindowManager().getDefaultDisplay();
fragmentManager = getSupportFragmentManager();
rootContainer = findViewById(R.id.configRoot);
tfScreenWidth = findViewById(R.id.tfScreenWidth);
tfScreenHeight = findViewById(R.id.tfScreenHeight);
cbLockAspect = findViewById(R.id.cbLockAspect);
tfScreenBack = findViewById(R.id.tfScreenBack);
spScreenGravity = findViewById(R.id.spScreenGravity);
spScaleType = findViewById(R.id.spScaleType);
sbScaleRatio = findViewById(R.id.sbScaleRatio);
tfScaleRatioValue = findViewById(R.id.tfScaleRatioValue);
spOrientation = findViewById(R.id.spOrientation);
cxFilter = findViewById(R.id.cxFilter);
cxImmediate = findViewById(R.id.cxImmediate);
spGraphicsMode = findViewById(R.id.spGraphicsMode);
spShader = findViewById(R.id.spShader);
btShaderTune = findViewById(R.id.btShaderTune);
shaderContainer = findViewById(R.id.shaderContainer);
cxParallel = findViewById(R.id.cxParallel);
cxForceFullscreen = findViewById(R.id.cxForceFullscreen);
cxShowFps = findViewById(R.id.cxShowFps);
tfFpsLimit = findViewById(R.id.etFpsLimit);
tfFontSizeSmall = findViewById(R.id.tfFontSizeSmall);
tfFontSizeMedium = findViewById(R.id.tfFontSizeMedium);
tfFontSizeLarge = findViewById(R.id.tfFontSizeLarge);
cxFontSizeInSP = findViewById(R.id.cxFontSizeInSP);
cxFontAA = findViewById(R.id.cxFontAA);
tfSystemProperties = findViewById(R.id.tfSystemProperties);
rootInputConfig = findViewById(R.id.rootInputConfig);
cxTouchInput = findViewById(R.id.cxTouchInput);
cxShowKeyboard = findViewById(R.id.cxIsShowKeyboard);
groupVkConfig = findViewById(R.id.groupVkConfig);
cxVKFeedback = findViewById(R.id.cxVKFeedback);
cxVKForceOpacity = findViewById(R.id.cxVKForceOpacity);
spLayout = findViewById(R.id.spLayout);
spButtonsShape = findViewById(R.id.spButtonsShape);
sbVKAlpha = findViewById(R.id.sbVKAlpha);
tfVKHideDelay = findViewById(R.id.tfVKHideDelay);
tfVKFore = findViewById(R.id.tfVKFore);
tfVKBack = findViewById(R.id.tfVKBack);
tfVKSelFore = findViewById(R.id.tfVKSelFore);
tfVKSelBack = findViewById(R.id.tfVKSelBack);
tfVKOutline = findViewById(R.id.tfVKOutline);
fillScreenSizePresets(display.getWidth(), display.getHeight());
addFontSizePreset("128 x 128", 9, 13, 15);
addFontSizePreset("128 x 160", 13, 15, 20);
addFontSizePreset("176 x 220", 15, 18, 22);
addFontSizePreset("240 x 320", 18, 22, 26);
cbLockAspect.setOnCheckedChangeListener(this::onLockAspectChanged);
findViewById(R.id.cmdScreenSizePresets).setOnClickListener(this::showScreenPresets);
findViewById(R.id.cmdSwapSizes).setOnClickListener(this);
findViewById(R.id.cmdAddToPreset).setOnClickListener(v -> addResolutionToPresets());
findViewById(R.id.cmdFontSizePresets).setOnClickListener(this);
findViewById(R.id.cmdScreenBack).setOnClickListener(this);
findViewById(R.id.cmdKeyMappings).setOnClickListener(this);
findViewById(R.id.cmdVKBack).setOnClickListener(this);
findViewById(R.id.cmdVKFore).setOnClickListener(this);
findViewById(R.id.cmdVKSelBack).setOnClickListener(this);
findViewById(R.id.cmdVKSelFore).setOnClickListener(this);
findViewById(R.id.cmdVKOutline).setOnClickListener(this);
findViewById(R.id.btEncoding).setOnClickListener(this::showCharsetPicker);
btShaderTune.setOnClickListener(this::showShaderSettings);
sbScaleRatio.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (fromUser) tfScaleRatioValue.setText(String.valueOf(progress));
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
tfScaleRatioValue.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int length = s.length();
if (length > 3) {
if (start >= 3) {
tfScaleRatioValue.getText().delete(3, length);
} else {
int st = start + count;
int end = st + (before == 0 ? count : before);
tfScaleRatioValue.getText().delete(st, Math.min(end, length));
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) return;
try {
int progress = Integer.parseInt(s.toString());
if (progress <= 100) {
sbScaleRatio.setProgress(progress);
} else {
s.replace(0, s.length(), "100");
}
} catch (NumberFormatException e) {
s.clear();
}
}
});
spGraphicsMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
case 3:
cxParallel.setVisibility(View.VISIBLE);
shaderContainer.setVisibility(View.GONE);
break;
case 1:
cxParallel.setVisibility(View.GONE);
initShaderSpinner();
break;
case 2:
cxParallel.setVisibility(View.GONE);
shaderContainer.setVisibility(View.GONE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
cxShowKeyboard.setOnClickListener((b) -> {
View.OnLayoutChangeListener onLayoutChangeListener = new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
View focus = rootContainer.findFocus();
if (focus != null) focus.clearFocus();
v.scrollTo(0, rootInputConfig.getTop());
v.removeOnLayoutChangeListener(this);
}
};
rootContainer.addOnLayoutChangeListener(onLayoutChangeListener);
groupVkConfig.setVisibility(cxShowKeyboard.isChecked() ? View.VISIBLE : View.GONE);
});
tfScreenBack.addTextChangedListener(new ColorTextWatcher(tfScreenBack));
tfVKFore.addTextChangedListener(new ColorTextWatcher(tfVKFore));
tfVKBack.addTextChangedListener(new ColorTextWatcher(tfVKBack));
tfVKSelFore.addTextChangedListener(new ColorTextWatcher(tfVKSelFore));
tfVKSelBack.addTextChangedListener(new ColorTextWatcher(tfVKSelBack));
tfVKOutline.addTextChangedListener(new ColorTextWatcher(tfVKOutline));
}
private void onLockAspectChanged(CompoundButton cb, boolean isChecked) {
if (isChecked) {
float w;
try {
w = Integer.parseInt(tfScreenWidth.getText().toString());
} catch (Exception ignored) {
w = 0;
}
if (w <= 0) {
cb.setChecked(false);
return;
}
float h;
try {
h = Integer.parseInt(tfScreenHeight.getText().toString());
} catch (Exception ignored) {
h = 0;
}
if (h <= 0) {
cb.setChecked(false);
return;
}
float finalW = w;
float finalH = h;
tfScreenWidth.setOnFocusChangeListener(new ResolutionAutoFill(tfScreenWidth, tfScreenHeight, finalH / finalW));
tfScreenHeight.setOnFocusChangeListener(new ResolutionAutoFill(tfScreenHeight, tfScreenWidth, finalW / finalH));
} else {
View.OnFocusChangeListener listener = tfScreenWidth.getOnFocusChangeListener();
if (listener != null) {
listener.onFocusChange(tfScreenWidth, false);
tfScreenWidth.setOnFocusChangeListener(null);
}
listener = tfScreenHeight.getOnFocusChangeListener();
if (listener != null) {
listener.onFocusChange(tfScreenHeight, false);
tfScreenHeight.setOnFocusChangeListener(null);
}
}
}
void loadConfig() {
params = ProfilesManager.loadConfig(configDir);
if (params == null && defProfile != null) {
FileUtils.copyFiles(new File(Config.getProfilesDir(), defProfile), configDir, null);
params = ProfilesManager.loadConfig(configDir);
}
if (params == null) {
params = new ProfileModel(configDir);
}
}
private void showShaderSettings(View v) {
ShaderInfo shader = (ShaderInfo) spShader.getSelectedItem();
params.shader = shader;
ShaderTuneAlert.newInstance(shader).show(getSupportFragmentManager(), "ShaderTuning");
}
private void initShaderSpinner() {
if (spShaderAdapter != null) {
shaderContainer.setVisibility(View.VISIBLE);
return;
}
File dir = new File(workDir + Config.SHADERS_DIR);
if (!dir.exists()) {
//noinspection ResultOfMethodCallIgnored
dir.mkdirs();
}
ArrayList<ShaderInfo> infos = new ArrayList<>();
spShaderAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, infos);
spShaderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spShader.setAdapter(spShaderAdapter);
File[] files = dir.listFiles((f) -> f.isFile() && f.getName().toLowerCase().endsWith(".ini"));
if (files != null) {
for (File file : files) {
String text = FileUtils.getText(file.getAbsolutePath());
String[] split = text.split("[\\n\\r]+");
ShaderInfo info = null;
for (String line : split) {
if (line.startsWith("[")) {
if (info != null && info.fragment != null && info.vertex != null) {
infos.add(info);
}
info = new ShaderInfo(line.replaceAll("[\\[\\]]", ""), "unknown");
} else if (info != null) {
try {
info.set(line);
} catch (Exception e) {
Log.e(TAG, "initShaderSpinner: ", e);
}
}
}
if (info != null && info.fragment != null && info.vertex != null) {
infos.add(info);
}
}
Collections.sort(infos);
}
infos.add(0, new ShaderInfo(getString(R.string.identity_filter), "woesss"));
spShaderAdapter.notifyDataSetChanged();
ShaderInfo selected = params.shader;
if (selected != null) {
int position = infos.indexOf(selected);
if (position > 0) {
infos.get(position).values = selected.values;
spShader.setSelection(position);
}
}
shaderContainer.setVisibility(View.VISIBLE);
spShader.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ShaderInfo item = (ShaderInfo) parent.getItemAtPosition(position);
ShaderInfo.Setting[] settings = item.settings;
float[] values = item.values;
if (values == null) {
for (int i = 0; i < 4; i++) {
if (settings[i] != null) {
if (values == null) {
values = new float[4];
}
values[i] = settings[i].def;
}
}
}
if (values == null) {
btShaderTune.setVisibility(View.GONE);
} else {
item.values = values;
btShaderTune.setVisibility(View.VISIBLE);
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void showCharsetPicker(View v) {
String[] charsets = Charset.availableCharsets().keySet().toArray(new String[0]);
new AlertDialog.Builder(this).setItems(charsets, (d, w) -> {
String enc = "microedition.encoding: " + charsets[w];
String[] props = tfSystemProperties.getText().toString().split("[\\n\\r]+");
int propsLength = props.length;
if (propsLength == 0) {
tfSystemProperties.setText(enc);
return;
}
int i = propsLength - 1;
while (i >= 0) {
if (props[i].startsWith("microedition.encoding")) {
props[i] = enc;
break;
}
i--;
}
if (i < 0) {
tfSystemProperties.append(enc);
return;
}
tfSystemProperties.setText(TextUtils.join("\n", props));
}).setTitle(R.string.pref_encoding_title).show();
}
private void loadKeyLayout() {
File file = new File(configDir, Config.MIDLET_KEY_LAYOUT_FILE);
keylayoutFile = file;
if (isProfile || file.exists()) {
return;
}
if (defProfile == null) {
return;
}
File defaultKeyLayoutFile = new File(Config.getProfilesDir() + defProfile, Config.MIDLET_KEY_LAYOUT_FILE);
if (!defaultKeyLayoutFile.exists()) {
return;
}
try {
FileUtils.copyFileUsingChannel(defaultKeyLayoutFile, file);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onPause() {
if (needShow && configDir != null) {
saveParams();
}
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
if (needShow) {
loadParams(true);
}
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
fillScreenSizePresets(display.getWidth(), display.getHeight());
}
private void fillScreenSizePresets(int w, int h) {
ArrayList<String> screenPresets = this.screenPresets;
screenPresets.clear();
screenPresets.add("128 x 128");
screenPresets.add("128 x 160");
screenPresets.add("132 x 176");
screenPresets.add("176 x 220");
screenPresets.add("240 x 320");
screenPresets.add("352 x 416");
screenPresets.add("640 x 360");
screenPresets.add("800 x 480");
if (w > h) {
screenPresets.add(h * 3 / 4 + " x " + h);
screenPresets.add(h * 4 / 3 + " x " + h);
} else {
screenPresets.add(w + " x " + w * 4 / 3);
screenPresets.add(w + " x " + w * 3 / 4);
}
screenPresets.add(w + " x " + h);
Set<String> preset = PreferenceManager.getDefaultSharedPreferences(this)
.getStringSet("ResolutionsPreset", null);
if (preset != null) {
screenPresets.addAll(preset);
}
Collections.sort(screenPresets, (o1, o2) -> {
int sep1 = o1.indexOf(" x ");
int sep2 = o2.indexOf(" x ");
if (sep1 == -1) {
if (sep2 != -1) return -1;
else return 0;
} else if (sep2 == -1) return 1;
int r = Integer.decode(o1.substring(0, sep1)).compareTo(Integer.decode(o2.substring(0, sep2)));
if (r != 0) return r;
return Integer.decode(o1.substring(sep1 + 3)).compareTo(Integer.decode(o2.substring(sep2 + 3)));
});
String prev = null;
for (Iterator<String> iterator = screenPresets.iterator(); iterator.hasNext(); ) {
String next = iterator.next();
if (next.equals(prev)) iterator.remove();
else prev = next;
}
}
private void addFontSizePreset(String title, int small, int medium, int large) {
fontPresetValues.add(new int[]{small, medium, large});
fontPresetTitles.add(title);
}
private int parseInt(String s) {
return parseInt(s, 10);
}
private int parseInt(String s, int radix) {
int result;
try {
result = Integer.parseInt(s, radix);
} catch (NumberFormatException e) {
result = 0;
}
return result;
}
@SuppressLint("SetTextI18n")
public void loadParams(boolean reloadFromFile) {
if (reloadFromFile) {
loadConfig();
}
int screenWidth = params.screenWidth;
if (screenWidth != 0) {
tfScreenWidth.setText(Integer.toString(screenWidth));
}
int screenHeight = params.screenHeight;
if (screenHeight != 0) {
tfScreenHeight.setText(Integer.toString(screenHeight));
}
tfScreenBack.setText(String.format("%06X", params.screenBackgroundColor));
sbScaleRatio.setProgress(params.screenScaleRatio);
tfScaleRatioValue.setText(Integer.toString(params.screenScaleRatio));
spOrientation.setSelection(params.orientation);
spScaleType.setSelection(params.screenScaleType);
spScreenGravity.setSelection(params.screenGravity);
cxFilter.setChecked(params.screenFilter);
cxImmediate.setChecked(params.immediateMode);
cxParallel.setChecked(params.parallelRedrawScreen);
cxForceFullscreen.setChecked(params.forceFullscreen);
spGraphicsMode.setSelection(params.graphicsMode);
cxShowFps.setChecked(params.showFps);
tfFontSizeSmall.setText(Integer.toString(params.fontSizeSmall));
tfFontSizeMedium.setText(Integer.toString(params.fontSizeMedium));
tfFontSizeLarge.setText(Integer.toString(params.fontSizeLarge));
cxFontSizeInSP.setChecked(params.fontApplyDimensions);
cxFontAA.setChecked(params.fontAA);
boolean showVk = params.showKeyboard;
cxShowKeyboard.setChecked(showVk);
groupVkConfig.setVisibility(showVk ? View.VISIBLE : View.GONE);
cxVKFeedback.setChecked(params.vkFeedback);
cxVKForceOpacity.setChecked(params.vkForceOpacity);
cxTouchInput.setChecked(params.touchInput);
int fpsLimit = params.fpsLimit;
if (fpsLimit > 0) {
tfFpsLimit.setText(Integer.toString(fpsLimit));
}
spLayout.setSelection(params.keyCodesLayout);
spButtonsShape.setSelection(params.vkButtonShape);
sbVKAlpha.setProgress(params.vkAlpha);
int vkHideDelay = params.vkHideDelay;
if (vkHideDelay > 0) {
tfVKHideDelay.setText(Integer.toString(vkHideDelay));
}
tfVKBack.setText(String.format("%06X", params.vkBgColor));
tfVKFore.setText(String.format("%06X", params.vkFgColor));
tfVKSelBack.setText(String.format("%06X", params.vkBgColorSelected));
tfVKSelFore.setText(String.format("%06X", params.vkFgColorSelected));
tfVKOutline.setText(String.format("%06X", params.vkOutlineColor));
String systemProperties = params.systemProperties;
if (systemProperties == null) {
systemProperties = ContextHolder.getAssetAsString("defaults/system.props");
}
tfSystemProperties.setText(systemProperties);
}
private void saveParams() {
try {
int width = parseInt(tfScreenWidth.getText().toString());
params.screenWidth = width;
int height = parseInt(tfScreenHeight.getText().toString());
params.screenHeight = height;
try {
params.screenBackgroundColor = Integer.parseInt(tfScreenBack.getText().toString(), 16);
} catch (NumberFormatException ignored) {
}
params.screenScaleRatio = sbScaleRatio.getProgress();
params.orientation = spOrientation.getSelectedItemPosition();
params.screenGravity = spScreenGravity.getSelectedItemPosition();
params.screenScaleType = spScaleType.getSelectedItemPosition();
params.screenFilter = cxFilter.isChecked();
params.immediateMode = cxImmediate.isChecked();
int mode = spGraphicsMode.getSelectedItemPosition();
params.graphicsMode = mode;
if (mode == 1) {
if (spShader.getSelectedItemPosition() == 0)
params.shader = null;
else
params.shader = (ShaderInfo) spShader.getSelectedItem();
}
params.parallelRedrawScreen = cxParallel.isChecked();
params.forceFullscreen = cxForceFullscreen.isChecked();
params.showFps = cxShowFps.isChecked();
params.fpsLimit = parseInt(tfFpsLimit.getText().toString());
try {
params.fontSizeSmall = Integer.parseInt(tfFontSizeSmall.getText().toString());
} catch (NumberFormatException e) {
params.fontSizeSmall = 0;
}
try {
params.fontSizeMedium = Integer.parseInt(tfFontSizeMedium.getText().toString());
} catch (NumberFormatException e) {
params.fontSizeMedium = 0;
}
try {
params.fontSizeLarge = Integer.parseInt(tfFontSizeLarge.getText().toString());
} catch (NumberFormatException e) {
params.fontSizeLarge = 0;
}
params.fontApplyDimensions = cxFontSizeInSP.isChecked();
params.fontAA = cxFontAA.isChecked();
params.showKeyboard = cxShowKeyboard.isChecked();
params.vkFeedback = cxVKFeedback.isChecked();
params.vkForceOpacity = cxVKForceOpacity.isChecked();
params.touchInput = cxTouchInput.isChecked();
params.keyCodesLayout = spLayout.getSelectedItemPosition();
params.vkButtonShape = spButtonsShape.getSelectedItemPosition();
params.vkAlpha = sbVKAlpha.getProgress();
params.vkHideDelay = parseInt(tfVKHideDelay.getText().toString());
try {
params.vkBgColor = Integer.parseInt(tfVKBack.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkFgColor = Integer.parseInt(tfVKFore.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkBgColorSelected = Integer.parseInt(tfVKSelBack.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkFgColorSelected = Integer.parseInt(tfVKSelFore.getText().toString(), 16);
} catch (Exception ignored) {
}
try {
params.vkOutlineColor = Integer.parseInt(tfVKOutline.getText().toString(), 16);
} catch (Exception ignored) {
}
params.systemProperties = getSystemProperties();
ProfilesManager.saveConfig(params);
} catch (Throwable t) {
t.printStackTrace();
}
}
@NonNull
private String getSystemProperties() {
String s = tfSystemProperties.getText().toString();
String[] lines = s.split("\\n");
StringBuilder sb = new StringBuilder(s.length());
boolean validCharset = false;
for (int i = lines.length - 1; i >= 0; i--) {
String line = lines[i];
if (line.trim().isEmpty()) continue;
if (line.startsWith("microedition.encoding:")) {
if (validCharset) continue;
try {
Charset.forName(line.substring(22).trim());
validCharset = true;
} catch (Exception ignored) {
continue;
}
}
sb.append(line).append('\n');
}
return sb.toString();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.config, menu);
if (isProfile) {
menu.findItem(R.id.action_start).setVisible(false);
menu.findItem(R.id.action_clear_data).setVisible(false);
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
if (itemId == R.id.action_start) {
startMIDlet();
} else if (itemId == R.id.action_clear_data) {
showClearDataDialog();
} else if (itemId == R.id.action_reset_settings) {
params = new ProfileModel(configDir);
loadParams(false);
} else if (itemId == R.id.action_reset_layout) {//noinspection ResultOfMethodCallIgnored
keylayoutFile.delete();
loadKeyLayout();
} else if (itemId == R.id.action_load_profile) {
LoadProfileAlert.newInstance(keylayoutFile.getParent())
.show(fragmentManager, "load_profile");
} else if (itemId == R.id.action_save_profile) {
saveParams();
SaveProfileAlert.getInstance(keylayoutFile.getParent())
.show(fragmentManager, "save_profile");
} else if (itemId == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void showClearDataDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle(android.R.string.dialog_alert_title)
.setMessage(R.string.message_clear_data)
.setPositiveButton(android.R.string.ok, (d, w) -> FileUtils.clearDirectory(dataDir))
.setNegativeButton(android.R.string.cancel, null);
builder.show();
}
private void startMIDlet() {
Intent i = new Intent(this, MicroActivity.class);
i.setData(getIntent().getData());
i.putExtra(KEY_MIDLET_NAME, getIntent().getStringExtra(KEY_MIDLET_NAME));
startActivity(i);
finish();
}
@SuppressLint("SetTextI18n")
@Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.cmdSwapSizes) {
String tmp = tfScreenWidth.getText().toString();
tfScreenWidth.setText(tfScreenHeight.getText().toString());
tfScreenHeight.setText(tmp);
} else if (id == R.id.cmdFontSizePresets) {
new AlertDialog.Builder(this)
.setTitle(getString(R.string.SIZE_PRESETS))
.setItems(fontPresetTitles.toArray(new String[0]),
(dialog, which) -> {
int[] values = fontPresetValues.get(which);
tfFontSizeSmall.setText(Integer.toString(values[0]));
tfFontSizeMedium.setText(Integer.toString(values[1]));
tfFontSizeLarge.setText(Integer.toString(values[2]));
})
.show();
} else if (id == R.id.cmdScreenBack) {
showColorPicker(tfScreenBack);
} else if (id == R.id.cmdVKBack) {
showColorPicker(tfVKBack);
} else if (id == R.id.cmdVKFore) {
showColorPicker(tfVKFore);
} else if (id == R.id.cmdVKSelFore) {
showColorPicker(tfVKSelFore);
} else if (id == R.id.cmdVKSelBack) {
showColorPicker(tfVKSelBack);
} else if (id == R.id.cmdVKOutline) {
showColorPicker(tfVKOutline);
} else if (id == R.id.cmdKeyMappings) {
Intent i = new Intent(getIntent().getAction(), Uri.parse(configDir.getPath()),
this, KeyMapperActivity.class);
startActivity(i);
}
}
private void showScreenPresets(View v) {
PopupMenu popup = new PopupMenu(this, v);
Menu menu = popup.getMenu();
for (String preset : screenPresets) {
menu.add(preset);
}
popup.setOnMenuItemClickListener(item -> {
String string = item.getTitle().toString();
int separator = string.indexOf(" x ");
tfScreenWidth.setText(string.substring(0, separator));
tfScreenHeight.setText(string.substring(separator + 3));
return true;
});
popup.show();
}
private void showColorPicker(EditText et) {
AmbilWarnaDialog.OnAmbilWarnaListener colorListener = new AmbilWarnaDialog.OnAmbilWarnaListener() {
@Override
public void onOk(AmbilWarnaDialog dialog, int color) {
et.setText(String.format("%06X", color & 0xFFFFFF));
ColorDrawable drawable = (ColorDrawable) et.getCompoundDrawablesRelative()[2];
drawable.setColor(color);
}
@Override
public void onCancel(AmbilWarnaDialog dialog) {
}
};
int color = parseInt(et.getText().toString().trim(), 16);
new AmbilWarnaDialog(this, color | 0xFF000000, colorListener).show();
}
private void addResolutionToPresets() {
String width = tfScreenWidth.getText().toString();
String height = tfScreenHeight.getText().toString();
if (width.isEmpty()) width = "-1";
if (height.isEmpty()) height = "-1";
int w = parseInt(width);
int h = parseInt(height);
if (w <= 0 || h <= 0) {
Toast.makeText(this, R.string.error, Toast.LENGTH_SHORT).show();
return;
}
String preset = width + " x " + height;
if (screenPresets.contains(preset)) {
Toast.makeText(this, R.string.not_saved_exists, Toast.LENGTH_SHORT).show();
return;
}
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
Set<String> set = preferences.getStringSet("ResolutionsPreset", null);
if (set == null) {
set = new HashSet<>(1);
}
if (set.add(preset)) {
preferences.edit().putStringSet("ResolutionsPreset", set).apply();
screenPresets.add(preset);
Toast.makeText(this, R.string.saved, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, R.string.not_saved_exists, Toast.LENGTH_SHORT).show();
}
}
@Override
public void onTuneComplete(float[] values) {
params.shader.values = values;
}
private static class ColorTextWatcher implements TextWatcher {
private final EditText editText;
private final ColorDrawable drawable;
ColorTextWatcher(EditText editText) {
this.editText = editText;
int size = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 32,
editText.getResources().getDisplayMetrics());
ColorDrawable colorDrawable = new ColorDrawable();
colorDrawable.setBounds(0, 0, size, size);
editText.setCompoundDrawablesRelative(null, null, colorDrawable, null);
drawable = colorDrawable;
editText.setFilters(new InputFilter[]{this::filter});
}
private CharSequence filter(CharSequence src, int ss, int se, Spanned dst, int ds, int de) {
StringBuilder sb = new StringBuilder(se - ss);
for (int i = ss; i < se; i++) {
char c = src.charAt(i);
if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F')) {
sb.append(c);
} else if (c >= 'a' && c <= 'f') {
sb.append((char) (c - 32));
}
}
return sb;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length() > 6) {
if (start >= 6) editText.getText().delete(6, s.length());
else {
int st = start + count;
int end = st + (before == 0 ? count : before);
editText.getText().delete(st, Math.min(end, s.length()));
}
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) return;
try {
int color = Integer.parseInt(s.toString(), 16);
drawable.setColor(color | Color.BLACK);
} catch (NumberFormatException e) {
drawable.setColor(Color.BLACK);
s.clear();
}
}
}
private static class ResolutionAutoFill implements TextWatcher, View.OnFocusChangeListener {
private final EditText src;
private final EditText dst;
private final float aspect;
public ResolutionAutoFill(EditText src, EditText dst, float aspect) {
this.src = src;
this.dst = dst;
this.aspect = aspect;
if (src.hasFocus())
src.addTextChangedListener(this);
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
int size = Integer.parseInt(src.getText().toString());
if (size <= 0) return;
int value = Math.round(size * aspect);
dst.setText(Integer.toString(value));
} catch (NumberFormatException ignored) { }
}
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
src.addTextChangedListener(this);
} else {
src.removeTextChangedListener(this);
}
}
}
}
| Fixed: Some options were not reset when resetting and loading config (#899)
Optimization: CompoundDrawables use TextViewCompat function
Co-authored-by: jobs_xie <[email protected]> | app/src/main/java/ru/playsoftware/j2meloader/config/ConfigActivity.java | Fixed: Some options were not reset when resetting and loading config (#899) | <ide><path>pp/src/main/java/ru/playsoftware/j2meloader/config/ConfigActivity.java
<ide> import androidx.appcompat.widget.PopupMenu;
<ide> import androidx.fragment.app.FragmentManager;
<ide> import androidx.preference.PreferenceManager;
<add>import androidx.core.widget.TextViewCompat;
<add>
<ide> import ru.playsoftware.j2meloader.R;
<ide> import ru.playsoftware.j2meloader.base.BaseActivity;
<ide> import ru.playsoftware.j2meloader.settings.KeyMapperActivity;
<ide> cxVKForceOpacity.setChecked(params.vkForceOpacity);
<ide> cxTouchInput.setChecked(params.touchInput);
<ide> int fpsLimit = params.fpsLimit;
<del> if (fpsLimit > 0) {
<del> tfFpsLimit.setText(Integer.toString(fpsLimit));
<del> }
<add> tfFpsLimit.setText(fpsLimit > 0 ? Integer.toString(fpsLimit) : "");
<ide>
<ide> spLayout.setSelection(params.keyCodesLayout);
<ide> spButtonsShape.setSelection(params.vkButtonShape);
<ide> sbVKAlpha.setProgress(params.vkAlpha);
<ide> int vkHideDelay = params.vkHideDelay;
<del> if (vkHideDelay > 0) {
<del> tfVKHideDelay.setText(Integer.toString(vkHideDelay));
<del> }
<add> tfVKHideDelay.setText(vkHideDelay > 0 ? Integer.toString(vkHideDelay) : "");
<ide>
<ide> tfVKBack.setText(String.format("%06X", params.vkBgColor));
<ide> tfVKFore.setText(String.format("%06X", params.vkFgColor));
<ide> @Override
<ide> public void onOk(AmbilWarnaDialog dialog, int color) {
<ide> et.setText(String.format("%06X", color & 0xFFFFFF));
<del> ColorDrawable drawable = (ColorDrawable) et.getCompoundDrawablesRelative()[2];
<add> ColorDrawable drawable = (ColorDrawable) TextViewCompat.getCompoundDrawablesRelative(et)[2];
<ide> drawable.setColor(color);
<ide> }
<ide>
<ide> editText.getResources().getDisplayMetrics());
<ide> ColorDrawable colorDrawable = new ColorDrawable();
<ide> colorDrawable.setBounds(0, 0, size, size);
<del> editText.setCompoundDrawablesRelative(null, null, colorDrawable, null);
<add> TextViewCompat.setCompoundDrawablesRelative(editText,null, null, colorDrawable, null);
<ide> drawable = colorDrawable;
<ide> editText.setFilters(new InputFilter[]{this::filter});
<ide> } |
|
Java | apache-2.0 | a9b2f06eb4951a4752b3098c56dff842bafe29bf | 0 | OSEHRA/ISAAC,OSEHRA/ISAAC,OSEHRA/ISAAC | /*
* Copyright 2019 Organizations participating in ISAAC, ISAAC's KOMET, and SOLOR development include the
US Veterans Health Administration, OSHERA, and the Health Services Platform Consortium..
*
* 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 sh.isaac.solor.direct.ho;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import sh.isaac.MetaData;
import sh.isaac.api.AssemblageService;
import sh.isaac.api.ConceptProxy;
import sh.isaac.api.Get;
import sh.isaac.api.IdentifiedComponentBuilder;
import sh.isaac.api.IdentifierService;
import sh.isaac.api.LookupService;
import sh.isaac.api.Status;
import sh.isaac.api.bootstrap.TermAux;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.chronicle.Version;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.commit.StampService;
import sh.isaac.api.component.concept.ConceptBuilder;
import sh.isaac.api.component.concept.ConceptBuilderService;
import sh.isaac.api.component.concept.ConceptChronology;
import sh.isaac.api.component.concept.ConceptService;
import sh.isaac.api.component.concept.ConceptSpecification;
import sh.isaac.api.component.semantic.SemanticBuilder;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.component.semantic.version.DescriptionVersion;
import sh.isaac.api.component.semantic.version.StringVersion;
import sh.isaac.api.externalizable.IsaacObjectType;
import sh.isaac.api.index.IndexBuilderService;
import sh.isaac.api.logic.LogicalExpressionBuilder;
import sh.isaac.api.logic.assertions.ConceptAssertion;
import sh.isaac.api.task.TimedTaskWithProgressTracker;
import sh.isaac.api.util.UuidT3Generator;
import sh.isaac.api.util.UuidT5Generator;
import sh.isaac.model.ModelGet;
import static sh.isaac.solor.direct.ho.HoDirectImporter.ALLERGEN_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_CCS_MULTI_1_ICD_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_CCS_MULTI_2_ICD_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_CCS_SINGLE_ICD_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICD10CM_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICD10PCS_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICF_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICPC_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_LEGACY_IS_A;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_MDC_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_MESH_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_RADLEX_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_RXCUI_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HUMAN_DX_MODULE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.INEXACT_SNOMED_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.IS_CATEGORY_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.IS_DIAGNOSIS_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.LEGACY_HUMAN_DX_ROOT_CONCEPT;
import static sh.isaac.solor.direct.ho.HoDirectImporter.REFID_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.SNOMED_MAP_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.SNOMED_SIB_CHILD_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ENTITY_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.LEGACY_HUMAN_DX_MODULE;
/**
*
* @author kec
*/
public class HoWriter extends TimedTaskWithProgressTracker<Void> {
//Name ref id Parents Abbreviations Description Is Diagnosis? Is category? Deprecated icd_10_cm icd_10_pcs icd_9_cm
//icf icpc loinc mdc mesh radlex rx_cui snomed_ct ccs-single_category_icd_10 ccs-multi_level_1_icd_10 ccs-multi_level_2_icd_10
//Inexact RxNormS Sibling/Child Inexact SNOMED Sibling/Child
//Name
public static final int NAME = 0;
//ref id
public static final int REFID = 1;
//Parent Names
public static final int PARENT_NAMES = 2;
//Parent Ref IDs
public static final int PARENT_REF_IDS = 3;
//Mapped to Allergen?
public static final int MAPPED_TO_ALLERGEN = 4;
//Abbreviations
public static final int ABBREVIATIONS = 5;
//Description
public static final int DESCRIPTION = 6;
//Is Diagnosis?
public static final int IS_DIAGNOSIS = 7;
//Is category?
public static final int IS_CATEGORY = 8;
//Deprecated
public static final int DEPRECATED = 9;
//icd_10_cm
public static final int ICD10CM = 10;
//icd_10_pcs
public static final int ICD10PCS = 11;
//icd_9_cm
public static final int ICD9CM = 12;
//icf
public static final int ICF = 13;
//icpc
public static final int ICPC = 14;
//loinc
public static final int LOINC = 15;
//mdc
public static final int MDC = 16;
//mesh
public static final int MESH = 17;
//radlex
public static final int RADLEX = 18;
//rx_cui
public static final int RXCUI = 19;
//snomed_ct
public static final int SNOMEDCT = 20;
//ccs-single_category_icd_10
public static final int CCS_SINGLE_CAT_ICD = 21;
//ccs-multi_level_1_icd_10
public static final int CCS_MULTI_LEVEL_1_ICD = 22;
//ccs-multi_level_2_icd_10
public static final int CCS_MULTI_LEVEL_2_ICD = 23;
//Inexact RxNorm
public static final int INEXACT_RXNORM = 24;
//RxNorm Sibling/Child
public static final int RXNORM_SIB_CHILD = 25;
//Inexact SNOMED
public static final int INEXACT_SNOMED_1 = 26;
//SNOMED Sibling/Child
public static final int SNOMED_SIB_CHILD_1 = 27;
//Inexact SNOMED
public static final int INEXACT_SNOMED_2 = 28;
//SNOMED Sibling/Child
public static final int SNOMED_SIB_CHILD_2 = 29;
//Inexact SNOMED
public static final int INEXACT_SNOMED_3 = 30;
//SNOMED Sibling/Child
public static final int SNOMED_SIB_CHILD_3 = 31;
private final List<String[]> hoRecords;
private final Semaphore writeSemaphore;
private final List<IndexBuilderService> indexers;
private final long commitTime;
private final IdentifierService identifierService = Get.identifierService();
private final AssemblageService assemblageService = Get.assemblageService();
private final HoDirectImporter importer;
private final ConceptProxy allergyToSubstance = new ConceptProxy("Allergy to substance (disorder)", UUID.fromString("dddb93ba-3e25-313d-b3be-5081a91cce37"));
private final ConceptProxy after = new ConceptProxy("After (attribute)", UUID.fromString("fb6758e0-442c-3393-bb2e-ff536711cde7"));
private final ConceptProxy allergicSensitization = new ConceptProxy("Allergic sensitization (disorder)", UUID.fromString("3944bbe7-9080-3d20-9466-3302fcfcd403"));
private final ConceptProxy causativeAgent = new ConceptProxy("Causative agent (attribute)", UUID.fromString("f770e2d8-91e6-3c55-91be-f794ee835265"));
public static UUID refidToUuid(String refid) {
return UuidT5Generator.get(LEGACY_HUMAN_DX_ROOT_CONCEPT.getPrimordialUuid(), refid);
}
public static int refidToNid(String refid) {
return Get.nidWithAssignment(UuidT5Generator.get(LEGACY_HUMAN_DX_ROOT_CONCEPT.getPrimordialUuid(), refid));
}
public static UUID refidToSolorUuid(String refid) {
return UuidT5Generator.get(HUMAN_DX_MODULE.getPrimordialUuid(), refid);
}
public static int refidToSolorNid(String refid) {
return Get.nidWithAssignment(UuidT5Generator.get(HUMAN_DX_MODULE.getPrimordialUuid(), refid));
}
public HoWriter(List<String[]> hoRecords,
Semaphore writeSemaphore, String message, long commitTime, HoDirectImporter importer) {
this.hoRecords = hoRecords;
this.writeSemaphore = writeSemaphore;
this.writeSemaphore.acquireUninterruptibly();
this.commitTime = commitTime;
indexers = LookupService.get().getAllServices(IndexBuilderService.class);
updateTitle("Importing LOINC batch of size: " + hoRecords.size());
updateMessage(message);
addToTotalWork(hoRecords.size());
Get.activeTasks().add(this);
this.importer = importer;
}
private void index(Chronology chronicle) {
for (IndexBuilderService indexer : indexers) {
indexer.indexNow(chronicle);
}
}
@Override
protected Void call() throws Exception {
try {
HashSet<String> allergenParents = new HashSet<>();
allergenParents.add("1");
allergenParents.add("3239");
allergenParents.add("13592");
ConceptService conceptService = Get.conceptService();
StampService stampService = Get.stampService();
int authorNid = TermAux.USER.getNid();
int pathNid = TermAux.DEVELOPMENT_PATH.getNid();
int moduleNid = HUMAN_DX_MODULE.getNid();
int conceptAssemblageNid = TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid();
List<String[]> noSuchElementList = new ArrayList<>();
HashMap<String, String> nameRefidMap = new HashMap<>();
for (String[] hoRec : hoRecords) {
nameRefidMap.put(hoRec[NAME], hoRec[REFID]);
}
// All deprecated records are filtered out already
for (String[] hoRec : hoRecords) {
if (hoRec.length < SNOMED_SIB_CHILD_3 + 1) {
String[] newRec = new String[SNOMED_SIB_CHILD_3 + 1];
Arrays.fill(newRec, "");
for (int i = 0; i < hoRec.length; i++) {
newRec[i] = hoRec[i];
}
hoRec = newRec;
}
hoRec = clean(hoRec);
try {
int recordStamp = stampService.getStampSequence(Status.ACTIVE, commitTime, authorNid, moduleNid, pathNid);
int legacyStamp = stampService.getStampSequence(Status.ACTIVE, commitTime, authorNid, LEGACY_HUMAN_DX_MODULE.getNid(), pathNid);
int inactiveLegacyStamp = stampService.getStampSequence(Status.INACTIVE, commitTime, authorNid, LEGACY_HUMAN_DX_MODULE.getNid(), pathNid);
// See if the concept is created (from the SNOMED/LOINC expressions.
UUID conceptUuid = refidToUuid(hoRec[REFID]);
int conceptNid = Get.nidWithAssignment(conceptUuid);
Optional<? extends ConceptChronology> optionalConcept = Get.conceptService().getOptionalConcept(conceptUuid);
if (!optionalConcept.isPresent()) {
int[] parentNids = new int[]{LEGACY_HUMAN_DX_ROOT_CONCEPT.getNid()};
if (hoRec[PARENT_NAMES] != null & !hoRec[PARENT_NAMES].isEmpty()) {
String[] parentRefIds = hoRec[PARENT_REF_IDS].split("; ");
parentNids = new int[parentRefIds.length];
for (int i = 0; i < parentRefIds.length; i++) {
String refId = parentRefIds[i];
if (allergenParents.contains(refId)) {
if (Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
// Add allergy concept...
LOG.info("Allergen record: " + Arrays.asList(hoRec));
addAllergy(hoRec[NAME], recordStamp, hoRec);
}
} else if (Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
LOG.info("Allergen record, no allergy parent: " + Arrays.asList(hoRec));
}
UUID parentUuid = refidToUuid(refId);
parentNids[i] = Get.nidWithAssignment(parentUuid);
ModelGet.identifierService().setupNid(parentNids[i], TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid(), IsaacObjectType.CONCEPT, VersionType.CONCEPT);
}
}
// Need to create new concept, and a stated definition...
buildConcept(conceptUuid, hoRec[NAME], recordStamp, legacyStamp, inactiveLegacyStamp, parentNids, hoRec);
// LogicalExpressionBuilder builder = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
//
// ConceptAssertion[] conceptAssertions = new ConceptAssertion[parentNids.length];
// for (int i = 0; i < conceptAssertions.length; i++) {
// conceptAssertions[i] = builder.conceptAssertion(parentNids[i]);
// }
// builder.necessarySet(builder.and(conceptAssertions));
// LogicalExpression logicalExpression = builder.build();
// logicalExpression.getNodeCount();
// addLogicGraph(conceptUuid, hoRec[NAME],
// logicalExpression);
}
// make regular descriptions
// String shortName = hoRec[SHORTNAME];
// if (shortName == null || shortName.isEmpty()) {
// shortName = fullyQualifiedName + " with no sn";
// }
//
// addDescription(hoRec, shortName, TermAux.REGULAR_NAME_DESCRIPTION_TYPE, conceptUuid, recordStamp);
} catch (NoSuchElementException ex) {
noSuchElementList.add(new String[]{ex.getMessage()});
noSuchElementList.add(hoRec);
}
completedUnitOfWork();
}
if (!noSuchElementList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String[] item : noSuchElementList) {
for (String field : item) {
sb.append(field);
sb.append("|");
}
sb.append("\n");
}
LOG.error("Continuing after import failed with no such element exception for record count: " + noSuchElementList.size()
+ "\n\n" + sb.toString());
}
return null;
} finally {
this.writeSemaphore.release();
Get.activeTasks().remove(this);
}
}
protected void buildConcept(UUID conceptUuid, String conceptName, int stamp, int legacyStamp, int inactiveLegacyStamp, int[] parentConceptNids, String[] hoRec) throws IllegalStateException, NoSuchElementException {
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
int conceptNid = Get.nidForUuids(conceptUuid);
ConceptAssertion[] parents = new ConceptAssertion[parentConceptNids.length];
for (int i = 0; i < parentConceptNids.length; i++) {
parents[i] = eb.conceptAssertion(parentConceptNids[i]);
}
eb.necessarySet(eb.and(parents));
if (!hoRec[SNOMEDCT].isEmpty()) {
if (hoRec[INEXACT_SNOMED_1].isEmpty()
&& hoRec[SNOMED_SIB_CHILD_1].isEmpty()
&& !hoRec[SNOMEDCT].contains(".")) {
UUID snomedUuid = UuidT3Generator.fromSNOMED(hoRec[SNOMEDCT]);
if (Get.identifierService().hasUuid(snomedUuid)) {
int snomedNid = Get.nidForUuids(snomedUuid);
SemanticBuilder semanticBuilder = Get.semanticBuilderService().getComponentSemanticBuilder(snomedNid, conceptNid, HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addItemsIfNew(hoRec, ICD10PCS, snomedNid, HDX_ICD10PCS_MAP, stamp);
addItemsIfNew(hoRec, ICF, snomedNid, HDX_ICF_MAP, stamp);
addItemsIfNew(hoRec, ICPC, snomedNid, HDX_ICPC_MAP, stamp);
addItemsIfNew(hoRec, MDC, snomedNid, HDX_MDC_MAP, stamp);
addItemsIfNew(hoRec, MESH, snomedNid, HDX_MESH_MAP, stamp);
addItemsIfNew(hoRec, RADLEX, snomedNid, HDX_RADLEX_MAP, stamp);
addItemsIfNew(hoRec, RXCUI, snomedNid, HDX_RXCUI_MAP, stamp);
addItemsIfNew(hoRec, CCS_SINGLE_CAT_ICD, snomedNid, HDX_CCS_SINGLE_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_1_ICD, snomedNid, HDX_CCS_MULTI_1_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_2_ICD, snomedNid, HDX_CCS_MULTI_2_ICD_MAP, stamp);
addDescriptionsIfNew(hoRec, snomedNid, stamp);
} else {
LOG.info("No concept for: |" + hoRec[SNOMEDCT] + "|" + snomedUuid.toString());
}
} else if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
LOG.error("SNOMED and inexact populated: " + Arrays.asList(hoRec));
}
} else if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
// '22325002' 'Child' 8510008' 'Child'
// '16737003' 'Sibling'
// '216757002' 'Parent' - Remember to process a parent relationship like a sibling one
switch (hoRec[SNOMED_SIB_CHILD_1]) {
case "Child":
addChild(conceptName, stamp, hoRec);
break;
case "Sibling":
case "Parent":
addSibling(conceptName, stamp, hoRec);
break;
}
}
ConceptBuilderService builderService = Get.conceptBuilderService();
String[] parentNames = hoRec[PARENT_NAMES].split("; ");
String[] abbreviations = hoRec[ABBREVIATIONS].split("; ");
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HO " + parentNames[0],
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
for (int parentNid : parentConceptNids) {
builder.addComponentSemantic(new ConceptProxy(parentNid), HDX_LEGACY_IS_A);
}
addMaps(hoRec, builder);
// white-coated tongue; white coating on tongue; tongue with white coating
for (int i = 0; i < abbreviations.length; i++) {
if (!abbreviations[i].isEmpty()) {
builder.addDescription(abbreviations[i], MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR);
}
}
if (!hoRec[REFID].isEmpty()) {
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
}
if (!hoRec[MAPPED_TO_ALLERGEN].isEmpty()) {
builder.addStringSemantic(hoRec[MAPPED_TO_ALLERGEN], ALLERGEN_ASSEMBLAGE);
}
if (!hoRec[IS_DIAGNOSIS].isEmpty()) {
builder.addStringSemantic(hoRec[IS_DIAGNOSIS], IS_DIAGNOSIS_ASSEMBLAGE);
}
if (!hoRec[IS_CATEGORY].isEmpty()) {
builder.addStringSemantic(hoRec[IS_CATEGORY], IS_CATEGORY_ASSEMBLAGE);
}
if (!hoRec[SNOMEDCT].isEmpty()) {
if (!hoRec[MAPPED_TO_ALLERGEN].isEmpty() && Boolean.parseBoolean(hoRec[MAPPED_TO_ALLERGEN])) {
// The SNOMED record is not the correct record, since it is mapped to an allergen, and
// will thus have an allegy concept created for it.
} else {
UUID snomedUuid = UuidT3Generator.fromSNOMED(hoRec[SNOMEDCT]);
if (Get.identifierService().hasUuid(snomedUuid)) {
int snomedNid = Get.nidForUuids(snomedUuid);
builder.addStringSemantic(hoRec[SNOMEDCT], SNOMED_MAP_ASSEMBLAGE);
// Add reverse semantic
addReverseSemantic(hoRec, conceptNid, snomedNid, stamp);
} else {
throw new NoSuchElementException("No identifier for: " + hoRec[SNOMEDCT]);
}
}
}
if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
builder.addStringSemantic(hoRec[INEXACT_SNOMED_1], INEXACT_SNOMED_ASSEMBLAGE);
}
if (!hoRec[SNOMED_SIB_CHILD_1].isEmpty()) {
builder.addStringSemantic(hoRec[SNOMED_SIB_CHILD_1], SNOMED_SIB_CHILD_ASSEMBLAGE);
}
if (!hoRec[INEXACT_SNOMED_2].isEmpty()) {
builder.addStringSemantic(hoRec[INEXACT_SNOMED_2], INEXACT_SNOMED_ASSEMBLAGE);
}
if (!hoRec[SNOMED_SIB_CHILD_2].isEmpty()) {
builder.addStringSemantic(hoRec[SNOMED_SIB_CHILD_2], SNOMED_SIB_CHILD_ASSEMBLAGE);
}
if (!hoRec[INEXACT_SNOMED_3].isEmpty()) {
builder.addStringSemantic(hoRec[INEXACT_SNOMED_3], INEXACT_SNOMED_ASSEMBLAGE);
}
if (!hoRec[SNOMED_SIB_CHILD_3].isEmpty()) {
builder.addStringSemantic(hoRec[SNOMED_SIB_CHILD_3], SNOMED_SIB_CHILD_ASSEMBLAGE);
}
if (!hoRec[DEPRECATED].isEmpty() && Boolean.parseBoolean(hoRec[DEPRECATED])) {
buildAndIndex(builder, inactiveLegacyStamp, hoRec);
} else {
buildAndIndex(builder, legacyStamp, hoRec);
}
}
private void addReverseSemantic(String[] hoRec, int legacyHdxNid, int solorNid, int stamp) throws NoSuchElementException, IllegalStateException {
int assemblageConceptNid = HDX_ENTITY_ASSEMBLAGE.getNid();
//int componentNid,
SemanticBuilder semanticBuilder = Get.semanticBuilderService().getComponentSemanticBuilder(legacyHdxNid, solorNid, assemblageConceptNid);
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
}
protected void buildAndIndex(IdentifiedComponentBuilder builder, int stamp, String[] hoRec) throws IllegalStateException {
List<Chronology> builtObjects = new ArrayList<>();
builder.build(stamp, builtObjects);
for (Chronology chronology : builtObjects) {
Get.identifiedObjectService().putChronologyData(chronology);
if (chronology.getVersionType() == VersionType.LOGIC_GRAPH) {
try {
Get.taxonomyService().updateTaxonomy((SemanticChronology) chronology);
} catch (RuntimeException e) {
LOG.error("Processing " + Arrays.toString(hoRec), e);
}
}
index(chronology);
}
}
private String[] clean(String[] hoRec) {
for (int i = 0; i < hoRec.length; i++) {
hoRec[i] = hoRec[i].trim();
if (hoRec[i].startsWith("'")) {
hoRec[i] = hoRec[i].substring(1);
}
if (hoRec[i].endsWith("'")) {
hoRec[i] = hoRec[i].substring(0, hoRec[i].length() - 1);
}
if (hoRec[i].startsWith("\"")) {
hoRec[i] = hoRec[i].substring(1);
}
if (hoRec[i].endsWith("\"")) {
hoRec[i] = hoRec[i].substring(0, hoRec[i].length() - 1);
}
}
return hoRec;
}
private void addChild(String conceptName, int stamp, String[] hoRec) {
List<Integer> parentConceptNidList = new ArrayList<>();
if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
parentConceptNidList.add(getNidForSCTID(hoRec[INEXACT_SNOMED_1]));
}
if (!hoRec[INEXACT_SNOMED_2].isEmpty()) {
parentConceptNidList.add(getNidForSCTID(hoRec[INEXACT_SNOMED_2]));
}
if (!hoRec[INEXACT_SNOMED_3].isEmpty()) {
parentConceptNidList.add(getNidForSCTID(hoRec[INEXACT_SNOMED_3]));
}
int[] parentConceptNids = new int[parentConceptNidList.size()];
for (int i = 0; i < parentConceptNids.length; i++) {
parentConceptNids[i] = parentConceptNidList.get(i);
}
HdxConceptHash hdxConceptHash = new HdxConceptHash(conceptName, parentConceptNids, hoRec[REFID]);
UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
int conceptNid = Get.nidWithAssignment(conceptUuid);
if (this.importer.getHdxSolorConcepts().containsKey(hdxConceptHash)) {
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), this.importer.getHdxSolorConcepts().get(hdxConceptHash).getNid(), stamp);
//builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
addItemsIfNew(hoRec, ICD10PCS, conceptNid, HDX_ICD10PCS_MAP, stamp);
addItemsIfNew(hoRec, ICF, conceptNid, HDX_ICF_MAP, stamp);
addItemsIfNew(hoRec, ICPC, conceptNid, HDX_ICPC_MAP, stamp);
addItemsIfNew(hoRec, MDC, conceptNid, HDX_MDC_MAP, stamp);
addItemsIfNew(hoRec, MESH, conceptNid, HDX_MESH_MAP, stamp);
addItemsIfNew(hoRec, RADLEX, conceptNid, HDX_RADLEX_MAP, stamp);
addItemsIfNew(hoRec, RXCUI, conceptNid, HDX_RXCUI_MAP, stamp);
addItemsIfNew(hoRec, CCS_SINGLE_CAT_ICD, conceptNid, HDX_CCS_SINGLE_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_1_ICD, conceptNid, HDX_CCS_MULTI_1_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_2_ICD, conceptNid, HDX_CCS_MULTI_2_ICD_MAP, stamp);
} else {
this.importer.getHdxSolorConcepts().put(hdxConceptHash, new ConceptProxy(conceptName, conceptUuid));
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
ConceptAssertion[] parents = new ConceptAssertion[parentConceptNidList.size()];
for (int i = 0; i < parentConceptNidList.size(); i++) {
parents[i] = eb.conceptAssertion(parentConceptNidList.get(i));
}
eb.necessarySet(eb.and(parents));
ConceptBuilderService builderService = Get.conceptBuilderService();
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HDX",
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
});
addMaps(hoRec, builder);
buildAndIndex(builder, stamp, hoRec);
//
if (!Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
SemanticBuilder semanticBuilder = Get.semanticBuilderService().getComponentSemanticBuilder(conceptNid, refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
}
}
}
private int getNidForSCTID(String sctid) {
UUID snomedUuid = UuidT3Generator.fromSNOMED(sctid);
return Get.nidForUuids(snomedUuid);
}
HashMap<String, Integer> snomedAllergyMap = new HashMap<>();
private void addAllergy(String conceptName, int stamp, String[] hoRec) {
// see if allergy already added...
if (snomedAllergyMap.containsKey(hoRec[SNOMEDCT])) {
// already added, add info to existing concept.
int existingAllergyNid = snomedAllergyMap.get(hoRec[SNOMEDCT]);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), existingAllergyNid, stamp);
buildAndIndex(Get.semanticBuilderService().getStringSemanticBuilder(hoRec[REFID], existingAllergyNid, REFID_ASSEMBLAGE.getNid()), stamp, hoRec);
} else {
UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
// Parent is 419199007 |Allergy to substance (finding)|
// Has realization → Allergic process
// Causative agent → Substance
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
eb.sufficientSet(eb.and(eb.conceptAssertion(allergyToSubstance), eb.someRole(MetaData.ROLE_GROUP____SOLOR,
eb.and(eb.someRole(after, eb.conceptAssertion(allergicSensitization)),
eb.someRole(causativeAgent, eb.conceptAssertion(getNidForSCTID(hoRec[SNOMEDCT])))))));
ConceptBuilderService builderService = Get.conceptBuilderService();
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HDX",
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
});
int conceptNid = builder.getNid();
buildAndIndex(builder, stamp, hoRec);
snomedAllergyMap.put(hoRec[SNOMEDCT], conceptNid);
//
SemanticBuilder semanticBuilder = Get.semanticBuilderService()
.getComponentSemanticBuilder(refidToSolorNid(hoRec[REFID]),
refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
}
}
private void addSibling(String conceptName, int stamp, String[] hoRec) {
UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
int[] parentConceptNids = new int[]{getNidForSCTID(hoRec[INEXACT_SNOMED_1])};
HdxConceptHash hdxConceptHash = new HdxConceptHash(conceptName, parentConceptNids, hoRec[REFID]);
if (this.importer.getHdxSolorConcepts().containsKey(hdxConceptHash)) {
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), this.importer.getHdxSolorConcepts().get(hdxConceptHash).getNid(), stamp);
//builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
int conceptNid = Get.nidForUuids(conceptUuid);
addItemsIfNew(hoRec, ICD10PCS, conceptNid, HDX_ICD10PCS_MAP, stamp);
addItemsIfNew(hoRec, ICF, conceptNid, HDX_ICF_MAP, stamp);
addItemsIfNew(hoRec, ICPC, conceptNid, HDX_ICPC_MAP, stamp);
addItemsIfNew(hoRec, MDC, conceptNid, HDX_MDC_MAP, stamp);
addItemsIfNew(hoRec, MESH, conceptNid, HDX_MESH_MAP, stamp);
addItemsIfNew(hoRec, RADLEX, conceptNid, HDX_RADLEX_MAP, stamp);
addItemsIfNew(hoRec, RXCUI, conceptNid, HDX_RXCUI_MAP, stamp);
addItemsIfNew(hoRec, CCS_SINGLE_CAT_ICD, conceptNid, HDX_CCS_SINGLE_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_1_ICD, conceptNid, HDX_CCS_MULTI_1_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_2_ICD, conceptNid, HDX_CCS_MULTI_2_ICD_MAP, stamp);
} else {
this.importer.getHdxSolorConcepts().put(hdxConceptHash, new ConceptProxy(conceptName, conceptUuid));
int[] parentNids = this.importer.getTaxonomy().getTaxonomyParentConceptNids(parentConceptNids[0]);
ConceptAssertion[] parents = new ConceptAssertion[parentNids.length];
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
for (int i = 0; i < parentNids.length; i++) {
parents[i] = eb.conceptAssertion(parentNids[i]);
}
eb.necessarySet(eb.and(parents));
ConceptBuilderService builderService = Get.conceptBuilderService();
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HDX",
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
});
int conceptNid = builder.getNid();
addMaps(hoRec, builder);
buildAndIndex(builder, stamp, hoRec);
//
SemanticBuilder semanticBuilder = Get.semanticBuilderService()
.getComponentSemanticBuilder(refidToSolorNid(hoRec[REFID]),
refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
}
}
private void addMaps(String[] hoRec, ConceptBuilder builder) {
if (!hoRec[ICD10CM].isEmpty()) {
String[] dataArray = hoRec[ICD10CM].split("; ");
for (String data : dataArray) {
builder.addStringSemantic(data, HDX_ICD10CM_MAP);
}
}
addItems(hoRec, ICD10PCS, builder, HDX_ICD10PCS_MAP);
addItems(hoRec, ICF, builder, HDX_ICF_MAP);
addItems(hoRec, ICPC, builder, HDX_ICPC_MAP);
addItems(hoRec, MDC, builder, HDX_MDC_MAP);
addItems(hoRec, MESH, builder, HDX_MESH_MAP);
addItems(hoRec, RADLEX, builder, HDX_RADLEX_MAP);
addItems(hoRec, RXCUI, builder, HDX_RXCUI_MAP);
addItems(hoRec, CCS_SINGLE_CAT_ICD, builder, HDX_CCS_SINGLE_ICD_MAP);
addItems(hoRec, CCS_MULTI_LEVEL_1_ICD, builder, HDX_CCS_MULTI_1_ICD_MAP);
addItems(hoRec, CCS_MULTI_LEVEL_2_ICD, builder, HDX_CCS_MULTI_2_ICD_MAP);
}
private void addItems(String[] hoRec, int index, ConceptBuilder builder, ConceptSpecification assemblage) {
if (!hoRec[index].isEmpty()) {
String[] dataArray = hoRec[index].split("; ");
for (String data : dataArray) {
builder.addStringSemantic(data, assemblage);
}
}
}
private void addItemsIfNew(String[] hoRec, int index, int conceptNid, ConceptSpecification assemblage, int stamp) {
HashSet<String> existing = new HashSet();
Get.assemblageService().getSemanticChronologyStreamForComponentFromAssemblage(conceptNid, assemblage.getNid())
.forEach(semanticChronology -> {
for (Version v : semanticChronology.getVersionList()) {
existing.add(((StringVersion) v).getString());
}
});
if (!hoRec[index].isEmpty()) {
String[] dataArray = hoRec[index].split("; ");
for (String data : dataArray) {
if (!existing.contains(data)) {
SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getStringSemanticBuilder(data, conceptNid, assemblage.getNid());
buildAndIndex(b, stamp, hoRec);
}
}
}
}
private void addDescriptionsIfNew(String[] hoRec, int snomedNid, int stamp) {
if (Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
return;
}
HashSet<String> existing = new HashSet();
Get.assemblageService().getSemanticChronologyStreamForComponentFromAssemblage(snomedNid, TermAux.ENGLISH_LANGUAGE.getNid())
.forEach(semanticChronology -> {
for (Version v : semanticChronology.getVersionList()) {
existing.add(((DescriptionVersion) v).getText());
}
});
String[] abbreviations = hoRec[ABBREVIATIONS].split("; ");
for (int i = 0; i < abbreviations.length; i++) {
if (!abbreviations[i].isEmpty() && !existing.contains(abbreviations[i])) {
SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
abbreviations[i], snomedNid);
b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
buildAndIndex(b, stamp, hoRec);
}
}
if (!existing.contains(hoRec[NAME])) {
SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
hoRec[NAME], snomedNid);
b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
buildAndIndex(b, stamp, hoRec);
}
}
}
| solor/direct-import/src/main/java/sh/isaac/solor/direct/ho/HoWriter.java | /*
* Copyright 2019 Organizations participating in ISAAC, ISAAC's KOMET, and SOLOR development include the
US Veterans Health Administration, OSHERA, and the Health Services Platform Consortium..
*
* 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 sh.isaac.solor.direct.ho;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.Semaphore;
import sh.isaac.MetaData;
import sh.isaac.api.AssemblageService;
import sh.isaac.api.ConceptProxy;
import sh.isaac.api.Get;
import sh.isaac.api.IdentifiedComponentBuilder;
import sh.isaac.api.IdentifierService;
import sh.isaac.api.LookupService;
import sh.isaac.api.Status;
import sh.isaac.api.bootstrap.TermAux;
import sh.isaac.api.chronicle.Chronology;
import sh.isaac.api.chronicle.Version;
import sh.isaac.api.chronicle.VersionType;
import sh.isaac.api.commit.StampService;
import sh.isaac.api.component.concept.ConceptBuilder;
import sh.isaac.api.component.concept.ConceptBuilderService;
import sh.isaac.api.component.concept.ConceptChronology;
import sh.isaac.api.component.concept.ConceptService;
import sh.isaac.api.component.concept.ConceptSpecification;
import sh.isaac.api.component.semantic.SemanticBuilder;
import sh.isaac.api.component.semantic.SemanticChronology;
import sh.isaac.api.component.semantic.version.DescriptionVersion;
import sh.isaac.api.component.semantic.version.StringVersion;
import sh.isaac.api.externalizable.IsaacObjectType;
import sh.isaac.api.index.IndexBuilderService;
import sh.isaac.api.logic.LogicalExpressionBuilder;
import sh.isaac.api.logic.assertions.ConceptAssertion;
import sh.isaac.api.task.TimedTaskWithProgressTracker;
import sh.isaac.api.util.UuidT3Generator;
import sh.isaac.api.util.UuidT5Generator;
import sh.isaac.model.ModelGet;
import static sh.isaac.solor.direct.ho.HoDirectImporter.ALLERGEN_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_CCS_MULTI_1_ICD_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_CCS_MULTI_2_ICD_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_CCS_SINGLE_ICD_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICD10CM_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICD10PCS_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICF_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ICPC_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_LEGACY_IS_A;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_MDC_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_MESH_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_RADLEX_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_RXCUI_MAP;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HUMAN_DX_MODULE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.INEXACT_SNOMED_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.IS_CATEGORY_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.IS_DIAGNOSIS_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.LEGACY_HUMAN_DX_ROOT_CONCEPT;
import static sh.isaac.solor.direct.ho.HoDirectImporter.REFID_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.SNOMED_MAP_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.SNOMED_SIB_CHILD_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HDX_ENTITY_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE;
import static sh.isaac.solor.direct.ho.HoDirectImporter.LEGACY_HUMAN_DX_MODULE;
/**
*
* @author kec
*/
public class HoWriter extends TimedTaskWithProgressTracker<Void> {
//Name ref id Parents Abbreviations Description Is Diagnosis? Is category? Deprecated icd_10_cm icd_10_pcs icd_9_cm
//icf icpc loinc mdc mesh radlex rx_cui snomed_ct ccs-single_category_icd_10 ccs-multi_level_1_icd_10 ccs-multi_level_2_icd_10
//Inexact RxNormS Sibling/Child Inexact SNOMED Sibling/Child
//Name
public static final int NAME = 0;
//ref id
public static final int REFID = 1;
//Parent Names
public static final int PARENT_NAMES = 2;
//Parent Ref IDs
public static final int PARENT_REF_IDS = 3;
//Mapped to Allergen?
public static final int MAPPED_TO_ALLERGEN = 4;
//Abbreviations
public static final int ABBREVIATIONS = 5;
//Description
public static final int DESCRIPTION = 6;
//Is Diagnosis?
public static final int IS_DIAGNOSIS = 7;
//Is category?
public static final int IS_CATEGORY = 8;
//Deprecated
public static final int DEPRECATED = 9;
//icd_10_cm
public static final int ICD10CM = 10;
//icd_10_pcs
public static final int ICD10PCS = 11;
//icd_9_cm
public static final int ICD9CM = 12;
//icf
public static final int ICF = 13;
//icpc
public static final int ICPC = 14;
//loinc
public static final int LOINC = 15;
//mdc
public static final int MDC = 16;
//mesh
public static final int MESH = 17;
//radlex
public static final int RADLEX = 18;
//rx_cui
public static final int RXCUI = 19;
//snomed_ct
public static final int SNOMEDCT = 20;
//ccs-single_category_icd_10
public static final int CCS_SINGLE_CAT_ICD = 21;
//ccs-multi_level_1_icd_10
public static final int CCS_MULTI_LEVEL_1_ICD = 22;
//ccs-multi_level_2_icd_10
public static final int CCS_MULTI_LEVEL_2_ICD = 23;
//Inexact RxNorm
public static final int INEXACT_RXNORM = 24;
//RxNorm Sibling/Child
public static final int RXNORM_SIB_CHILD = 25;
//Inexact SNOMED
public static final int INEXACT_SNOMED_1 = 26;
//SNOMED Sibling/Child
public static final int SNOMED_SIB_CHILD_1 = 27;
//Inexact SNOMED
public static final int INEXACT_SNOMED_2 = 28;
//SNOMED Sibling/Child
public static final int SNOMED_SIB_CHILD_2 = 29;
//Inexact SNOMED
public static final int INEXACT_SNOMED_3 = 30;
//SNOMED Sibling/Child
public static final int SNOMED_SIB_CHILD_3 = 31;
private final List<String[]> hoRecords;
private final Semaphore writeSemaphore;
private final List<IndexBuilderService> indexers;
private final long commitTime;
private final IdentifierService identifierService = Get.identifierService();
private final AssemblageService assemblageService = Get.assemblageService();
private final HoDirectImporter importer;
private final ConceptProxy allergyToSubstance = new ConceptProxy("Allergy to substance (disorder)", UUID.fromString("dddb93ba-3e25-313d-b3be-5081a91cce37"));
private final ConceptProxy after = new ConceptProxy("After (attribute)", UUID.fromString("fb6758e0-442c-3393-bb2e-ff536711cde7"));
private final ConceptProxy allergicSensitization = new ConceptProxy("Allergic sensitization (disorder)", UUID.fromString("3944bbe7-9080-3d20-9466-3302fcfcd403"));
private final ConceptProxy causativeAgent = new ConceptProxy("Causative agent (attribute)", UUID.fromString("f770e2d8-91e6-3c55-91be-f794ee835265"));
public static UUID refidToUuid(String refid) {
return UuidT5Generator.get(LEGACY_HUMAN_DX_ROOT_CONCEPT.getPrimordialUuid(), refid);
}
public static int refidToNid(String refid) {
return Get.nidWithAssignment(UuidT5Generator.get(LEGACY_HUMAN_DX_ROOT_CONCEPT.getPrimordialUuid(), refid));
}
public static UUID refidToSolorUuid(String refid) {
return UuidT5Generator.get(HUMAN_DX_MODULE.getPrimordialUuid(), refid);
}
public static int refidToSolorNid(String refid) {
return Get.nidWithAssignment(UuidT5Generator.get(HUMAN_DX_MODULE.getPrimordialUuid(), refid));
}
public HoWriter(List<String[]> hoRecords,
Semaphore writeSemaphore, String message, long commitTime, HoDirectImporter importer) {
this.hoRecords = hoRecords;
this.writeSemaphore = writeSemaphore;
this.writeSemaphore.acquireUninterruptibly();
this.commitTime = commitTime;
indexers = LookupService.get().getAllServices(IndexBuilderService.class);
updateTitle("Importing LOINC batch of size: " + hoRecords.size());
updateMessage(message);
addToTotalWork(hoRecords.size());
Get.activeTasks().add(this);
this.importer = importer;
}
private void index(Chronology chronicle) {
for (IndexBuilderService indexer : indexers) {
indexer.indexNow(chronicle);
}
}
@Override
protected Void call() throws Exception {
try {
HashSet<String> allergenParents = new HashSet<>();
allergenParents.add("1");
allergenParents.add("3239");
allergenParents.add("13592");
ConceptService conceptService = Get.conceptService();
StampService stampService = Get.stampService();
int authorNid = TermAux.USER.getNid();
int pathNid = TermAux.DEVELOPMENT_PATH.getNid();
int moduleNid = HUMAN_DX_MODULE.getNid();
int conceptAssemblageNid = TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid();
List<String[]> noSuchElementList = new ArrayList<>();
HashMap<String, String> nameRefidMap = new HashMap<>();
for (String[] hoRec : hoRecords) {
nameRefidMap.put(hoRec[NAME], hoRec[REFID]);
}
// All deprecated records are filtered out already
for (String[] hoRec : hoRecords) {
if (hoRec.length < SNOMED_SIB_CHILD_3 + 1) {
String[] newRec = new String[SNOMED_SIB_CHILD_3 + 1];
Arrays.fill(newRec, "");
for (int i = 0; i < hoRec.length; i++) {
newRec[i] = hoRec[i];
}
hoRec = newRec;
}
hoRec = clean(hoRec);
try {
int recordStamp = stampService.getStampSequence(Status.ACTIVE, commitTime, authorNid, moduleNid, pathNid);
int legacyStamp = stampService.getStampSequence(Status.ACTIVE, commitTime, authorNid, LEGACY_HUMAN_DX_MODULE.getNid(), pathNid);
int inactiveLegacyStamp = stampService.getStampSequence(Status.INACTIVE, commitTime, authorNid, LEGACY_HUMAN_DX_MODULE.getNid(), pathNid);
// See if the concept is created (from the SNOMED/LOINC expressions.
UUID conceptUuid = refidToUuid(hoRec[REFID]);
int conceptNid = Get.nidWithAssignment(conceptUuid);
Optional<? extends ConceptChronology> optionalConcept = Get.conceptService().getOptionalConcept(conceptUuid);
if (!optionalConcept.isPresent()) {
int[] parentNids = new int[]{LEGACY_HUMAN_DX_ROOT_CONCEPT.getNid()};
if (hoRec[PARENT_NAMES] != null & !hoRec[PARENT_NAMES].isEmpty()) {
String[] parentRefIds = hoRec[PARENT_REF_IDS].split("; ");
parentNids = new int[parentRefIds.length];
for (int i = 0; i < parentRefIds.length; i++) {
String refId = parentRefIds[i];
if (allergenParents.contains(refId)) {
if (Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
// Add allergy concept...
LOG.info("Allergen record: " + Arrays.asList(hoRec));
addAllergy(hoRec[NAME], recordStamp, hoRec);
}
} else if (Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
LOG.info("Allergen record, no allergy parent: " + Arrays.asList(hoRec));
}
UUID parentUuid = refidToUuid(refId);
parentNids[i] = Get.nidWithAssignment(parentUuid);
ModelGet.identifierService().setupNid(parentNids[i], TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid(), IsaacObjectType.CONCEPT, VersionType.CONCEPT);
}
}
// Need to create new concept, and a stated definition...
buildConcept(conceptUuid, hoRec[NAME], recordStamp, legacyStamp, inactiveLegacyStamp, parentNids, hoRec);
// LogicalExpressionBuilder builder = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
//
// ConceptAssertion[] conceptAssertions = new ConceptAssertion[parentNids.length];
// for (int i = 0; i < conceptAssertions.length; i++) {
// conceptAssertions[i] = builder.conceptAssertion(parentNids[i]);
// }
// builder.necessarySet(builder.and(conceptAssertions));
// LogicalExpression logicalExpression = builder.build();
// logicalExpression.getNodeCount();
// addLogicGraph(conceptUuid, hoRec[NAME],
// logicalExpression);
}
// make regular descriptions
// String shortName = hoRec[SHORTNAME];
// if (shortName == null || shortName.isEmpty()) {
// shortName = fullyQualifiedName + " with no sn";
// }
//
// addDescription(hoRec, shortName, TermAux.REGULAR_NAME_DESCRIPTION_TYPE, conceptUuid, recordStamp);
} catch (NoSuchElementException ex) {
noSuchElementList.add(new String[]{ex.getMessage()});
noSuchElementList.add(hoRec);
}
completedUnitOfWork();
}
if (!noSuchElementList.isEmpty()) {
StringBuilder sb = new StringBuilder();
for (String[] item : noSuchElementList) {
for (String field : item) {
sb.append(field);
sb.append("|");
}
sb.append("\n");
}
LOG.error("Continuing after import failed with no such element exception for record count: " + noSuchElementList.size()
+ "\n\n" + sb.toString());
}
return null;
} finally {
this.writeSemaphore.release();
Get.activeTasks().remove(this);
}
}
protected void buildConcept(UUID conceptUuid, String conceptName, int stamp, int legacyStamp, int inactiveLegacyStamp, int[] parentConceptNids, String[] hoRec) throws IllegalStateException, NoSuchElementException {
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
int conceptNid = Get.nidForUuids(conceptUuid);
ConceptAssertion[] parents = new ConceptAssertion[parentConceptNids.length];
for (int i = 0; i < parentConceptNids.length; i++) {
parents[i] = eb.conceptAssertion(parentConceptNids[i]);
}
eb.necessarySet(eb.and(parents));
if (!hoRec[SNOMEDCT].isEmpty()) {
if (hoRec[INEXACT_SNOMED_1].isEmpty()
&& hoRec[SNOMED_SIB_CHILD_1].isEmpty()
&& !hoRec[SNOMEDCT].contains(".")) {
UUID snomedUuid = UuidT3Generator.fromSNOMED(hoRec[SNOMEDCT]);
if (Get.identifierService().hasUuid(snomedUuid)) {
int snomedNid = Get.nidForUuids(snomedUuid);
SemanticBuilder semanticBuilder = Get.semanticBuilderService().getComponentSemanticBuilder(snomedNid, conceptNid, HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addItemsIfNew(hoRec, ICD10PCS, snomedNid, HDX_ICD10PCS_MAP, stamp);
addItemsIfNew(hoRec, ICF, snomedNid, HDX_ICF_MAP, stamp);
addItemsIfNew(hoRec, ICPC, snomedNid, HDX_ICPC_MAP, stamp);
addItemsIfNew(hoRec, MDC, snomedNid, HDX_MDC_MAP, stamp);
addItemsIfNew(hoRec, MESH, snomedNid, HDX_MESH_MAP, stamp);
addItemsIfNew(hoRec, RADLEX, snomedNid, HDX_RADLEX_MAP, stamp);
addItemsIfNew(hoRec, RXCUI, snomedNid, HDX_RXCUI_MAP, stamp);
addItemsIfNew(hoRec, CCS_SINGLE_CAT_ICD, snomedNid, HDX_CCS_SINGLE_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_1_ICD, snomedNid, HDX_CCS_MULTI_1_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_2_ICD, snomedNid, HDX_CCS_MULTI_2_ICD_MAP, stamp);
addDescriptionsIfNew(hoRec, snomedNid, stamp);
} else {
LOG.info("No concept for: |" + hoRec[SNOMEDCT] + "|" + snomedUuid.toString());
}
} else if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
LOG.error("SNOMED and inexact populated: " + Arrays.asList(hoRec));
}
} else if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
// '22325002' 'Child' 8510008' 'Child'
// '16737003' 'Sibling'
// '216757002' 'Parent' - Remember to process a parent relationship like a sibling one
switch (hoRec[SNOMED_SIB_CHILD_1]) {
case "Child":
addChild(conceptName, stamp, hoRec);
break;
case "Sibling":
case "Parent":
addSibling(conceptName, stamp, hoRec);
break;
}
}
ConceptBuilderService builderService = Get.conceptBuilderService();
String[] parentNames = hoRec[PARENT_NAMES].split("; ");
String[] abbreviations = hoRec[ABBREVIATIONS].split("; ");
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HO " + parentNames[0],
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
for (int parentNid : parentConceptNids) {
builder.addComponentSemantic(new ConceptProxy(parentNid), HDX_LEGACY_IS_A);
}
addMaps(hoRec, builder);
// white-coated tongue; white coating on tongue; tongue with white coating
for (int i = 0; i < abbreviations.length; i++) {
if (!abbreviations[i].isEmpty()) {
builder.addDescription(abbreviations[i], MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR);
}
}
if (!hoRec[REFID].isEmpty()) {
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
}
if (!hoRec[MAPPED_TO_ALLERGEN].isEmpty()) {
builder.addStringSemantic(hoRec[MAPPED_TO_ALLERGEN], ALLERGEN_ASSEMBLAGE);
}
if (!hoRec[IS_DIAGNOSIS].isEmpty()) {
builder.addStringSemantic(hoRec[IS_DIAGNOSIS], IS_DIAGNOSIS_ASSEMBLAGE);
}
if (!hoRec[IS_CATEGORY].isEmpty()) {
builder.addStringSemantic(hoRec[IS_CATEGORY], IS_CATEGORY_ASSEMBLAGE);
}
if (!hoRec[SNOMEDCT].isEmpty()) {
UUID snomedUuid = UuidT3Generator.fromSNOMED(hoRec[SNOMEDCT]);
if (Get.identifierService().hasUuid(snomedUuid)) {
int snomedNid = Get.nidForUuids(snomedUuid);
builder.addStringSemantic(hoRec[SNOMEDCT], SNOMED_MAP_ASSEMBLAGE);
// Add reverse semantic
addReverseSemantic(hoRec, conceptNid, snomedNid, stamp);
} else {
throw new NoSuchElementException("No identifier for: " + hoRec[SNOMEDCT]);
}
}
if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
builder.addStringSemantic(hoRec[INEXACT_SNOMED_1], INEXACT_SNOMED_ASSEMBLAGE);
}
if (!hoRec[SNOMED_SIB_CHILD_1].isEmpty()) {
builder.addStringSemantic(hoRec[SNOMED_SIB_CHILD_1], SNOMED_SIB_CHILD_ASSEMBLAGE);
}
if (!hoRec[INEXACT_SNOMED_2].isEmpty()) {
builder.addStringSemantic(hoRec[INEXACT_SNOMED_2], INEXACT_SNOMED_ASSEMBLAGE);
}
if (!hoRec[SNOMED_SIB_CHILD_2].isEmpty()) {
builder.addStringSemantic(hoRec[SNOMED_SIB_CHILD_2], SNOMED_SIB_CHILD_ASSEMBLAGE);
}
if (!hoRec[INEXACT_SNOMED_3].isEmpty()) {
builder.addStringSemantic(hoRec[INEXACT_SNOMED_3], INEXACT_SNOMED_ASSEMBLAGE);
}
if (!hoRec[SNOMED_SIB_CHILD_3].isEmpty()) {
builder.addStringSemantic(hoRec[SNOMED_SIB_CHILD_3], SNOMED_SIB_CHILD_ASSEMBLAGE);
}
if (!hoRec[DEPRECATED].isEmpty() && Boolean.parseBoolean(hoRec[DEPRECATED])) {
buildAndIndex(builder, inactiveLegacyStamp, hoRec);
} else {
buildAndIndex(builder, legacyStamp, hoRec);
}
}
private void addReverseSemantic(String[] hoRec, int legacyHdxNid, int solorNid, int stamp) throws NoSuchElementException, IllegalStateException {
int assemblageConceptNid = HDX_ENTITY_ASSEMBLAGE.getNid();
//int componentNid,
SemanticBuilder semanticBuilder = Get.semanticBuilderService().getComponentSemanticBuilder(legacyHdxNid, solorNid, assemblageConceptNid);
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
}
protected void buildAndIndex(IdentifiedComponentBuilder builder, int stamp, String[] hoRec) throws IllegalStateException {
List<Chronology> builtObjects = new ArrayList<>();
builder.build(stamp, builtObjects);
for (Chronology chronology : builtObjects) {
Get.identifiedObjectService().putChronologyData(chronology);
if (chronology.getVersionType() == VersionType.LOGIC_GRAPH) {
try {
Get.taxonomyService().updateTaxonomy((SemanticChronology) chronology);
} catch (RuntimeException e) {
LOG.error("Processing " + Arrays.toString(hoRec), e);
}
}
index(chronology);
}
}
private String[] clean(String[] hoRec) {
for (int i = 0; i < hoRec.length; i++) {
hoRec[i] = hoRec[i].trim();
if (hoRec[i].startsWith("'")) {
hoRec[i] = hoRec[i].substring(1);
}
if (hoRec[i].endsWith("'")) {
hoRec[i] = hoRec[i].substring(0, hoRec[i].length() - 1);
}
if (hoRec[i].startsWith("\"")) {
hoRec[i] = hoRec[i].substring(1);
}
if (hoRec[i].endsWith("\"")) {
hoRec[i] = hoRec[i].substring(0, hoRec[i].length() - 1);
}
}
return hoRec;
}
private void addChild(String conceptName, int stamp, String[] hoRec) {
List<Integer> parentConceptNidList = new ArrayList<>();
if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
parentConceptNidList.add(getNidForSCTID(hoRec[INEXACT_SNOMED_1]));
}
if (!hoRec[INEXACT_SNOMED_2].isEmpty()) {
parentConceptNidList.add(getNidForSCTID(hoRec[INEXACT_SNOMED_2]));
}
if (!hoRec[INEXACT_SNOMED_3].isEmpty()) {
parentConceptNidList.add(getNidForSCTID(hoRec[INEXACT_SNOMED_3]));
}
int[] parentConceptNids = new int[parentConceptNidList.size()];
for (int i = 0; i < parentConceptNids.length; i++) {
parentConceptNids[i] = parentConceptNidList.get(i);
}
HdxConceptHash hdxConceptHash = new HdxConceptHash(conceptName, parentConceptNids, hoRec[REFID]);
UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
int conceptNid = Get.nidWithAssignment(conceptUuid);
if (this.importer.getHdxSolorConcepts().containsKey(hdxConceptHash)) {
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), this.importer.getHdxSolorConcepts().get(hdxConceptHash).getNid(), stamp);
//builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
addItemsIfNew(hoRec, ICD10PCS, conceptNid, HDX_ICD10PCS_MAP, stamp);
addItemsIfNew(hoRec, ICF, conceptNid, HDX_ICF_MAP, stamp);
addItemsIfNew(hoRec, ICPC, conceptNid, HDX_ICPC_MAP, stamp);
addItemsIfNew(hoRec, MDC, conceptNid, HDX_MDC_MAP, stamp);
addItemsIfNew(hoRec, MESH, conceptNid, HDX_MESH_MAP, stamp);
addItemsIfNew(hoRec, RADLEX, conceptNid, HDX_RADLEX_MAP, stamp);
addItemsIfNew(hoRec, RXCUI, conceptNid, HDX_RXCUI_MAP, stamp);
addItemsIfNew(hoRec, CCS_SINGLE_CAT_ICD, conceptNid, HDX_CCS_SINGLE_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_1_ICD, conceptNid, HDX_CCS_MULTI_1_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_2_ICD, conceptNid, HDX_CCS_MULTI_2_ICD_MAP, stamp);
} else {
this.importer.getHdxSolorConcepts().put(hdxConceptHash, new ConceptProxy(conceptName, conceptUuid));
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
ConceptAssertion[] parents = new ConceptAssertion[parentConceptNidList.size()];
for (int i = 0; i < parentConceptNidList.size(); i++) {
parents[i] = eb.conceptAssertion(parentConceptNidList.get(i));
}
eb.necessarySet(eb.and(parents));
ConceptBuilderService builderService = Get.conceptBuilderService();
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HDX",
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
});
addMaps(hoRec, builder);
buildAndIndex(builder, stamp, hoRec);
//
if (!Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
SemanticBuilder semanticBuilder = Get.semanticBuilderService().getComponentSemanticBuilder(conceptNid, refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
}
}
}
private int getNidForSCTID(String sctid) {
UUID snomedUuid = UuidT3Generator.fromSNOMED(sctid);
return Get.nidForUuids(snomedUuid);
}
private void addAllergy(String conceptName, int stamp, String[] hoRec) {
UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
// Parent is 419199007 |Allergy to substance (finding)|
// Has realization → Allergic process
// Causative agent → Substance
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
eb.sufficientSet(eb.and(eb.conceptAssertion(allergyToSubstance), eb.someRole(MetaData.ROLE_GROUP____SOLOR,
eb.and(eb.someRole(after, eb.conceptAssertion(allergicSensitization)),
eb.someRole(causativeAgent, eb.conceptAssertion(getNidForSCTID(hoRec[SNOMEDCT])))))));
ConceptBuilderService builderService = Get.conceptBuilderService();
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HDX",
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
});
int conceptNid = builder.getNid();
buildAndIndex(builder, stamp, hoRec);
//
SemanticBuilder semanticBuilder = Get.semanticBuilderService()
.getComponentSemanticBuilder(refidToSolorNid(hoRec[REFID]),
refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
}
private void addSibling(String conceptName, int stamp, String[] hoRec) {
UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
int[] parentConceptNids = new int[]{getNidForSCTID(hoRec[INEXACT_SNOMED_1])};
HdxConceptHash hdxConceptHash = new HdxConceptHash(conceptName, parentConceptNids, hoRec[REFID]);
if (this.importer.getHdxSolorConcepts().containsKey(hdxConceptHash)) {
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), this.importer.getHdxSolorConcepts().get(hdxConceptHash).getNid(), stamp);
//builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
int conceptNid = Get.nidForUuids(conceptUuid);
addItemsIfNew(hoRec, ICD10PCS, conceptNid, HDX_ICD10PCS_MAP, stamp);
addItemsIfNew(hoRec, ICF, conceptNid, HDX_ICF_MAP, stamp);
addItemsIfNew(hoRec, ICPC, conceptNid, HDX_ICPC_MAP, stamp);
addItemsIfNew(hoRec, MDC, conceptNid, HDX_MDC_MAP, stamp);
addItemsIfNew(hoRec, MESH, conceptNid, HDX_MESH_MAP, stamp);
addItemsIfNew(hoRec, RADLEX, conceptNid, HDX_RADLEX_MAP, stamp);
addItemsIfNew(hoRec, RXCUI, conceptNid, HDX_RXCUI_MAP, stamp);
addItemsIfNew(hoRec, CCS_SINGLE_CAT_ICD, conceptNid, HDX_CCS_SINGLE_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_1_ICD, conceptNid, HDX_CCS_MULTI_1_ICD_MAP, stamp);
addItemsIfNew(hoRec, CCS_MULTI_LEVEL_2_ICD, conceptNid, HDX_CCS_MULTI_2_ICD_MAP, stamp);
} else {
this.importer.getHdxSolorConcepts().put(hdxConceptHash, new ConceptProxy(conceptName, conceptUuid));
int[] parentNids = this.importer.getTaxonomy().getTaxonomyParentConceptNids(parentConceptNids[0]);
ConceptAssertion[] parents = new ConceptAssertion[parentNids.length];
LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
for (int i = 0; i < parentNids.length; i++) {
parents[i] = eb.conceptAssertion(parentNids[i]);
}
eb.necessarySet(eb.and(parents));
ConceptBuilderService builderService = Get.conceptBuilderService();
ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
"HDX",
eb.build(),
TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
builder.setPrimordialUuid(conceptUuid);
builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
});
int conceptNid = builder.getNid();
addMaps(hoRec, builder);
buildAndIndex(builder, stamp, hoRec);
//
SemanticBuilder semanticBuilder = Get.semanticBuilderService()
.getComponentSemanticBuilder(refidToSolorNid(hoRec[REFID]),
refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
List<Chronology> builtObjects = new ArrayList<>();
semanticBuilder.build(stamp, builtObjects);
buildAndIndex(semanticBuilder, stamp, hoRec);
addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
}
}
private void addMaps(String[] hoRec, ConceptBuilder builder) {
if (!hoRec[ICD10CM].isEmpty()) {
String[] dataArray = hoRec[ICD10CM].split("; ");
for (String data : dataArray) {
builder.addStringSemantic(data, HDX_ICD10CM_MAP);
}
}
addItems(hoRec, ICD10PCS, builder, HDX_ICD10PCS_MAP);
addItems(hoRec, ICF, builder, HDX_ICF_MAP);
addItems(hoRec, ICPC, builder, HDX_ICPC_MAP);
addItems(hoRec, MDC, builder, HDX_MDC_MAP);
addItems(hoRec, MESH, builder, HDX_MESH_MAP);
addItems(hoRec, RADLEX, builder, HDX_RADLEX_MAP);
addItems(hoRec, RXCUI, builder, HDX_RXCUI_MAP);
addItems(hoRec, CCS_SINGLE_CAT_ICD, builder, HDX_CCS_SINGLE_ICD_MAP);
addItems(hoRec, CCS_MULTI_LEVEL_1_ICD, builder, HDX_CCS_MULTI_1_ICD_MAP);
addItems(hoRec, CCS_MULTI_LEVEL_2_ICD, builder, HDX_CCS_MULTI_2_ICD_MAP);
}
private void addItems(String[] hoRec, int index, ConceptBuilder builder, ConceptSpecification assemblage) {
if (!hoRec[index].isEmpty()) {
String[] dataArray = hoRec[index].split("; ");
for (String data : dataArray) {
builder.addStringSemantic(data, assemblage);
}
}
}
private void addItemsIfNew(String[] hoRec, int index, int conceptNid, ConceptSpecification assemblage, int stamp) {
HashSet<String> existing = new HashSet();
Get.assemblageService().getSemanticChronologyStreamForComponentFromAssemblage(conceptNid, assemblage.getNid())
.forEach(semanticChronology -> {
for (Version v : semanticChronology.getVersionList()) {
existing.add(((StringVersion) v).getString());
}
});
if (!hoRec[index].isEmpty()) {
String[] dataArray = hoRec[index].split("; ");
for (String data : dataArray) {
if (!existing.contains(data)) {
SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getStringSemanticBuilder(data, conceptNid, assemblage.getNid());
buildAndIndex(b, stamp, hoRec);
}
}
}
}
private void addDescriptionsIfNew(String[] hoRec, int snomedNid, int stamp) {
HashSet<String> existing = new HashSet();
Get.assemblageService().getSemanticChronologyStreamForComponentFromAssemblage(snomedNid, TermAux.ENGLISH_LANGUAGE.getNid())
.forEach(semanticChronology -> {
for (Version v : semanticChronology.getVersionList()) {
existing.add(((DescriptionVersion) v).getText());
}
});
String[] abbreviations = hoRec[ABBREVIATIONS].split("; ");
for (int i = 0; i < abbreviations.length; i++) {
if (!abbreviations[i].isEmpty() && !existing.contains(abbreviations[i])) {
SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
abbreviations[i], snomedNid);
b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
buildAndIndex(b, stamp, hoRec);
}
}
if (!existing.contains(hoRec[NAME])) {
SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
hoRec[NAME], snomedNid);
b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
buildAndIndex(b, stamp, hoRec);
}
}
}
| Work on allergy concept representation for HO import.
| solor/direct-import/src/main/java/sh/isaac/solor/direct/ho/HoWriter.java | Work on allergy concept representation for HO import. | <ide><path>olor/direct-import/src/main/java/sh/isaac/solor/direct/ho/HoWriter.java
<ide> builder.addStringSemantic(hoRec[IS_CATEGORY], IS_CATEGORY_ASSEMBLAGE);
<ide> }
<ide> if (!hoRec[SNOMEDCT].isEmpty()) {
<del> UUID snomedUuid = UuidT3Generator.fromSNOMED(hoRec[SNOMEDCT]);
<del> if (Get.identifierService().hasUuid(snomedUuid)) {
<del> int snomedNid = Get.nidForUuids(snomedUuid);
<del> builder.addStringSemantic(hoRec[SNOMEDCT], SNOMED_MAP_ASSEMBLAGE);
<del> // Add reverse semantic
<del> addReverseSemantic(hoRec, conceptNid, snomedNid, stamp);
<add> if (!hoRec[MAPPED_TO_ALLERGEN].isEmpty() && Boolean.parseBoolean(hoRec[MAPPED_TO_ALLERGEN])) {
<add> // The SNOMED record is not the correct record, since it is mapped to an allergen, and
<add> // will thus have an allegy concept created for it.
<ide> } else {
<del> throw new NoSuchElementException("No identifier for: " + hoRec[SNOMEDCT]);
<add> UUID snomedUuid = UuidT3Generator.fromSNOMED(hoRec[SNOMEDCT]);
<add> if (Get.identifierService().hasUuid(snomedUuid)) {
<add> int snomedNid = Get.nidForUuids(snomedUuid);
<add> builder.addStringSemantic(hoRec[SNOMEDCT], SNOMED_MAP_ASSEMBLAGE);
<add> // Add reverse semantic
<add> addReverseSemantic(hoRec, conceptNid, snomedNid, stamp);
<add> } else {
<add> throw new NoSuchElementException("No identifier for: " + hoRec[SNOMEDCT]);
<add> }
<ide> }
<ide> }
<ide> if (!hoRec[INEXACT_SNOMED_1].isEmpty()) {
<ide> } else {
<ide> buildAndIndex(builder, legacyStamp, hoRec);
<ide> }
<del>
<add>
<ide> }
<ide>
<ide> private void addReverseSemantic(String[] hoRec, int legacyHdxNid, int solorNid, int stamp) throws NoSuchElementException, IllegalStateException {
<ide> builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
<ide> descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
<ide> });
<del>
<add>
<ide> addMaps(hoRec, builder);
<ide> buildAndIndex(builder, stamp, hoRec);
<ide> //
<ide> return Get.nidForUuids(snomedUuid);
<ide> }
<ide>
<add> HashMap<String, Integer> snomedAllergyMap = new HashMap<>();
<add>
<ide> private void addAllergy(String conceptName, int stamp, String[] hoRec) {
<del> UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
<del>
<del> // Parent is 419199007 |Allergy to substance (finding)|
<del> // Has realization → Allergic process
<del> // Causative agent → Substance
<del> LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
<del> eb.sufficientSet(eb.and(eb.conceptAssertion(allergyToSubstance), eb.someRole(MetaData.ROLE_GROUP____SOLOR,
<del> eb.and(eb.someRole(after, eb.conceptAssertion(allergicSensitization)),
<del> eb.someRole(causativeAgent, eb.conceptAssertion(getNidForSCTID(hoRec[SNOMEDCT])))))));
<del>
<del> ConceptBuilderService builderService = Get.conceptBuilderService();
<del> ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
<del> "HDX",
<del> eb.build(),
<del> TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
<del> builder.setPrimordialUuid(conceptUuid);
<del> builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
<add> // see if allergy already added...
<add> if (snomedAllergyMap.containsKey(hoRec[SNOMEDCT])) {
<add> // already added, add info to existing concept.
<add> int existingAllergyNid = snomedAllergyMap.get(hoRec[SNOMEDCT]);
<add> addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), existingAllergyNid, stamp);
<add> buildAndIndex(Get.semanticBuilderService().getStringSemanticBuilder(hoRec[REFID], existingAllergyNid, REFID_ASSEMBLAGE.getNid()), stamp, hoRec);
<add> } else {
<add>
<add> UUID conceptUuid = refidToSolorUuid(hoRec[REFID]);
<add>
<add> // Parent is 419199007 |Allergy to substance (finding)|
<add> // Has realization → Allergic process
<add> // Causative agent → Substance
<add> LogicalExpressionBuilder eb = Get.logicalExpressionBuilderService().getLogicalExpressionBuilder();
<add> eb.sufficientSet(eb.and(eb.conceptAssertion(allergyToSubstance), eb.someRole(MetaData.ROLE_GROUP____SOLOR,
<add> eb.and(eb.someRole(after, eb.conceptAssertion(allergicSensitization)),
<add> eb.someRole(causativeAgent, eb.conceptAssertion(getNidForSCTID(hoRec[SNOMEDCT])))))));
<add>
<add> ConceptBuilderService builderService = Get.conceptBuilderService();
<add> ConceptBuilder builder = builderService.getDefaultConceptBuilder(conceptName,
<add> "HDX",
<add> eb.build(),
<add> TermAux.SOLOR_CONCEPT_ASSEMBLAGE.getNid());
<add> builder.setPrimordialUuid(conceptUuid);
<add> builder.addStringSemantic(hoRec[REFID], REFID_ASSEMBLAGE);
<ide> builder.addAssemblageMembership(HUMAN_DX_SOLOR_CONCEPT_ASSEMBLAGE);
<ide> builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
<ide> descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
<ide> });
<del>
<del> int conceptNid = builder.getNid();
<del> buildAndIndex(builder, stamp, hoRec);
<del> //
<del> SemanticBuilder semanticBuilder = Get.semanticBuilderService()
<del> .getComponentSemanticBuilder(refidToSolorNid(hoRec[REFID]),
<del> refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
<del> List<Chronology> builtObjects = new ArrayList<>();
<del> semanticBuilder.build(stamp, builtObjects);
<del> buildAndIndex(semanticBuilder, stamp, hoRec);
<del> addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
<add>
<add> int conceptNid = builder.getNid();
<add> buildAndIndex(builder, stamp, hoRec);
<add> snomedAllergyMap.put(hoRec[SNOMEDCT], conceptNid);
<add> //
<add> SemanticBuilder semanticBuilder = Get.semanticBuilderService()
<add> .getComponentSemanticBuilder(refidToSolorNid(hoRec[REFID]),
<add> refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
<add> List<Chronology> builtObjects = new ArrayList<>();
<add> semanticBuilder.build(stamp, builtObjects);
<add> buildAndIndex(semanticBuilder, stamp, hoRec);
<add> addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
<add> }
<add>
<ide> }
<ide>
<ide> private void addSibling(String conceptName, int stamp, String[] hoRec) {
<ide> builder.getDescriptionBuilders().forEach(descriptionBuilder -> {
<ide> descriptionBuilder.addAssemblageMembership(HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE);
<ide> });
<del>
<add>
<ide> int conceptNid = builder.getNid();
<ide> addMaps(hoRec, builder);
<ide> buildAndIndex(builder, stamp, hoRec);
<ide> refidToNid(hoRec[REFID]), HDX_SOLOR_EQUIVALENCE_ASSEMBLAGE.getNid());
<ide> List<Chronology> builtObjects = new ArrayList<>();
<ide> semanticBuilder.build(stamp, builtObjects);
<del>
<add>
<ide> buildAndIndex(semanticBuilder, stamp, hoRec);
<ide> addReverseSemantic(hoRec, refidToNid(hoRec[REFID]), conceptNid, stamp);
<ide> }
<ide> }
<ide>
<ide> private void addDescriptionsIfNew(String[] hoRec, int snomedNid, int stamp) {
<add> if (Boolean.valueOf(hoRec[MAPPED_TO_ALLERGEN])) {
<add> return;
<add> }
<ide> HashSet<String> existing = new HashSet();
<ide> Get.assemblageService().getSemanticChronologyStreamForComponentFromAssemblage(snomedNid, TermAux.ENGLISH_LANGUAGE.getNid())
<ide> .forEach(semanticChronology -> {
<ide> existing.add(((DescriptionVersion) v).getText());
<ide> }
<ide> });
<del>
<add>
<ide> String[] abbreviations = hoRec[ABBREVIATIONS].split("; ");
<ide> for (int i = 0; i < abbreviations.length; i++) {
<ide> if (!abbreviations[i].isEmpty() && !existing.contains(abbreviations[i])) {
<ide> SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
<ide> MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
<del> abbreviations[i], snomedNid);
<add> abbreviations[i], snomedNid);
<ide> b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
<ide> buildAndIndex(b, stamp, hoRec);
<ide> }
<ide> }
<del> if (!existing.contains(hoRec[NAME])) {
<del> SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
<del> MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
<del> hoRec[NAME], snomedNid);
<del> b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
<del> buildAndIndex(b, stamp, hoRec);
<del> }
<add> if (!existing.contains(hoRec[NAME])) {
<add> SemanticBuilder<? extends SemanticChronology> b = Get.semanticBuilderService().getDescriptionBuilder(
<add> MetaData.DESCRIPTION_NOT_CASE_SENSITIVE____SOLOR.getNid(), MetaData.ENGLISH_LANGUAGE____SOLOR.getNid(), MetaData.REGULAR_NAME_DESCRIPTION_TYPE____SOLOR.getNid(),
<add> hoRec[NAME], snomedNid);
<add> b.addSemantic(Get.semanticBuilderService().getMembershipSemanticBuilder(b.getNid(), HUMAN_DX_SOLOR_DESCRIPTION_ASSEMBLAGE.getNid()));
<add> buildAndIndex(b, stamp, hoRec);
<add> }
<ide>
<ide> }
<ide> |
|
Java | agpl-3.0 | 0403ba46cfc1110a529aa874aef95c8a6862247a | 0 | istemi-bahceci/cbioportal,HectorWon/cbioportal,xmao/cbioportal,zhx828/cbioportal,holtgrewe/cbioportal,zhx828/cbioportal,leedonghn4/cbio-portal-webgl,j-hudecek/cbioportal,zhx828/cbioportal,d3b-center/pedcbioportal,shrumit/cbioportal-gsoc-final,yichaoS/cbioportal,inodb/cbioportal,n1zea144/cbioportal,adamabeshouse/cbioportal,d3b-center/pedcbioportal,HectorWon/cbioportal,onursumer/cbioportal,inodb/cbioportal,pughlab/cbioportal,gsun83/cbioportal,leedonghn4/cbioportal,gsun83/cbioportal,fcriscuo/cbioportal,adamabeshouse/cbioportal,IntersectAustralia/cbioportal,pughlab/cbioportal,bihealth/cbioportal,leedonghn4/cbioportal,zhx828/cbioportal,fcriscuo/cbioportal,sheridancbio/cbioportal,yichaoS/cbioportal,leedonghn4/cbio-portal-webgl,gsun83/cbioportal,zheins/cbioportal,cBioPortal/cbioportal,sheridancbio/cbioportal,IntersectAustralia/cbioportal,yichaoS/cbioportal,adamabeshouse/cbioportal,istemi-bahceci/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,inodb/cbioportal,onursumer/cbioportal,istemi-bahceci/cbioportal,angelicaochoa/cbioportal,holtgrewe/cbioportal,shrumit/cbioportal-gsoc-final,j-hudecek/cbioportal,yichaoS/cbioportal,mandawilson/cbioportal,jjgao/cbioportal,kalletlak/cbioportal,d3b-center/pedcbioportal,kalletlak/cbioportal,j-hudecek/cbioportal,cBioPortal/cbioportal,yichaoS/cbioportal,mandawilson/cbioportal,holtgrewe/cbioportal,kalletlak/cbioportal,bengusty/cbioportal,IntersectAustralia/cbioportal,HectorWon/cbioportal,mandawilson/cbioportal,d3b-center/pedcbioportal,yichaoS/cbioportal,kalletlak/cbioportal,leedonghn4/cbioportal,angelicaochoa/cbioportal,xmao/cbioportal,mandawilson/cbioportal,istemi-bahceci/cbioportal,inodb/cbioportal,pughlab/cbioportal,fcriscuo/cbioportal,angelicaochoa/cbioportal,angelicaochoa/cbioportal,bihealth/cbioportal,zheins/cbioportal,istemi-bahceci/cbioportal,jjgao/cbioportal,sheridancbio/cbioportal,sheridancbio/cbioportal,n1zea144/cbioportal,fcriscuo/cbioportal,holtgrewe/cbioportal,n1zea144/cbioportal,leedonghn4/cbio-portal-webgl,HectorWon/cbioportal,sheridancbio/cbioportal,mandawilson/cbioportal,angelicaochoa/cbioportal,onursumer/cbioportal,pughlab/cbioportal,zhx828/cbioportal,leedonghn4/cbio-portal-webgl,bihealth/cbioportal,bengusty/cbioportal,IntersectAustralia/cbioportal,adamabeshouse/cbioportal,xmao/cbioportal,onursumer/cbioportal,adamabeshouse/cbioportal,j-hudecek/cbioportal,d3b-center/pedcbioportal,zheins/cbioportal,IntersectAustralia/cbioportal,angelicaochoa/cbioportal,n1zea144/cbioportal,n1zea144/cbioportal,cBioPortal/cbioportal,kalletlak/cbioportal,mandawilson/cbioportal,cBioPortal/cbioportal,j-hudecek/cbioportal,d3b-center/pedcbioportal,yichaoS/cbioportal,fcriscuo/cbioportal,xmao/cbioportal,bengusty/cbioportal,leedonghn4/cbioportal,zheins/cbioportal,kalletlak/cbioportal,onursumer/cbioportal,jjgao/cbioportal,bengusty/cbioportal,holtgrewe/cbioportal,n1zea144/cbioportal,jjgao/cbioportal,jjgao/cbioportal,adamabeshouse/cbioportal,mandawilson/cbioportal,shrumit/cbioportal-gsoc-final,gsun83/cbioportal,sheridancbio/cbioportal,leedonghn4/cbioportal,bihealth/cbioportal,n1zea144/cbioportal,zhx828/cbioportal,gsun83/cbioportal,xmao/cbioportal,jjgao/cbioportal,IntersectAustralia/cbioportal,onursumer/cbioportal,jjgao/cbioportal,bihealth/cbioportal,d3b-center/pedcbioportal,pughlab/cbioportal,angelicaochoa/cbioportal,HectorWon/cbioportal,leedonghn4/cbioportal,bihealth/cbioportal,shrumit/cbioportal-gsoc-final,inodb/cbioportal,leedonghn4/cbio-portal-webgl,inodb/cbioportal,pughlab/cbioportal,holtgrewe/cbioportal,gsun83/cbioportal,istemi-bahceci/cbioportal,zheins/cbioportal,cBioPortal/cbioportal,zhx828/cbioportal,IntersectAustralia/cbioportal,bengusty/cbioportal,adamabeshouse/cbioportal,j-hudecek/cbioportal,HectorWon/cbioportal,bihealth/cbioportal,zheins/cbioportal,shrumit/cbioportal-gsoc-final,pughlab/cbioportal,cBioPortal/cbioportal,shrumit/cbioportal-gsoc-final,bengusty/cbioportal,fcriscuo/cbioportal,gsun83/cbioportal,leedonghn4/cbio-portal-webgl,kalletlak/cbioportal,xmao/cbioportal |
package org.mskcc.portal.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.mskcc.portal.network.Edge;
import org.owasp.validator.html.PolicyException;
import org.mskcc.portal.model.ProfileData;
import org.mskcc.portal.model.ProfileDataSummary;
import org.mskcc.portal.network.Network;
import org.mskcc.portal.network.NetworkIO;
import org.mskcc.portal.network.Node;
import org.mskcc.portal.oncoPrintSpecLanguage.GeneticTypeLevel;
import org.mskcc.portal.oncoPrintSpecLanguage.OncoPrintSpecification;
import org.mskcc.portal.oncoPrintSpecLanguage.ParserOutput;
import org.mskcc.portal.remote.GetCaseSets;
import org.mskcc.portal.remote.GetGeneticProfiles;
import org.mskcc.portal.remote.GetPathwayCommonsNetwork;
import org.mskcc.portal.util.GeneticProfileUtil;
import org.mskcc.portal.util.OncoPrintSpecificationDriver;
import org.mskcc.portal.util.ProfileMerger;
import org.mskcc.portal.util.XDebug;
import org.mskcc.cgds.model.CaseList;
import org.mskcc.cgds.model.GeneticProfile;
import org.mskcc.cgds.model.GeneticAlterationType;
import org.mskcc.cgds.dao.DaoException;
import org.mskcc.cgds.web_api.GetProfileData;
/**
* Retrieving
* @author jj
*/
public class NetworkServlet extends HttpServlet {
private static final String HGNC = "HGNC";
private static final String NODE_ATTR_IN_QUERY = "IN_QUERY";
private static final String NODE_ATTR_IN_PORTAL = "IN_PORTAL";
private static final String NODE_ATTR_PERCENT_ALTERED = "PERCENT_ALTERED";
private static final String NODE_ATTR_PERCENT_MUTATED = "PERCENT_MUTATED";
private static final String NODE_ATTR_PERCENT_CNA_AMPLIFIED = "PERCENT_CNA_AMPLIFIED";
private static final String NODE_ATTR_PERCENT_CNA_GAINED = "PERCENT_CNA_GAINED";
private static final String NODE_ATTR_PERCENT_CNA_HOM_DEL = "PERCENT_CNA_HOMOZYGOUSLY_DELETED";
private static final String NODE_ATTR_PERCENT_CNA_HET_LOSS = "PERCENT_CNA_HEMIZYGOUSLY_DELETED";
private static final String NODE_ATTR_PERCENT_MRNA_WAY_UP = "PERCENT_MRNA_WAY_UP";
private static final String NODE_ATTR_PERCENT_MRNA_WAY_DOWN = "PERCENT_MRNA_WAY_DOWN";
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
this.doPost(req, res);
}
/**
* Processes Post Request.
*
* @param req HttpServletRequest Object.
* @param res HttpServletResponse Object.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
@Override
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/xml");
try {
XDebug xdebug = new XDebug( req );
String xd = req.getParameter("xdebug");
ServletXssUtil xssUtil;
try {
xssUtil = ServletXssUtil.getInstance();
} catch (PolicyException e) {
throw new ServletException (e);
}
if (xd!=null && xd.equals("1")) {
xdebug.logMsg(this, "<a href=\""+getNetworkServletUrl(req, xssUtil)+"\" target=\"_blank\">NetworkServlet URL</a>");
}
// Get User Defined Gene List
String geneListStr = xssUtil.getCleanInput(req, QueryBuilder.GENE_LIST);
Set<String> queryGenes = new HashSet<String>(Arrays.asList(geneListStr.toUpperCase().split(" ")));
//String geneticProfileIdSetStr = xssUtil.getCleanInput (req, QueryBuilder.GENETIC_PROFILE_IDS);
Network network;
try {
xdebug.startTimer();
network = GetPathwayCommonsNetwork.getNetwork(queryGenes, xdebug);
xdebug.stopTimer();
xdebug.logMsg(this, "Successfully retrieved networks from cPath2: took "+xdebug.getTimeElapsed()+"ms");
} catch (Exception e) {
xdebug.logMsg(this, "Failed retrieving networks from cPath2\n"+e.getMessage());
network = new Network(); // send an empty network instead
}
// remove small molecules
xdebug.startTimer();
network.filter(new Network.Filter() {
public boolean filterNode(Node node) {
if (node == null) {
return true;
}
return !"Protein".equals(node.getType());
}
public boolean filterEdge(Edge edge) {
return filterNode(edge.getSourceNode()) || filterNode(edge.getTargetNode());
}
});
xdebug.stopTimer();
xdebug.logMsg(this, "Removed non-protein nodes: took "+xdebug.getTimeElapsed()+"ms");
if (!network.getNodes().isEmpty()) {
// add attribute is_query to indicate if a node is in query genes
// and get the list of genes in network
xdebug.logMsg(this, "Retrieving data from CGDS...");
ArrayList<String> netGenes = new ArrayList<String>();
for (Node node : network.getNodes()) {
Set<String> ngnc = node.getXref(HGNC);
boolean inQuery = false;
if (!ngnc.isEmpty()) {
String sym = ngnc.iterator().next();
inQuery = queryGenes.contains(sym);
netGenes.add(sym);
}
node.addAttribute(NODE_ATTR_IN_QUERY, Boolean.toString(inQuery));
}
// Get User Selected Genetic Profiles
xdebug.startTimer();
HashSet<String> geneticProfileIdSet = new HashSet<String>();
for (String geneticProfileIdsStr : req.getParameterValues(QueryBuilder.GENETIC_PROFILE_IDS)) {
geneticProfileIdSet.addAll(Arrays.asList(geneticProfileIdsStr.split(" ")));
}
String cancerTypeId = xssUtil.getCleanInput(req, QueryBuilder.CANCER_STUDY_ID);
xdebug.stopTimer();
xdebug.logMsg(this, "Got User Selected Genetic Profiles. Took "+xdebug.getTimeElapsed()+"ms");
// Get Genetic Profiles for Selected Cancer Type
xdebug.startTimer();
ArrayList<GeneticProfile> profileList = GetGeneticProfiles.getGeneticProfiles(cancerTypeId);
String caseIds = xssUtil.getCleanInput(req, QueryBuilder.CASE_IDS);
if (caseIds==null || caseIds.isEmpty()) {
String caseSetId = xssUtil.getCleanInput(req, QueryBuilder.CASE_SET_ID);
// Get Case Sets for Selected Cancer Type
ArrayList<CaseList> caseSets = GetCaseSets.getCaseSets(cancerTypeId);
for (CaseList cs : caseSets) {
if (cs.getStableId().equals(caseSetId)) {
caseIds = cs.getCaseListAsString();
break;
}
}
}
xdebug.stopTimer();
xdebug.logMsg(this, "Got Genetic Profiles for Selected Cancer Type. Took "+xdebug.getTimeElapsed()+"ms");
// retrieve profile data from CGDS for new genes
Set<GeneticAlterationType> alterationTypes = new HashSet();
ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
for (String profileId : geneticProfileIdSet) {
xdebug.startTimer();
GeneticProfile profile = GeneticProfileUtil.getProfile(profileId, profileList);
alterationTypes.add(profile.getGeneticAlterationType());
if( null == profile ){
continue;
}
GetProfileData remoteCall = new GetProfileData(profile, netGenes, caseIds);
ProfileData pData = remoteCall.getProfileData();
if( pData == null ){
System.err.println( "pData == null" );
}else{
if( pData.getGeneList() == null ){
System.err.println( "pData.getValidGeneList() == null" );
}
}
profileDataList.add(pData);
xdebug.stopTimer();
xdebug.logMsg(this, "Got profile data from CGDS for new genes for "+profile.getProfileName()+". Took "+xdebug.getTimeElapsed()+"ms");
}
xdebug.startTimer();
ProfileMerger merger = new ProfileMerger(profileDataList);
xdebug.stopTimer();
xdebug.logMsg(this, "Merged profiles. Took "+xdebug.getTimeElapsed()+"ms");
xdebug.startTimer();
ProfileData netMergedProfile = merger.getMergedProfile();
ArrayList<String> netGeneList = netMergedProfile.getGeneList();
double zScoreThreshold = Double.parseDouble(xssUtil.getCleanInput(req, QueryBuilder.Z_SCORE_THRESHOLD));
ParserOutput netOncoPrintSpecParserOutput = OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(
StringUtils.join(netGeneList, " "), geneticProfileIdSet,
profileList, zScoreThreshold);
OncoPrintSpecification netOncoPrintSpec = netOncoPrintSpecParserOutput.getTheOncoPrintSpecification();
ProfileDataSummary netDataSummary = new ProfileDataSummary(netMergedProfile,
netOncoPrintSpec, zScoreThreshold );
xdebug.stopTimer();
xdebug.logMsg(this, "Got profile data summary. Took "+xdebug.getTimeElapsed()+"ms");
// add attributes
xdebug.startTimer();
for (String gene : netGeneList) {
for (Node node : network.getNodesByXref(HGNC, gene.toUpperCase())) {
node.addAttribute(NODE_ATTR_PERCENT_ALTERED, netDataSummary.getPercentCasesWhereGeneIsAltered(gene));
if (alterationTypes.contains(GeneticAlterationType.MUTATION_EXTENDED) ||
alterationTypes.contains(GeneticAlterationType.MUTATION_EXTENDED)) {
node.addAttribute(NODE_ATTR_PERCENT_MUTATED, netDataSummary.getPercentCasesWhereGeneIsMutated(gene));
}
if (alterationTypes.contains(GeneticAlterationType.COPY_NUMBER_ALTERATION)) {
node.addAttribute(NODE_ATTR_PERCENT_CNA_AMPLIFIED, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.Amplified));
node.addAttribute(NODE_ATTR_PERCENT_CNA_GAINED, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.Gained));
node.addAttribute(NODE_ATTR_PERCENT_CNA_HOM_DEL, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.HomozygouslyDeleted));
node.addAttribute(NODE_ATTR_PERCENT_CNA_HET_LOSS, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.HemizygouslyDeleted));
}
if (alterationTypes.contains(GeneticAlterationType.MRNA_EXPRESSION)) {
node.addAttribute(NODE_ATTR_PERCENT_MRNA_WAY_UP, netDataSummary.getPercentCasesWhereMRNAIsUpRegulated(gene));
node.addAttribute(NODE_ATTR_PERCENT_MRNA_WAY_DOWN, netDataSummary.getPercentCasesWhereMRNAIsDownRegulated(gene));
}
}
}
xdebug.stopTimer();
xdebug.logMsg(this, "Added node attributes. Took "+xdebug.getTimeElapsed()+"ms");
}
String graphml = NetworkIO.writeNetwork2GraphML(network, new NetworkIO.NodeLabelHandler() {
// using HGNC gene symbol as label if available
public String getLabel(Node node) {
Set<String> ngnc = node.getXref(HGNC);
if (!ngnc.isEmpty()) {
return ngnc.iterator().next();
}
Set<Object> strNames = node.getAttributes().get("PARTICIPANT_NAME");
if (strNames!=null && !strNames.isEmpty()) {
String[] names = strNames.iterator().next().toString().split(";");
if (names.length>0) {
return names[0];
}
}
return node.getId();
}
});
if (xd!=null && xd.equals("1")) {
writeXDebug(xdebug,req,res);
}
PrintWriter writer = res.getWriter();
writer.write(graphml);
writer.flush();
} catch (DaoException e) {
throw new ServletException (e);
}
}
private String getNetworkServletUrl(HttpServletRequest req, ServletXssUtil xssUtil) {
String geneListStr = xssUtil.getCleanInput(req, QueryBuilder.GENE_LIST);
String geneticProfileIdsStr = xssUtil.getCleanInput(req, QueryBuilder.GENETIC_PROFILE_IDS);
String cancerTypeId = xssUtil.getCleanInput(req, QueryBuilder.CANCER_STUDY_ID);
String caseSetId = xssUtil.getCleanInput(req, QueryBuilder.CASE_SET_ID);
String zscoreThreshold = xssUtil.getCleanInput(req, QueryBuilder.Z_SCORE_THRESHOLD);
return "network.do?"+QueryBuilder.GENE_LIST+"="+geneListStr
+"&"+QueryBuilder.GENETIC_PROFILE_IDS+"="+geneticProfileIdsStr
+"&"+QueryBuilder.CANCER_STUDY_ID+"="+cancerTypeId
+"&"+QueryBuilder.CASE_SET_ID+"="+caseSetId
+"&"+QueryBuilder.Z_SCORE_THRESHOLD+"="+zscoreThreshold;
}
private void writeXDebug(XDebug xdebug, HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
PrintWriter writer = res.getWriter();
writer.write("<!--xdebug messages begin:\n");
for (Object msg : xdebug.getDebugMessages()) {
writer.write(((org.mskcc.portal.util.XDebugMessage)msg).getMessage());
writer.write("\n");
}
writer.write("xdebug messages end-->\n");
}
}
| portal/src/org/mskcc/portal/servlet/NetworkServlet.java |
package org.mskcc.portal.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.mskcc.portal.network.Edge;
import org.owasp.validator.html.PolicyException;
import org.mskcc.portal.model.ProfileData;
import org.mskcc.portal.model.ProfileDataSummary;
import org.mskcc.portal.network.Network;
import org.mskcc.portal.network.NetworkIO;
import org.mskcc.portal.network.Node;
import org.mskcc.portal.oncoPrintSpecLanguage.GeneticTypeLevel;
import org.mskcc.portal.oncoPrintSpecLanguage.OncoPrintSpecification;
import org.mskcc.portal.oncoPrintSpecLanguage.ParserOutput;
import org.mskcc.portal.remote.GetCaseSets;
import org.mskcc.portal.remote.GetGeneticProfiles;
import org.mskcc.portal.remote.GetPathwayCommonsNetwork;
import org.mskcc.portal.util.GeneticProfileUtil;
import org.mskcc.portal.util.OncoPrintSpecificationDriver;
import org.mskcc.portal.util.ProfileMerger;
import org.mskcc.portal.util.XDebug;
import org.mskcc.cgds.model.CaseList;
import org.mskcc.cgds.model.GeneticProfile;
import org.mskcc.cgds.model.GeneticAlterationType;
import org.mskcc.cgds.dao.DaoException;
import org.mskcc.cgds.web_api.GetProfileData;
/**
* Retrieving
* @author jj
*/
public class NetworkServlet extends HttpServlet {
private static final String HGNC = "HGNC";
private static final String NODE_ATTR_IN_QUERY = "IN_QUERY";
private static final String NODE_ATTR_IN_PORTAL = "IN_PORTAL";
private static final String NODE_ATTR_PERCENT_ALTERED = "PERCENT_ALTERED";
private static final String NODE_ATTR_PERCENT_MUTATED = "PERCENT_MUTATED";
private static final String NODE_ATTR_PERCENT_CNA_AMPLIFIED = "PERCENT_CNA_AMPLIFIED";
private static final String NODE_ATTR_PERCENT_CNA_GAINED = "PERCENT_CNA_GAINED";
private static final String NODE_ATTR_PERCENT_CNA_HOM_DEL = "PERCENT_CNA_HOMOZYGOUSLY_DELETED";
private static final String NODE_ATTR_PERCENT_CNA_HET_LOSS = "PERCENT_CNA_HEMIZYGOUSLY_DELETED";
private static final String NODE_ATTR_PERCENT_MRNA_WAY_UP = "PERCENT_MRNA_WAY_UP";
private static final String NODE_ATTR_PERCENT_MRNA_WAY_DOWN = "PERCENT_MRNA_WAY_DOWN";
@Override
public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
this.doPost(req, res);
}
/**
* Processes Post Request.
*
* @param req HttpServletRequest Object.
* @param res HttpServletResponse Object.
* @throws ServletException Servlet Error.
* @throws IOException IO Error.
*/
@Override
public void doPost(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/xml");
try {
XDebug xdebug = new XDebug( req );
String xd = req.getParameter("xdebug");
ServletXssUtil xssUtil;
try {
xssUtil = ServletXssUtil.getInstance();
} catch (PolicyException e) {
throw new ServletException (e);
}
if (xd!=null && xd.equals("1")) {
xdebug.logMsg(this, "<a href=\""+getNetworkServletUrl(req, xssUtil)+"\" target=\"_blank\">NetworkServlet URL</a>");
}
// Get User Defined Gene List
String geneListStr = xssUtil.getCleanInput(req, QueryBuilder.GENE_LIST);
Set<String> queryGenes = new HashSet<String>(Arrays.asList(geneListStr.toUpperCase().split(" ")));
//String geneticProfileIdSetStr = xssUtil.getCleanInput (req, QueryBuilder.GENETIC_PROFILE_IDS);
Network network;
try {
xdebug.startTimer();
network = GetPathwayCommonsNetwork.getNetwork(queryGenes, xdebug);
xdebug.stopTimer();
xdebug.logMsg(this, "Successfully retrieved networks from cPath2: took "+xdebug.getTimeElapsed()+"ms");
} catch (Exception e) {
xdebug.logMsg(this, "Failed retrieving networks from cPath2\n"+e.getMessage());
network = new Network(); // send an empty network instead
}
// remove small molecules
xdebug.startTimer();
network.filter(new Network.Filter() {
public boolean filterNode(Node node) {
if (node == null) {
return true;
}
return !"Protein".equals(node.getType());
}
public boolean filterEdge(Edge edge) {
return filterNode(edge.getSourceNode()) || filterNode(edge.getTargetNode());
}
});
xdebug.stopTimer();
xdebug.logMsg(this, "Removed non-protein nodes: took "+xdebug.getTimeElapsed()+"ms");
if (!network.getNodes().isEmpty()) {
// add attribute is_query to indicate if a node is in query genes
// and get the list of genes in network
xdebug.logMsg(this, "Retrieving data from CGDS...");
ArrayList<String> netGenes = new ArrayList<String>();
for (Node node : network.getNodes()) {
Set<String> ngnc = node.getXref(HGNC);
boolean in_query = false;
if (!ngnc.isEmpty()) {
String sym = ngnc.iterator().next();
in_query = queryGenes.contains(sym);
netGenes.add(sym);
}
node.addAttribute(NODE_ATTR_IN_QUERY, Boolean.toString(in_query));
}
// Get User Selected Genetic Profiles
xdebug.startTimer();
HashSet<String> geneticProfileIdSet = new HashSet<String>();
for (String geneticProfileIdsStr : req.getParameterValues(QueryBuilder.GENETIC_PROFILE_IDS)) {
geneticProfileIdSet.addAll(Arrays.asList(geneticProfileIdsStr.split(" ")));
}
String cancerTypeId = xssUtil.getCleanInput(req, QueryBuilder.CANCER_STUDY_ID);
xdebug.stopTimer();
xdebug.logMsg(this, "Got User Selected Genetic Profiles. Took "+xdebug.getTimeElapsed()+"ms");
// Get Genetic Profiles for Selected Cancer Type
xdebug.startTimer();
ArrayList<GeneticProfile> profileList = GetGeneticProfiles.getGeneticProfiles(cancerTypeId);
String caseIds = xssUtil.getCleanInput(req, QueryBuilder.CASE_IDS);
if (caseIds==null || caseIds.isEmpty()) {
String caseSetId = xssUtil.getCleanInput(req, QueryBuilder.CASE_SET_ID);
// Get Case Sets for Selected Cancer Type
ArrayList<CaseList> caseSets = GetCaseSets.getCaseSets(cancerTypeId);
for (CaseList cs : caseSets) {
if (cs.getStableId().equals(caseSetId)) {
caseIds = cs.getCaseListAsString();
break;
}
}
}
xdebug.stopTimer();
xdebug.logMsg(this, "Got Genetic Profiles for Selected Cancer Type. Took "+xdebug.getTimeElapsed()+"ms");
// retrieve profile data from CGDS for new genes
Set<GeneticAlterationType> alterationTypes = new HashSet();
ArrayList<ProfileData> profileDataList = new ArrayList<ProfileData>();
for (String profileId : geneticProfileIdSet) {
xdebug.startTimer();
GeneticProfile profile = GeneticProfileUtil.getProfile(profileId, profileList);
alterationTypes.add(profile.getGeneticAlterationType());
if( null == profile ){
continue;
}
GetProfileData remoteCall = new GetProfileData(profile, netGenes, caseIds);
ProfileData pData = remoteCall.getProfileData();
if( pData == null ){
System.err.println( "pData == null" );
}else{
if( pData.getGeneList() == null ){
System.err.println( "pData.getValidGeneList() == null" );
}
}
profileDataList.add(pData);
xdebug.stopTimer();
xdebug.logMsg(this, "Got profile data from CGDS for new genes for "+profile.getProfileName()+". Took "+xdebug.getTimeElapsed()+"ms");
}
xdebug.startTimer();
ProfileMerger merger = new ProfileMerger(profileDataList);
xdebug.stopTimer();
xdebug.logMsg(this, "Merged profiles. Took "+xdebug.getTimeElapsed()+"ms");
xdebug.startTimer();
ProfileData netMergedProfile = merger.getMergedProfile();
ArrayList<String> netGeneList = netMergedProfile.getGeneList();
double zScoreThreshold = Double.parseDouble(xssUtil.getCleanInput(req, QueryBuilder.Z_SCORE_THRESHOLD));
ParserOutput netOncoPrintSpecParserOutput = OncoPrintSpecificationDriver.callOncoPrintSpecParserDriver(
StringUtils.join(netGeneList, " "), geneticProfileIdSet,
profileList, zScoreThreshold);
OncoPrintSpecification netOncoPrintSpec = netOncoPrintSpecParserOutput.getTheOncoPrintSpecification();
ProfileDataSummary netDataSummary = new ProfileDataSummary(netMergedProfile,
netOncoPrintSpec, zScoreThreshold );
xdebug.stopTimer();
xdebug.logMsg(this, "Got profile data summary. Took "+xdebug.getTimeElapsed()+"ms");
// add attributes
xdebug.startTimer();
for (String gene : netGeneList) {
for (Node node : network.getNodesByXref(HGNC, gene.toUpperCase())) {
node.addAttribute(NODE_ATTR_PERCENT_ALTERED, netDataSummary.getPercentCasesWhereGeneIsAltered(gene));
if (alterationTypes.contains(GeneticAlterationType.MUTATION_EXTENDED) ||
alterationTypes.contains(GeneticAlterationType.MUTATION_EXTENDED)) {
node.addAttribute(NODE_ATTR_PERCENT_MUTATED, netDataSummary.getPercentCasesWhereGeneIsMutated(gene));
}
if (alterationTypes.contains(GeneticAlterationType.COPY_NUMBER_ALTERATION)) {
node.addAttribute(NODE_ATTR_PERCENT_CNA_AMPLIFIED, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.Amplified));
node.addAttribute(NODE_ATTR_PERCENT_CNA_GAINED, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.Gained));
node.addAttribute(NODE_ATTR_PERCENT_CNA_HOM_DEL, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.HomozygouslyDeleted));
node.addAttribute(NODE_ATTR_PERCENT_CNA_HET_LOSS, netDataSummary.getPercentCasesWhereGeneIsAtCNALevel(gene, GeneticTypeLevel.HemizygouslyDeleted));
}
if (alterationTypes.contains(GeneticAlterationType.MRNA_EXPRESSION)) {
node.addAttribute(NODE_ATTR_PERCENT_MRNA_WAY_UP, netDataSummary.getPercentCasesWhereMRNAIsUpRegulated(gene));
node.addAttribute(NODE_ATTR_PERCENT_MRNA_WAY_DOWN, netDataSummary.getPercentCasesWhereMRNAIsDownRegulated(gene));
}
}
}
xdebug.stopTimer();
xdebug.logMsg(this, "Added node attributes. Took "+xdebug.getTimeElapsed()+"ms");
}
String graphml = NetworkIO.writeNetwork2GraphML(network, new NetworkIO.NodeLabelHandler() {
// using HGNC gene symbol as label if available
public String getLabel(Node node) {
Set<String> ngnc = node.getXref(HGNC);
if (!ngnc.isEmpty())
return ngnc.iterator().next();
Set<Object> names = node.getAttributes().get("name");
if (names!=null && !names.isEmpty())
return names.iterator().next().toString();
return node.getId();
}
});
if (xd!=null && xd.equals("1")) {
writeXDebug(xdebug,req,res);
}
PrintWriter writer = res.getWriter();
writer.write(graphml);
writer.flush();
} catch (DaoException e) {
throw new ServletException (e);
}
}
private String getNetworkServletUrl(HttpServletRequest req, ServletXssUtil xssUtil) {
String geneListStr = xssUtil.getCleanInput(req, QueryBuilder.GENE_LIST);
String geneticProfileIdsStr = xssUtil.getCleanInput(req, QueryBuilder.GENETIC_PROFILE_IDS);
String cancerTypeId = xssUtil.getCleanInput(req, QueryBuilder.CANCER_STUDY_ID);
String caseSetId = xssUtil.getCleanInput(req, QueryBuilder.CASE_SET_ID);
String zscoreThreshold = xssUtil.getCleanInput(req, QueryBuilder.Z_SCORE_THRESHOLD);
return "network.do?"+QueryBuilder.GENE_LIST+"="+geneListStr
+"&"+QueryBuilder.GENETIC_PROFILE_IDS+"="+geneticProfileIdsStr
+"&"+QueryBuilder.CANCER_STUDY_ID+"="+cancerTypeId
+"&"+QueryBuilder.CASE_SET_ID+"="+caseSetId
+"&"+QueryBuilder.Z_SCORE_THRESHOLD+"="+zscoreThreshold;
}
private void writeXDebug(XDebug xdebug, HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
PrintWriter writer = res.getWriter();
writer.write("<!--xdebug messages begin:\n");
for (Object msg : xdebug.getDebugMessages()) {
writer.write(((org.mskcc.portal.util.XDebugMessage)msg).getMessage());
writer.write("\n");
}
writer.write("xdebug messages end-->\n");
}
}
| fix issue: long node label of http://... shows again
| portal/src/org/mskcc/portal/servlet/NetworkServlet.java | fix issue: long node label of http://... shows again | <ide><path>ortal/src/org/mskcc/portal/servlet/NetworkServlet.java
<ide> for (Node node : network.getNodes()) {
<ide> Set<String> ngnc = node.getXref(HGNC);
<ide>
<del> boolean in_query = false;
<add> boolean inQuery = false;
<ide> if (!ngnc.isEmpty()) {
<ide> String sym = ngnc.iterator().next();
<del> in_query = queryGenes.contains(sym);
<add> inQuery = queryGenes.contains(sym);
<ide> netGenes.add(sym);
<ide> }
<del> node.addAttribute(NODE_ATTR_IN_QUERY, Boolean.toString(in_query));
<add> node.addAttribute(NODE_ATTR_IN_QUERY, Boolean.toString(inQuery));
<ide> }
<ide>
<ide> // Get User Selected Genetic Profiles
<ide> // using HGNC gene symbol as label if available
<ide> public String getLabel(Node node) {
<ide> Set<String> ngnc = node.getXref(HGNC);
<del> if (!ngnc.isEmpty())
<add> if (!ngnc.isEmpty()) {
<ide> return ngnc.iterator().next();
<del>
<del> Set<Object> names = node.getAttributes().get("name");
<del> if (names!=null && !names.isEmpty())
<del> return names.iterator().next().toString();
<del>
<add> }
<add>
<add> Set<Object> strNames = node.getAttributes().get("PARTICIPANT_NAME");
<add> if (strNames!=null && !strNames.isEmpty()) {
<add> String[] names = strNames.iterator().next().toString().split(";");
<add> if (names.length>0) {
<add> return names[0];
<add> }
<add> }
<add>
<ide> return node.getId();
<ide> }
<ide> }); |
|
Java | bsd-3-clause | 8f755be36e4fc42409e540cffeb69447f0963d84 | 0 | miguel01997/cookcc,miguel01997/cookcc,coconut2015/cookcc,coconut2015/cookcc,coconut2015/cookcc | /*
* Copyright (c) 2008, Heng Yuan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the Heng Yuan nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Heng Yuan ''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 Heng Yuan 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 org.yuanheng.cookcc.codegen.xml;
import java.io.PrintWriter;
import org.yuanheng.cookcc.doc.GrammarDoc;
import org.yuanheng.cookcc.doc.ParserDoc;
import org.yuanheng.cookcc.doc.RhsDoc;
/**
* @author Heng Yuan
* @version $Id$
*/
class XmlParserOutput
{
private void printRhs (RhsDoc rhs, PrintWriter p)
{
p.println ("\t\t\t<rhs>" + Utils.translate (rhs.getTerms ()) + "</rhs>");
String action = rhs.getAction ();
if (action != null && action.length () > 0)
p.println ("\t\t\t<action>" + Utils.translate (rhs.getAction ()) + "</action>");
}
private void printGrammar (GrammarDoc grammar, PrintWriter p)
{
p.println ("\t\t<grammar rule=\"" + grammar.getRule () + "\">");
for (RhsDoc rhs : grammar.getRhs ())
printRhs (rhs, p);
p.println ("\t\t</grammar>");
}
public void printParserDoc (ParserDoc doc, PrintWriter p)
{
if (doc == null)
return;
p.println ("\t<parser" + (doc.getStart () == null ? "" : ( " start=\"" + doc.getStart () + "\")")) + ">");
for (GrammarDoc grammar : doc.getGrammars ())
printGrammar (grammar, p);
p.println ("\t</parser>");
}
}
| src/org/yuanheng/cookcc/codegen/xml/XmlParserOutput.java | /*
* Copyright (c) 2008, Heng Yuan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of the Heng Yuan nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Heng Yuan ''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 Heng Yuan 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 org.yuanheng.cookcc.codegen.xml;
import java.io.PrintWriter;
import org.yuanheng.cookcc.doc.GrammarDoc;
import org.yuanheng.cookcc.doc.ParserDoc;
import org.yuanheng.cookcc.doc.RhsDoc;
/**
* @author Heng Yuan
* @version $Id$
*/
class XmlParserOutput
{
private void printRhs (RhsDoc rhs, PrintWriter p)
{
p.println ("\t\t\t<rhs>" + Utils.translate (rhs.getTerms ()) + "</rhs>");
String action = rhs.getAction ();
if (action != null && action.length () > 0)
p.println ("\t\t\t<action>" + Utils.translate (rhs.getAction ()) + "</action>");
}
private void printGrammar (GrammarDoc grammar, PrintWriter p)
{
p.println ("\t\t<grammar term=\"" + grammar.getTerm () + "\">");
for (RhsDoc rhs : grammar.getRhs ())
printRhs (rhs, p);
p.println ("\t\t</grammar>");
}
public void printParserDoc (ParserDoc doc, PrintWriter p)
{
if (doc == null)
return;
p.println ("\t<parser" + (doc.getStart () == null ? "" : ( " start=\"" + doc.getStart () + "\")")) + ">");
for (GrammarDoc grammar : doc.getGrammars ())
printGrammar (grammar, p);
p.println ("\t</parser>");
}
}
| rename attribute term to rule since it is really non-terminal... Hard to find a good name. | src/org/yuanheng/cookcc/codegen/xml/XmlParserOutput.java | rename attribute term to rule since it is really non-terminal... Hard to find a good name. | <ide><path>rc/org/yuanheng/cookcc/codegen/xml/XmlParserOutput.java
<ide>
<ide> private void printGrammar (GrammarDoc grammar, PrintWriter p)
<ide> {
<del> p.println ("\t\t<grammar term=\"" + grammar.getTerm () + "\">");
<add> p.println ("\t\t<grammar rule=\"" + grammar.getRule () + "\">");
<ide> for (RhsDoc rhs : grammar.getRhs ())
<ide> printRhs (rhs, p);
<ide> p.println ("\t\t</grammar>"); |
|
Java | apache-2.0 | 0b0e870027c3485246b965150a14987681bf1c89 | 0 | maksimov/dasein-cloud-test | /**
* Copyright (C) 2009-2015 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.test.identity;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.identity.*;
import org.dasein.cloud.test.DaseinTestManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Iterator;
import java.util.UUID;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeTrue;
/**
* Tests of the stateless features of Dasein Cloud IAM support.
* <p>Created by George Reese: 2/28/13 7:24 AM</p>
* @author George Reese
* @version 2013.04 initial version
* @since 2013.04
*/
public class StatelessIAMTests {
static private DaseinTestManager tm;
@BeforeClass
static public void configure() {
tm = new DaseinTestManager(StatelessIAMTests.class);
}
@AfterClass
static public void cleanUp() {
if( tm != null ) {
tm.close();
}
}
@Rule
public final TestName name = new TestName();
private String testGroupId;
private String testUserId;
private IdentityServices identityServices;
private IdentityAndAccessSupport identityAndAccessSupport;
public StatelessIAMTests() { }
@Before
public void before() {
tm.begin(name.getMethodName());
assumeTrue(!tm.isTestSkipped());
identityServices = tm.getProvider().getIdentityServices();
if( identityServices == null ) {
tm.ok("Identity services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
identityAndAccessSupport = identityServices.getIdentityAndAccessSupport();
if( identityAndAccessSupport == null ) {
tm.ok("Identity and access management is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
testGroupId = tm.getTestGroupId(DaseinTestManager.STATELESS, false);
testUserId = tm.getTestUserId(DaseinTestManager.STATELESS, false, testGroupId);
}
@After
public void after() {
tm.end();
}
@Test
public void checkMetaData() throws CloudException, InternalException {
assumeNotNull(identityServices);
if( identityAndAccessSupport == null ) {
tm.ok("Identity and access management is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
tm.out("Subscribed", identityAndAccessSupport.isSubscribed());
tm.out("Supports Access Controls", identityAndAccessSupport.getCapabilities().supportsAccessControls());
tm.out("Supports API Access", identityAndAccessSupport.getCapabilities().supportsApiAccess());
tm.out("Supports Console Access", identityAndAccessSupport.getCapabilities().supportsConsoleAccess());
}
@Test
public void getBogusGroup() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
CloudGroup group = identityAndAccessSupport.getGroup(UUID.randomUUID().toString());
tm.out("Bogus Group", group);
assertNull("A bogus group was found with a random UUID as an identifier", group);
}
@Test
public void getGroup() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
CloudGroup group = identityAndAccessSupport.getGroup(testGroupId);
tm.out("Group", group);
assertNotNull("No group was found under the test group ID", group);
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
private void assertGroup(@Nonnull CloudGroup group) {
assertNotNull("The group ID may not be null", group.getProviderGroupId());
assertNotNull("The owner account may not be null", group.getProviderOwnerId());
assertNotNull("The name may not be null", group.getName());
}
@Test
public void groupContent() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
CloudGroup group = identityAndAccessSupport.getGroup(testGroupId);
assertNotNull("No group was found under the test group ID", group);
tm.out("Group ID", group.getProviderGroupId());
tm.out("Name", group.getName());
tm.out("Owner Account", group.getProviderOwnerId());
tm.out("Path", group.getPath());
assertGroup(group);
assertEquals("ID does not match requested group", testGroupId, group.getProviderGroupId());
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listGroups() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudGroup> groups = identityAndAccessSupport.listGroups(null);
int count = 0;
assertNotNull("The groups listing may not be null regardless of subscription level or requested path base", groups);
for( CloudGroup group : groups ) {
count++;
tm.out("Group", group);
}
tm.out("Total Group Count", count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no groups exist");
}
else {
tm.warn("No groups were returned so this test may be invalid");
}
}
for( CloudGroup group : groups ) {
assertGroup(group);
}
}
@Test
public void listGroupPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.INLINE_POLICY).withProviderGroupId(testGroupId));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level or requested group", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out(testGroupId + " Group Policy", policy);
}
tm.out("Total Group Policy Count in " + testGroupId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listAccountManagedPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.ACCOUNT_MANAGED_POLICY));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out("Managed Policy", policy);
}
tm.out("Total Managed Policy Count", count);
boolean supportsAccountManagedPolicies = false;
for( CloudPolicyType type : identityAndAccessSupport.getCapabilities().listSupportedPolicyTypes() ) {
if( CloudPolicyType.ACCOUNT_MANAGED_POLICY.equals(type) ) {
supportsAccountManagedPolicies = true;
break;
}
}
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsAccountManagedPolicies ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void listAccessKeys() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<AccessKey> accessKeys = identityAndAccessSupport.listAccessKeys(null);
int count = 0;
assertNotNull("The access keys listing may not be null regardless of subscription level", accessKeys);
for( AccessKey accessKey : accessKeys ) {
count++;
tm.out("Access Key", accessKey);
}
tm.out("Total Access Key Count", count);
boolean supportsAccessKeys = identityAndAccessSupport.getCapabilities().supportsApiAccess();
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsAccessKeys ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void listAccessKeys() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<AccessKey> accessKeys = identityAndAccessSupport.listAccessKeys(null);
int count = 0;
assertNotNull("The access keys listing may not be null regardless of subscription level", accessKeys);
for( AccessKey accessKey : accessKeys ) {
count++;
tm.out("Access Key", accessKey);
}
tm.out("Total Access Key Count", count);
boolean supportsAccessKeys = identityAndAccessSupport.getCapabilities().supportsApiAccess();
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsAccessKeys ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void listPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.PROVIDER_MANAGED_POLICY));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out("Managed Policy", policy);
}
tm.out("Total Managed Policy Count", count);
boolean supportsProviderManagedPolicies = false;
for( CloudPolicyType type : identityAndAccessSupport.getCapabilities().listSupportedPolicyTypes() ) {
if( CloudPolicyType.PROVIDER_MANAGED_POLICY.equals(type) ) {
supportsProviderManagedPolicies = true;
break;
}
}
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsProviderManagedPolicies ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void getBogusUser() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
CloudUser user = identityAndAccessSupport.getUser(UUID.randomUUID().toString());
tm.out("Bogus User", user);
assertNull("A bogus user was found with a random UUID as an identifier", user);
}
@Test
public void getUser() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
CloudUser user = identityAndAccessSupport.getUser(testUserId);
tm.out("User", user);
assertNotNull("No user was found under the test user ID", user);
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test user exists for running " + name.getMethodName());
}
}
}
@Test
public void getPolicy() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
boolean supportsProviderManagedPolicies = false;
for( CloudPolicyType type : identityAndAccessSupport.getCapabilities().listSupportedPolicyTypes() ) {
if( CloudPolicyType.PROVIDER_MANAGED_POLICY.equals(type) ) {
supportsProviderManagedPolicies = true;
break;
}
}
if( supportsProviderManagedPolicies ) {
Iterator<CloudPolicy> policiesIterator = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.PROVIDER_MANAGED_POLICY)).iterator();
assertTrue("List of policies must include at least one policy", policiesIterator.hasNext());
String testPolicyId = policiesIterator.next().getProviderPolicyId();
CloudPolicy policy = identityAndAccessSupport.getPolicy(testPolicyId, null);
tm.out("Policy", policy);
assertNotNull("No policy was found under the test policy ID [" + testPolicyId + "]", policy);
assertPolicy(policy, CloudPolicyType.PROVIDER_MANAGED_POLICY);
}
else {
try {
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.PROVIDER_MANAGED_POLICY));
assertNotNull("List of policies may not be null", policies);
assertFalse("List of policies should be empty since managed policies are declared as not supported",
policies.iterator().hasNext()
);
}
catch(CloudException|InternalException e) {
tm.ok("Managed policies are not supported");
}
}
}
private void assertPolicy(@Nonnull CloudPolicy policy, CloudPolicyType type) {
assertNotNull("The policy ID may not be null", policy.getProviderPolicyId());
assertNotNull("The policy name may not be null", policy.getName());
assertEquals("The policy type is wrong", type, policy.getType());
}
private void assertUser(@Nonnull CloudUser user) {
assertNotNull("The user ID may not be null", user.getProviderUserId());
assertNotNull("The owner account may not be null", user.getProviderOwnerId());
assertNotNull("The user name may not be null", user.getUserName());
}
@Test
public void userContent() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
CloudUser user = identityAndAccessSupport.getUser(testUserId);
assertNotNull("No user was found under the test user ID", user);
tm.out("User ID", user.getProviderUserId());
tm.out("User Name", user.getUserName());
tm.out("Owner Account", user.getProviderOwnerId());
tm.out("Path", user.getPath());
assertUser(user);
assertEquals("The ID for the returned user does not match the one requested", testUserId, user.getProviderUserId());
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test user exists for running " + name.getMethodName());
}
}
}
@Test
public void listUsersInPath() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudUser> users = identityAndAccessSupport.listUsersInPath(null);
int count = 0;
assertNotNull("The users listing may not be null regardless of subscription level or requested path base", users);
for( CloudUser user : users ) {
count++;
tm.out("User", user);
}
tm.out("Total User Count", count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no users exist");
}
else {
tm.warn("No users were returned so this test may be invalid");
}
}
for( CloudUser user : users ) {
assertUser(user);
}
}
@Test
public void listUsersInGroup() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
Iterable<CloudUser> users = identityAndAccessSupport.listUsersInGroup(testGroupId);
int count = 0;
assertNotNull("The users listing may not be null regardless of subscription level or requested group", users);
for( CloudUser user : users ) {
count++;
tm.out(testGroupId + " User", user);
}
tm.out("Total User Count in " + testGroupId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no users exist");
}
else {
tm.warn("No users were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listGroupsForUser() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
Iterable<CloudGroup> groups = identityAndAccessSupport.listGroupsForUser(testUserId);
int count = 0;
assertNotNull("The groups listing may not be null regardless of subscription level or requested user", groups);
for( CloudGroup group : groups ) {
count++;
tm.out(testUserId + " Group", group);
}
tm.out("Total Group Count for " + testUserId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no groups exist");
}
else {
tm.warn("No groups were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listUserPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.INLINE_POLICY).withProviderUserId(testUserId));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level or requested user", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out(testUserId + " User Policy", policy);
assertPolicy(policy, CloudPolicyType.INLINE_POLICY);
}
tm.out("Total Policy Count in " + testUserId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test user exists for running " + name.getMethodName());
}
}
}
}
| src/main/java/org/dasein/cloud/test/identity/StatelessIAMTests.java | /**
* Copyright (C) 2009-2015 Dell, Inc.
* See annotations for authorship information
*
* ====================================================================
* 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.dasein.cloud.test.identity;
import org.dasein.cloud.CloudException;
import org.dasein.cloud.InternalException;
import org.dasein.cloud.identity.*;
import org.dasein.cloud.test.DaseinTestManager;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import javax.annotation.Nonnull;
import java.util.Arrays;
import java.util.Iterator;
import java.util.UUID;
import static org.junit.Assert.*;
import static org.junit.Assume.assumeNotNull;
import static org.junit.Assume.assumeTrue;
/**
* Tests of the stateless features of Dasein Cloud IAM support.
* <p>Created by George Reese: 2/28/13 7:24 AM</p>
* @author George Reese
* @version 2013.04 initial version
* @since 2013.04
*/
public class StatelessIAMTests {
static private DaseinTestManager tm;
@BeforeClass
static public void configure() {
tm = new DaseinTestManager(StatelessIAMTests.class);
}
@AfterClass
static public void cleanUp() {
if( tm != null ) {
tm.close();
}
}
@Rule
public final TestName name = new TestName();
private String testGroupId;
private String testUserId;
private IdentityServices identityServices;
private IdentityAndAccessSupport identityAndAccessSupport;
public StatelessIAMTests() { }
@Before
public void before() {
tm.begin(name.getMethodName());
assumeTrue(!tm.isTestSkipped());
identityServices = tm.getProvider().getIdentityServices();
if( identityServices == null ) {
tm.ok("Identity services are not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
identityAndAccessSupport = identityServices.getIdentityAndAccessSupport();
if( identityAndAccessSupport == null ) {
tm.ok("Identity and access management is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
testGroupId = tm.getTestGroupId(DaseinTestManager.STATELESS, false);
testUserId = tm.getTestUserId(DaseinTestManager.STATELESS, false, testGroupId);
}
@After
public void after() {
tm.end();
}
@Test
public void checkMetaData() throws CloudException, InternalException {
assumeNotNull(identityServices);
if( identityAndAccessSupport == null ) {
tm.ok("Identity and access management is not supported in " + tm.getContext().getRegionId() + " of " + tm.getProvider().getCloudName());
return;
}
tm.out("Subscribed", identityAndAccessSupport.isSubscribed());
tm.out("Supports Access Controls", identityAndAccessSupport.getCapabilities().supportsAccessControls());
tm.out("Supports API Access", identityAndAccessSupport.getCapabilities().supportsApiAccess());
tm.out("Supports Console Access", identityAndAccessSupport.getCapabilities().supportsConsoleAccess());
}
@Test
public void getBogusGroup() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
CloudGroup group = identityAndAccessSupport.getGroup(UUID.randomUUID().toString());
tm.out("Bogus Group", group);
assertNull("A bogus group was found with a random UUID as an identifier", group);
}
@Test
public void getGroup() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
CloudGroup group = identityAndAccessSupport.getGroup(testGroupId);
tm.out("Group", group);
assertNotNull("No group was found under the test group ID", group);
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
private void assertGroup(@Nonnull CloudGroup group) {
assertNotNull("The group ID may not be null", group.getProviderGroupId());
assertNotNull("The owner account may not be null", group.getProviderOwnerId());
assertNotNull("The name may not be null", group.getName());
}
@Test
public void groupContent() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
CloudGroup group = identityAndAccessSupport.getGroup(testGroupId);
assertNotNull("No group was found under the test group ID", group);
tm.out("Group ID", group.getProviderGroupId());
tm.out("Name", group.getName());
tm.out("Owner Account", group.getProviderOwnerId());
tm.out("Path", group.getPath());
assertGroup(group);
assertEquals("ID does not match requested group", testGroupId, group.getProviderGroupId());
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listGroups() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudGroup> groups = identityAndAccessSupport.listGroups(null);
int count = 0;
assertNotNull("The groups listing may not be null regardless of subscription level or requested path base", groups);
for( CloudGroup group : groups ) {
count++;
tm.out("Group", group);
}
tm.out("Total Group Count", count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no groups exist");
}
else {
tm.warn("No groups were returned so this test may be invalid");
}
}
for( CloudGroup group : groups ) {
assertGroup(group);
}
}
@Test
public void listGroupPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.INLINE_POLICY).withProviderGroupId(testGroupId));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level or requested group", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out(testGroupId + " Group Policy", policy);
}
tm.out("Total Group Policy Count in " + testGroupId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listAccountManagedPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.ACCOUNT_MANAGED_POLICY));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out("Managed Policy", policy);
}
tm.out("Total Managed Policy Count", count);
boolean supportsAccountManagedPolicies = false;
for( CloudPolicyType type : identityAndAccessSupport.getCapabilities().listSupportedPolicyTypes() ) {
if( CloudPolicyType.ACCOUNT_MANAGED_POLICY.equals(type) ) {
supportsAccountManagedPolicies = true;
break;
}
}
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsAccountManagedPolicies ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void listAccessKeys() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<AccessKey> accessKeys = identityAndAccessSupport.listAccessKeys(null);
int count = 0;
assertNotNull("The access keys listing may not be null regardless of subscription level", accessKeys);
for( AccessKey accessKey : accessKeys ) {
count++;
tm.out("Access Key", accessKey);
}
tm.out("Total Access Key Count", count);
boolean supportsAccessKeys = identityAndAccessSupport.getCapabilities().supportsApiAccess();
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsAccessKeys ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void listPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.PROVIDER_MANAGED_POLICY));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out("Managed Policy", policy);
}
tm.out("Total Managed Policy Count", count);
boolean supportsProviderManagedPolicies = false;
for( CloudPolicyType type : identityAndAccessSupport.getCapabilities().listSupportedPolicyTypes() ) {
if( CloudPolicyType.PROVIDER_MANAGED_POLICY.equals(type) ) {
supportsProviderManagedPolicies = true;
break;
}
}
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else if( supportsProviderManagedPolicies ) {
fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
@Test
public void getBogusUser() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
CloudUser user = identityAndAccessSupport.getUser(UUID.randomUUID().toString());
tm.out("Bogus User", user);
assertNull("A bogus user was found with a random UUID as an identifier", user);
}
@Test
public void getUser() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
CloudUser user = identityAndAccessSupport.getUser(testUserId);
tm.out("User", user);
assertNotNull("No user was found under the test user ID", user);
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test user exists for running " + name.getMethodName());
}
}
}
@Test
public void getPolicy() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
boolean supportsProviderManagedPolicies = false;
for( CloudPolicyType type : identityAndAccessSupport.getCapabilities().listSupportedPolicyTypes() ) {
if( CloudPolicyType.PROVIDER_MANAGED_POLICY.equals(type) ) {
supportsProviderManagedPolicies = true;
break;
}
}
if( supportsProviderManagedPolicies ) {
Iterator<CloudPolicy> policiesIterator = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.PROVIDER_MANAGED_POLICY)).iterator();
assertTrue("List of policies must include at least one policy", policiesIterator.hasNext());
String testPolicyId = policiesIterator.next().getProviderPolicyId();
CloudPolicy policy = identityAndAccessSupport.getPolicy(testPolicyId, null);
tm.out("Policy", policy);
assertNotNull("No policy was found under the test policy ID [" + testPolicyId + "]", policy);
assertPolicy(policy, CloudPolicyType.PROVIDER_MANAGED_POLICY);
}
else {
try {
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.PROVIDER_MANAGED_POLICY));
assertNotNull("List of policies may not be null", policies);
assertFalse("List of policies should be empty since managed policies are declared as not supported",
policies.iterator().hasNext()
);
}
catch(CloudException|InternalException e) {
tm.ok("Managed policies are not supported");
}
}
}
private void assertPolicy(@Nonnull CloudPolicy policy, CloudPolicyType type) {
assertNotNull("The policy ID may not be null", policy.getProviderPolicyId());
assertNotNull("The policy name may not be null", policy.getName());
assertEquals("The policy type is wrong", type, policy.getType());
}
private void assertUser(@Nonnull CloudUser user) {
assertNotNull("The user ID may not be null", user.getProviderUserId());
assertNotNull("The owner account may not be null", user.getProviderOwnerId());
assertNotNull("The user name may not be null", user.getUserName());
}
@Test
public void userContent() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
CloudUser user = identityAndAccessSupport.getUser(testUserId);
assertNotNull("No user was found under the test user ID", user);
tm.out("User ID", user.getProviderUserId());
tm.out("User Name", user.getUserName());
tm.out("Owner Account", user.getProviderOwnerId());
tm.out("Path", user.getPath());
assertUser(user);
assertEquals("The ID for the returned user does not match the one requested", testUserId, user.getProviderUserId());
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test user exists for running " + name.getMethodName());
}
}
}
@Test
public void listUsersInPath() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
Iterable<CloudUser> users = identityAndAccessSupport.listUsersInPath(null);
int count = 0;
assertNotNull("The users listing may not be null regardless of subscription level or requested path base", users);
for( CloudUser user : users ) {
count++;
tm.out("User", user);
}
tm.out("Total User Count", count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no users exist");
}
else {
tm.warn("No users were returned so this test may be invalid");
}
}
for( CloudUser user : users ) {
assertUser(user);
}
}
@Test
public void listUsersInGroup() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testGroupId != null ) {
Iterable<CloudUser> users = identityAndAccessSupport.listUsersInGroup(testGroupId);
int count = 0;
assertNotNull("The users listing may not be null regardless of subscription level or requested group", users);
for( CloudUser user : users ) {
count++;
tm.out(testGroupId + " User", user);
}
tm.out("Total User Count in " + testGroupId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no users exist");
}
else {
tm.warn("No users were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listGroupsForUser() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
Iterable<CloudGroup> groups = identityAndAccessSupport.listGroupsForUser(testUserId);
int count = 0;
assertNotNull("The groups listing may not be null regardless of subscription level or requested user", groups);
for( CloudGroup group : groups ) {
count++;
tm.out(testUserId + " Group", group);
}
tm.out("Total Group Count for " + testUserId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no groups exist");
}
else {
tm.warn("No groups were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test group exists for running " + name.getMethodName());
}
}
}
@Test
public void listUserPolicies() throws CloudException, InternalException {
assumeNotNull(identityServices);
assumeNotNull(identityAndAccessSupport);
if( testUserId != null ) {
Iterable<CloudPolicy> policies = identityAndAccessSupport.listPolicies(CloudPolicyFilterOptions.getInstance(CloudPolicyType.INLINE_POLICY).withProviderUserId(testUserId));
int count = 0;
assertNotNull("The policies listing may not be null regardless of subscription level or requested user", policies);
for( CloudPolicy policy : policies ) {
count++;
tm.out(testUserId + " User Policy", policy);
assertPolicy(policy, CloudPolicyType.INLINE_POLICY);
}
tm.out("Total Policy Count in " + testUserId, count);
if( count < 1 ) {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services, so no policies exist");
}
else {
tm.warn("No policies were returned so this test may be invalid");
}
}
}
else {
if( !identityAndAccessSupport.isSubscribed() ) {
tm.ok("Not subscribed to IAM services");
}
else {
fail("No test user exists for running " + name.getMethodName());
}
}
}
}
| Added listKeys test
| src/main/java/org/dasein/cloud/test/identity/StatelessIAMTests.java | Added listKeys test | <ide><path>rc/main/java/org/dasein/cloud/test/identity/StatelessIAMTests.java
<ide> }
<ide>
<ide> @Test
<add> public void listAccessKeys() throws CloudException, InternalException {
<add> assumeNotNull(identityServices);
<add> assumeNotNull(identityAndAccessSupport);
<add>
<add> Iterable<AccessKey> accessKeys = identityAndAccessSupport.listAccessKeys(null);
<add> int count = 0;
<add>
<add> assertNotNull("The access keys listing may not be null regardless of subscription level", accessKeys);
<add>
<add> for( AccessKey accessKey : accessKeys ) {
<add> count++;
<add> tm.out("Access Key", accessKey);
<add> }
<add> tm.out("Total Access Key Count", count);
<add> boolean supportsAccessKeys = identityAndAccessSupport.getCapabilities().supportsApiAccess();
<add>
<add> if( count < 1 ) {
<add> if( !identityAndAccessSupport.isSubscribed() ) {
<add> tm.ok("Not subscribed to IAM services, so no policies exist");
<add> }
<add> else if( supportsAccessKeys ) {
<add> fail("Provider " + tm.getProvider().getProviderName() + " declares its support for provider managed policies, however there were no policies returned");
<add> }
<add> else {
<add> tm.warn("No policies were returned so this test may be invalid");
<add> }
<add> }
<add> }
<add>
<add> @Test
<ide> public void listPolicies() throws CloudException, InternalException {
<ide> assumeNotNull(identityServices);
<ide> assumeNotNull(identityAndAccessSupport); |
|
Java | mit | 7da714de06f99de5e08684836b379cda41b6885b | 0 | yegor256/cactoos | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 Yegor Bugayenko
*
* 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 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.
*/
package org.cactoos.scalar;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import org.cactoos.Fallback;
import org.cactoos.Scalar;
import org.cactoos.func.FuncWithFallback;
import org.cactoos.iterable.IterableOf;
import org.cactoos.iterator.Filtered;
import org.cactoos.iterator.Sorted;
import org.cactoos.map.MapOf;
/**
* Scalar with fallbacks that enable it to recover from errors.
*
* <p>There is no thread-safety guarantee.
*
* @param <T> Type of result
* @see FuncWithFallback
* @since 0.31
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class ScalarWithFallback<T> implements Scalar<T> {
/**
* The origin scalar.
*/
private final Scalar<T> origin;
/**
* The fallback.
*/
private final Iterable<Fallback<? extends T>> fallbacks;
/**
* Ctor.
* @param origin Original scalar
* @param fbks The fallbacks
*/
@SafeVarargs
public ScalarWithFallback(
final Scalar<T> origin,
final Fallback<? extends T>... fbks
) {
this(origin, new IterableOf<>(fbks));
}
/**
* Ctor.
* @param origin Original scalar
* @param fbks Fallbacks
*/
public ScalarWithFallback(final Scalar<T> origin,
final Iterable<Fallback<? extends T>> fbks) {
this.origin = origin;
this.fallbacks = fbks;
}
@Override
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public T value() throws Exception {
T result;
try {
result = this.origin.value();
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
result = this.fallback(ex);
// @checkstyle IllegalCatchCheck (1 line)
} catch (final Throwable ex) {
result = this.fallback(ex);
}
return result;
}
/**
* Finds the best fallback for the given exception type and apply it to
* the exception or throw the original error if no fallback found.
* @param exp The original exception
* @return Result of the most suitable fallback
* @throws Exception The original exception if no fallback found
*/
@SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
private T fallback(final Throwable exp) throws Exception {
final Iterator<? extends Map.Entry<Fallback<? extends T>, Integer>> candidates =
new Sorted<>(
Comparator.comparing(Map.Entry::getValue),
new Filtered<>(
new org.cactoos.func.Flattened<>(
entry -> new Not(
new Equals<Integer, Integer>(
entry::getValue,
new Constant<>(Integer.MIN_VALUE)
)
)
),
new MapOf<Fallback<? extends T>, Integer>(
fbk -> fbk,
fbk -> fbk.support(exp),
this.fallbacks
).entrySet().iterator()
)
);
if (candidates.hasNext()) {
return candidates.next().getKey().apply(exp);
} else {
throw new Exception(
"No fallback found - throw the original exception",
exp
);
}
}
}
| src/main/java/org/cactoos/scalar/ScalarWithFallback.java | /*
* The MIT License (MIT)
*
* Copyright (c) 2017-2020 Yegor Bugayenko
*
* 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 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.
*/
package org.cactoos.scalar;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import org.cactoos.Fallback;
import org.cactoos.Scalar;
import org.cactoos.func.FuncWithFallback;
import org.cactoos.iterable.IterableOf;
import org.cactoos.iterator.Filtered;
import org.cactoos.iterator.Sorted;
import org.cactoos.map.MapOf;
/**
* Scalar with fallbacks that enable it to recover from errors.
*
* <p>There is no thread-safety guarantee.
*
* @param <T> Type of result
* @see FuncWithFallback
* @since 0.31
* @checkstyle ClassDataAbstractionCouplingCheck (500 lines)
*/
public final class ScalarWithFallback<T> implements Scalar<T> {
/**
* The origin scalar.
*/
private final Scalar<T> origin;
/**
* The fallback.
*/
private final Iterable<Fallback<T>> fallbacks;
/**
* Ctor.
* @param origin Original scalar
* @param fbks The fallbacks
*/
@SafeVarargs
public ScalarWithFallback(
final Scalar<T> origin,
final Fallback<T>... fbks
) {
this(origin, new IterableOf<>(fbks));
}
/**
* Ctor.
* @param origin Original scalar
* @param fbks Fallbacks
*/
public ScalarWithFallback(final Scalar<T> origin,
final Iterable<Fallback<T>> fbks) {
this.origin = origin;
this.fallbacks = fbks;
}
@Override
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public T value() throws Exception {
T result;
try {
result = this.origin.value();
} catch (final InterruptedException ex) {
Thread.currentThread().interrupt();
result = this.fallback(ex);
// @checkstyle IllegalCatchCheck (1 line)
} catch (final Throwable ex) {
result = this.fallback(ex);
}
return result;
}
/**
* Finds the best fallback for the given exception type and apply it to
* the exception or throw the original error if no fallback found.
* @param exp The original exception
* @return Result of the most suitable fallback
* @throws Exception The original exception if no fallback found
*/
@SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
private T fallback(final Throwable exp) throws Exception {
final Iterator<Map.Entry<Fallback<T>, Integer>> candidates =
new Sorted<>(
Comparator.comparing(Map.Entry::getValue),
new Filtered<>(
new org.cactoos.func.Flattened<>(
entry -> new Not(
new Equals<Integer, Integer>(
entry::getValue,
new Constant<>(Integer.MIN_VALUE)
)
)
),
new MapOf<>(
fbk -> fbk,
fbk -> fbk.support(exp),
this.fallbacks
).entrySet().iterator()
)
);
if (candidates.hasNext()) {
return candidates.next().getKey().apply(exp);
} else {
throw new Exception(
"No fallback found - throw the original exception",
exp
);
}
}
}
| (#1572) Generify ScalarWithFallback
| src/main/java/org/cactoos/scalar/ScalarWithFallback.java | (#1572) Generify ScalarWithFallback | <ide><path>rc/main/java/org/cactoos/scalar/ScalarWithFallback.java
<ide> /**
<ide> * The fallback.
<ide> */
<del> private final Iterable<Fallback<T>> fallbacks;
<add> private final Iterable<Fallback<? extends T>> fallbacks;
<ide>
<ide> /**
<ide> * Ctor.
<ide> @SafeVarargs
<ide> public ScalarWithFallback(
<ide> final Scalar<T> origin,
<del> final Fallback<T>... fbks
<add> final Fallback<? extends T>... fbks
<ide> ) {
<ide> this(origin, new IterableOf<>(fbks));
<ide> }
<ide> * @param fbks Fallbacks
<ide> */
<ide> public ScalarWithFallback(final Scalar<T> origin,
<del> final Iterable<Fallback<T>> fbks) {
<add> final Iterable<Fallback<? extends T>> fbks) {
<ide> this.origin = origin;
<ide> this.fallbacks = fbks;
<ide> }
<ide> */
<ide> @SuppressWarnings("PMD.AvoidThrowingRawExceptionTypes")
<ide> private T fallback(final Throwable exp) throws Exception {
<del> final Iterator<Map.Entry<Fallback<T>, Integer>> candidates =
<add> final Iterator<? extends Map.Entry<Fallback<? extends T>, Integer>> candidates =
<ide> new Sorted<>(
<ide> Comparator.comparing(Map.Entry::getValue),
<ide> new Filtered<>(
<ide> )
<ide> )
<ide> ),
<del> new MapOf<>(
<add> new MapOf<Fallback<? extends T>, Integer>(
<ide> fbk -> fbk,
<ide> fbk -> fbk.support(exp),
<ide> this.fallbacks |
|
Java | apache-2.0 | 08356c94aa4b4aac0c3267a540ec29423764dcfa | 0 | italiangrid/voms-clients,ellert/voms-clients,ellert/voms-clients,italiangrid/voms-clients | package org.italiangrid.voms.clients.impl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.bouncycastle.asn1.x509.AttributeCertificate;
import org.bouncycastle.openssl.PasswordFinder;
import org.italiangrid.voms.VOMSError;
import org.italiangrid.voms.VOMSValidators;
import org.italiangrid.voms.ac.VOMSACValidator;
import org.italiangrid.voms.ac.ValidationResultListener;
import org.italiangrid.voms.ac.impl.DefaultVOMSValidator;
import org.italiangrid.voms.clients.ProxyInitParams;
import org.italiangrid.voms.clients.strategies.ProxyInitStrategy;
import org.italiangrid.voms.clients.strategies.VOMSCommandsParsingStrategy;
import org.italiangrid.voms.clients.util.PasswordFinders;
import org.italiangrid.voms.clients.util.VOMSProxyPathBuilder;
import org.italiangrid.voms.credential.LoadCredentialsEventListener;
import org.italiangrid.voms.credential.LoadCredentialsStrategy;
import org.italiangrid.voms.credential.VOMSEnvironmentVariables;
import org.italiangrid.voms.credential.impl.DefaultLoadCredentialsStrategy;
import org.italiangrid.voms.request.VOMSACRequest;
import org.italiangrid.voms.request.VOMSACService;
import org.italiangrid.voms.request.VOMSESLookupStrategy;
import org.italiangrid.voms.request.VOMSProtocolListener;
import org.italiangrid.voms.request.VOMSRequestListener;
import org.italiangrid.voms.request.VOMSServerInfoStore;
import org.italiangrid.voms.request.VOMSServerInfoStoreListener;
import org.italiangrid.voms.request.impl.BaseVOMSESLookupStrategy;
import org.italiangrid.voms.request.impl.DefaultVOMSACRequest;
import org.italiangrid.voms.request.impl.DefaultVOMSACService;
import org.italiangrid.voms.request.impl.DefaultVOMSESLookupStrategy;
import org.italiangrid.voms.request.impl.DefaultVOMSServerInfoStore;
import org.italiangrid.voms.store.VOMSTrustStore;
import org.italiangrid.voms.store.VOMSTrustStoreStatusListener;
import org.italiangrid.voms.store.impl.DefaultVOMSTrustStore;
import org.italiangrid.voms.util.CertificateValidatorBuilder;
import org.italiangrid.voms.util.CredentialsUtils;
import org.italiangrid.voms.util.VOMSFQANNamingScheme;
import eu.emi.security.authn.x509.StoreUpdateListener;
import eu.emi.security.authn.x509.ValidationErrorListener;
import eu.emi.security.authn.x509.ValidationResult;
import eu.emi.security.authn.x509.X509CertChainValidatorExt;
import eu.emi.security.authn.x509.X509Credential;
import eu.emi.security.authn.x509.helpers.proxy.ExtendedProxyType;
import eu.emi.security.authn.x509.helpers.proxy.ProxyHelper;
import eu.emi.security.authn.x509.proxy.ProxyCertificate;
import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions;
import eu.emi.security.authn.x509.proxy.ProxyChainInfo;
import eu.emi.security.authn.x509.proxy.ProxyChainType;
import eu.emi.security.authn.x509.proxy.ProxyGenerator;
import eu.emi.security.authn.x509.proxy.ProxyPolicy;
import eu.emi.security.authn.x509.proxy.ProxyType;
import eu.emi.security.authn.x509.proxy.ProxyUtils;
/**
* The default VOMS proxy init behaviour.
*
* @author andreaceccanti
*
*/
public class DefaultVOMSProxyInitBehaviour implements ProxyInitStrategy {
private VOMSCommandsParsingStrategy commandsParser;
private X509CertChainValidatorExt certChainValidator;
private VOMSACValidator vomsValidator;
private ValidationResultListener validationResultListener;
private VOMSRequestListener requestListener;
private ProxyCreationListener proxyCreationListener;
private VOMSServerInfoStoreListener serverInfoStoreListener;
private LoadCredentialsEventListener loadCredentialsEventListener;
private ValidationErrorListener certChainValidationErrorListener;
private VOMSTrustStoreStatusListener vomsTrustStoreListener;
private StoreUpdateListener storeUpdateListener;
private VOMSProtocolListener protocolListener;
public DefaultVOMSProxyInitBehaviour(VOMSCommandsParsingStrategy commandsParser,
ValidationResultListener validationListener,
VOMSRequestListener requestListener,
ProxyCreationListener pxCreationListener,
VOMSServerInfoStoreListener serverInfoStoreListener,
LoadCredentialsEventListener loadCredEventListener,
ValidationErrorListener certChainListener,
VOMSTrustStoreStatusListener vomsTSListener,
StoreUpdateListener trustStoreUpdateListener,
VOMSProtocolListener protocolListener)
{
this.commandsParser = commandsParser;
this.validationResultListener = validationListener;
this.requestListener = requestListener;
this.proxyCreationListener = pxCreationListener;
this.serverInfoStoreListener = serverInfoStoreListener;
this.loadCredentialsEventListener = loadCredEventListener;
this.certChainValidationErrorListener = certChainListener;
this.vomsTrustStoreListener = vomsTSListener;
this.storeUpdateListener = trustStoreUpdateListener;
this.protocolListener = protocolListener;
}
public DefaultVOMSProxyInitBehaviour(VOMSCommandsParsingStrategy commandsParser,
InitListenerAdapter listenerAdapter){
this.commandsParser = commandsParser;
this.validationResultListener = listenerAdapter;
this.requestListener = listenerAdapter;
this.proxyCreationListener = listenerAdapter;
this.serverInfoStoreListener = listenerAdapter;
this.loadCredentialsEventListener = listenerAdapter;
this.certChainValidationErrorListener = listenerAdapter;
this.vomsTrustStoreListener = listenerAdapter;
this.storeUpdateListener = listenerAdapter;
this.protocolListener = listenerAdapter;
}
protected void validateUserCredential(ProxyInitParams params, X509Credential cred){
ValidationResult result = certChainValidator.validate(cred.getCertificateChain());
if (!result.isValid())
throw new VOMSError("User credential is not valid!");
}
private void init(ProxyInitParams params){
boolean hasVOMSCommands = params.getVomsCommands() != null
&& !params.getVomsCommands().isEmpty();
if (hasVOMSCommands || params.validateUserCredential()){
params.setValidateUserCredential(true);
initCertChainValidator(params);
if (params.verifyAC() && hasVOMSCommands){
initVOMSValidator(params);
}
}
}
public void initProxy(ProxyInitParams params) {
init(params);
VOMSServerInfoStore serverInfoStore = null;
// Fail fast if VO is not configured correctly
if (params.getVomsCommands() != null && !params.getVomsCommands().isEmpty()){
serverInfoStore = initServerInfoStore(params);
checkCommands(params, serverInfoStore);
}
X509Credential cred = lookupCredential(params);
if (cred == null)
throw new VOMSError("No credentials found!");
if (params.validateUserCredential())
validateUserCredential(params, cred);
List<AttributeCertificate> acs = Collections.emptyList();
if (params.getVomsCommands() != null && !params.getVomsCommands().isEmpty()){
initCertChainValidator(params);
acs = getAttributeCertificates(params, cred, serverInfoStore);
}
if (params.verifyAC() && !acs.isEmpty())
verifyACs(params, acs);
createProxy(params, cred, acs);
}
private void checkCommands(ProxyInitParams params, VOMSServerInfoStore sis){
Map<String, List<String>> vomsCommandsMap = commandsParser
.parseCommands(params.getVomsCommands());
for (String voOrAlias: vomsCommandsMap.keySet()){
if (sis.getVOMSServerInfo(voOrAlias).isEmpty()){
String msg = String.format("VOMS server for VO %s is not known! "
+ "Check your vomses configuration.", voOrAlias);
throw new VOMSError(msg);
}
}
}
private VOMSServerInfoStore initServerInfoStore(ProxyInitParams params){
VOMSServerInfoStore sis = null;
if (params.getVomsCommands() != null && !params.getVomsCommands().isEmpty()){
sis = new DefaultVOMSServerInfoStore.Builder()
.lookupStrategy(getVOMSESLookupStrategyFromParams(params))
.storeListener(serverInfoStoreListener)
.build();
}
return sis;
}
private void directorySanityChecks(String dirPath, String preambleMessage){
File f = new File(dirPath);
String errorTemplate = String.format("%s: '%s'", preambleMessage, dirPath);
errorTemplate = errorTemplate +" (%s)";
if (!f.exists()){
Throwable t = new FileNotFoundException(String.format(errorTemplate, "file not found"));
throw new VOMSError(t.getMessage(), t);
}
if (!f.isDirectory()){
throw new VOMSError(String.format(errorTemplate, "not a directory"));
}
if (!f.canRead())
throw new VOMSError(String.format(errorTemplate, "not readable"));
}
private void initCertChainValidator(ProxyInitParams params){
if (certChainValidator == null){
String trustAnchorsDir = DefaultVOMSValidator.DEFAULT_TRUST_ANCHORS_DIR;
if (System.getenv(VOMSEnvironmentVariables.X509_CERT_DIR) != null)
trustAnchorsDir = System.getenv(VOMSEnvironmentVariables.X509_CERT_DIR);
if (params.getTrustAnchorsDir()!=null)
trustAnchorsDir = params.getTrustAnchorsDir();
directorySanityChecks(trustAnchorsDir, "Invalid trust anchors location");
CertificateValidatorBuilder builder = new CertificateValidatorBuilder();
certChainValidator = builder
.trustAnchorsDir(trustAnchorsDir)
.storeUpdateListener(storeUpdateListener)
.lazyAnchorsLoading(true)
.validationErrorListener(certChainValidationErrorListener)
.build();
}
}
private VOMSACValidator initVOMSValidator(ProxyInitParams params){
if (vomsValidator != null)
return vomsValidator;
String vomsdir = DefaultVOMSTrustStore.DEFAULT_VOMS_DIR;
if (System.getenv(VOMSEnvironmentVariables.X509_VOMS_DIR) != null)
vomsdir = System.getenv(VOMSEnvironmentVariables.X509_VOMS_DIR);
if (params.getVomsdir() != null)
vomsdir = params.getVomsdir();
directorySanityChecks(vomsdir, "Invalid vomsdir location");
VOMSTrustStore trustStore = new DefaultVOMSTrustStore(Arrays.asList(vomsdir)
, vomsTrustStoreListener);
vomsValidator = VOMSValidators.newValidator(trustStore,
certChainValidator,
validationResultListener);
return vomsValidator;
}
private void verifyACs(ProxyInitParams params, List<AttributeCertificate> acs) {
VOMSACValidator acValidator = initVOMSValidator(params);
acValidator.validateACs(acs);
}
// Why we have to do this nonsense?
private ProxyType extendedProxyTypeAsProxyType(ExtendedProxyType pt){
switch(pt){
case DRAFT_RFC:
return ProxyType.DRAFT_RFC;
case LEGACY:
return ProxyType.LEGACY;
case RFC3820:
return ProxyType.RFC3820;
default:
return null;
}
}
private void ensureProxyTypeIsCompatibleWithIssuingCredential(ProxyCertificateOptions options,
X509Credential issuingCredential,
List<String> proxyCreationWarnings){
if (ProxyUtils.isProxy(issuingCredential.getCertificateChain())){
ProxyType issuingProxyType = extendedProxyTypeAsProxyType(ProxyHelper.getProxyType(issuingCredential.getCertificateChain()[0]));
if (!issuingProxyType.equals(options.getType())){
proxyCreationWarnings.add("forced "+issuingProxyType.name()+" proxy type to be compatible with the type of the issuing proxy.");
options.setType(issuingProxyType);
}
try {
boolean issuingProxyIsLimited = ProxyHelper.isLimited(issuingCredential.getCertificateChain()[0]);
if (issuingProxyIsLimited && !options.isLimited()){
proxyCreationWarnings.add("forced the creation of a limited proxy to be compatible with the type of the issuing proxy.");
limitProxy(options);
}
} catch (IOException e) {
throw new VOMSError(e.getMessage(),e);
}
}
}
private void checkMixedProxyChain(X509Credential issuingCredential){
if (ProxyUtils.isProxy(issuingCredential.getCertificateChain())){
ProxyChainInfo ci;
try {
ci = new ProxyChainInfo(issuingCredential.getCertificateChain());
if (ci.getProxyType().equals(ProxyChainType.MIXED))
throw new VOMSError("Cannot generate a proxy certificate starting from a mixed type proxy chain.");
} catch (CertificateException e) {
throw new VOMSError(e.getMessage(), e);
}
}
}
private void ensureProxyLifetimeIsConsistentWithIssuingCredential(ProxyCertificateOptions options,
X509Credential issuingCredential,
List<String> proxyCreationWarnings){
Calendar cal = Calendar.getInstance();
Date proxyStartTime = cal.getTime();
cal.add(Calendar.SECOND, options.getLifetime());
Date proxyEndTime = cal.getTime();
Date issuingCredentialEndTime = issuingCredential.getCertificate().getNotAfter();
options.setValidityBounds(proxyStartTime, proxyEndTime);
if ( proxyEndTime.after(issuingCredentialEndTime) ){
proxyCreationWarnings.add("proxy lifetime limited to issuing " +
"credential lifetime.");
options.setValidityBounds(proxyStartTime, issuingCredentialEndTime);
}
}
private void limitProxy(ProxyCertificateOptions proxyOptions){
proxyOptions.setLimited(true);
if (proxyOptions.getType().equals(ProxyType.RFC3820)|| proxyOptions.getType().equals(ProxyType.DRAFT_RFC))
proxyOptions.setPolicy(new ProxyPolicy(ProxyPolicy.LIMITED_PROXY_OID));
}
private void createProxy(ProxyInitParams params,
X509Credential credential, List<AttributeCertificate> acs) {
List<String> proxyCreationWarnings = new ArrayList<String>();
String proxyFilePath = VOMSProxyPathBuilder.buildProxyPath();
String envProxyPath = System.getenv(VOMSEnvironmentVariables.X509_USER_PROXY);
if (envProxyPath != null)
proxyFilePath = envProxyPath;
if (params.getGeneratedProxyFile() != null)
proxyFilePath = params.getGeneratedProxyFile();
ProxyCertificateOptions proxyOptions = new ProxyCertificateOptions(credential.getCertificateChain());
proxyOptions.setProxyPathLimit(params.getPathLenConstraint());
proxyOptions.setLimited(params.isLimited());
proxyOptions.setLifetime(params.getProxyLifetimeInSeconds());
proxyOptions.setType(params.getProxyType());
proxyOptions.setKeyLength(params.getKeySize());
if (params.isEnforcingChainIntegrity()){
checkMixedProxyChain(credential);
ensureProxyTypeIsCompatibleWithIssuingCredential(proxyOptions,
credential, proxyCreationWarnings);
ensureProxyLifetimeIsConsistentWithIssuingCredential(proxyOptions,
credential, proxyCreationWarnings);
}
if (params.isLimited())
limitProxy(proxyOptions);
if (acs != null && !acs.isEmpty())
proxyOptions.setAttributeCertificates(acs.toArray(new AttributeCertificate[acs.size()]));
try {
ProxyCertificate proxy = ProxyGenerator.generate(proxyOptions, credential.getKey());
CredentialsUtils.saveProxyCredentials(proxyFilePath, proxy.getCredential());
proxyCreationListener.proxyCreated(proxyFilePath, proxy, proxyCreationWarnings);
} catch (Throwable t) {
throw new VOMSError("Error creating proxy certificate: "+t.getMessage(), t);
}
}
protected List<String> sortFQANsIfRequested(ProxyInitParams params, List<String> unsortedFQANs){
if (params.getFqanOrder() != null && !params.getFqanOrder().isEmpty()){
Set<String> fqans = new LinkedHashSet<String>();
for (String fqan: params.getFqanOrder()){
if (VOMSFQANNamingScheme.isGroup(fqan))
fqans.add(fqan);
if (VOMSFQANNamingScheme.isQualifiedRole(fqan) && unsortedFQANs.contains(fqan))
fqans.add(fqan);
}
fqans.addAll(unsortedFQANs);
return new ArrayList<String>(fqans);
}
return unsortedFQANs;
}
protected VOMSESLookupStrategy getVOMSESLookupStrategyFromParams(ProxyInitParams params){
if (params.getVomsesLocations() != null && ! params.getVomsesLocations().isEmpty())
return new BaseVOMSESLookupStrategy(params.getVomsesLocations());
else
return new DefaultVOMSESLookupStrategy();
}
protected List<AttributeCertificate> getAttributeCertificates(
ProxyInitParams params, X509Credential cred,
VOMSServerInfoStore serverInfoStore) {
List<String> vomsCommands = params.getVomsCommands();
if (vomsCommands == null || vomsCommands.isEmpty())
return Collections.emptyList();
Map<String, List<String>> vomsCommandsMap = commandsParser
.parseCommands(params.getVomsCommands());
List<AttributeCertificate> acs = new ArrayList<AttributeCertificate>();
for (String vo : vomsCommandsMap.keySet()) {
List<String> fqans = vomsCommandsMap.get(vo);
VOMSACRequest request = new DefaultVOMSACRequest.Builder(vo)
.fqans(sortFQANsIfRequested(params, fqans))
.targets(params.getTargets())
.lifetime(params.getAcLifetimeInSeconds())
.build();
VOMSACService acService = new DefaultVOMSACService
.Builder(certChainValidator)
.requestListener(requestListener)
.serverInfoStore(serverInfoStore)
.vomsesLookupStrategy(getVOMSESLookupStrategyFromParams(params))
.protocolListener(protocolListener)
.connectTimeout((int)TimeUnit.SECONDS.toMillis(params.getTimeoutInSeconds()))
.readTimeout((int)TimeUnit.SECONDS.toMillis(params.getTimeoutInSeconds()))
.build();
AttributeCertificate ac = acService.getVOMSAttributeCertificate(
cred, request);
if (ac != null)
acs.add(ac);
}
if (!vomsCommandsMap.keySet().isEmpty() && acs.isEmpty())
throw new VOMSError("User's request for VOMS attributes could not be fulfilled.");
return acs;
}
private LoadCredentialsStrategy strategyFromParams(ProxyInitParams params){
if (params.isNoRegen()){
return new LoadProxyCredential(loadCredentialsEventListener, params.getCertFile());
}
if (params.getCertFile()!=null && params.getKeyFile() == null)
return new LoadUserCredential(loadCredentialsEventListener, params.getCertFile());
if (params.getCertFile()!=null && params.getKeyFile()!=null)
return new LoadUserCredential(loadCredentialsEventListener, params.getCertFile(), params.getKeyFile());
return new DefaultLoadCredentialsStrategy(System.getProperty(DefaultLoadCredentialsStrategy.HOME_PROPERTY),
DefaultLoadCredentialsStrategy.TMPDIR_PROPERTY,
loadCredentialsEventListener);
}
private X509Credential lookupCredential(ProxyInitParams params) {
PasswordFinder pf = null;
if (params.isReadPasswordFromStdin())
pf = PasswordFinders.getNoPromptInputStreamPasswordFinder(System.in, System.out);
else
pf = PasswordFinders.getDefault();
LoadCredentialsStrategy loadCredStrategy = strategyFromParams(params);
return loadCredStrategy.loadCredentials(pf);
}
}
| src/main/java/org/italiangrid/voms/clients/impl/DefaultVOMSProxyInitBehaviour.java | package org.italiangrid.voms.clients.impl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.bouncycastle.asn1.x509.AttributeCertificate;
import org.bouncycastle.openssl.PasswordFinder;
import org.italiangrid.voms.VOMSError;
import org.italiangrid.voms.VOMSValidators;
import org.italiangrid.voms.ac.VOMSACValidator;
import org.italiangrid.voms.ac.ValidationResultListener;
import org.italiangrid.voms.ac.impl.DefaultVOMSValidator;
import org.italiangrid.voms.clients.ProxyInitParams;
import org.italiangrid.voms.clients.strategies.ProxyInitStrategy;
import org.italiangrid.voms.clients.strategies.VOMSCommandsParsingStrategy;
import org.italiangrid.voms.clients.util.PasswordFinders;
import org.italiangrid.voms.clients.util.VOMSProxyPathBuilder;
import org.italiangrid.voms.credential.LoadCredentialsEventListener;
import org.italiangrid.voms.credential.LoadCredentialsStrategy;
import org.italiangrid.voms.credential.VOMSEnvironmentVariables;
import org.italiangrid.voms.credential.impl.DefaultLoadCredentialsStrategy;
import org.italiangrid.voms.request.VOMSACRequest;
import org.italiangrid.voms.request.VOMSACService;
import org.italiangrid.voms.request.VOMSESLookupStrategy;
import org.italiangrid.voms.request.VOMSProtocolListener;
import org.italiangrid.voms.request.VOMSRequestListener;
import org.italiangrid.voms.request.VOMSServerInfoStore;
import org.italiangrid.voms.request.VOMSServerInfoStoreListener;
import org.italiangrid.voms.request.impl.BaseVOMSESLookupStrategy;
import org.italiangrid.voms.request.impl.DefaultVOMSACRequest;
import org.italiangrid.voms.request.impl.DefaultVOMSACService;
import org.italiangrid.voms.request.impl.DefaultVOMSESLookupStrategy;
import org.italiangrid.voms.request.impl.DefaultVOMSServerInfoStore;
import org.italiangrid.voms.store.VOMSTrustStore;
import org.italiangrid.voms.store.VOMSTrustStoreStatusListener;
import org.italiangrid.voms.store.impl.DefaultVOMSTrustStore;
import org.italiangrid.voms.util.CertificateValidatorBuilder;
import org.italiangrid.voms.util.CredentialsUtils;
import org.italiangrid.voms.util.VOMSFQANNamingScheme;
import eu.emi.security.authn.x509.StoreUpdateListener;
import eu.emi.security.authn.x509.ValidationErrorListener;
import eu.emi.security.authn.x509.ValidationResult;
import eu.emi.security.authn.x509.X509CertChainValidatorExt;
import eu.emi.security.authn.x509.X509Credential;
import eu.emi.security.authn.x509.helpers.proxy.ExtendedProxyType;
import eu.emi.security.authn.x509.helpers.proxy.ProxyHelper;
import eu.emi.security.authn.x509.proxy.ProxyCertificate;
import eu.emi.security.authn.x509.proxy.ProxyCertificateOptions;
import eu.emi.security.authn.x509.proxy.ProxyChainInfo;
import eu.emi.security.authn.x509.proxy.ProxyChainType;
import eu.emi.security.authn.x509.proxy.ProxyGenerator;
import eu.emi.security.authn.x509.proxy.ProxyPolicy;
import eu.emi.security.authn.x509.proxy.ProxyType;
import eu.emi.security.authn.x509.proxy.ProxyUtils;
/**
* The default VOMS proxy init behaviour.
*
* @author andreaceccanti
*
*/
public class DefaultVOMSProxyInitBehaviour implements ProxyInitStrategy {
private VOMSCommandsParsingStrategy commandsParser;
private X509CertChainValidatorExt certChainValidator;
private VOMSACValidator vomsValidator;
private ValidationResultListener validationResultListener;
private VOMSRequestListener requestListener;
private ProxyCreationListener proxyCreationListener;
private VOMSServerInfoStoreListener serverInfoStoreListener;
private LoadCredentialsEventListener loadCredentialsEventListener;
private ValidationErrorListener certChainValidationErrorListener;
private VOMSTrustStoreStatusListener vomsTrustStoreListener;
private StoreUpdateListener storeUpdateListener;
private VOMSProtocolListener protocolListener;
public DefaultVOMSProxyInitBehaviour(VOMSCommandsParsingStrategy commandsParser,
ValidationResultListener validationListener,
VOMSRequestListener requestListener,
ProxyCreationListener pxCreationListener,
VOMSServerInfoStoreListener serverInfoStoreListener,
LoadCredentialsEventListener loadCredEventListener,
ValidationErrorListener certChainListener,
VOMSTrustStoreStatusListener vomsTSListener,
StoreUpdateListener trustStoreUpdateListener,
VOMSProtocolListener protocolListener)
{
this.commandsParser = commandsParser;
this.validationResultListener = validationListener;
this.requestListener = requestListener;
this.proxyCreationListener = pxCreationListener;
this.serverInfoStoreListener = serverInfoStoreListener;
this.loadCredentialsEventListener = loadCredEventListener;
this.certChainValidationErrorListener = certChainListener;
this.vomsTrustStoreListener = vomsTSListener;
this.storeUpdateListener = trustStoreUpdateListener;
this.protocolListener = protocolListener;
}
public DefaultVOMSProxyInitBehaviour(VOMSCommandsParsingStrategy commandsParser, InitListenerAdapter listenerAdapter){
this.commandsParser = commandsParser;
this.validationResultListener = listenerAdapter;
this.requestListener = listenerAdapter;
this.proxyCreationListener = listenerAdapter;
this.serverInfoStoreListener = listenerAdapter;
this.loadCredentialsEventListener = listenerAdapter;
this.certChainValidationErrorListener = listenerAdapter;
this.vomsTrustStoreListener = listenerAdapter;
this.storeUpdateListener = listenerAdapter;
this.protocolListener = listenerAdapter;
}
protected void validateUserCredential(ProxyInitParams params, X509Credential cred){
ValidationResult result = certChainValidator.validate(cred.getCertificateChain());
if (!result.isValid())
throw new VOMSError("User credential is not valid!");
}
private void init(ProxyInitParams params){
boolean hasVOMSCommands = params.getVomsCommands() != null
&& !params.getVomsCommands().isEmpty();
if (hasVOMSCommands)
params.setValidateUserCredential(true);
if (params.validateUserCredential() || hasVOMSCommands)
initCertChainValidator(params);
if (params.verifyAC())
initVOMSValidator(params);
}
public void initProxy(ProxyInitParams params) {
init(params);
VOMSServerInfoStore serverInfoStore = null;
// Fail fast if VO is not configured correctly
if (params.getVomsCommands() != null && !params.getVomsCommands().isEmpty()){
serverInfoStore = initServerInfoStore(params);
checkCommands(params, serverInfoStore);
}
X509Credential cred = lookupCredential(params);
if (cred == null)
throw new VOMSError("No credentials found!");
if (params.validateUserCredential())
validateUserCredential(params, cred);
List<AttributeCertificate> acs = Collections.emptyList();
if (params.getVomsCommands() != null && !params.getVomsCommands().isEmpty()){
initCertChainValidator(params);
acs = getAttributeCertificates(params, cred, serverInfoStore);
}
if (params.verifyAC() && !acs.isEmpty())
verifyACs(params, acs);
createProxy(params, cred, acs);
}
private void checkCommands(ProxyInitParams params, VOMSServerInfoStore sis){
Map<String, List<String>> vomsCommandsMap = commandsParser
.parseCommands(params.getVomsCommands());
for (String voOrAlias: vomsCommandsMap.keySet()){
if (sis.getVOMSServerInfo(voOrAlias).isEmpty()){
String msg = String.format("VOMS server for VO %s is not known! "
+ "Check your vomses configuration.", voOrAlias);
throw new VOMSError(msg);
}
}
}
private VOMSServerInfoStore initServerInfoStore(ProxyInitParams params){
VOMSServerInfoStore sis = null;
if (params.getVomsCommands() != null && !params.getVomsCommands().isEmpty()){
sis = new DefaultVOMSServerInfoStore.Builder()
.lookupStrategy(getVOMSESLookupStrategyFromParams(params))
.storeListener(serverInfoStoreListener)
.build();
}
return sis;
}
private void directorySanityChecks(String dirPath, String preambleMessage){
File f = new File(dirPath);
String errorTemplate = String.format("%s: '%s'", preambleMessage, dirPath);
errorTemplate = errorTemplate +" (%s)";
if (!f.exists()){
Throwable t = new FileNotFoundException(String.format(errorTemplate, "file not found"));
throw new VOMSError(t.getMessage(), t);
}
if (!f.isDirectory()){
throw new VOMSError(String.format(errorTemplate, "not a directory"));
}
if (!f.canRead())
throw new VOMSError(String.format(errorTemplate, "not readable"));
}
private void initCertChainValidator(ProxyInitParams params){
if (certChainValidator == null){
String trustAnchorsDir = DefaultVOMSValidator.DEFAULT_TRUST_ANCHORS_DIR;
if (System.getenv(VOMSEnvironmentVariables.X509_CERT_DIR) != null)
trustAnchorsDir = System.getenv(VOMSEnvironmentVariables.X509_CERT_DIR);
if (params.getTrustAnchorsDir()!=null)
trustAnchorsDir = params.getTrustAnchorsDir();
directorySanityChecks(trustAnchorsDir, "Invalid trust anchors location");
CertificateValidatorBuilder builder = new CertificateValidatorBuilder();
certChainValidator = builder
.trustAnchorsDir(trustAnchorsDir)
.storeUpdateListener(storeUpdateListener)
.lazyAnchorsLoading(true)
.validationErrorListener(certChainValidationErrorListener)
.build();
}
}
private VOMSACValidator initVOMSValidator(ProxyInitParams params){
if (vomsValidator != null)
return vomsValidator;
String vomsdir = DefaultVOMSTrustStore.DEFAULT_VOMS_DIR;
if (System.getenv(VOMSEnvironmentVariables.X509_VOMS_DIR) != null)
vomsdir = System.getenv(VOMSEnvironmentVariables.X509_VOMS_DIR);
if (params.getVomsdir() != null)
vomsdir = params.getVomsdir();
directorySanityChecks(vomsdir, "Invalid vomsdir location");
VOMSTrustStore trustStore = new DefaultVOMSTrustStore(Arrays.asList(vomsdir)
, vomsTrustStoreListener);
vomsValidator = VOMSValidators.newValidator(trustStore,
certChainValidator,
validationResultListener);
return vomsValidator;
}
private void verifyACs(ProxyInitParams params, List<AttributeCertificate> acs) {
VOMSACValidator acValidator = initVOMSValidator(params);
acValidator.validateACs(acs);
}
// Why we have to do this nonsense?
private ProxyType extendedProxyTypeAsProxyType(ExtendedProxyType pt){
switch(pt){
case DRAFT_RFC:
return ProxyType.DRAFT_RFC;
case LEGACY:
return ProxyType.LEGACY;
case RFC3820:
return ProxyType.RFC3820;
default:
return null;
}
}
private void ensureProxyTypeIsCompatibleWithIssuingCredential(ProxyCertificateOptions options,
X509Credential issuingCredential,
List<String> proxyCreationWarnings){
if (ProxyUtils.isProxy(issuingCredential.getCertificateChain())){
ProxyType issuingProxyType = extendedProxyTypeAsProxyType(ProxyHelper.getProxyType(issuingCredential.getCertificateChain()[0]));
if (!issuingProxyType.equals(options.getType())){
proxyCreationWarnings.add("forced "+issuingProxyType.name()+" proxy type to be compatible with the type of the issuing proxy.");
options.setType(issuingProxyType);
}
try {
boolean issuingProxyIsLimited = ProxyHelper.isLimited(issuingCredential.getCertificateChain()[0]);
if (issuingProxyIsLimited && !options.isLimited()){
proxyCreationWarnings.add("forced the creation of a limited proxy to be compatible with the type of the issuing proxy.");
limitProxy(options);
}
} catch (IOException e) {
throw new VOMSError(e.getMessage(),e);
}
}
}
private void checkMixedProxyChain(X509Credential issuingCredential){
if (ProxyUtils.isProxy(issuingCredential.getCertificateChain())){
ProxyChainInfo ci;
try {
ci = new ProxyChainInfo(issuingCredential.getCertificateChain());
if (ci.getProxyType().equals(ProxyChainType.MIXED))
throw new VOMSError("Cannot generate a proxy certificate starting from a mixed type proxy chain.");
} catch (CertificateException e) {
throw new VOMSError(e.getMessage(), e);
}
}
}
private void ensureProxyLifetimeIsConsistentWithIssuingCredential(ProxyCertificateOptions options,
X509Credential issuingCredential,
List<String> proxyCreationWarnings){
Calendar cal = Calendar.getInstance();
Date proxyStartTime = cal.getTime();
cal.add(Calendar.SECOND, options.getLifetime());
Date proxyEndTime = cal.getTime();
Date issuingCredentialEndTime = issuingCredential.getCertificate().getNotAfter();
options.setValidityBounds(proxyStartTime, proxyEndTime);
if ( proxyEndTime.after(issuingCredentialEndTime) ){
proxyCreationWarnings.add("proxy lifetime limited to issuing " +
"credential lifetime.");
options.setValidityBounds(proxyStartTime, issuingCredentialEndTime);
}
}
private void limitProxy(ProxyCertificateOptions proxyOptions){
proxyOptions.setLimited(true);
if (proxyOptions.getType().equals(ProxyType.RFC3820)|| proxyOptions.getType().equals(ProxyType.DRAFT_RFC))
proxyOptions.setPolicy(new ProxyPolicy(ProxyPolicy.LIMITED_PROXY_OID));
}
private void createProxy(ProxyInitParams params,
X509Credential credential, List<AttributeCertificate> acs) {
List<String> proxyCreationWarnings = new ArrayList<String>();
String proxyFilePath = VOMSProxyPathBuilder.buildProxyPath();
String envProxyPath = System.getenv(VOMSEnvironmentVariables.X509_USER_PROXY);
if (envProxyPath != null)
proxyFilePath = envProxyPath;
if (params.getGeneratedProxyFile() != null)
proxyFilePath = params.getGeneratedProxyFile();
ProxyCertificateOptions proxyOptions = new ProxyCertificateOptions(credential.getCertificateChain());
proxyOptions.setProxyPathLimit(params.getPathLenConstraint());
proxyOptions.setLimited(params.isLimited());
proxyOptions.setLifetime(params.getProxyLifetimeInSeconds());
proxyOptions.setType(params.getProxyType());
proxyOptions.setKeyLength(params.getKeySize());
if (params.isEnforcingChainIntegrity()){
checkMixedProxyChain(credential);
ensureProxyTypeIsCompatibleWithIssuingCredential(proxyOptions,
credential, proxyCreationWarnings);
ensureProxyLifetimeIsConsistentWithIssuingCredential(proxyOptions,
credential, proxyCreationWarnings);
}
if (params.isLimited())
limitProxy(proxyOptions);
if (acs != null && !acs.isEmpty())
proxyOptions.setAttributeCertificates(acs.toArray(new AttributeCertificate[acs.size()]));
try {
ProxyCertificate proxy = ProxyGenerator.generate(proxyOptions, credential.getKey());
CredentialsUtils.saveProxyCredentials(proxyFilePath, proxy.getCredential());
proxyCreationListener.proxyCreated(proxyFilePath, proxy, proxyCreationWarnings);
} catch (Throwable t) {
throw new VOMSError("Error creating proxy certificate: "+t.getMessage(), t);
}
}
protected List<String> sortFQANsIfRequested(ProxyInitParams params, List<String> unsortedFQANs){
if (params.getFqanOrder() != null && !params.getFqanOrder().isEmpty()){
Set<String> fqans = new LinkedHashSet<String>();
for (String fqan: params.getFqanOrder()){
if (VOMSFQANNamingScheme.isGroup(fqan))
fqans.add(fqan);
if (VOMSFQANNamingScheme.isQualifiedRole(fqan) && unsortedFQANs.contains(fqan))
fqans.add(fqan);
}
fqans.addAll(unsortedFQANs);
return new ArrayList<String>(fqans);
}
return unsortedFQANs;
}
protected VOMSESLookupStrategy getVOMSESLookupStrategyFromParams(ProxyInitParams params){
if (params.getVomsesLocations() != null && ! params.getVomsesLocations().isEmpty())
return new BaseVOMSESLookupStrategy(params.getVomsesLocations());
else
return new DefaultVOMSESLookupStrategy();
}
protected List<AttributeCertificate> getAttributeCertificates(
ProxyInitParams params, X509Credential cred,
VOMSServerInfoStore serverInfoStore) {
List<String> vomsCommands = params.getVomsCommands();
if (vomsCommands == null || vomsCommands.isEmpty())
return Collections.emptyList();
Map<String, List<String>> vomsCommandsMap = commandsParser
.parseCommands(params.getVomsCommands());
List<AttributeCertificate> acs = new ArrayList<AttributeCertificate>();
for (String vo : vomsCommandsMap.keySet()) {
List<String> fqans = vomsCommandsMap.get(vo);
VOMSACRequest request = new DefaultVOMSACRequest.Builder(vo)
.fqans(sortFQANsIfRequested(params, fqans))
.targets(params.getTargets())
.lifetime(params.getAcLifetimeInSeconds())
.build();
VOMSACService acService = new DefaultVOMSACService
.Builder(certChainValidator)
.requestListener(requestListener)
.serverInfoStore(serverInfoStore)
.vomsesLookupStrategy(getVOMSESLookupStrategyFromParams(params))
.protocolListener(protocolListener)
.connectTimeout((int)TimeUnit.SECONDS.toMillis(params.getTimeoutInSeconds()))
.readTimeout((int)TimeUnit.SECONDS.toMillis(params.getTimeoutInSeconds()))
.build();
AttributeCertificate ac = acService.getVOMSAttributeCertificate(
cred, request);
if (ac != null)
acs.add(ac);
}
if (!vomsCommandsMap.keySet().isEmpty() && acs.isEmpty())
throw new VOMSError("User's request for VOMS attributes could not be fulfilled.");
return acs;
}
private LoadCredentialsStrategy strategyFromParams(ProxyInitParams params){
if (params.isNoRegen()){
return new LoadProxyCredential(loadCredentialsEventListener, params.getCertFile());
}
if (params.getCertFile()!=null && params.getKeyFile() == null)
return new LoadUserCredential(loadCredentialsEventListener, params.getCertFile());
if (params.getCertFile()!=null && params.getKeyFile()!=null)
return new LoadUserCredential(loadCredentialsEventListener, params.getCertFile(), params.getKeyFile());
return new DefaultLoadCredentialsStrategy(System.getProperty(DefaultLoadCredentialsStrategy.HOME_PROPERTY),
DefaultLoadCredentialsStrategy.TMPDIR_PROPERTY,
loadCredentialsEventListener);
}
private X509Credential lookupCredential(ProxyInitParams params) {
PasswordFinder pf = null;
if (params.isReadPasswordFromStdin())
pf = PasswordFinders.getNoPromptInputStreamPasswordFinder(System.in, System.out);
else
pf = PasswordFinders.getDefault();
LoadCredentialsStrategy loadCredStrategy = strategyFromParams(params);
return loadCredStrategy.loadCredentials(pf);
}
}
| Some code cleanup. | src/main/java/org/italiangrid/voms/clients/impl/DefaultVOMSProxyInitBehaviour.java | Some code cleanup. | <ide><path>rc/main/java/org/italiangrid/voms/clients/impl/DefaultVOMSProxyInitBehaviour.java
<ide> this.protocolListener = protocolListener;
<ide> }
<ide>
<del> public DefaultVOMSProxyInitBehaviour(VOMSCommandsParsingStrategy commandsParser, InitListenerAdapter listenerAdapter){
<add> public DefaultVOMSProxyInitBehaviour(VOMSCommandsParsingStrategy commandsParser,
<add> InitListenerAdapter listenerAdapter){
<add>
<ide> this.commandsParser = commandsParser;
<ide> this.validationResultListener = listenerAdapter;
<ide> this.requestListener = listenerAdapter;
<ide> boolean hasVOMSCommands = params.getVomsCommands() != null
<ide> && !params.getVomsCommands().isEmpty();
<ide>
<del> if (hasVOMSCommands)
<del> params.setValidateUserCredential(true);
<del>
<del> if (params.validateUserCredential() || hasVOMSCommands)
<add> if (hasVOMSCommands || params.validateUserCredential()){
<add>
<add> params.setValidateUserCredential(true);
<ide> initCertChainValidator(params);
<del>
<del> if (params.verifyAC())
<del> initVOMSValidator(params);
<add>
<add> if (params.verifyAC() && hasVOMSCommands){
<add> initVOMSValidator(params);
<add> }
<add> }
<ide>
<ide> }
<ide> |
|
Java | mit | 402bb4948f4f630b31a49d1ae3f9b6a2010a1b92 | 0 | accentation/resource-server,accentation/resource-server | package com.accenture.banking;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment =WebEnvironment.DEFINED_PORT)
public class TestApplicationBuilder {
@Autowired
TestRestTemplate restTemplate;
@Test
public void testOfficeById() throws Exception {
String response = restTemplate.getForObject("http://localhost:8082/offices/1", String.class);
assertThat(response, containsString("678678678"));
}
@Test
public void testClientById() throws Exception {
String response = restTemplate.getForObject("http://localhost:8082/clients/1", String.class);
assertThat(response, containsString("Zinedine"));
}
@Test
public void testClients() throws Exception {
String response = restTemplate.getForObject("http://localhost:8082/clients/", String.class);
assertThat(response, containsString("Ladrón Gonzalez"));
}
@Test
public void contextLoads() {
}
}
| src/test/java/com/accenture/banking/TestApplicationBuilder.java | package com.accenture.banking;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment =WebEnvironment.DEFINED_PORT)
public class TestApplicationBuilder {
@Autowired
TestRestTemplate restTemplate;
@Test
public void testOfficeById() throws Exception {
String response = restTemplate.getForObject("http://localhost:8082/offices/1", String.class);
assertThat(response, containsString("678678678"));
}
@Test
public void contextLoads() {
}
}
| Client test Ok
| src/test/java/com/accenture/banking/TestApplicationBuilder.java | Client test Ok | <ide><path>rc/test/java/com/accenture/banking/TestApplicationBuilder.java
<ide> String response = restTemplate.getForObject("http://localhost:8082/offices/1", String.class);
<ide>
<ide> assertThat(response, containsString("678678678"));
<add> }
<add>
<add> @Test
<add> public void testClientById() throws Exception {
<add>
<add> String response = restTemplate.getForObject("http://localhost:8082/clients/1", String.class);
<add>
<add> assertThat(response, containsString("Zinedine"));
<add> }
<add>
<add> @Test
<add> public void testClients() throws Exception {
<add>
<add> String response = restTemplate.getForObject("http://localhost:8082/clients/", String.class);
<add>
<add> assertThat(response, containsString("Ladrón Gonzalez"));
<ide> }
<ide>
<ide> @Test |
|
Java | mit | d32fdf414995be00517c7a69eef15b8ce3e5d027 | 0 | bThink-BGU/BPjs,bThink-BGU/BPjs | package il.ac.bgu.cs.bp.bpjs.bprogram.runtimeengine;
import java.io.Serializable;
import java.util.Optional;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContinuationPending;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeContinuation;
import org.mozilla.javascript.Scriptable;
import il.ac.bgu.cs.bp.bpjs.bprogram.runtimeengine.jsproxy.BThreadJsProxy;
import il.ac.bgu.cs.bp.bpjs.events.BEvent;
import il.ac.bgu.cs.bp.bpjs.search.ContinuationProgramState;
import java.util.Objects;
/**
* The state of a BThread at {@code bsync}.
*
* @author orelmosheweinstock
* @author Michael
*/
public class BThreadSyncSnapshot implements Serializable {
/** Name of the BThread described */
private String name;
/**
* The Javascript function that will be called when {@code this} BThread runs.
*/
private Function entryPoint;
/**
* BThreads may specify a function that runs when they are removed because of a
* {@code breakUpon} statement.
*/
private Function interruptHandler = null;
/** Proxy to {@code this}, used from the Javascript code. */
private final BThreadJsProxy proxy = new BThreadJsProxy(this);
/** Scope for the Javascript code execution. */
private Scriptable scope;
/** Continuation of the code. */
private Object continuation;
/** BSync statement of the BThread at the time of the snapshot. */
private BSyncStatement bSyncStatement;
public BThreadSyncSnapshot(String aName, Function anEntryPoint) {
name = aName;
entryPoint = anEntryPoint;
}
/**
* Convenience constructor with default parameters.
*/
public BThreadSyncSnapshot() {
this(BThreadSyncSnapshot.class.getName(), null);
}
/**
* Fully detailed constructor. Mostly useful for getting objects out of
* serialized forms.
*
* @param name
* @param entryPoint
* @param interruptHandler
* @param scope
* @param continuation
* @param bSyncStatement
*/
public BThreadSyncSnapshot(String name, Function entryPoint, Function interruptHandler, Scriptable scope,
Object continuation, BSyncStatement bSyncStatement) {
this.name = name;
this.entryPoint = entryPoint;
this.interruptHandler = interruptHandler;
this.scope = scope;
this.continuation = continuation;
this.bSyncStatement = bSyncStatement;
}
/**
* Creates the next snapshot of the BThread in a given run.
*
* @param aContinuation
* The BThread's continuation for the next sync.
* @param aStatement
* The BThread's statement for the next sync.
* @return a copy of {@code this} with updated continuation and statement.
*/
public BThreadSyncSnapshot copyWith(Object aContinuation, BSyncStatement aStatement) {
BThreadSyncSnapshot retVal = new BThreadSyncSnapshot(name, entryPoint);
retVal.continuation = aContinuation;
retVal.setInterruptHandler(interruptHandler);
retVal.setupScope(scope.getParentScope());
retVal.bSyncStatement = aStatement;
aStatement.setBthread(retVal);
return retVal;
}
/**
* Runs the b-thread from the start to the first {@code bsync}. If there are no
* calls to {@code bsync}, runs to completion.
*
* @return a snapshot of the b-thread after the first {@code bsync} call, or
* {@code null} in case no such call exists.
*/
public BThreadSyncSnapshot startBThread() {
try {
Context jsContext = Context.enter();
jsContext.callFunctionWithContinuations(getEntryPoint(), getScope(), new Object[0]);
return null;
} catch (ContinuationPending cbs) {
return copyWith(cbs.getContinuation(), (BSyncStatement) cbs.getApplicationState());
} finally {
Context.exit();
}
}
/**
* Makes the call to {@code bsync} on which the b-thread snapshot was made
* return the passed event. Then returns the snapshot at the next {@code bsync},
* if any.
*
* @param anEvent
* The event to trigger
* @return snapshot of the bthread at the next call to {@code bsync}, or
* {@code null}, if the b-thread ran to completion.
*/
public BThreadSyncSnapshot triggerEvent(BEvent anEvent) {
try {
Context jsContext = Context.enter();
Object toResume = getContinuation();
Object eventInJS = Context.javaToJS(anEvent, getScope());
jsContext.resumeContinuation(toResume, getScope(), eventInJS);
return null;
} catch (ContinuationPending cbs) {
return copyWith(cbs.getContinuation(), (BSyncStatement) cbs.getApplicationState());
} finally {
Context.exit();
}
}
void setupScope(Scriptable programScope) {
scope = (Scriptable) Context.javaToJS(proxy, programScope);
scope.delete("equals");
scope.setParentScope(programScope);
Scriptable curScope = entryPoint.getParentScope();
if (curScope.getParentScope() == null) {
entryPoint.setParentScope(scope);
scope.setParentScope(curScope);
} else {
while (curScope.getParentScope().getParentScope() != null) {
curScope = curScope.getParentScope();
}
scope.setParentScope(curScope.getParentScope());
curScope.setParentScope(scope);
}
}
public BSyncStatement getBSyncStatement() {
return bSyncStatement;
}
public void setBSyncStatement(BSyncStatement stmt) {
bSyncStatement = stmt;
if (bSyncStatement.getBthread() != this) {
bSyncStatement.setBthread(this);
}
}
public Object getContinuation() {
return continuation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[BThreadSyncSnapshot: " + name + "]";
}
public Optional<Function> getInterrupt() {
return Optional.ofNullable(interruptHandler);
}
public void setInterruptHandler(Function anInterruptHandler) {
interruptHandler = anInterruptHandler;
}
public Scriptable getScope() {
return scope;
}
public Function getEntryPoint() {
return entryPoint;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((continuation == null) ? 0 : (new ContinuationProgramState((NativeContinuation) continuation).hashCode()));
return result;
}
@Override
public boolean equals(Object obj) {
// Quick circuit-breakers
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BThreadSyncSnapshot other = (BThreadSyncSnapshot) obj;
if ( ! Objects.equals(getName(), other.getName())) return false;
if (continuation == null) {
return (other.continuation == null);
} else {
NativeContinuation natCont = (NativeContinuation) continuation;
NativeContinuation natOtherCont = (NativeContinuation) other.continuation;
return new ContinuationProgramState(natCont).equals(new ContinuationProgramState(natOtherCont));
}
}
}
| src/main/java/il/ac/bgu/cs/bp/bpjs/bprogram/runtimeengine/BThreadSyncSnapshot.java | package il.ac.bgu.cs.bp.bpjs.bprogram.runtimeengine;
import java.io.Serializable;
import java.util.Optional;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ContinuationPending;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeContinuation;
import org.mozilla.javascript.Scriptable;
import il.ac.bgu.cs.bp.bpjs.bprogram.runtimeengine.jsproxy.BThreadJsProxy;
import il.ac.bgu.cs.bp.bpjs.events.BEvent;
import il.ac.bgu.cs.bp.bpjs.search.ContinuationProgramState;
/**
* The state of a BThread at {@code bsync}.
*
* @author orelmosheweinstock
* @author Michael
*/
public class BThreadSyncSnapshot implements Serializable {
/** Name of the BThread described */
private String name;
/**
* The Javascript function that will be called when {@code this} BThread runs.
*/
private Function entryPoint;
/**
* BThreads may specify a function that runs when they are removed because of a
* {@code breakUpon} statement.
*/
private Function interruptHandler = null;
/** Proxy to {@code this}, used from the Javascript code. */
private final BThreadJsProxy proxy = new BThreadJsProxy(this);
/** Scope for the Javascript code execution. */
private Scriptable scope;
/** Continuation of the code. */
private Object continuation;
/** BSync statement of the BThread at the time of the snapshot. */
private BSyncStatement bSyncStatement;
public BThreadSyncSnapshot(String aName, Function anEntryPoint) {
name = aName;
entryPoint = anEntryPoint;
}
/**
* Convenience constructor with default parameters.
*/
public BThreadSyncSnapshot() {
this(BThreadSyncSnapshot.class.getName(), null);
}
/**
* Fully detailed constructor. Mostly useful for getting objects out of
* serialized forms.
*
* @param name
* @param entryPoint
* @param interruptHandler
* @param scope
* @param continuation
* @param bSyncStatement
*/
public BThreadSyncSnapshot(String name, Function entryPoint, Function interruptHandler, Scriptable scope,
Object continuation, BSyncStatement bSyncStatement) {
this.name = name;
this.entryPoint = entryPoint;
this.interruptHandler = interruptHandler;
this.scope = scope;
this.continuation = continuation;
this.bSyncStatement = bSyncStatement;
}
/**
* Creates the next snapshot of the BThread in a given run.
*
* @param aContinuation
* The BThread's continuation for the next sync.
* @param aStatement
* The BThread's statement for the next sync.
* @return a copy of {@code this} with updated continuation and statement.
*/
public BThreadSyncSnapshot copyWith(Object aContinuation, BSyncStatement aStatement) {
BThreadSyncSnapshot retVal = new BThreadSyncSnapshot(name, entryPoint);
retVal.continuation = aContinuation;
retVal.setInterruptHandler(interruptHandler);
retVal.setupScope(scope.getParentScope());
retVal.bSyncStatement = aStatement;
aStatement.setBthread(retVal);
return retVal;
}
/**
* Runs the b-thread from the start to the first {@code bsync}. If there are no
* calls to {@code bsync}, runs to completion.
*
* @return a snapshot of the b-thread after the first {@code bsync} call, or
* {@code null} in case no such call exists.
*/
public BThreadSyncSnapshot startBThread() {
try {
Context jsContext = Context.enter();
jsContext.callFunctionWithContinuations(getEntryPoint(), getScope(), new Object[0]);
return null;
} catch (ContinuationPending cbs) {
return copyWith(cbs.getContinuation(), (BSyncStatement) cbs.getApplicationState());
} finally {
Context.exit();
}
}
/**
* Makes the call to {@code bsync} on which the b-thread snapshot was made
* return the passed event. Then returns the snapshot at the next {@code bsync},
* if any.
*
* @param anEvent
* The event to trigger
* @return snapshot of the bthread at the next call to {@code bsync}, or
* {@code null}, if the b-thread ran to completion.
*/
public BThreadSyncSnapshot triggerEvent(BEvent anEvent) {
try {
Context jsContext = Context.enter();
Object toResume = getContinuation();
Object eventInJS = Context.javaToJS(anEvent, getScope());
jsContext.resumeContinuation(toResume, getScope(), eventInJS);
return null;
} catch (ContinuationPending cbs) {
return copyWith(cbs.getContinuation(), (BSyncStatement) cbs.getApplicationState());
} finally {
Context.exit();
}
}
void setupScope(Scriptable programScope) {
scope = (Scriptable) Context.javaToJS(proxy, programScope);
scope.delete("equals");
scope.setParentScope(programScope);
Scriptable curScope = entryPoint.getParentScope();
if (curScope.getParentScope() == null) {
entryPoint.setParentScope(scope);
scope.setParentScope(curScope);
} else {
while (curScope.getParentScope().getParentScope() != null) {
curScope = curScope.getParentScope();
}
scope.setParentScope(curScope.getParentScope());
curScope.setParentScope(scope);
}
}
public BSyncStatement getBSyncStatement() {
return bSyncStatement;
}
public void setBSyncStatement(BSyncStatement stmt) {
bSyncStatement = stmt;
if (bSyncStatement.getBthread() != this) {
bSyncStatement.setBthread(this);
}
}
public Object getContinuation() {
return continuation;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "[BThreadSyncSnapshot: " + name + "]";
}
public Optional<Function> getInterrupt() {
return Optional.ofNullable(interruptHandler);
}
public void setInterruptHandler(Function anInterruptHandler) {
interruptHandler = anInterruptHandler;
}
public Scriptable getScope() {
return scope;
}
public Function getEntryPoint() {
return entryPoint;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((continuation == null) ? 0 : (new ContinuationProgramState((NativeContinuation) continuation).hashCode()));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
BThreadSyncSnapshot other = (BThreadSyncSnapshot) obj;
if (continuation == null) {
return (other.continuation == null)
} else {
NativeContinuation natCont = (NativeContinuation) continuation;
NativeContinuation natOtherCont = (NativeContinuation) other.continuation;
return new ContinuationProgramState(natCont).equals(new ContinuationProgramState(natOtherCont))
}
}
}
| Fixed code to enable normal forward execution
| src/main/java/il/ac/bgu/cs/bp/bpjs/bprogram/runtimeengine/BThreadSyncSnapshot.java | Fixed code to enable normal forward execution | <ide><path>rc/main/java/il/ac/bgu/cs/bp/bpjs/bprogram/runtimeengine/BThreadSyncSnapshot.java
<ide> import il.ac.bgu.cs.bp.bpjs.bprogram.runtimeengine.jsproxy.BThreadJsProxy;
<ide> import il.ac.bgu.cs.bp.bpjs.events.BEvent;
<ide> import il.ac.bgu.cs.bp.bpjs.search.ContinuationProgramState;
<add>import java.util.Objects;
<ide>
<ide> /**
<ide> * The state of a BThread at {@code bsync}.
<ide>
<ide> @Override
<ide> public boolean equals(Object obj) {
<del> if (this == obj) return true;
<add>
<add> // Quick circuit-breakers
<add> if (this == obj) return true;
<ide> if (obj == null) return false;
<ide> if (getClass() != obj.getClass()) return false;
<del>
<ide> BThreadSyncSnapshot other = (BThreadSyncSnapshot) obj;
<add> if ( ! Objects.equals(getName(), other.getName())) return false;
<add>
<ide> if (continuation == null) {
<del> return (other.continuation == null)
<add> return (other.continuation == null);
<ide>
<ide> } else {
<ide> NativeContinuation natCont = (NativeContinuation) continuation;
<ide> NativeContinuation natOtherCont = (NativeContinuation) other.continuation;
<del> return new ContinuationProgramState(natCont).equals(new ContinuationProgramState(natOtherCont))
<add> return new ContinuationProgramState(natCont).equals(new ContinuationProgramState(natOtherCont));
<ide> }
<ide> }
<ide> |
|
Java | lgpl-2.1 | e60cd6018779890d8a0957f9d57490b731f63ff1 | 0 | jessealama/exist,jensopetersen/exist,jessealama/exist,patczar/exist,opax/exist,wolfgangmm/exist,ambs/exist,patczar/exist,eXist-db/exist,RemiKoutcherawy/exist,ljo/exist,windauer/exist,ljo/exist,ambs/exist,windauer/exist,jessealama/exist,zwobit/exist,patczar/exist,joewiz/exist,joewiz/exist,MjAbuz/exist,wolfgangmm/exist,olvidalo/exist,RemiKoutcherawy/exist,dizzzz/exist,adamretter/exist,shabanovd/exist,hungerburg/exist,shabanovd/exist,jessealama/exist,MjAbuz/exist,eXist-db/exist,wshager/exist,MjAbuz/exist,MjAbuz/exist,joewiz/exist,windauer/exist,ambs/exist,RemiKoutcherawy/exist,patczar/exist,wshager/exist,wshager/exist,ljo/exist,olvidalo/exist,kohsah/exist,eXist-db/exist,MjAbuz/exist,olvidalo/exist,wshager/exist,hungerburg/exist,kohsah/exist,ambs/exist,shabanovd/exist,lcahlander/exist,opax/exist,ljo/exist,joewiz/exist,jensopetersen/exist,zwobit/exist,dizzzz/exist,patczar/exist,jensopetersen/exist,hungerburg/exist,jensopetersen/exist,lcahlander/exist,patczar/exist,wolfgangmm/exist,opax/exist,kohsah/exist,hungerburg/exist,adamretter/exist,opax/exist,jensopetersen/exist,olvidalo/exist,MjAbuz/exist,wolfgangmm/exist,eXist-db/exist,wolfgangmm/exist,jessealama/exist,kohsah/exist,ambs/exist,zwobit/exist,shabanovd/exist,zwobit/exist,windauer/exist,lcahlander/exist,kohsah/exist,adamretter/exist,hungerburg/exist,zwobit/exist,shabanovd/exist,lcahlander/exist,ljo/exist,joewiz/exist,RemiKoutcherawy/exist,eXist-db/exist,eXist-db/exist,shabanovd/exist,wshager/exist,adamretter/exist,dizzzz/exist,jensopetersen/exist,wolfgangmm/exist,adamretter/exist,lcahlander/exist,joewiz/exist,wshager/exist,ambs/exist,opax/exist,dizzzz/exist,windauer/exist,lcahlander/exist,adamretter/exist,zwobit/exist,RemiKoutcherawy/exist,windauer/exist,jessealama/exist,kohsah/exist,dizzzz/exist,RemiKoutcherawy/exist,ljo/exist,olvidalo/exist,dizzzz/exist | /*
* eXist Open Source Native XML Database
* Copyright (C) 2010 The eXist Project
* http://exist-db.org
*
* This program 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.w3c.tests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import junit.framework.Assert;
import org.custommonkey.xmlunit.Diff;
import org.exist.Namespaces;
import org.exist.dom.NodeProxy;
import org.exist.memtree.NodeImpl;
import org.exist.memtree.SAXAdapter;
import org.exist.security.Subject;
import org.exist.storage.BrokerPool;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.xmldb.LocalCollection;
import org.exist.xmldb.LocalXMLResource;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.AtomicValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
/**
* @author <a href="mailto:[email protected]">Dmitriy Shabanov</a>
*
*/
public abstract class TestCase {
public static org.exist.start.Main database = null;
private static int inUse = 0;
public static Collection testCollection = null;
public static BrokerPool pool = null;
private static Thread shutdowner = null;
public static final String testLocation = "test/external/";
static class Shutdowner implements Runnable {
public void run() {
try {
while (true) {
Thread.sleep(10 * 1000);
if (inUse == 0) {
//double check
Thread.sleep(10 * 1000);
if (inUse == 0) {
database.shutdown();
System.out.println("database was shutdown");
database = null;
}
}
}
} catch (InterruptedException e) {
}
}
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("setUpBeforeClass ENTERED");
try {
if (database == null) {
System.out.println("Start up database...");
database = new org.exist.start.Main("jetty");
database.run(new String[] { "jetty" });
// testCollection = DatabaseManager.getCollection("xmldb:exist:///db/XQTS", "admin", "");
if (shutdowner == null) {
shutdowner = new Thread(new Shutdowner());
shutdowner.start();
}
pool = BrokerPool.getInstance();
System.out.println("Database ready.");
}
synchronized (database) {
inUse++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("setUpBeforeClass PASSED");
}
public abstract void loadTS() throws Exception;
@AfterClass
public static void tearDownAfterClass() throws Exception {
synchronized (database) {
inUse--;
}
System.out.println("tearDownAfterClass PASSED");
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
System.out.println("setUp ENTERED");
synchronized (database) {
if (testCollection == null) {
System.out.println("setUp no TS data");
loadTS();
System.out.println("setUp checking TS data");
testCollection = DatabaseManager.getCollection("xmldb:exist://"+getCollection(), "admin", "");
if (testCollection == null) {
Assert.fail("There is no Test Suite data at database");
}
}
}
System.out.println("setUp PASSED");
}
protected abstract String getCollection();
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
// System.out.println("tearDown PASSED");
}
public Exception catchError(Sequence result) {
try {
for(SequenceIterator i = result.iterate(); i.hasNext(); ) {
Resource xmldbResource = getResource(i.nextItem());
xmldbResource.getContent().toString();
}
} catch (Exception e) {
return e;
}
return null;
}
public boolean compareResult(String testCase, String folder, Element outputFile, Sequence result) {
if (outputFile == null)
Assert.fail("no expected result information");
File expectedResult = new File(testLocation+folder, outputFile.getNodeValue());
if (!expectedResult.canRead()) Assert.fail("can't read expected result");
String compare = outputFile.getAttribute("compare");
if (compare == null) compare = "Fragment";
compare = compare.toUpperCase();
Reader reader = null;
try {
reader = new BufferedReader(new FileReader(expectedResult));
if (result.isEmpty() && expectedResult.length() > 0)
return false;
int pos = 0;
for(SequenceIterator i = result.iterate(); i.hasNext(); ) {
Resource xmldbResource = getResource(i.nextItem());
// StringWriter writer = new StringWriter();
// Properties outputProperties = new Properties();
// outputProperties.setProperty("indent", "yes");
// SAXSerializer serializer = new SAXSerializer(writer, outputProperties);
// xmldbResource.getContentAsSAX(serializer);
String res = xmldbResource.getContent().toString();
int l;
//expected result length is only one result
if (result.getItemCount() == 1)
l = (int) expectedResult.length();
//caught-on length on last result
else if (!i.hasNext())
l = (int) expectedResult.length() - pos;
else
l = res.length();
l += fixResultLength(testCase);
int skipped = 0;
char[] chars = new char[l];
for (int x = 0; x < l; x++) {
if (!reader.ready()) {
skipped += l - x;
break;
}
chars[x] = (char)reader.read();
if (chars[x] == '\r') {
chars[x] = (char)reader.read();
pos++;
}
pos++;
}
if ( (result.getItemCount() == 1 || !i.hasNext() ) && skipped != 0) {
char[] oldChars = chars;
chars = new char[l-skipped];
System.arraycopy(oldChars, 0, chars, 0, l-skipped);
}
String expResult = String.copyValueOf(chars);
boolean ok = false;
if (compare.equals("XML")) {
try {
ok = diffXML(expResult, res);
} catch (Exception e) {
}
}
if (!ok) {
if (!expResult.equals(res))
if (compare.equals("FRAGMENT") || compare.equals("INSPECT")) {
try {
ok = diffXML(expResult, res);
} catch (Exception e) {
}
if (!ok) {
//workaround problematic results
if (expResult.equals("<?pi ?>") && (res.equals("<?pi?>")))
;
else
return false;
}
} else {
//workaround problematic results
if (expResult.equals("&") && res.equals("&"))
;
else if (expResult.equals("<") && res.equals("<"))
;
else {
//last try
expResult = expResult.replaceAll("<","<");
expResult = expResult.replaceAll(">",">");
expResult = expResult.replaceAll("&","&");
if (!expResult.equals(res))
return false;
}
}
if ((compare.equals("TEXT") || compare.equals("FRAGMENT")) && (i.hasNext())) {
reader.mark(1);
if (' ' != (char)reader.read())
reader.reset();
else
pos++;
}
}
}
} catch (Exception e) {
return false;
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
return true;
}
public int fixResultLength(String testCase) {
return 0;
}
private boolean diffXML(String expResult, String res) throws SAXException, IOException {
res = res.replaceAll("\n", "");
res = res.replaceAll("\t", "");
expResult = expResult.replaceAll("\n", "");
expResult = expResult.replaceAll("\t", "");
Diff diff = new Diff(expResult.trim(), res);
if (!diff.identical()) {
System.out.println("expected:");
System.out.println(expResult);
System.out.println("get:");
System.out.println(res);
System.out.println(diff.toString());
return false;
}
return true;
}
public final static String NORMALIZE_HTML = "normalize-html";
protected final static Properties defaultProperties = new Properties();
static {
defaultProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
defaultProperties.setProperty(OutputKeys.INDENT, "no");
defaultProperties.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes");
defaultProperties.setProperty(EXistOutputKeys.PROCESS_XSL_PI, "no");
defaultProperties.setProperty(NORMALIZE_HTML, "yes");
}
public Resource getResource(Object r) throws XMLDBException {
LocalCollection collection = null;
Subject user = null;
LocalXMLResource res = null;
if (r instanceof NodeProxy) {
NodeProxy p = (NodeProxy) r;
res = new LocalXMLResource(user, pool, collection, p);
} else if (r instanceof Node) {
res = new LocalXMLResource(user, pool, collection, XmldbURI.EMPTY_URI);
res.setContentAsDOM((Node)r);
} else if (r instanceof AtomicValue) {
res = new LocalXMLResource(user, pool, collection, XmldbURI.EMPTY_URI);
res.setContent(r);
} else if (r instanceof LocalXMLResource)
res = (LocalXMLResource) r;
else
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "unknown object "+r.getClass());
try {
Field field = res.getClass().getDeclaredField("outputProperties");
field.setAccessible(true);
field.set(res, new Properties(defaultProperties));
} catch (Exception e) {
}
return res;
}
public NodeImpl loadVarFromURI(XQueryContext context, String uri) throws IOException {
SAXAdapter adapter = new SAXAdapter(context);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xr;
try {
SAXParser parser = factory.newSAXParser();
xr = parser.getXMLReader();
xr.setContentHandler(adapter);
xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
} catch (Exception e) {
throw new IOException(e);
}
try {
// URL url = new URL(uri);
// InputStreamReader isr = new InputStreamReader(url.openStream(), "UTF-8");
InputStreamReader isr = new InputStreamReader(new FileInputStream(uri), "UTF-8");
InputSource src = new InputSource(isr);
xr.parse(src);
isr.close();
adapter.getDocument().setDocumentURI(new File(uri).getAbsoluteFile().toString());
return (NodeImpl) adapter.getDocument();
} catch (SAXException e) {
//workaround BOM
if (e.getMessage().equals("Content is not allowed in prolog.")) {
try {
String xml = readFileAsString(new File(uri));
xml = xml.trim().replaceFirst("^([\\W]+)<","<");
InputSource src = new InputSource(new StringReader(xml));
xr.parse(src);
adapter.getDocument().setDocumentURI(new File(uri).getAbsoluteFile().toString());
return (NodeImpl) adapter.getDocument();
} catch (SAXException e1) {
throw new IOException(e);
}
}
throw new IOException(e);
}
}
public NodeImpl loadVarFromString(XQueryContext context, String source) throws IOException {
SAXAdapter adapter = new SAXAdapter(context);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xr;
try {
SAXParser parser = factory.newSAXParser();
xr = parser.getXMLReader();
xr.setContentHandler(adapter);
xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
} catch (Exception e) {
throw new IOException(e);
}
try {
InputSource src = new InputSource(new StringReader(source));
xr.parse(src);
return (NodeImpl) adapter.getDocument();
} catch (SAXException e) {
throw new IOException(e);
}
}
public static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
try {
f.read(buffer);
return new String(buffer);
} finally {
f.close();
}
}
public static String readFileAsString(File file, long limit) throws IOException {
if (file.length() >= limit) return "DATA TOO BIG";
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
try {
f.read(buffer);
return new String(buffer);
} finally {
f.close();
}
}
public String sequenceToString(Sequence seq) {
StringBuilder res = new StringBuilder();
try {
for(SequenceIterator i = seq.iterate(); i.hasNext(); ) {
Resource resource = getResource(i.nextItem());
res.append(resource.getContent().toString());
if (i.hasNext()) res.append(" ");
//avoid to big output
if (res.length() >= 1024) return "{TOO BIG}";
}
} catch (Exception e) {
res.append(e.getMessage());
}
return res.toString();
}
}
| test/src/org/exist/w3c/tests/TestCase.java | /*
* eXist Open Source Native XML Database
* Copyright (C) 2010 The eXist Project
* http://exist-db.org
*
* This program 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
* 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
* $Id$
*/
package org.exist.w3c.tests;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.Properties;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.OutputKeys;
import junit.framework.Assert;
import org.custommonkey.xmlunit.Diff;
import org.exist.Namespaces;
import org.exist.dom.NodeProxy;
import org.exist.memtree.NodeImpl;
import org.exist.memtree.SAXAdapter;
import org.exist.security.Subject;
import org.exist.storage.BrokerPool;
import org.exist.storage.serializers.EXistOutputKeys;
import org.exist.xmldb.LocalCollection;
import org.exist.xmldb.LocalXMLResource;
import org.exist.xmldb.XmldbURI;
import org.exist.xquery.XQueryContext;
import org.exist.xquery.value.AtomicValue;
import org.exist.xquery.value.Sequence;
import org.exist.xquery.value.SequenceIterator;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xmldb.api.DatabaseManager;
import org.xmldb.api.base.Collection;
import org.xmldb.api.base.ErrorCodes;
import org.xmldb.api.base.Resource;
import org.xmldb.api.base.XMLDBException;
/**
* @author <a href="mailto:[email protected]">Dmitriy Shabanov</a>
*
*/
public abstract class TestCase {
public static org.exist.start.Main database = null;
private static int inUse = 0;
public static Collection testCollection = null;
public static BrokerPool pool = null;
private static Thread shutdowner = null;
public static final String testLocation = "test/external/";
static class Shutdowner implements Runnable {
public void run() {
try {
while (true) {
Thread.sleep(10 * 1000);
if (inUse == 0) {
//double check
Thread.sleep(10 * 1000);
if (inUse == 0) {
database.shutdown();
System.out.println("database was shutdown");
database = null;
}
}
}
} catch (InterruptedException e) {
}
}
}
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("setUpBeforeClass ENTERED");
try {
if (database == null) {
System.out.println("Start up database...");
database = new org.exist.start.Main("jetty");
database.run(new String[] { "jetty" });
// testCollection = DatabaseManager.getCollection("xmldb:exist:///db/XQTS", "admin", "");
if (shutdowner == null) {
shutdowner = new Thread(new Shutdowner());
shutdowner.start();
}
pool = BrokerPool.getInstance();
System.out.println("Database ready.");
}
synchronized (database) {
inUse++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("setUpBeforeClass PASSED");
}
public abstract void loadTS() throws Exception;
@AfterClass
public static void tearDownAfterClass() throws Exception {
synchronized (database) {
inUse--;
}
System.out.println("tearDownAfterClass PASSED");
}
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
synchronized (database) {
if (testCollection == null) {
loadTS();
testCollection = DatabaseManager.getCollection("xmldb:exist://"+getCollection(), "admin", "");
if (testCollection == null) {
Assert.fail("There is no Test Suite data at database");
}
}
}
}
protected abstract String getCollection();
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
// System.out.println("tearDown PASSED");
}
public Exception catchError(Sequence result) {
try {
for(SequenceIterator i = result.iterate(); i.hasNext(); ) {
Resource xmldbResource = getResource(i.nextItem());
xmldbResource.getContent().toString();
}
} catch (Exception e) {
return e;
}
return null;
}
public boolean compareResult(String testCase, String folder, Element outputFile, Sequence result) {
if (outputFile == null)
Assert.fail("no expected result information");
File expectedResult = new File(testLocation+folder, outputFile.getNodeValue());
if (!expectedResult.canRead()) Assert.fail("can't read expected result");
String compare = outputFile.getAttribute("compare");
if (compare == null) compare = "Fragment";
compare = compare.toUpperCase();
Reader reader = null;
try {
reader = new BufferedReader(new FileReader(expectedResult));
if (result.isEmpty() && expectedResult.length() > 0)
return false;
int pos = 0;
for(SequenceIterator i = result.iterate(); i.hasNext(); ) {
Resource xmldbResource = getResource(i.nextItem());
// StringWriter writer = new StringWriter();
// Properties outputProperties = new Properties();
// outputProperties.setProperty("indent", "yes");
// SAXSerializer serializer = new SAXSerializer(writer, outputProperties);
// xmldbResource.getContentAsSAX(serializer);
String res = xmldbResource.getContent().toString();
int l;
//expected result length is only one result
if (result.getItemCount() == 1)
l = (int) expectedResult.length();
//caught-on length on last result
else if (!i.hasNext())
l = (int) expectedResult.length() - pos;
else
l = res.length();
l += fixResultLength(testCase);
int skipped = 0;
char[] chars = new char[l];
for (int x = 0; x < l; x++) {
if (!reader.ready()) {
skipped += l - x;
break;
}
chars[x] = (char)reader.read();
if (chars[x] == '\r') {
chars[x] = (char)reader.read();
pos++;
}
pos++;
}
if ( (result.getItemCount() == 1 || !i.hasNext() ) && skipped != 0) {
char[] oldChars = chars;
chars = new char[l-skipped];
System.arraycopy(oldChars, 0, chars, 0, l-skipped);
}
String expResult = String.copyValueOf(chars);
boolean ok = false;
if (compare.equals("XML")) {
try {
ok = diffXML(expResult, res);
} catch (Exception e) {
}
}
if (!ok) {
if (!expResult.equals(res))
if (compare.equals("FRAGMENT") || compare.equals("INSPECT")) {
try {
ok = diffXML(expResult, res);
} catch (Exception e) {
}
if (!ok) {
//workaround problematic results
if (expResult.equals("<?pi ?>") && (res.equals("<?pi?>")))
;
else
return false;
}
} else {
//workaround problematic results
if (expResult.equals("&") && res.equals("&"))
;
else if (expResult.equals("<") && res.equals("<"))
;
else {
//last try
expResult = expResult.replaceAll("<","<");
expResult = expResult.replaceAll(">",">");
expResult = expResult.replaceAll("&","&");
if (!expResult.equals(res))
return false;
}
}
if ((compare.equals("TEXT") || compare.equals("FRAGMENT")) && (i.hasNext())) {
reader.mark(1);
if (' ' != (char)reader.read())
reader.reset();
else
pos++;
}
}
}
} catch (Exception e) {
return false;
} finally {
if (reader != null)
try {
reader.close();
} catch (IOException e) {
}
}
return true;
}
public int fixResultLength(String testCase) {
return 0;
}
private boolean diffXML(String expResult, String res) throws SAXException, IOException {
res = res.replaceAll("\n", "");
res = res.replaceAll("\t", "");
expResult = expResult.replaceAll("\n", "");
expResult = expResult.replaceAll("\t", "");
Diff diff = new Diff(expResult.trim(), res);
if (!diff.identical()) {
System.out.println("expected:");
System.out.println(expResult);
System.out.println("get:");
System.out.println(res);
System.out.println(diff.toString());
return false;
}
return true;
}
public final static String NORMALIZE_HTML = "normalize-html";
protected final static Properties defaultProperties = new Properties();
static {
defaultProperties.setProperty(OutputKeys.ENCODING, "UTF-8");
defaultProperties.setProperty(OutputKeys.INDENT, "no");
defaultProperties.setProperty(EXistOutputKeys.EXPAND_XINCLUDES, "yes");
defaultProperties.setProperty(EXistOutputKeys.PROCESS_XSL_PI, "no");
defaultProperties.setProperty(NORMALIZE_HTML, "yes");
}
public Resource getResource(Object r) throws XMLDBException {
LocalCollection collection = null;
Subject user = null;
LocalXMLResource res = null;
if (r instanceof NodeProxy) {
NodeProxy p = (NodeProxy) r;
res = new LocalXMLResource(user, pool, collection, p);
} else if (r instanceof Node) {
res = new LocalXMLResource(user, pool, collection, XmldbURI.EMPTY_URI);
res.setContentAsDOM((Node)r);
} else if (r instanceof AtomicValue) {
res = new LocalXMLResource(user, pool, collection, XmldbURI.EMPTY_URI);
res.setContent(r);
} else if (r instanceof LocalXMLResource)
res = (LocalXMLResource) r;
else
throw new XMLDBException(ErrorCodes.VENDOR_ERROR, "unknown object "+r.getClass());
try {
Field field = res.getClass().getDeclaredField("outputProperties");
field.setAccessible(true);
field.set(res, new Properties(defaultProperties));
} catch (Exception e) {
}
return res;
}
public NodeImpl loadVarFromURI(XQueryContext context, String uri) throws IOException {
SAXAdapter adapter = new SAXAdapter(context);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xr;
try {
SAXParser parser = factory.newSAXParser();
xr = parser.getXMLReader();
xr.setContentHandler(adapter);
xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
} catch (Exception e) {
throw new IOException(e);
}
try {
// URL url = new URL(uri);
// InputStreamReader isr = new InputStreamReader(url.openStream(), "UTF-8");
InputStreamReader isr = new InputStreamReader(new FileInputStream(uri), "UTF-8");
InputSource src = new InputSource(isr);
xr.parse(src);
isr.close();
adapter.getDocument().setDocumentURI(new File(uri).getAbsoluteFile().toString());
return (NodeImpl) adapter.getDocument();
} catch (SAXException e) {
//workaround BOM
if (e.getMessage().equals("Content is not allowed in prolog.")) {
try {
String xml = readFileAsString(new File(uri));
xml = xml.trim().replaceFirst("^([\\W]+)<","<");
InputSource src = new InputSource(new StringReader(xml));
xr.parse(src);
adapter.getDocument().setDocumentURI(new File(uri).getAbsoluteFile().toString());
return (NodeImpl) adapter.getDocument();
} catch (SAXException e1) {
throw new IOException(e);
}
}
throw new IOException(e);
}
}
public NodeImpl loadVarFromString(XQueryContext context, String source) throws IOException {
SAXAdapter adapter = new SAXAdapter(context);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xr;
try {
SAXParser parser = factory.newSAXParser();
xr = parser.getXMLReader();
xr.setContentHandler(adapter);
xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter);
} catch (Exception e) {
throw new IOException(e);
}
try {
InputSource src = new InputSource(new StringReader(source));
xr.parse(src);
return (NodeImpl) adapter.getDocument();
} catch (SAXException e) {
throw new IOException(e);
}
}
public static String readFileAsString(File file) throws IOException {
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
try {
f.read(buffer);
return new String(buffer);
} finally {
f.close();
}
}
public static String readFileAsString(File file, long limit) throws IOException {
if (file.length() >= limit) return "DATA TOO BIG";
byte[] buffer = new byte[(int) file.length()];
FileInputStream f = new FileInputStream(file);
try {
f.read(buffer);
return new String(buffer);
} finally {
f.close();
}
}
public String sequenceToString(Sequence seq) {
StringBuilder res = new StringBuilder();
try {
for(SequenceIterator i = seq.iterate(); i.hasNext(); ) {
Resource resource = getResource(i.nextItem());
res.append(resource.getContent().toString());
if (i.hasNext()) res.append(" ");
//avoid to big output
if (res.length() >= 1024) return "{TOO BIG}";
}
} catch (Exception e) {
res.append(e.getMessage());
}
return res.toString();
}
}
| [ignore] add debug messages
svn path=/trunk/eXist/; revision=17378
| test/src/org/exist/w3c/tests/TestCase.java | [ignore] add debug messages | <ide><path>est/src/org/exist/w3c/tests/TestCase.java
<ide> */
<ide> @Before
<ide> public void setUp() throws Exception {
<add> System.out.println("setUp ENTERED");
<ide> synchronized (database) {
<ide> if (testCollection == null) {
<add> System.out.println("setUp no TS data");
<ide> loadTS();
<add> System.out.println("setUp checking TS data");
<ide> testCollection = DatabaseManager.getCollection("xmldb:exist://"+getCollection(), "admin", "");
<ide> if (testCollection == null) {
<ide> Assert.fail("There is no Test Suite data at database");
<ide> }
<ide> }
<ide> }
<add> System.out.println("setUp PASSED");
<ide> }
<ide>
<ide> protected abstract String getCollection(); |
|
Java | apache-2.0 | 05eb512f2f35a87dde359f2edd7d8a280159ba67 | 0 | orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb,orientechnologies/orientdb | package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.common.concur.OTimeoutException;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.sql.parser.OIdentifier;
import java.util.Map;
import java.util.Optional;
/**
* Returns the number of records contained in a class (including subclasses)
* Executes a count(*) on a class and returns a single record that contains that value (with a specific alias).
*
* Created by luigidellaquila on 17/03/17.
*/
public class CountFromClassStep extends AbstractExecutionStep {
private final OIdentifier target;
private final String alias;
private long cost = 0;
private boolean executed = false;
/**
*
* @param targetClass An identifier containing the name of the class to count
* @param alias the name of the property returned in the result-set
* @param ctx the query context
* @param profilingEnabled true to enable the profiling of the execution (for SQL PROFILE)
*/
public CountFromClassStep(OIdentifier targetClass, String alias, OCommandContext ctx, boolean profilingEnabled) {
super(ctx, profilingEnabled);
this.target = targetClass;
this.alias = alias;
}
@Override
public OResultSet syncPull(OCommandContext ctx, int nRecords) throws OTimeoutException {
getPrev().ifPresent(x -> x.syncPull(ctx, nRecords));
return new OResultSet() {
@Override
public boolean hasNext() {
return !executed;
}
@Override
public OResult next() {
if (executed) {
throw new IllegalStateException();
}
long begin = profilingEnabled ? System.nanoTime() : 0;
try {
OClass clazz = ctx.getDatabase().getClass(target.getStringValue());
long size = clazz.count();
executed = true;
OResultInternal result = new OResultInternal();
result.setProperty(alias, size);
return result;
} finally {
if(profilingEnabled){cost += (System.nanoTime() - begin);}
}
}
@Override
public void close() {
}
@Override
public Optional<OExecutionPlan> getExecutionPlan() {
return null;
}
@Override
public Map<String, Long> getQueryStats() {
return null;
}
@Override
public void reset() {
CountFromClassStep.this.reset();
}
};
}
@Override
public void reset() {
executed = false;
}
@Override
public String prettyPrint(int depth, int indent) {
String spaces = OExecutionStepInternal.getIndent(depth, indent);
String result = spaces + "+ CALCULATE CLASS SIZE: " + target;
if (profilingEnabled) {
result += " (" + getCostFormatted() + ")";
}
return result;
}
@Override
public long getCost() {
return cost;
}
}
| core/src/main/java/com/orientechnologies/orient/core/sql/executor/CountFromClassStep.java | package com.orientechnologies.orient.core.sql.executor;
import com.orientechnologies.common.concur.OTimeoutException;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.sql.parser.OIdentifier;
import java.util.Map;
import java.util.Optional;
/**
* Created by luigidellaquila on 17/03/17.
*/
public class CountFromClassStep extends AbstractExecutionStep {
private final OIdentifier target;
private final String alias;
private long cost = 0;
private boolean executed = false;
public CountFromClassStep(OIdentifier targetIndex, String alias, OCommandContext ctx, boolean profilingEnabled) {
super(ctx, profilingEnabled);
this.target = targetIndex;
this.alias = alias;
}
@Override
public OResultSet syncPull(OCommandContext ctx, int nRecords) throws OTimeoutException {
getPrev().ifPresent(x -> x.syncPull(ctx, nRecords));
return new OResultSet() {
@Override
public boolean hasNext() {
return !executed;
}
@Override
public OResult next() {
if (executed) {
throw new IllegalStateException();
}
long begin = profilingEnabled ? System.nanoTime() : 0;
try {
OClass clazz = ctx.getDatabase().getClass(target.getStringValue());
long size = clazz.count();
executed = true;
OResultInternal result = new OResultInternal();
result.setProperty(alias, size);
return result;
} finally {
if(profilingEnabled){cost += (System.nanoTime() - begin);}
}
}
@Override
public void close() {
}
@Override
public Optional<OExecutionPlan> getExecutionPlan() {
return null;
}
@Override
public Map<String, Long> getQueryStats() {
return null;
}
@Override
public void reset() {
CountFromClassStep.this.reset();
}
};
}
@Override
public void reset() {
executed = false;
}
@Override
public String prettyPrint(int depth, int indent) {
String spaces = OExecutionStepInternal.getIndent(depth, indent);
String result = spaces + "+ CALCULATE CLASS SIZE: " + target;
if (profilingEnabled) {
result += " (" + getCostFormatted() + ")";
}
return result;
}
@Override
public long getCost() {
return cost;
}
}
| Add javadoc to CountFromClassStep (SQL)
| core/src/main/java/com/orientechnologies/orient/core/sql/executor/CountFromClassStep.java | Add javadoc to CountFromClassStep (SQL) | <ide><path>ore/src/main/java/com/orientechnologies/orient/core/sql/executor/CountFromClassStep.java
<ide> import java.util.Optional;
<ide>
<ide> /**
<add> * Returns the number of records contained in a class (including subclasses)
<add> * Executes a count(*) on a class and returns a single record that contains that value (with a specific alias).
<add> *
<ide> * Created by luigidellaquila on 17/03/17.
<ide> */
<ide> public class CountFromClassStep extends AbstractExecutionStep {
<ide>
<ide> private boolean executed = false;
<ide>
<del> public CountFromClassStep(OIdentifier targetIndex, String alias, OCommandContext ctx, boolean profilingEnabled) {
<add> /**
<add> *
<add> * @param targetClass An identifier containing the name of the class to count
<add> * @param alias the name of the property returned in the result-set
<add> * @param ctx the query context
<add> * @param profilingEnabled true to enable the profiling of the execution (for SQL PROFILE)
<add> */
<add> public CountFromClassStep(OIdentifier targetClass, String alias, OCommandContext ctx, boolean profilingEnabled) {
<ide> super(ctx, profilingEnabled);
<del> this.target = targetIndex;
<add> this.target = targetClass;
<ide> this.alias = alias;
<ide> }
<ide> |
|
JavaScript | apache-2.0 | 1c6bcf308dfea17cbefbb39cb6223adb690a8c15 | 0 | SAP/openui5,SAP/openui5,SAP/openui5,SAP/openui5 | /*!
* ${copyright}
*/
// Provides control sap.f.ProductSwitchItem
sap.ui.define([
"sap/ui/core/Control",
"sap/ui/core/Icon",
"sap/ui/core/library",
"sap/m/Text",
"sap/ui/events/KeyCodes",
"sap/f/ProductSwitchItemRenderer"
],
function (
Control,
Icon,
library,
Text,
KeyCodes,
ProductSwitchItemRenderer
) {
"use strict";
// shortcut for sap.ui.core.TextAlign
var TextAlign = library.TextAlign;
/**
* Constructor for a new <code>ProductSwitchItem</code>.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* A control that is used as a child of <code>ProductSwitch</code>
*
* <b>Note:</b> <code>ProductSwitchItem</code> is not supported when used outside of <code>ProductSwitch</code>.
*
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version ${version}
*
* @constructor
* @public
* @experimental Since 1.72. This class is experimental and provides only limited functionality. Also the API might be changed in future.
* @alias sap.f.ProductSwitchItem
* @since 1.72
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ProductSwitchItem = Control.extend("sap.f.ProductSwitchItem", {
metadata: {
library: "sap.f",
properties: {
/**
* Defines the icon to be displayed as graphical element within the <code>ProductSwitchItem</code>.
* It can be an icon from the SAP icon font.
*/
src: { type: "sap.ui.core.URI", defaultValue: null },
/**
* Determines the title of the <code>ProductSwitchItem</code>.
*/
title: { type: "string", defaultValue: null },
/**
* Determines the subtitle of the <code>ProductSwitchItem</code>.
*/
subTitle: { type: "string", defaultValue: null },
/**
* Defines the <code>ProductSwitchItem</code> target URI. Supports standard hyperlink behavior.
*/
targetSrc: { type: "sap.ui.core.URI", group: "Data", defaultValue: null },
/**
* Specifies a target where the <code>targetSrc</code> content must be open.
*
* Options are the standard values for window.open() supported by browsers:
* <code>_self</code>, <code>_top</code>, <code>_blank</code>, <code>_parent</code>, <code>_search</code>.
* Alternatively, a frame name can be entered.
*/
target: { type: "string", group: "Behavior", defaultValue: null }
},
aggregations: {
/**
* Holds the internally created Icon.
*/
_icon: { type: "sap.ui.core.Icon", visibility: "hidden", multiple: false },
/**
* Holds the internally created Text.
*/
_title: { type: "sap.m.Text", visibility: "hidden", multiple: false }
}
}
});
ProductSwitchItem.prototype.init = function () {
this._bSpaceEnterPressed = false;
this._bEscapeShiftKeyPress = false;
};
ProductSwitchItem.prototype.setTitle = function (sTitle) {
this.setProperty("title", sTitle);
this._getTitle().setText(sTitle);
return this;
};
ProductSwitchItem.prototype.setSrc = function (sSrc) {
this.setProperty("src", sSrc);
this._getIcon().setSrc(sSrc);
return this;
};
ProductSwitchItem.prototype.setSubTitle = function (sSubTitle) {
this.setProperty("subTitle", sSubTitle);
this._getTitle().setMaxLines(sSubTitle ? 1 : 2);
return this;
};
/**
* Gets content of aggregation _icon.
* @returns {sap.ui.core.Icon}
* @private
*/
ProductSwitchItem.prototype._getIcon = function () {
var oIcon = this.getAggregation("_icon");
if (!oIcon) {
oIcon = new Icon();
if (this.getSrc()) {
oIcon.setSrc(this.getSrc());
}
this.setAggregation("_icon", oIcon);
}
return oIcon;
};
/**
* Gets content of aggregation _title.
* @returns {sap.m.Text}
* @private
*/
ProductSwitchItem.prototype._getTitle = function () {
var oText = this.getAggregation("_title");
if (!oText) {
oText = new Text({ text: this.getTitle(), maxLines: 2, textAlign: TextAlign.Initial })
.addStyleClass("sapFPSItemMainTitle")
.addStyleClass("sapFPSItemTitle");
this.setAggregation("_title", oText);
}
return oText;
};
/**
* Gets the parent ProductSwitch instance.
* @returns {sap.f.ProductSwitch}
* @private
*/
ProductSwitchItem.prototype._getProductSwitch = function () {
return this.getParent().getParent();
};
ProductSwitchItem.prototype.onkeyup = function (oEvent) {
if ((oEvent.keyCode === KeyCodes.SPACE && !this._bEscapeShiftKeyPress)) {
this.fireEvent("_itemPress");
}
if (oEvent.keyCode === KeyCodes.SPACE || oEvent.keyCode === KeyCodes.ENTER) {
this._bSpaceEnterPressed = false;
this._bEscapeShiftKeyPress = false;
}
};
ProductSwitchItem.prototype.ontap = function () {
this.fireEvent("_itemPress");
};
ProductSwitchItem.prototype.onkeydown = function (oEvent) {
if ((oEvent.keyCode === KeyCodes.ESCAPE || oEvent.keyCode === KeyCodes.SHIFT) && this._bSpaceEnterPressed) {
this._bEscapeShiftKeyPress = true;
}
if (oEvent.keyCode === KeyCodes.SPACE || oEvent.keyCode === KeyCodes.ENTER) {
this._bSpaceEnterPressed = true;
if (oEvent.keyCode === KeyCodes.ENTER && !this._bEscapeShiftKeyPress) {
this.fireEvent("_itemPress");
}
oEvent.preventDefault();
}
};
return ProductSwitchItem;
});
| src/sap.f/src/sap/f/ProductSwitchItem.js | /*!
* ${copyright}
*/
// Provides control sap.f.ProductSwitchItem
sap.ui.define([
"sap/ui/core/Control",
"sap/ui/core/Icon",
"sap/ui/core/library",
"sap/m/Text",
"sap/ui/events/KeyCodes",
"sap/f/ProductSwitchItemRenderer"
],
function (
Control,
Icon,
library,
Text,
KeyCodes,
ProductSwitchItemRenderer
) {
"use strict";
// shortcut for sap.ui.core.TextAlign
var TextAlign = library.TextAlign;
/**
* Constructor for a new <code>ProductSwitchItem</code>.
*
* @param {string} [sId] ID for the new control, generated automatically if no ID is given
* @param {object} [mSettings] Initial settings for the new control
*
* @class
* A control that is used as a child of <code>ProductSwitch</code>
*
* <b>Note:</b> <code>ProductSwitchItem</code> is not supported when used outside of <code>ProductSwitch</code>.
*
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version ${version}
*
* @constructor
* @public
* @experimental Since 1.72. This class is experimental and provides only limited functionality. Also the API might be changed in future.
* @alias sap.f.ProductSwitchItem
* @since 1.72
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var ProductSwitchItem = Control.extend("sap.f.ProductSwitchItem", {
metadata: {
library: "sap.f",
properties: {
/**
* Defines the icon to be displayed as graphical element within the <code>ProductSwitchItem</code>.
* It can be an image or an icon from the SAP icon font.
*/
src: { type: "sap.ui.core.URI", defaultValue: null },
/**
* Determines the title of the <code>ProductSwitchItem</code>.
*/
title: { type: "string", defaultValue: null },
/**
* Determines the subtitle of the <code>ProductSwitchItem</code>.
*/
subTitle: { type: "string", defaultValue: null },
/**
* Defines the <code>ProductSwitchItem</code> target URI. Supports standard hyperlink behavior.
*/
targetSrc: { type: "sap.ui.core.URI", group: "Data", defaultValue: null },
/**
* Specifies a target where the <code>targetSrc</code> content must be open.
*
* Options are the standard values for window.open() supported by browsers:
* <code>_self</code>, <code>_top</code>, <code>_blank</code>, <code>_parent</code>, <code>_search</code>.
* Alternatively, a frame name can be entered.
*/
target: { type: "string", group: "Behavior", defaultValue: null }
},
aggregations: {
/**
* Holds the internally created Icon.
*/
_icon: { type: "sap.ui.core.Icon", visibility: "hidden", multiple: false },
/**
* Holds the internally created Text.
*/
_title: { type: "sap.m.Text", visibility: "hidden", multiple: false }
}
}
});
ProductSwitchItem.prototype.init = function () {
this._bSpaceEnterPressed = false;
this._bEscapeShiftKeyPress = false;
};
ProductSwitchItem.prototype.setTitle = function (sTitle) {
this.setProperty("title", sTitle);
this._getTitle().setText(sTitle);
return this;
};
ProductSwitchItem.prototype.setSrc = function (sSrc) {
this.setProperty("src", sSrc);
this._getIcon().setSrc(sSrc);
return this;
};
ProductSwitchItem.prototype.setSubTitle = function (sSubTitle) {
this.setProperty("subTitle", sSubTitle);
this._getTitle().setMaxLines(sSubTitle ? 1 : 2);
return this;
};
/**
* Gets content of aggregation _icon.
* @returns {sap.ui.core.Icon}
* @private
*/
ProductSwitchItem.prototype._getIcon = function () {
var oIcon = this.getAggregation("_icon");
if (!oIcon) {
oIcon = new Icon();
if (this.getSrc()) {
oIcon.setSrc(this.getSrc());
}
this.setAggregation("_icon", oIcon);
}
return oIcon;
};
/**
* Gets content of aggregation _title.
* @returns {sap.m.Text}
* @private
*/
ProductSwitchItem.prototype._getTitle = function () {
var oText = this.getAggregation("_title");
if (!oText) {
oText = new Text({ text: this.getTitle(), maxLines: 2, textAlign: TextAlign.Initial })
.addStyleClass("sapFPSItemMainTitle")
.addStyleClass("sapFPSItemTitle");
this.setAggregation("_title", oText);
}
return oText;
};
/**
* Gets the parent ProductSwitch instance.
* @returns {sap.f.ProductSwitch}
* @private
*/
ProductSwitchItem.prototype._getProductSwitch = function () {
return this.getParent().getParent();
};
ProductSwitchItem.prototype.onkeyup = function (oEvent) {
if ((oEvent.keyCode === KeyCodes.SPACE && !this._bEscapeShiftKeyPress)) {
this.fireEvent("_itemPress");
}
if (oEvent.keyCode === KeyCodes.SPACE || oEvent.keyCode === KeyCodes.ENTER) {
this._bSpaceEnterPressed = false;
this._bEscapeShiftKeyPress = false;
}
};
ProductSwitchItem.prototype.ontap = function () {
this.fireEvent("_itemPress");
};
ProductSwitchItem.prototype.onkeydown = function (oEvent) {
if ((oEvent.keyCode === KeyCodes.ESCAPE || oEvent.keyCode === KeyCodes.SHIFT) && this._bSpaceEnterPressed) {
this._bEscapeShiftKeyPress = true;
}
if (oEvent.keyCode === KeyCodes.SPACE || oEvent.keyCode === KeyCodes.ENTER) {
this._bSpaceEnterPressed = true;
if (oEvent.keyCode === KeyCodes.ENTER && !this._bEscapeShiftKeyPress) {
this.fireEvent("_itemPress");
}
oEvent.preventDefault();
}
};
return ProductSwitchItem;
});
| [FIX] sap.f.ProductSwitchItem: Documentation for 'src' property is updated
Problem: In the documentation for the 'src' property, we were stating that
we support icons as well as images. The sap.f.ProductSwitchItem is not
supposed to have images by design.
Solution: In the documentation for the 'src' property, we are now stating
that we support icons only.
Change-Id: I5895216375d8ca964c4ff18963774d25cfe5e370
BCP: 2170022736
Fixes: https://github.com/SAP/openui5/issues/3188
| src/sap.f/src/sap/f/ProductSwitchItem.js | [FIX] sap.f.ProductSwitchItem: Documentation for 'src' property is updated | <ide><path>rc/sap.f/src/sap/f/ProductSwitchItem.js
<ide> properties: {
<ide> /**
<ide> * Defines the icon to be displayed as graphical element within the <code>ProductSwitchItem</code>.
<del> * It can be an image or an icon from the SAP icon font.
<add> * It can be an icon from the SAP icon font.
<ide> */
<ide> src: { type: "sap.ui.core.URI", defaultValue: null },
<ide> /** |
|
Java | mit | 6a42468381f129d284a6d3a808f3b218381fbda6 | 0 | JCPedroza/XochiJava | import java.util.Arrays;
public class main{
public static void main(String args[]){
Sound aSound = new Sound(440.03, 60, 1, 1, 127, 1);
Note aNote = new Note("A", 440.00, 60, 1, 1, 127, 1);
Formulas aFormula = new Formulas();
System.out.println(aSound.getFrequency());
System.out.println(aNote.getName());
System.out.println(Arrays.toString(aFormula.pentmin));
}
} | main.java | public class main{
public static void main(String args[]){
System.out.println("test");
}
} | tests for Formulas ans Note
| main.java | tests for Formulas ans Note | <ide><path>ain.java
<add>import java.util.Arrays;
<add>
<ide> public class main{
<ide>
<ide> public static void main(String args[]){
<del> System.out.println("test");
<add> Sound aSound = new Sound(440.03, 60, 1, 1, 127, 1);
<add> Note aNote = new Note("A", 440.00, 60, 1, 1, 127, 1);
<add> Formulas aFormula = new Formulas();
<add>
<add> System.out.println(aSound.getFrequency());
<add> System.out.println(aNote.getName());
<add> System.out.println(Arrays.toString(aFormula.pentmin));
<ide> }
<ide> } |
|
JavaScript | mit | 1aebe875e9d5292f9a8ec561546159eec9a6c776 | 0 | mirceaalexandru/seneca-auth,rjrodger/seneca-auth,senecajs/seneca-auth | /* Copyright (c) 2012-2014 Richard Rodger, MIT License */
"use strict";
var util = require('util')
var _ = require('underscore')
var async = require('async')
var S = require('string')
var gex = require('gex')
var Cookies = require('cookies')
var passport = require('passport')
var seneca_auth_token
= require('seneca-auth-token-cookie')
var seneca_auth_redirect
= require('seneca-auth-redirect')
var localAuth = require('seneca-local-auth')
var default_options
= require('./default-options.js')
var error = require('eraro')({
package: 'auth'
})
module.exports = function auth( options ) {
var seneca = this
var plugin = 'auth'
seneca.depends(plugin,['web','user'])
// using seneca.util.deepextend here, as there are sub properties
options = seneca.util.deepextend( default_options, options )
function migrateOptions(){
if (options.service){
throw error('<service> option is no longer supported, please check seneca-auth documentation for migrating to new version of seneca-auth')
}
if (options.sendemail){
throw error('<sendemail> option is no longer supported, please check seneca-auth documentation for migrating to new version of seneca-auth')
}
if (options.email){
throw error('<email> option is no longer supported, please check seneca-auth documentation for migrating to new version of seneca-auth')
}
}
migrateOptions()
loadDefaultPlugins()
var m
if( (m = options.prefix.match(/^(.*)\/+$/)) ) {
options.prefix = m[1]
}
_.each(options.urlpath,function(v,k){
options.urlpath[k] = '/'==v[0] ? v : options.prefix+'/'+v
})
// define seneca actions
seneca.add({ role:plugin, wrap:'user' }, wrap_user)
seneca.add({ init:plugin }, init)
seneca.add({role:plugin,cmd:'register'}, cmd_register)
seneca.add({role:plugin,cmd:'instance'}, cmd_instance)
seneca.add({role:plugin,cmd:'clean'}, cmd_clean)
seneca.add({role:plugin,cmd:'create_reset'}, cmd_create_reset)
seneca.add({role:plugin,cmd:'load_reset'}, cmd_load_reset)
seneca.add({role:plugin,cmd:'execute_reset'}, cmd_execute_reset)
seneca.add({role:plugin,cmd:'confirm'}, cmd_confirm)
seneca.add({role:plugin,cmd:'update_user'}, cmd_update_user)
seneca.add({role:plugin,cmd:'change_password'},cmd_change_password)
seneca.add({role: plugin, cmd:'login'}, cmd_login)
seneca.add({role: plugin, cmd:'logout'}, cmd_logout)
seneca.add({role: plugin, cmd:'register_service' },
cmd_register_service)
seneca.add({role: plugin, cmd: 'mapFields'}, aliasfields)
function loadDefaultPlugins(){
seneca.use(seneca_auth_token)
seneca.use(seneca_auth_redirect, options.redirect || {})
}
function urlmatcher( spec ) {
spec = _.isArray(spec) ? spec : [spec]
var checks = []
_.each(spec,function(path){
if( _.isFunction(path) ) return checks.push(path);
if( _.isRegExp(path) ) return checks.push( function(req) { return path.test(req.url) } );
if( !_.isString(path) ) return;
path = ~path.indexOf(':') ? path : 'prefix:'+path
var parts = path.split(':')
var kind = parts[0]
var spec = parts.slice(1)
function regex() {
var pat = spec, mod = '', re
var m = /^\/(.*)\/([^\/]*)$/.exec(spec)
if(m) {
pat = m[1]
mod = m[2]
re = new RegExp(pat,mod)
return function(req){return re.test(req.url)}
}
else return function(){return false};
}
var pass = {
prefix: function(req) { return gex(spec+'*').on(req.url) },
suffix: function(req) { return gex('*'+spec).on(req.url) },
contains: function(req) { return gex('*'+spec+'*').on(req.url) },
gex: function(req) { return gex(spec).on(req.url) },
exact: function(req) { return spec === req.url },
regex: regex()
}
pass.re = pass.regexp = pass.regex
checks.push(pass[kind])
})
return checks
}
function checkurl( match ) {
var checks = urlmatcher( match )
return function(req) {
for( var i = 0; i < checks.length; i++ ) {
if( checks[i](req) ) {
return true
}
}
return false
}
}
var exclude_url = checkurl(options.exclude)
var include_url = checkurl(options.include)
var userent = seneca.make$('sys/user')
passport.serializeUser(function(user, done) {
done(null, user.user.id);
})
passport.deserializeUser(function(id, done) {
done(null)
})
// default service login trigger
function trigger_service_login( args, done ) {
var seneca = this
if (!args.user){
return done( null, {ok: false, why: 'no-user'} )
}
var userData = args.user
var q = {}
if( userData.identifier ) {
q[ args.service + '_id' ] = userData.identifier
}
else {
return done( null, {ok: false, why: 'no-identifier'} )
}
userent.load$(q,function(err,user){
if( err ) return done( null, {ok: false, why: 'no-identifier'} );
if( !user ) {
seneca.act(_.extend({role:'user',cmd:'register'}, userData), function(err,out){
if( err ) {
return done( null, {ok: false, why: err} )
}
done( null, out.user )
})
}
else {
user.data$( seneca.util.deepextend( user.data$(), userData) )
user.save$( done )
}
})
}
function cmd_register_service(args, cb) {
seneca.log.info('registering auth service [' + args.service + ']')
passport.use(args.service, args.plugin)
registerService(args.service, args.conf)
cb()
}
function registerService(service, conf){
seneca.add({role: plugin, cmd: 'auth-' + service}, _login_service.bind(this, service))
seneca.add({role: plugin, cmd: 'auth-' + service + '-callback'}, _service_callback.bind(this, service))
var map = {}
map['auth-' + service] = {GET: true, POST: true, alias: '/' + service, responder: _blank_responder}
map['auth-' + service + '-callback'] = {GET: true, POST: true, alias: '/' + service + '/callback'}
seneca.act({
role:'web',
plugin:plugin,
config:config,
use:{
prefix:options.prefix,
pin:{role:plugin,cmd:'*'},
map: map
}
})
seneca.add({ role:plugin, trigger:'service-login-' + service }, trigger_service_login)
configureServices(service, conf)
}
function wrap_user( args, done ) {
this.act({
role:'util',
cmd:'ensure_entity',
pin:args.pin,
entmap:{
user:userent
}
})
this.wrap(args.pin, function( args, done ){
args.user = args.user || (args.req$ && args.req$.seneca && args.req$.seneca.user ) || null
this.parent(args,done)
})
done()
}
function aliasfields(userData, cb){
var data = userData.data
data.nick =
data.nick ?
data.nick :
data.username ?
data.username :
data.email
return cb(null, data)
}
function cmd_register( args, done ) {
var seneca = this
seneca.act({role: plugin, cmd: 'mapFields', action: 'register', data: args.data}, function(err, details){
var req = args.req$
var res = args.res$
seneca.act(_.extend({role:'user',cmd:'register'}, details), function( err, out ){
if( err || !out.ok ) {
return done( err, out );
}
seneca.act(_.extend({role:'user',cmd:'login'}, { nick:out.user.nick, auto:true }), function( err, out ){
if( err || !out.ok ) {
return done( err, out );
}
if( req && req.seneca ) {
req.seneca.user = out.user
req.seneca.login = out.login
if( res ) {
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, token: req.seneca.login.id, req: req, res: res}, function(err){
return done(null, {
ok: out.ok,
user: out.user,
login: out.login
})
})
}
}
else{
done(null, {
ok: out.ok,
user: out.user,
login: out.login
})
}
})
})
})
}
function cmd_create_reset( args, done ) {
seneca.act({role: plugin, cmd: 'mapFields', action: 'create_reset', data: args.data}, function(err, userData){
var nick = userData.nick
var email = userData.email
var args = {}
if( void 0 != nick ) args.nick = nick;
if( void 0 != email ) args.email = email;
seneca.act(_.extend({role:'user',cmd:'create_reset'}, args), done)
})
}
function cmd_load_reset( args, done ) {
var token = args.data.token
seneca.act({role:'user',cmd:'load_reset', token:token}, function( err, out ) {
if( err || !out.ok ) {
return done( err, out );
}
return done(null, {
ok: out.ok,
nick: out.user.nick
})
})
}
function cmd_execute_reset( args, done ) {
var token = args.data.token
var password = args.data.password
var repeat = args.data.repeat
seneca.act({role:'user',cmd:'execute_reset', token:token, password:password, repeat:repeat}, done)
}
function cmd_confirm( args, done ) {
var code = args.data.code
seneca.act({role:'user',cmd:'confirm', code:code}, done)
}
function cmd_update_user( args, done ) {
seneca.act({role: plugin, cmd: 'mapFields', action: 'update', data: args.data}, function(err, userData){
seneca.act(_.extend({role:'user',cmd:'update'}, userData), done)
})
}
function cmd_change_password( args, done ) {
var user = args.user
seneca.act({role:'user',cmd:'change_password', user:user, password:args.data.password, repeat:args.data.repeat }, done )
}
function cmd_instance( args, done ) {
var seneca = this
var user = args.user
var login = args.login
seneca.act({ role:plugin, cmd:'clean', user:user, login:login}, function( err, out ){
if( err ) {
return done( err );
}
out.ok = true
out = seneca.util.clean( out )
return done( null, out )
})
}
function cmd_clean( args, done ) {
var seneca = this
var user = args.user && seneca.util.clean( args.user.data$() ) || null
var login = args.login && seneca.util.clean( args.login.data$() ) || null
if( user ) {
delete user.pass
delete user.salt
delete user.active
delete user.accounts
delete user.confirmcode
}
return done(null,{ user:user, login:login })
}
var pp_auth = {}
function configureServices(service, conf){
conf = conf || {}
var func = null
pp_auth[service] = function( req, res, next ){
if (service != 'local') {
func = function (err, user, info) {
seneca.act(_.extend({},{role: 'auth', trigger: 'service-login-' + service, service: service, user: user}),
function (err, user) {
if (err) {
return afterlogin( err, next, req, res );
}
seneca.act({role: 'user', cmd: 'login', nick: user.nick, auto: true}, function (err, out) {
req.user = out
afterlogin( err, next, req, res )
})
}
)
}
}
passport.authenticate(service, conf, func)(req, res, next)
}
}
function buildservice() {
var pp_init = passport.initialize()
function init_session( req, res, cb ) {
seneca.act({role: 'auth', get: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(err, result){
var token
if (result){
token = result.token
}
// var token = req.seneca.cookies.get( options.tokenkey )
if( token ) {
seneca.act({role:'user',cmd:'auth', token:token}, function(err, out){
if( err ) {
return cb(err);
}
if( out.ok ) {
req.user = {user:out.user,login:out.login}
req.seneca.user = out.user
req.seneca.login = out.login
return cb();
}
else {
// dead login - get rid of the token
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(){
return cb();
})
}
})
}
else {
return cb();
}
})
}
var restriction = (function(){
if( _.isFunction(options.restrict) ) return options.restrict;
var checks = urlmatcher(options.restrict)
return function( req, res, next ) {
for( var cI = 0; cI < checks.length; cI++ ) {
var restrict = checks[cI](req)
if( restrict && !(req.seneca && req.seneca.user) ) {
var redirect = false
var ct = (req.headers['content-type']||'').split(';')[0]
if( 'application/json' == ct ) {
redirect = false
}
else redirect = true;
if( redirect ) {
return next(null, {http$: {status: 302,redirect:options.redirect.restrict}})
}
else {
return next(null, { ok:false, why:'restricted', http$: {status: 401} })
}
break;
}
}
if( cI == checks.length ) next();
}
})();
return function(req,res,next){
if( exclude_url(req) && !include_url(req) ) {
return next()
}
if (!req.seneca){
return next('Cannot process, seneca-web dependency problem');
}
req.seneca.cookies = new Cookies(req,res)
pp_init( req, res, function(err){
if( err) {
return next(err);
}
init_session( req, res, function(err){
if( err) {
return next(err);
}
restriction( req, res, function(err){
if( err) {
return next(err);
}
})
next()
})
})
}
}
function init( args, done ) {
done()
}
function authcontext( req, res, args, act, respond ) {
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: args.cmd}, function(err, redirect){
var user = req.seneca && req.seneca.user
if( user ) {
args.user = user
}
var login = req.seneca && req.seneca.login
if( login ) {
args.login = login
}
act(args,function( err, out ){
if( err ) {
seneca.log.debug(err)
out = out || {}
out.http$ = {
status: 400,
redirect: redirect && redirect.fail
}
return respond(null, out);
}
out.http$ = {
status: out.ok ? 200 : 400,
redirect: redirect && redirect.win
}
respond(null,out)
})
})
}
var config = {prefix:options.prefix,redirects:{}}
if( options.defaultpages ) {
_.each(options.loginpages, function(loginpage){
config.redirects[loginpage.path]={redirect:loginpage.redirect,title:loginpage.title}
})
}
//LOGIN START
function afterlogin( err, next, req, res ) {
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(redirectErr, redirect){
// req.user actually == {ok:,user:,login:}
if( err && !err.why ) {
return next(null, {http$: {status: 301,redirect:redirect.fail}})
}
if( req.user && req.user.ok ) {
// rename passport req.user prop
req.seneca.user = req.user.user
req.seneca.login = req.user.login
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, token: req.seneca.login.id, req: req, res: res}, function(){
return do_respond(null, redirect, next)
})
}
else {
//var out = {ok:false,why:(req.user&&req.user.why)||'no-user'}
//delete req.user
var out = { ok:false, why: (err ? err.why : 'Unknown error') }
if( redirect ) {
req.seneca.log.debug( 'redirect', 'login', 'fail', redirect.fail )
return next(null, {http$: {status: 301,redirect:redirect.fail}})
}
else {
return next(null, out)
}
}
})
function do_respond(err, redirect, cb) {
if( err) {
return cb(null, {http$: { status: 302 } })
}
if( redirect ) {
req.seneca.log.debug( 'redirect', 'login', 'win', redirect.win )
return cb(null, {http$: {status: 301,redirect:redirect.win}})
}
else {
// FIX: this should call instance
// FIX: how to handle errors here?
seneca.act({role:plugin, cmd:'clean', user:req.seneca.user, login:req.seneca.login},function(err, out){
out.ok = true
return cb(null, out)
})
}
}
}
function cmd_login(args, cb) {
var req = args.req$
var res = args.res$
req.query = _.extend( {}, req.query || {}, req.body || {} )
seneca.act({role: plugin, cmd: 'mapFields', action: 'login', data: args.data}, function(err, userData){
req.query.username =
req.query.username ?
req.query.username :
(
req.query.nick ?
req.query.nick :
(
userData.username ?
userData.username :
userData.nick
)
)
pp_auth.local(req, res, function (loginerr, out) {
if (loginerr){
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(err, redirect){
if ( redirect ){
return cb(null, { http$: { status: 301, redirect:redirect.fail }})
}else{
return cb(null, { http$: { status: 401 }, ok: false, why: loginerr})
}
})
}
else{
afterlogin(err, cb, req, res)
}
})
})
}
//LOGIN END
f
//LOGOUT START
function cmd_logout(args, cb) {
var req = args.req$
var res = args.res$
// get token from request
seneca.act({role: 'auth', get: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(err, clienttoken){
clienttoken = clienttoken.token
// delete token
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(){
var servertoken
if( req.seneca ) {
servertoken = req.seneca.login && req.seneca.login.token
delete req.seneca.user
delete req.seneca.login
}
var token = clienttoken || servertoken || ''
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'logout'}, function(err, redirect){
seneca.act({role:'user',cmd:'logout', token: token}, function(err) {
if( err ) {
seneca.log('error',err)
if (redirect){
return cb(null, {http$: {status: 301,redirect:redirect.fail}})
}
else{
return cb(null, { ok: false, why: err } )
}
}
try {
req.logout()
} catch(err) {
seneca.log('error',err)
if (redirect){
return cb(null, {http$: {status: 301,redirect:redirect.fail}})
}
else{
return cb(null, { ok: false, why: err } )
}
}
if (redirect){
return cb(null, { http$: { status: 301,redirect: redirect.win } } )
}
else{
return cb(null, { ok: true } )
}
})
})
})
})
}
//LOGOUT END
// seneca web endpoints map
var map = {
login: { POST: true, GET: true, data: true, alias: options.urlpath.login },
logout: { POST: true, GET: true, data: true, alias: options.urlpath.logout },
register: { POST:authcontext, data:true, alias: options.urlpath.register },
instance: { GET: authcontext, alias: options.urlpath.instance},
create_reset: { POST:authcontext, data:true, alias: options.urlpath.create_reset },
load_reset: { POST:authcontext, data:true, alias: options.urlpath.load_reset },
execute_reset: { POST:authcontext, data:true, alias: options.urlpath.execute_reset },
confirm: { POST:authcontext, data:true, alias: options.urlpath.confirm },
update_user: { POST:authcontext, data:true, alias: options.urlpath.update_user },
change_password: { POST:authcontext, data:true, alias: options.urlpath.change_password }
}
var _login_service = function (service, args, next) {
var req = args.req$
var res = args.res$
pp_auth[service](req, res, function (err) {
})
next()
}
var _blank_responder = function( req, res, err, out ){
// no need to do anything here as all response data is set by passport strategy
}
var _service_callback = function (service, args, next) {
var req = args.req$
var res = args.res$
pp_auth[service](req, res, function (err) {
if (err) {
return next(err);
}
afterlogin(err, next, req, res)
})
}
seneca.act({
role:'web',
plugin:plugin,
config:config,
use:{
prefix:options.prefix,
pin:{role:plugin,cmd:'*'},
startware:buildservice(),
map: map
}
})
return {
name:plugin
}
}
| auth.js | /* Copyright (c) 2012-2014 Richard Rodger, MIT License */
"use strict";
var util = require('util')
var _ = require('underscore')
var async = require('async')
var S = require('string')
var gex = require('gex')
var Cookies = require('cookies')
var passport = require('passport')
var seneca_auth_token
= require('seneca-auth-token-cookie')
var seneca_auth_redirect
= require('seneca-auth-redirect')
var localAuth = require('seneca-local-auth')
var default_options
= require('./default-options.js')
var error = require('eraro')({
package: 'auth'
})
module.exports = function auth( options ) {
var seneca = this
var plugin = 'auth'
seneca.depends(plugin,['web','user'])
// using seneca.util.deepextend here, as there are sub properties
options = seneca.util.deepextend( default_options, options )
function migrateOptions(){
if (options.service){
throw error('<service> option is no longer supported, please check seneca-auth documentation for migrating to new version of seneca-auth')
}
if (options.sendemail){
throw error('<sendemail> option is no longer supported, please check seneca-auth documentation for migrating to new version of seneca-auth')
}
if (options.email){
throw error('<email> option is no longer supported, please check seneca-auth documentation for migrating to new version of seneca-auth')
}
}
migrateOptions()
loadDefaultPlugins()
var m
if( (m = options.prefix.match(/^(.*)\/+$/)) ) {
options.prefix = m[1]
}
_.each(options.urlpath,function(v,k){
options.urlpath[k] = '/'==v[0] ? v : options.prefix+'/'+v
})
// define seneca actions
seneca.add({ role:plugin, wrap:'user' }, wrap_user)
seneca.add({ init:plugin }, init)
seneca.add({role:plugin,cmd:'register'}, cmd_register)
seneca.add({role:plugin,cmd:'instance'}, cmd_instance)
seneca.add({role:plugin,cmd:'clean'}, cmd_clean)
seneca.add({role:plugin,cmd:'create_reset'}, cmd_create_reset)
seneca.add({role:plugin,cmd:'load_reset'}, cmd_load_reset)
seneca.add({role:plugin,cmd:'execute_reset'}, cmd_execute_reset)
seneca.add({role:plugin,cmd:'confirm'}, cmd_confirm)
seneca.add({role:plugin,cmd:'update_user'}, cmd_update_user)
seneca.add({role:plugin,cmd:'change_password'},cmd_change_password)
seneca.add({role: plugin, cmd:'login'}, cmd_login)
seneca.add({role: plugin, cmd:'logout'}, cmd_logout)
seneca.add({role: plugin, cmd:'register_service' },
cmd_register_service)
seneca.add({role: plugin, cmd: 'mapFields'}, aliasfields)
function loadDefaultPlugins(){
seneca.use(seneca_auth_token)
seneca.use(seneca_auth_redirect, options.redirect || {})
}
function urlmatcher( spec ) {
spec = _.isArray(spec) ? spec : [spec]
var checks = []
_.each(spec,function(path){
if( _.isFunction(path) ) return checks.push(path);
if( _.isRegExp(path) ) return checks.push( function(req) { return path.test(req.url) } );
if( !_.isString(path) ) return;
path = ~path.indexOf(':') ? path : 'prefix:'+path
var parts = path.split(':')
var kind = parts[0]
var spec = parts.slice(1)
function regex() {
var pat = spec, mod = '', re
var m = /^\/(.*)\/([^\/]*)$/.exec(spec)
if(m) {
pat = m[1]
mod = m[2]
re = new RegExp(pat,mod)
return function(req){return re.test(req.url)}
}
else return function(){return false};
}
var pass = {
prefix: function(req) { return gex(spec+'*').on(req.url) },
suffix: function(req) { return gex('*'+spec).on(req.url) },
contains: function(req) { return gex('*'+spec+'*').on(req.url) },
gex: function(req) { return gex(spec).on(req.url) },
exact: function(req) { return spec === req.url },
regex: regex()
}
pass.re = pass.regexp = pass.regex
checks.push(pass[kind])
})
return checks
}
function checkurl( match ) {
var checks = urlmatcher( match )
return function(req) {
for( var i = 0; i < checks.length; i++ ) {
if( checks[i](req) ) {
return true
}
}
return false
}
}
var exclude_url = checkurl(options.exclude)
var include_url = checkurl(options.include)
var userent = seneca.make$('sys/user')
passport.serializeUser(function(user, done) {
done(null, user.user.id);
})
passport.deserializeUser(function(id, done) {
done(null)
})
// default service login trigger
function trigger_service_login( args, done ) {
var seneca = this
if (!args.user){
return done( null, {ok: false, why: 'no-user'} )
}
var userData = args.user
var q = {}
if( userData.identifier ) {
q[ args.service + '_id' ] = userData.identifier
}
else {
return done( null, {ok: false, why: 'no-identifier'} )
}
userent.load$(q,function(err,user){
if( err ) return done( null, {ok: false, why: 'no-identifier'} );
if( !user ) {
seneca.act(_.extend({role:'user',cmd:'register'}, userData), function(err,out){
if( err ) {
return done( null, {ok: false, why: err} )
}
done( null, out.user )
})
}
else {
user.data$( seneca.util.deepextend( user.data$(), userData) )
user.save$( done )
}
})
}
function cmd_register_service(args, cb) {
seneca.log.info('registering auth service [' + args.service + ']')
passport.use(args.service, args.plugin)
registerService(args.service, args.conf)
cb()
}
function registerService(service, conf){
seneca.add({role: plugin, cmd: 'auth-' + service}, _login_service.bind(this, service))
seneca.add({role: plugin, cmd: 'auth-' + service + '-callback'}, _service_callback.bind(this, service))
var map = {}
map['auth-' + service] = {GET: true, POST: true, alias: '/' + service, responder: _blank_responder}
map['auth-' + service + '-callback'] = {GET: true, POST: true, alias: '/' + service + '/callback'}
seneca.act({
role:'web',
plugin:plugin,
config:config,
use:{
prefix:options.prefix,
pin:{role:plugin,cmd:'*'},
map: map
}
})
seneca.add({ role:plugin, trigger:'service-login-' + service }, trigger_service_login)
configureServices(service, conf)
}
function wrap_user( args, done ) {
this.act({
role:'util',
cmd:'ensure_entity',
pin:args.pin,
entmap:{
user:userent
}
})
this.wrap(args.pin, function( args, done ){
args.user = args.user || (args.req$ && args.req$.seneca && args.req$.seneca.user ) || null
this.parent(args,done)
})
done()
}
function aliasfields(userData, cb){
var data = userData.data
data.nick =
data.nick ?
data.nick :
data.username ?
data.username :
data.email
return cb(null, data)
}
function cmd_register( args, done ) {
var seneca = this
seneca.act({role: plugin, cmd: 'mapFields', action: 'register', data: args.data}, function(err, details){
var req = args.req$
var res = args.res$
seneca.act(_.extend({role:'user',cmd:'register'}, details), function( err, out ){
if( err || !out.ok ) {
return done( err, out );
}
seneca.act(_.extend({role:'user',cmd:'login'}, { nick:out.user.nick, auto:true }), function( err, out ){
if( err || !out.ok ) {
return done( err, out );
}
if( req && req.seneca ) {
req.seneca.user = out.user
req.seneca.login = out.login
if( res ) {
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, token: req.seneca.login.id, req: req, res: res}, function(err){
return done(null, {
ok: out.ok,
user: out.user,
login: out.login
})
})
}
}
else{
done(null, {
ok: out.ok,
user: out.user,
login: out.login
})
}
})
})
})
}
function cmd_create_reset( args, done ) {
seneca.act({role: plugin, cmd: 'mapFields', action: 'create_reset', data: args.data}, function(err, userData){
var nick = userData.nick
var email = userData.email
var args = {}
if( void 0 != nick ) args.nick = nick;
if( void 0 != email ) args.email = email;
seneca.act(_.extend({role:'user',cmd:'create_reset'}, args), done)
})
}
function cmd_load_reset( args, done ) {
var token = args.data.token
seneca.act({role:'user',cmd:'load_reset', token:token}, function( err, out ) {
if( err || !out.ok ) {
return done( err, out );
}
return done(null, {
ok: out.ok,
nick: out.user.nick
})
})
}
function cmd_execute_reset( args, done ) {
var token = args.data.token
var password = args.data.password
var repeat = args.data.repeat
seneca.act({role:'user',cmd:'execute_reset', token:token, password:password, repeat:repeat}, done)
}
function cmd_confirm( args, done ) {
var code = args.data.code
seneca.act({role:'user',cmd:'confirm', code:code}, done)
}
function cmd_update_user( args, done ) {
seneca.act({role: plugin, cmd: 'mapFields', action: 'update', data: args.data}, function(err, userData){
seneca.act(_.extend({role:'user',cmd:'update'}, userData), done)
})
}
function cmd_change_password( args, done ) {
var user = args.user
seneca.act({role:'user',cmd:'change_password', user:user, password:args.data.password, repeat:args.data.repeat }, done )
}
function cmd_instance( args, done ) {
var seneca = this
var user = args.user
var login = args.login
seneca.act({ role:plugin, cmd:'clean', user:user, login:login}, function( err, out ){
if( err ) {
return done( err );
}
out.ok = true
out = seneca.util.clean( out )
return done( null, out )
})
}
function cmd_clean( args, done ) {
var seneca = this
var user = args.user && seneca.util.clean( args.user.data$() ) || null
var login = args.login && seneca.util.clean( args.login.data$() ) || null
if( user ) {
delete user.pass
delete user.salt
delete user.active
delete user.accounts
delete user.confirmcode
}
return done(null,{ user:user, login:login })
}
var pp_auth = {}
function configureServices(service, conf){
conf = conf || {}
var func = null
pp_auth[service] = function( req, res, next ){
if (service != 'local') {
func = function (err, user, info) {
seneca.act(_.extend({},{role: 'auth', trigger: 'service-login-' + service, service: service, user: user}),
function (err, user) {
if (err) {
return afterlogin( err, next, req, res );
}
seneca.act({role: 'user', cmd: 'login', nick: user.nick, auto: true}, function (err, out) {
req.user = out
afterlogin( err, next, req, res )
})
}
)
}
}
passport.authenticate(service, conf, func)(req, res, next)
}
}
function buildservice() {
var pp_init = passport.initialize()
function init_session( req, res, cb ) {
seneca.act({role: 'auth', get: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(err, result){
var token
if (result){
token = result.token
}
// var token = req.seneca.cookies.get( options.tokenkey )
if( token ) {
seneca.act({role:'user',cmd:'auth', token:token}, function(err, out){
if( err ) {
return cb(err);
}
if( out.ok ) {
req.user = {user:out.user,login:out.login}
req.seneca.user = out.user
req.seneca.login = out.login
return cb();
}
else {
// dead login - get rid of the token
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(){
return cb();
})
}
})
}
else {
return cb();
}
})
}
var restriction = (function(){
if( _.isFunction(options.restrict) ) return options.restrict;
var checks = urlmatcher(options.restrict)
return function( req, res, next ) {
for( var cI = 0; cI < checks.length; cI++ ) {
var restrict = checks[cI](req)
if( restrict && !(req.seneca && req.seneca.user) ) {
var redirect = false
var ct = (req.headers['content-type']||'').split(';')[0]
if( 'application/json' == ct ) {
redirect = false
}
else redirect = true;
if( redirect ) {
return next(null, {http$: {status: 302,redirect:options.redirect.restrict}})
}
else {
return next(null, { ok:false, why:'restricted', http$: {status: 401} })
}
break;
}
}
if( cI == checks.length ) next();
}
})();
return function(req,res,next){
if( exclude_url(req) && !include_url(req) ) {
return next()
}
if (!req.seneca){
return next('Cannot process, seneca-web dependency problem');
}
req.seneca.cookies = new Cookies(req,res)
pp_init( req, res, function(err){
if( err) {
return next(err);
}
init_session( req, res, function(err){
if( err) {
return next(err);
}
restriction( req, res, function(err){
if( err) {
return next(err);
}
})
next()
})
})
}
}
function init( args, done ) {
done()
}
function authcontext( req, res, args, act, respond ) {
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: args.cmd}, function(err, redirect){
var user = req.seneca && req.seneca.user
if( user ) {
args.user = user
}
var login = req.seneca && req.seneca.login
if( login ) {
args.login = login
}
act(args,function( err, out ){
if( err ) {
seneca.log.debug(err)
out = out || {}
out.http$ = {
status: 400,
redirect: redirect && redirect.fail
}
return respond(null, out);
}
out.http$ = {
status: out.ok ? 200 : 400,
redirect: redirect && redirect.win
}
respond(null,out)
})
})
}
var config = {prefix:options.prefix,redirects:{}}
if( options.defaultpages ) {
_.each(options.loginpages, function(loginpage){
config.redirects[loginpage.path]={redirect:loginpage.redirect,title:loginpage.title}
})
}
//LOGIN START
function afterlogin( err, next, req, res ) {
if( err && !err.why ) {
return next(null, {http$: {status: 302,redirect:redirect.fail}})
}
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(err, redirect){
// req.user actually == {ok:,user:,login:}
if( req.user && req.user.ok ) {
// rename passport req.user prop
req.seneca.user = req.user.user
req.seneca.login = req.user.login
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, token: req.seneca.login.id, req: req, res: res}, function(){
return do_respond(null, redirect, next)
})
}
else {
//var out = {ok:false,why:(req.user&&req.user.why)||'no-user'}
//delete req.user
var out = { ok:false, why: (err ? err.why : 'Unknown error') }
if( redirect ) {
req.seneca.log.debug( 'redirect', 'login', 'fail', redirect.fail )
return next(null, {http$: {status: 302,redirect:redirect.fail}})
}
else {
return next(null, out)
}
}
})
function do_respond(err, redirect, cb) {
if( err) {
return cb(null, {http$: { status: 302 } })
}
if( redirect ) {
req.seneca.log.debug( 'redirect', 'login', 'win', redirect.win )
return cb(null, {http$: {status: 302,redirect:redirect.win}})
}
else {
// FIX: this should call instance
// FIX: how to handle errors here?
seneca.act({role:plugin, cmd:'clean', user:req.seneca.user, login:req.seneca.login},function(err, out){
out.ok = true
return cb(null, out)
})
}
}
}
function cmd_login(args, cb) {
var req = args.req$
var res = args.res$
req.query = _.extend( {}, req.query || {}, req.body || {} )
seneca.act({role: plugin, cmd: 'mapFields', action: 'login', data: args.data}, function(err, userData){
req.query.username =
req.query.username ?
req.query.username :
(
req.query.nick ?
req.query.nick :
(
userData.username ?
userData.username :
userData.nick
)
)
pp_auth.local(req, res, function (err) {
if (err){
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(err, redirect){
return cb(null, {http$: {status: 302,redirect:redirect.fail}})
})
}
else{
afterlogin(err, cb, req, res)
}
})
})
}
//LOGIN END
//LOGOUT START
function cmd_logout(args, cb) {
var req = args.req$
var res = args.res$
// get token from request
seneca.act({role: 'auth', get: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(err, clienttoken){
clienttoken = clienttoken.token
// delete token
seneca.act({role: 'auth', set: 'token', tokenkey: options.tokenkey, req: req, res: res}, function(){
var servertoken
if( req.seneca ) {
servertoken = req.seneca.login && req.seneca.login.token
delete req.seneca.user
delete req.seneca.login
}
var token = clienttoken || servertoken || ''
seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'logout'}, function(err, redirect){
seneca.act({role:'user',cmd:'logout', token: token}, function(err) {
if( err ) {
seneca.log('error',err)
return cb(null, {http$: {status: 301,redirect:redirect.fail}})
}
try {
req.logout()
} catch(err) {
seneca.log('error',err)
return cb(null, {http$: {status: 301,redirect:redirect.fail}})
}
return cb(null, { http$: { status: 301,redirect: redirect.win } } )
})
})
})
})
}
//LOGOUT END
// seneca web endpoints map
var map = {
login: { POST: true, GET: true, data: true, alias: options.urlpath.login },
logout: { POST: true, GET: true, data: true, alias: options.urlpath.logout },
register: { POST:authcontext, data:true, alias: options.urlpath.register },
instance: { GET: authcontext, alias: options.urlpath.instance},
create_reset: { POST:authcontext, data:true, alias: options.urlpath.create_reset },
load_reset: { POST:authcontext, data:true, alias: options.urlpath.load_reset },
execute_reset: { POST:authcontext, data:true, alias: options.urlpath.execute_reset },
confirm: { POST:authcontext, data:true, alias: options.urlpath.confirm },
update_user: { POST:authcontext, data:true, alias: options.urlpath.update_user },
change_password: { POST:authcontext, data:true, alias: options.urlpath.change_password }
}
var _login_service = function (service, args, next) {
var req = args.req$
var res = args.res$
pp_auth[service](req, res, function (err) {
})
next()
}
var _blank_responder = function( req, res, err, out ){
// no need to do anything here as all response data is set by passport strategy
}
var _service_callback = function (service, args, next) {
var req = args.req$
var res = args.res$
pp_auth[service](req, res, function (err) {
if (err) {
return next(err);
}
afterlogin(err, next, req, res)
})
}
seneca.act({
role:'web',
plugin:plugin,
config:config,
use:{
prefix:options.prefix,
pin:{role:plugin,cmd:'*'},
startware:buildservice(),
map: map
}
})
return {
name:plugin
}
}
| changes for redirect
| auth.js | changes for redirect | <ide><path>uth.js
<ide>
<ide> //LOGIN START
<ide> function afterlogin( err, next, req, res ) {
<del> if( err && !err.why ) {
<del> return next(null, {http$: {status: 302,redirect:redirect.fail}})
<del> }
<del>
<del> seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(err, redirect){
<add> seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(redirectErr, redirect){
<ide> // req.user actually == {ok:,user:,login:}
<add> if( err && !err.why ) {
<add> return next(null, {http$: {status: 301,redirect:redirect.fail}})
<add> }
<add>
<ide> if( req.user && req.user.ok ) {
<ide> // rename passport req.user prop
<ide> req.seneca.user = req.user.user
<ide> if( redirect ) {
<ide> req.seneca.log.debug( 'redirect', 'login', 'fail', redirect.fail )
<ide>
<del> return next(null, {http$: {status: 302,redirect:redirect.fail}})
<add> return next(null, {http$: {status: 301,redirect:redirect.fail}})
<ide> }
<ide> else {
<ide> return next(null, out)
<ide>
<ide> if( redirect ) {
<ide> req.seneca.log.debug( 'redirect', 'login', 'win', redirect.win )
<del> return cb(null, {http$: {status: 302,redirect:redirect.win}})
<add> return cb(null, {http$: {status: 301,redirect:redirect.win}})
<ide> }
<ide> else {
<ide> // FIX: this should call instance
<ide> )
<ide>
<ide>
<del> pp_auth.local(req, res, function (err) {
<del> if (err){
<add> pp_auth.local(req, res, function (loginerr, out) {
<add> if (loginerr){
<ide> seneca.act({role: 'auth', cmd: 'redirect', req: req, res: res, kind: 'login'}, function(err, redirect){
<del> return cb(null, {http$: {status: 302,redirect:redirect.fail}})
<add> if ( redirect ){
<add> return cb(null, { http$: { status: 301, redirect:redirect.fail }})
<add> }else{
<add> return cb(null, { http$: { status: 401 }, ok: false, why: loginerr})
<add> }
<ide> })
<ide> }
<ide> else{
<ide> })
<ide> }
<ide> //LOGIN END
<del>
<add> f
<ide>
<ide> //LOGOUT START
<ide> function cmd_logout(args, cb) {
<ide> seneca.act({role:'user',cmd:'logout', token: token}, function(err) {
<ide> if( err ) {
<ide> seneca.log('error',err)
<del> return cb(null, {http$: {status: 301,redirect:redirect.fail}})
<add> if (redirect){
<add> return cb(null, {http$: {status: 301,redirect:redirect.fail}})
<add> }
<add> else{
<add> return cb(null, { ok: false, why: err } )
<add> }
<ide> }
<ide>
<ide> try {
<ide> req.logout()
<ide> } catch(err) {
<ide> seneca.log('error',err)
<del> return cb(null, {http$: {status: 301,redirect:redirect.fail}})
<del> }
<del>
<del> return cb(null, { http$: { status: 301,redirect: redirect.win } } )
<add> if (redirect){
<add> return cb(null, {http$: {status: 301,redirect:redirect.fail}})
<add> }
<add> else{
<add> return cb(null, { ok: false, why: err } )
<add> }
<add> }
<add>
<add> if (redirect){
<add> return cb(null, { http$: { status: 301,redirect: redirect.win } } )
<add> }
<add> else{
<add> return cb(null, { ok: true } )
<add> }
<ide> })
<ide> })
<ide> }) |
|
Java | apache-2.0 | 747ede4d7507b27748cea773b47600131f7de6b6 | 0 | endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS,endeavourhealth/EDS | package org.endeavourhealth.reference;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FilenameUtils;
import org.endeavourhealth.common.utility.ThreadPool;
import org.endeavourhealth.common.utility.ThreadPoolError;
import org.endeavourhealth.core.database.dal.DalProvider;
import org.endeavourhealth.core.database.dal.reference.ReferenceUpdaterDalI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
public class PostcodeUpdater {
private static final Logger LOG = LoggerFactory.getLogger(PostcodeUpdater.class);
private static final String POSTCODE_8_CHAR_FIXED = "PCD2";
private static final String POSTCODE_SINGLE_SPACE = "PCDS";
private static final String POSTCODE_DATE_ADDED = "DOINTR";
private static final String POSTCODE_DATE_REMOVED = "DOTERM";
private static final String POSTCODE_100M_EASTING = "OSEAST100M";
private static final String POSTCODE_100M_NORTHING = "OSNRTH100M";
private static final String POSTCODE_COUNTY_CODE = "OSCTY";
private static final String POSTCODE_LA_ORGANISATION = "ODSLAUA";
private static final String POSTCODE_LA_DISTRICT = "OSLAUA"; //Local authority district (LAD)/unitary authority (UA)/ metropolitan district (MD)/ London borough (LB)/ council area (CA)/district council area (DCA)
private static final String POSTCODE_WARD = "OSWARD";
private static final String POSTCODE_USER_TYPE = "USERTYPE";
private static final String POSTCODE_GRID_REFERENCE_QUALITY = "OSGRDIND";
private static final String POSTCODE_COUNTRY = "CTRY";
private static final String POSTCODE_FORMER_SHA_CODE = "OSHLTHAU";
private static final String POSTCODE_REGION_CODE = "RGN";
private static final String POSTCODE_FORMER_HA_CODE = "OLDHA";
private static final String POSTCODE_COMMISSIONING_REGION_CODE = "NHSER";
private static final String POSTCODE_CCG_CODE = "CCG";
private static final String POSTCODE_CENSUS_ENUMERATION_DISTRICT = "PSED";
private static final String POSTCODE_CENSUS_ENUMERATION_DISTRICT_2 = "CENED";
private static final String POSTCODE_ENUMERATION_DISTRICT_QUALITY_INDICATOR = "EDIND";
private static final String POSTCODE_1998_WARD = "WARD98";
private static final String POSTCODE_2001_CENSUS_OUTPUT_AREA = "OA01";
private static final String POSTCODE_NHS_REGION_GEOGRAPHY = "NHSRLO";
private static final String POSTCODE_FORMER_PAN_SHA = "HRO";
private static final String POSTCODE_2001_CENSUS_LSOA = "LSOA01";
private static final String POSTCODE_2001_URBAN_RURAL_INDICATOR = "UR01IND";
private static final String POSTCODE_2001_CENSUS_MSOA = "MSOA01";
private static final String POSTCODE_FORMER_CANCER_NETWORK = "CANNET";
private static final String POSTCODE_STRATEGIC_CLINICAL_NETWORK = "SCN";
private static final String POSTCODE_FIRST_WAVE_SHA = "OSHAPREV";
private static final String POSTCODE_FIRST_WAVE_PCT = "OLDPCT";
private static final String POSTCODE_OLD_IT_CLUSTER = "OLDHRO";
private static final String POSTCODE_PARLIMENTARY_CONSTITUENCY = "PCON";
private static final String POSTCODE_CANCER_REGISTRY = "CANREG";
private static final String POSTCODE_SECOND_WAVE_PCT = "PCT";
private static final String POSTCODE_1M_EASTING = "OSEAST1M";
private static final String POSTCODE_1M_NORTHING = "OSNRTH1M";
private static final String POSTCODE_2011_CENSUS_OUTPUT_AREA = "OA11";
private static final String POSTCODE_2011_CENSUS_LSOA = "LSOA11";
private static final String POSTCODE_2011_CENSUS_MSOA = "MSOA11";
private static final String POSTCODE_CANCER_ALLIANCE_VANGUARD = "CALNCV";
private static final String POSTCODE_STP_CODE = "STP";
public static void updatePostcodes(File postcodeFile) throws Exception {
LOG.info("Processing Postcode file from " + postcodeFile);
readPostcodeFile(postcodeFile);
LOG.info("Postcode Reference Update Complete from " + postcodeFile);
}
//private static void readPostcodeFile(File postcodeFile, Map<String, BigDecimal> townsendMap) throws Exception {
private static void readPostcodeFile(File postcodeFile) throws Exception {
ThreadPool threadPool = new ThreadPool(5, 1000);
CSVFormat format = CSVFormat.DEFAULT;
int rowsDone = 0;
CSVParser parser = null;
try {
//the postcode CSV file doesn't contain headers, so we must just pass in the headers we know should be there
parser = CSVParser.parse(postcodeFile, Charset.defaultCharset(), format.withHeader(getPostcodeHeadings()));
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
//bump saving into a thread pool for speed
//List<ThreadPoolError> errors = threadPool.submit(new SavePostcodeCallable(record, townsendMap));
List<ThreadPoolError> errors = threadPool.submit(new SavePostcodeCallable(record));
handleErrors(errors);
rowsDone ++;
if (rowsDone % 5000 == 0) {
LOG.info("Done " + rowsDone + " postcodes (of approx 2.6M)");
}
}
List<ThreadPoolError> errors = threadPool.waitAndStop();
handleErrors(errors);
LOG.info("Finished at " + rowsDone + " postcodes");
} finally {
if (parser != null) {
parser.close();
}
}
}
private static void handleErrors(List<ThreadPoolError> errors) throws Exception {
if (errors == null || errors.isEmpty()) {
return;
}
//if we've had multiple errors, just throw the first one, since they'll most-likely be the same
ThreadPoolError first = errors.get(0);
Throwable cause = first.getException();
//the cause may be an Exception or Error so we need to explicitly
//cast to the right type to throw it without changing the method signature
if (cause instanceof Exception) {
throw (Exception)cause;
} else if (cause instanceof Error) {
throw (Error)cause;
}
}
/*private static Map<String, BigDecimal> readTownsendMap(File townsendMapFile) throws Exception {
Map<String, BigDecimal> map = new ConcurrentHashMap<>();
CSVFormat format = CSVFormat.DEFAULT;
CSVParser parser = null;
try {
parser = CSVParser.parse(townsendMapFile, Charset.defaultCharset(), format.withHeader());
Iterator<CSVRecord> iterator = parser.iterator();
//validate the headers are what we expect
String[] expectedHeaders = new String[]{TOWNSEND_MAP_WARD_CODE, TOWNSEND_MAP_WARD_NAME, TOWNSEND_MAP_SCORE, TOWNSEND_MAP_QUINTILES};
CsvHelper.validateCsvHeaders(parser, townsendMapFile, expectedHeaders);
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
String ward = record.get(TOWNSEND_MAP_WARD_CODE);
String score = record.get(TOWNSEND_MAP_SCORE);
if (!Strings.isNullOrEmpty(score)) {
map.put(ward, new BigDecimal(score));
}
}
} finally {
if (parser != null) {
parser.close();
}
}
return map;
}*/
public static String[] getPostcodeHeadings() {
return new String[]{
POSTCODE_8_CHAR_FIXED,
POSTCODE_SINGLE_SPACE,
POSTCODE_DATE_ADDED,
POSTCODE_DATE_REMOVED,
POSTCODE_100M_EASTING,
POSTCODE_100M_NORTHING,
POSTCODE_COUNTY_CODE,
POSTCODE_LA_ORGANISATION,
POSTCODE_LA_DISTRICT,
POSTCODE_WARD,
POSTCODE_USER_TYPE,
POSTCODE_GRID_REFERENCE_QUALITY,
POSTCODE_COUNTRY,
POSTCODE_FORMER_SHA_CODE,
POSTCODE_REGION_CODE,
POSTCODE_FORMER_HA_CODE,
POSTCODE_COMMISSIONING_REGION_CODE,
POSTCODE_CCG_CODE,
POSTCODE_CENSUS_ENUMERATION_DISTRICT,
POSTCODE_CENSUS_ENUMERATION_DISTRICT_2,
POSTCODE_ENUMERATION_DISTRICT_QUALITY_INDICATOR,
POSTCODE_1998_WARD,
POSTCODE_2001_CENSUS_OUTPUT_AREA,
POSTCODE_NHS_REGION_GEOGRAPHY,
POSTCODE_FORMER_PAN_SHA,
POSTCODE_2001_CENSUS_LSOA,
POSTCODE_2001_URBAN_RURAL_INDICATOR,
POSTCODE_2001_CENSUS_MSOA,
POSTCODE_FORMER_CANCER_NETWORK,
POSTCODE_STRATEGIC_CLINICAL_NETWORK,
POSTCODE_FIRST_WAVE_SHA,
POSTCODE_FIRST_WAVE_PCT,
POSTCODE_OLD_IT_CLUSTER,
POSTCODE_PARLIMENTARY_CONSTITUENCY,
POSTCODE_CANCER_REGISTRY,
POSTCODE_SECOND_WAVE_PCT,
POSTCODE_1M_EASTING,
POSTCODE_1M_NORTHING,
POSTCODE_2011_CENSUS_OUTPUT_AREA,
POSTCODE_2011_CENSUS_LSOA,
POSTCODE_2011_CENSUS_MSOA,
POSTCODE_CANCER_ALLIANCE_VANGUARD,
POSTCODE_STP_CODE,
};
}
static class SavePostcodeCallable implements Callable {
private CSVRecord record = null;
//private Map<String, BigDecimal> townsendMap = null;
public SavePostcodeCallable(CSVRecord record) {
this.record = record;
}
/*public SavePostcodeCallable(CSVRecord record, Map<String, BigDecimal> townsendMap) {
this.record = record;
this.townsendMap = townsendMap;
}*/
@Override
public Object call() throws Exception {
String postcode = record.get(POSTCODE_SINGLE_SPACE);
String lsoaCode = record.get(POSTCODE_2011_CENSUS_LSOA);
String msoaCode = record.get(POSTCODE_2011_CENSUS_MSOA);
String ward = record.get(POSTCODE_WARD);
String ccgCode = record.get(POSTCODE_CCG_CODE);
String localAuthority = record.get(POSTCODE_LA_DISTRICT);
String lsoa2001Code = record.get(POSTCODE_2001_CENSUS_LSOA);
String lsoa2011Code = record.get(POSTCODE_2011_CENSUS_LSOA);
String msoa2001Code = record.get(POSTCODE_2001_CENSUS_MSOA);
String msoa2011Code = record.get(POSTCODE_2011_CENSUS_MSOA);
ReferenceUpdaterDalI referenceUpdaterDal = DalProvider.factoryReferenceUpdaterDal();
referenceUpdaterDal.updatePostcodeMap(postcode, lsoaCode, msoaCode, ward, ccgCode, localAuthority,
lsoa2001Code, lsoa2011Code, msoa2001Code, msoa2011Code);
return null;
}
}
public static File findFile(String[] args) {
if (args.length != 2) {
throw new RuntimeException("Incorrect number of parameters, expecting 2");
}
//C:\SFTPData\postcodes\NHSPD_MAY_2018_UK_FULL\Data\nhg18may.csv
String root = args[1];
File dir = new File(root);
if (!dir.exists()) {
throw new RuntimeException("" + dir + " does not exist");
}
dir = new File(dir, "Data");
if (!dir.exists()) {
throw new RuntimeException("" + dir + " does not exist");
}
//it's the largest CSV file in this dir
File ret = null;
long retSize = -1;
for (File child: dir.listFiles()) {
String ext = FilenameUtils.getExtension(child.getName());
if (!ext.equalsIgnoreCase("csv")) {
continue;
}
if (ret == null
|| child.length() > retSize) {
ret = child;
retSize = child.length();
}
}
if (ret == null) {
throw new RuntimeException("Failed to find postcode csv file in " + dir);
}
return ret;
}
}
| src/utility-postcode-updater/src/main/java/org/endeavourhealth/reference/PostcodeUpdater.java | package org.endeavourhealth.reference;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;
import org.apache.commons.io.FilenameUtils;
import org.endeavourhealth.common.utility.ThreadPool;
import org.endeavourhealth.common.utility.ThreadPoolError;
import org.endeavourhealth.core.database.dal.DalProvider;
import org.endeavourhealth.core.database.dal.reference.ReferenceUpdaterDalI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
public class PostcodeUpdater {
private static final Logger LOG = LoggerFactory.getLogger(PostcodeUpdater.class);
private static final String POSTCODE_8_CHAR_FIXED = "PCD2";
private static final String POSTCODE_SINGLE_SPACE = "PCDS";
private static final String POSTCODE_DATE_ADDED = "DOINTR";
private static final String POSTCODE_DATE_REMOVED = "DOTERM";
private static final String POSTCODE_100M_EASTING = "OSEAST100M";
private static final String POSTCODE_100M_NORTHING = "OSNRTH100M";
private static final String POSTCODE_COUNTY_CODE = "OSCTY";
private static final String POSTCODE_LA_ORGANISATION = "ODSLAUA";
private static final String POSTCODE_LA_DISTRICT = "OSLAUA"; //Local authority district (LAD)/unitary authority (UA)/ metropolitan district (MD)/ London borough (LB)/ council area (CA)/district council area (DCA)
private static final String POSTCODE_WARD = "OSWARD";
private static final String POSTCODE_USER_TYPE = "USERTYPE";
private static final String POSTCODE_GRID_REFERENCE_QUALITY = "OSGRDIND";
private static final String POSTCODE_COUNTRY = "CTRY";
private static final String POSTCODE_FORMER_SHA_CODE = "OSHLTHAU";
private static final String POSTCODE_REGION_CODE = "GOR";
private static final String POSTCODE_FORMER_HA_CODE = "OLDHA";
private static final String POSTCODE_COMMISSIONING_REGION_CODE = "NHSCR";
private static final String POSTCODE_CCG_CODE = "CCG";
private static final String POSTCODE_CENSUS_ENUMERATION_DISTRICT = "PSED";
private static final String POSTCODE_CENSUS_ENUMERATION_DISTRICT_2 = "CENED";
private static final String POSTCODE_ENUMERATION_DISTRICT_QUALITY_INDICATOR = "EDIND";
private static final String POSTCODE_1998_WARD = "WARD98";
private static final String POSTCODE_2001_CENSUS_OUTPUT_AREA = "OA01";
private static final String POSTCODE_NHS_REGION_GEOGRAPHY = "NHSRG";
private static final String POSTCODE_FORMER_PAN_SHA = "HRO";
private static final String POSTCODE_2001_CENSUS_LSOA = "LSOA01";
private static final String POSTCODE_2001_URBAN_RURAL_INDICATOR = "UR01IND";
private static final String POSTCODE_2001_CENSUS_MSOA = "MSOA01";
private static final String POSTCODE_FORMER_CANCER_NETWORK = "CANNET";
private static final String POSTCODE_STRATEGIC_CLINICAL_NETWORK = "SCN";
private static final String POSTCODE_FIRST_WAVE_SHA = "OSHAPREV";
private static final String POSTCODE_FIRST_WAVE_PCT = "OLDPCT";
private static final String POSTCODE_OLD_IT_CLUSTER = "OLDHRO";
private static final String POSTCODE_PARLIMENTARY_CONSTITUENCY = "PCON";
private static final String POSTCODE_CANCER_REGISTRY = "CANREG";
private static final String POSTCODE_SECOND_WAVE_PCT = "PCT";
private static final String POSTCODE_1M_EASTING = "OSEAST1M";
private static final String POSTCODE_1M_NORTHING = "OSNRTH1M";
private static final String POSTCODE_2011_CENSUS_OUTPUT_AREA = "OA11";
private static final String POSTCODE_2011_CENSUS_LSOA = "LSOA11";
private static final String POSTCODE_2011_CENSUS_MSOA = "MSOA11";
public static void updatePostcodes(File postcodeFile) throws Exception {
LOG.info("Processing Postcode file from " + postcodeFile);
readPostcodeFile(postcodeFile);
LOG.info("Postcode Reference Update Complete from " + postcodeFile);
}
//private static void readPostcodeFile(File postcodeFile, Map<String, BigDecimal> townsendMap) throws Exception {
private static void readPostcodeFile(File postcodeFile) throws Exception {
ThreadPool threadPool = new ThreadPool(5, 1000);
CSVFormat format = CSVFormat.DEFAULT;
int rowsDone = 0;
CSVParser parser = null;
try {
//the postcode CSV file doesn't contain headers, so we must just pass in the headers we know should be there
parser = CSVParser.parse(postcodeFile, Charset.defaultCharset(), format.withHeader(getPostcodeHeadings()));
Iterator<CSVRecord> iterator = parser.iterator();
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
//bump saving into a thread pool for speed
//List<ThreadPoolError> errors = threadPool.submit(new SavePostcodeCallable(record, townsendMap));
List<ThreadPoolError> errors = threadPool.submit(new SavePostcodeCallable(record));
handleErrors(errors);
rowsDone ++;
if (rowsDone % 5000 == 0) {
LOG.info("Done " + rowsDone + " postcodes (of approx 2.6M)");
}
}
List<ThreadPoolError> errors = threadPool.waitAndStop();
handleErrors(errors);
LOG.info("Finshed at " + rowsDone + " postcodes");
} finally {
if (parser != null) {
parser.close();
}
}
}
private static void handleErrors(List<ThreadPoolError> errors) throws Exception {
if (errors == null || errors.isEmpty()) {
return;
}
//if we've had multiple errors, just throw the first one, since they'll most-likely be the same
ThreadPoolError first = errors.get(0);
Throwable cause = first.getException();
//the cause may be an Exception or Error so we need to explicitly
//cast to the right type to throw it without changing the method signature
if (cause instanceof Exception) {
throw (Exception)cause;
} else if (cause instanceof Error) {
throw (Error)cause;
}
}
/*private static Map<String, BigDecimal> readTownsendMap(File townsendMapFile) throws Exception {
Map<String, BigDecimal> map = new ConcurrentHashMap<>();
CSVFormat format = CSVFormat.DEFAULT;
CSVParser parser = null;
try {
parser = CSVParser.parse(townsendMapFile, Charset.defaultCharset(), format.withHeader());
Iterator<CSVRecord> iterator = parser.iterator();
//validate the headers are what we expect
String[] expectedHeaders = new String[]{TOWNSEND_MAP_WARD_CODE, TOWNSEND_MAP_WARD_NAME, TOWNSEND_MAP_SCORE, TOWNSEND_MAP_QUINTILES};
CsvHelper.validateCsvHeaders(parser, townsendMapFile, expectedHeaders);
while (iterator.hasNext()) {
CSVRecord record = iterator.next();
String ward = record.get(TOWNSEND_MAP_WARD_CODE);
String score = record.get(TOWNSEND_MAP_SCORE);
if (!Strings.isNullOrEmpty(score)) {
map.put(ward, new BigDecimal(score));
}
}
} finally {
if (parser != null) {
parser.close();
}
}
return map;
}*/
public static String[] getPostcodeHeadings() {
return new String[]{
POSTCODE_8_CHAR_FIXED,
POSTCODE_SINGLE_SPACE,
POSTCODE_DATE_ADDED,
POSTCODE_DATE_REMOVED,
POSTCODE_100M_EASTING,
POSTCODE_100M_NORTHING,
POSTCODE_COUNTY_CODE,
POSTCODE_LA_ORGANISATION,
POSTCODE_LA_DISTRICT,
POSTCODE_WARD,
POSTCODE_USER_TYPE,
POSTCODE_GRID_REFERENCE_QUALITY,
POSTCODE_COUNTRY,
POSTCODE_FORMER_SHA_CODE,
POSTCODE_REGION_CODE,
POSTCODE_FORMER_HA_CODE,
POSTCODE_COMMISSIONING_REGION_CODE,
POSTCODE_CCG_CODE,
POSTCODE_CENSUS_ENUMERATION_DISTRICT,
POSTCODE_CENSUS_ENUMERATION_DISTRICT_2,
POSTCODE_ENUMERATION_DISTRICT_QUALITY_INDICATOR,
POSTCODE_1998_WARD,
POSTCODE_2001_CENSUS_OUTPUT_AREA,
POSTCODE_NHS_REGION_GEOGRAPHY,
POSTCODE_FORMER_PAN_SHA,
POSTCODE_2001_CENSUS_LSOA,
POSTCODE_2001_URBAN_RURAL_INDICATOR,
POSTCODE_2001_CENSUS_MSOA,
POSTCODE_FORMER_CANCER_NETWORK,
POSTCODE_STRATEGIC_CLINICAL_NETWORK,
POSTCODE_FIRST_WAVE_SHA,
POSTCODE_FIRST_WAVE_PCT,
POSTCODE_OLD_IT_CLUSTER,
POSTCODE_PARLIMENTARY_CONSTITUENCY,
POSTCODE_CANCER_REGISTRY,
POSTCODE_SECOND_WAVE_PCT,
POSTCODE_1M_EASTING,
POSTCODE_1M_NORTHING,
POSTCODE_2011_CENSUS_OUTPUT_AREA,
POSTCODE_2011_CENSUS_LSOA,
POSTCODE_2011_CENSUS_MSOA,
};
}
static class SavePostcodeCallable implements Callable {
private CSVRecord record = null;
//private Map<String, BigDecimal> townsendMap = null;
public SavePostcodeCallable(CSVRecord record) {
this.record = record;
}
/*public SavePostcodeCallable(CSVRecord record, Map<String, BigDecimal> townsendMap) {
this.record = record;
this.townsendMap = townsendMap;
}*/
@Override
public Object call() throws Exception {
String postcode = record.get(POSTCODE_SINGLE_SPACE);
String lsoaCode = record.get(POSTCODE_2011_CENSUS_LSOA);
String msoaCode = record.get(POSTCODE_2011_CENSUS_MSOA);
String ward = record.get(POSTCODE_WARD);
String ccgCode = record.get(POSTCODE_CCG_CODE);
String localAuthority = record.get(POSTCODE_LA_DISTRICT);
ReferenceUpdaterDalI referenceUpdaterDal = DalProvider.factoryReferenceUpdaterDal();
referenceUpdaterDal.updatePostcodeMap(postcode, lsoaCode, msoaCode, ward, ccgCode, localAuthority);
return null;
}
}
public static File findFile(String[] args) {
if (args.length != 2) {
throw new RuntimeException("Incorrect number of parameters, expecting 2");
}
//C:\SFTPData\postcodes\NHSPD_MAY_2018_UK_FULL\Data\nhg18may.csv
String root = args[1];
File dir = new File(root);
if (!dir.exists()) {
throw new RuntimeException("" + dir + " does not exist");
}
dir = new File(dir, "Data");
if (!dir.exists()) {
throw new RuntimeException("" + dir + " does not exist");
}
//it's the largest CSV file in this dir
File ret = null;
long retSize = -1;
for (File child: dir.listFiles()) {
String ext = FilenameUtils.getExtension(child.getName());
if (!ext.equalsIgnoreCase("csv")) {
continue;
}
if (ret == null
|| child.length() > retSize) {
ret = child;
retSize = child.length();
}
}
if (ret == null) {
throw new RuntimeException("Failed to find postcode csv file in " + dir);
}
return ret;
}
}
| Modified Postcode Updater class, to include LSOA 2001, LSOA 2011,
MSOA 2001 and MSOA 2011 fields in postcode_lookup table in reference database.
| src/utility-postcode-updater/src/main/java/org/endeavourhealth/reference/PostcodeUpdater.java | Modified Postcode Updater class, to include LSOA 2001, LSOA 2011, MSOA 2001 and MSOA 2011 fields in postcode_lookup table in reference database. | <ide><path>rc/utility-postcode-updater/src/main/java/org/endeavourhealth/reference/PostcodeUpdater.java
<ide> private static final String POSTCODE_GRID_REFERENCE_QUALITY = "OSGRDIND";
<ide> private static final String POSTCODE_COUNTRY = "CTRY";
<ide> private static final String POSTCODE_FORMER_SHA_CODE = "OSHLTHAU";
<del> private static final String POSTCODE_REGION_CODE = "GOR";
<add> private static final String POSTCODE_REGION_CODE = "RGN";
<ide> private static final String POSTCODE_FORMER_HA_CODE = "OLDHA";
<del> private static final String POSTCODE_COMMISSIONING_REGION_CODE = "NHSCR";
<add> private static final String POSTCODE_COMMISSIONING_REGION_CODE = "NHSER";
<ide> private static final String POSTCODE_CCG_CODE = "CCG";
<ide> private static final String POSTCODE_CENSUS_ENUMERATION_DISTRICT = "PSED";
<ide> private static final String POSTCODE_CENSUS_ENUMERATION_DISTRICT_2 = "CENED";
<ide> private static final String POSTCODE_ENUMERATION_DISTRICT_QUALITY_INDICATOR = "EDIND";
<ide> private static final String POSTCODE_1998_WARD = "WARD98";
<ide> private static final String POSTCODE_2001_CENSUS_OUTPUT_AREA = "OA01";
<del> private static final String POSTCODE_NHS_REGION_GEOGRAPHY = "NHSRG";
<add> private static final String POSTCODE_NHS_REGION_GEOGRAPHY = "NHSRLO";
<ide> private static final String POSTCODE_FORMER_PAN_SHA = "HRO";
<ide> private static final String POSTCODE_2001_CENSUS_LSOA = "LSOA01";
<ide> private static final String POSTCODE_2001_URBAN_RURAL_INDICATOR = "UR01IND";
<ide> private static final String POSTCODE_2011_CENSUS_OUTPUT_AREA = "OA11";
<ide> private static final String POSTCODE_2011_CENSUS_LSOA = "LSOA11";
<ide> private static final String POSTCODE_2011_CENSUS_MSOA = "MSOA11";
<add> private static final String POSTCODE_CANCER_ALLIANCE_VANGUARD = "CALNCV";
<add> private static final String POSTCODE_STP_CODE = "STP";
<ide>
<ide> public static void updatePostcodes(File postcodeFile) throws Exception {
<ide> LOG.info("Processing Postcode file from " + postcodeFile);
<ide> List<ThreadPoolError> errors = threadPool.waitAndStop();
<ide> handleErrors(errors);
<ide>
<del> LOG.info("Finshed at " + rowsDone + " postcodes");
<add> LOG.info("Finished at " + rowsDone + " postcodes");
<ide>
<ide> } finally {
<ide> if (parser != null) {
<ide> POSTCODE_2011_CENSUS_OUTPUT_AREA,
<ide> POSTCODE_2011_CENSUS_LSOA,
<ide> POSTCODE_2011_CENSUS_MSOA,
<add> POSTCODE_CANCER_ALLIANCE_VANGUARD,
<add> POSTCODE_STP_CODE,
<ide> };
<ide> }
<ide>
<ide> String ward = record.get(POSTCODE_WARD);
<ide> String ccgCode = record.get(POSTCODE_CCG_CODE);
<ide> String localAuthority = record.get(POSTCODE_LA_DISTRICT);
<add> String lsoa2001Code = record.get(POSTCODE_2001_CENSUS_LSOA);
<add> String lsoa2011Code = record.get(POSTCODE_2011_CENSUS_LSOA);
<add> String msoa2001Code = record.get(POSTCODE_2001_CENSUS_MSOA);
<add> String msoa2011Code = record.get(POSTCODE_2011_CENSUS_MSOA);
<ide>
<ide> ReferenceUpdaterDalI referenceUpdaterDal = DalProvider.factoryReferenceUpdaterDal();
<del> referenceUpdaterDal.updatePostcodeMap(postcode, lsoaCode, msoaCode, ward, ccgCode, localAuthority);
<add> referenceUpdaterDal.updatePostcodeMap(postcode, lsoaCode, msoaCode, ward, ccgCode, localAuthority,
<add> lsoa2001Code, lsoa2011Code, msoa2001Code, msoa2011Code);
<ide>
<ide> return null;
<ide> } |
|
Java | agpl-3.0 | 4a1ff7d8dfd86bec921cf7ba1386cdd15d6abb7f | 0 | ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne,ibcn-cloudlet/dianne | /*******************************************************************************
* DIANNE - Framework for distributed artificial neural networks
* Copyright (C) 2015 iMinds - IBCN - UGent
*
* This file is part of DIANNE.
*
* DIANNE 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/>.
*
* Contributors:
* Tim Verbelen, Steven Bohez
*******************************************************************************/
package be.iminds.iot.dianne.things.input;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import be.iminds.iot.dianne.api.io.InputDescription;
import be.iminds.iot.dianne.api.nn.module.Input;
import be.iminds.iot.dianne.tensor.Tensor;
import be.iminds.iot.sensor.api.Camera;
import be.iminds.iot.sensor.api.Frame;
import be.iminds.iot.sensor.api.LaserScanner;
import be.iminds.iot.sensor.api.PointCloud;
import be.iminds.iot.sensor.api.Scanner3D;
import be.iminds.iot.sensor.api.Sensor;
import be.iminds.iot.sensor.api.SensorListener;
import be.iminds.iot.sensor.api.SensorValue;
public class SensorInput extends ThingInput implements SensorListener {
private Sensor sensor;
private Tensor t;
private ServiceRegistration registration;
public SensorInput(UUID id, String name, Sensor s){
super(id, name, "Sensor");
if(s instanceof LaserScanner) {
super.type = "LaserScanner";
} else if(s instanceof Camera) {
super.type = "Camera";
} else if(s instanceof Scanner3D) {
super.type = "Scanner3D";
}
this.sensor = s;
}
@Override
public InputDescription getInputDescription(){
Map<String, String> properties = new HashMap<>();
if(sensor instanceof LaserScanner) {
LaserScanner laser = (LaserScanner) sensor;
properties.put("minAngle", ""+laser.getMinAngle());
properties.put("maxAngle", ""+laser.getMaxAngle());
} else if(sensor instanceof Camera) {
Camera camera = (Camera) sensor;
properties.put("width", ""+camera.getWidth());
properties.put("height", ""+camera.getHeight());
properties.put("encoding", ""+camera.getEncoding());
} else if(sensor instanceof Scanner3D) {
}
return new InputDescription(name, type, properties);
}
@Override
public void update(SensorValue value) {
try {
for(Input in : inputs){
if(t == null || t.size() != value.data.length){
t = new Tensor(value.data.length);
}
t.set(value.data);
// adapt shape when needed
if(type.equals("Camera")) {
Frame f = (Frame) value;
if(f.encoding == Frame.Encoding.RGB) {
t.reshape(3, f.height, f.width);
}
} else if(type.equals("Scanner3D")) {
PointCloud pcl = (PointCloud) value;
t.reshape(pcl.size, pcl.fields.length);
}
in.input(t);
}
} catch(Exception e){
// ignore exception ... probably NN was deployed while forwarding input
e.printStackTrace();
}
}
@Override
public void connect(Input input, BundleContext context) {
super.connect(input, context);
if(registration == null){
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("target", id.toString());
properties.put("aiolos.unique", true);
registration = context.registerService(SensorListener.class.getName(), this, properties);
}
}
@Override
public void disconnect(Input input){
super.disconnect(input);
if(registration != null && inputs.size() == 0){
registration.unregister();
registration = null;
}
}
}
| be.iminds.iot.dianne.io.things/src/be/iminds/iot/dianne/things/input/SensorInput.java | /*******************************************************************************
* DIANNE - Framework for distributed artificial neural networks
* Copyright (C) 2015 iMinds - IBCN - UGent
*
* This file is part of DIANNE.
*
* DIANNE 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/>.
*
* Contributors:
* Tim Verbelen, Steven Bohez
*******************************************************************************/
package be.iminds.iot.dianne.things.input;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.UUID;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import be.iminds.iot.dianne.api.io.InputDescription;
import be.iminds.iot.dianne.api.nn.module.Input;
import be.iminds.iot.dianne.tensor.Tensor;
import be.iminds.iot.sensor.api.Camera;
import be.iminds.iot.sensor.api.Frame;
import be.iminds.iot.sensor.api.LaserScanner;
import be.iminds.iot.sensor.api.PointCloud;
import be.iminds.iot.sensor.api.Scanner3D;
import be.iminds.iot.sensor.api.Sensor;
import be.iminds.iot.sensor.api.SensorListener;
import be.iminds.iot.sensor.api.SensorValue;
public class SensorInput extends ThingInput implements SensorListener {
private Sensor sensor;
private Tensor t;
private ServiceRegistration registration;
public SensorInput(UUID id, String name, Sensor s){
super(id, name, "Sensor");
if(s instanceof LaserScanner) {
super.type = "LaserScanner";
} else if(s instanceof Camera) {
super.type = "Camera";
} else if(s instanceof Scanner3D) {
super.type = "Scanner3D";
}
this.sensor = s;
}
@Override
public InputDescription getInputDescription(){
Map<String, String> properties = new HashMap<>();
if(sensor instanceof LaserScanner) {
LaserScanner laser = (LaserScanner) sensor;
properties.put("minAngle", ""+laser.getMinAngle());
properties.put("maxAngle", ""+laser.getMaxAngle());
} else if(sensor instanceof Camera) {
Camera camera = (Camera) sensor;
properties.put("width", ""+camera.getWidth());
properties.put("height", ""+camera.getHeight());
properties.put("encoding", ""+camera.getEncoding());
} else if(sensor instanceof Scanner3D) {
}
return new InputDescription(name, type, properties);
}
@Override
public void update(SensorValue value) {
try {
for(Input in : inputs){
if(t == null || t.size() != value.data.length){
t = new Tensor(value.data.length);
}
t.set(value.data);
// adapt shape when needed
if(type.equals("Camera")) {
Frame f = (Frame) value;
if(f.encoding == Frame.Encoding.RGB) {
t.reshape(3, f.width, f.height);
}
} else if(type.equals("Scanner3D")) {
PointCloud pcl = (PointCloud) value;
t.reshape(pcl.size, pcl.fields.length);
}
in.input(t);
}
} catch(Exception e){
// ignore exception ... probably NN was deployed while forwarding input
e.printStackTrace();
}
}
@Override
public void connect(Input input, BundleContext context) {
super.connect(input, context);
if(registration == null){
Dictionary<String, Object> properties = new Hashtable<String, Object>();
properties.put("target", id.toString());
properties.put("aiolos.unique", true);
registration = context.registerService(SensorListener.class.getName(), this, properties);
}
}
@Override
public void disconnect(Input input){
super.disconnect(input);
if(registration != null && inputs.size() == 0){
registration.unregister();
registration = null;
}
}
}
| fix camera sensor input reshaping | be.iminds.iot.dianne.io.things/src/be/iminds/iot/dianne/things/input/SensorInput.java | fix camera sensor input reshaping | <ide><path>e.iminds.iot.dianne.io.things/src/be/iminds/iot/dianne/things/input/SensorInput.java
<ide> if(type.equals("Camera")) {
<ide> Frame f = (Frame) value;
<ide> if(f.encoding == Frame.Encoding.RGB) {
<del> t.reshape(3, f.width, f.height);
<add> t.reshape(3, f.height, f.width);
<ide> }
<ide> } else if(type.equals("Scanner3D")) {
<ide> PointCloud pcl = (PointCloud) value; |
|
Java | mit | 2f9d53d30cb06b794dfc9b1370741bbbcda1af72 | 0 | bladecoder/blade-ink | package com.bladecoder.ink.runtime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Stack;
import com.bladecoder.ink.runtime.CallStack.Element;
/**
* A Story is the core class that represents a complete Ink narrative, and
* manages the evaluation and state of it.
*/
public class Story extends RTObject implements VariablesState.VariableChanged {
/**
* General purpose delegate definition for bound EXTERNAL function
* definitions from ink. Note that this version isn't necessary if you have
* a function with three arguments or less - see the overloads of
* BindExternalFunction.
*/
public interface ExternalFunction {
Object call(Object[] args) throws Exception;
}
// Version numbers are for engine itself and story file, rather
// than the story state save format (which is um, currently nonexistant)
// -- old engine, new format: always fail
// -- new engine, old format: possibly cope, based on this number
// When incrementing the version number above, the question you
// should ask yourself is:
// -- Will the engine be able to load an old story file from
// before I made these changes to the engine?
// If possible, you should support it, though it's not as
// critical as loading old save games, since it's an
// in-development problem only.
/**
* Delegate definition for variable observation - see ObserveVariable.
*/
public interface VariableObserver {
void call(String variableName, Object newValue);
}
/**
* The current version of the ink story file format.
*/
public static final int inkVersionCurrent = 15;
/**
* The minimum legacy version of ink that can be loaded by the current
* version of the code.
*/
public static final int inkVersionMinimumCompatible = 12;
private Container mainContentContainer;
/**
* An ink file can provide a fallback functions for when when an EXTERNAL
* has been left unbound by the client, and the fallback function will be
* called instead. Useful when testing a story in playmode, when it's not
* possible to write a client-side C# external function, but you don't want
* it to fail to run.
*/
private boolean allowExternalFunctionFallbacks;
private HashMap<String, ExternalFunction> externals;
private boolean hasValidatedExternals;
private StoryState state;
private Container temporaryEvaluationContainer;
private HashMap<String, List<VariableObserver>> variableObservers;
// Warning: When creating a Story using this constructor, you need to
// call ResetState on it before use. Intended for compiler use only.
// For normal use, use the constructor that takes a json string.
Story(Container contentContainer) {
mainContentContainer = contentContainer;
externals = new HashMap<String, ExternalFunction>();
}
/**
* Construct a Story Object using a JSON String compiled through inklecate.
*/
public Story(String jsonString) throws Exception {
this((Container) null);
HashMap<String, Object> rootObject = SimpleJson.textToHashMap(jsonString);
Object versionObj = rootObject.get("inkVersion");
if (versionObj == null)
throw new Exception("ink version number not found. Are you sure it's a valid .ink.json file?");
int formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj;
if (formatFromFile > inkVersionCurrent) {
throw new Exception("Version of ink used to build story was newer than the current verison of the engine");
} else if (formatFromFile < inkVersionMinimumCompatible) {
throw new Exception(
"Version of ink used to build story is too old to be loaded by this version of the engine");
} else if (formatFromFile != inkVersionCurrent) {
System.out.println(
"WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising.");
}
Object rootToken = rootObject.get("root");
if (rootToken == null)
throw new Exception("Root node for ink not found. Are you sure it's a valid .ink.json file?");
mainContentContainer = Json.jTokenToRuntimeObject(rootToken) instanceof Container
? (Container) Json.jTokenToRuntimeObject(rootToken) : null;
resetState();
}
void addError(String message, boolean useEndLineNumber) throws Exception {
DebugMetadata dm = currentDebugMetadata();
if (dm != null) {
int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber;
message = String.format("RUNTIME ERROR: '%s' line %d: %s", dm.fileName, lineNum, message);
} else {
message = "RUNTIME ERROR: " + message;
}
state.addError(message);
// In a broken state don't need to know about any other errors.
state.forceEnd();
}
void Assert(boolean condition, Object... formatParams) throws Exception {
Assert(condition, null, formatParams);
}
void Assert(boolean condition, String message, Object... formatParams) throws Exception {
if (condition == false) {
if (message == null) {
message = "Story assert";
}
if (formatParams != null && formatParams.length > 0) {
message = String.format(message, formatParams);
}
throw new Exception(message + " " + currentDebugMetadata());
}
}
/**
* Most general form of function binding that returns an Object and takes an
* array of Object parameters. The only way to bind a function with more
* than 3 arguments.
*
* @param funcName
* EXTERNAL ink function name to bind to.
* @param func
* The Java function to bind.
*/
public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception {
Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound.");
externals.put(funcName, func);
}
@SuppressWarnings("unchecked")
public <T> T tryCoerce(Object value, Class<T> type) throws Exception {
if (value == null)
return null;
if (type.isAssignableFrom(value.getClass()))
return (T) value;
if (value instanceof Float && type == Integer.class) {
Integer intVal = (int) Math.round((Float) value);
return (T) intVal;
}
if (value instanceof Integer && type == Float.class) {
Float floatVal = Float.valueOf((Integer) value);
return (T) floatVal;
}
if (value instanceof Integer && type == Boolean.class) {
int intVal = (Integer) value;
return (T) (intVal == 0 ? new Boolean(false) : new Boolean(true));
}
if (type == String.class) {
return (T) value.toString();
}
Assert(false, "Failed to cast " + value.getClass().getCanonicalName() + " to " + type.getCanonicalName());
return null;
}
/**
* Get any global tags associated with the story. These are defined as hash
* tags defined at the very top of the story.
*
* @throws Exception
*/
public List<String> getGlobalTags() throws Exception {
return tagsAtStartOfFlowContainerWithPathString("");
}
/**
* Gets any tags associated with a particular knot or knot.stitch. These are
* defined as hash tags defined at the very top of a knot or stitch.
*
* @param path
* The path of the knot or stitch, in the form "knot" or
* "knot.stitch".
* @throws Exception
*/
public List<String> tagsForContentAtPath(String path) throws Exception {
return tagsAtStartOfFlowContainerWithPathString(path);
}
List<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception {
Path path = new Path(pathString);
// Expected to be global story, knot or stitch
Container flowContainer = null;
RTObject c = contentAtPath(path);
if (c instanceof Container)
flowContainer = (Container) c;
// First element of the above constructs is a compiled weave
Container innerWeaveContainer = null;
if (flowContainer.getContent().get(0) instanceof Container)
innerWeaveContainer = (Container) flowContainer.getContent().get(0);
// Any initial tag objects count as the "main tags" associated with that
// story/knot/stitch
List<String> tags = null;
for (RTObject c2 : innerWeaveContainer.getContent()) {
Tag tag = null;
if (c2 instanceof Tag)
tag = (Tag) c2;
if (tag != null) {
if (tags == null)
tags = new ArrayList<String>();
tags.add(tag.getText());
} else
break;
}
return tags;
}
/**
* Useful when debugging a (very short) story, to visualise the state of the
* story. Add this call as a watch and open the extended text. A left-arrow
* mark will denote the current point of the story. It's only recommended
* that this is used on very short debug stories, since it can end up
* generate a large quantity of text otherwise.
*/
public String buildStringOfHierarchy() {
StringBuilder sb = new StringBuilder();
mainContentContainer.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject());
return sb.toString();
}
void callExternalFunction(String funcName, int numberOfArguments) throws Exception {
Container fallbackFunctionContainer = null;
ExternalFunction func = externals.get(funcName);
// Try to use fallback function?
if (func == null) {
if (allowExternalFunctionFallbacks) {
RTObject contentAtPath = contentAtPath(new Path(funcName));
fallbackFunctionContainer = contentAtPath instanceof Container ? (Container) contentAtPath : null;
Assert(fallbackFunctionContainer != null, "Trying to call EXTERNAL function '" + funcName
+ "' which has not been bound, and fallback ink function could not be found.");
// Divert direct into fallback function and we're done
state.getCallStack().push(PushPopType.Function);
state.setDivertedTargetObject(fallbackFunctionContainer);
return;
} else {
Assert(false, "Trying to call EXTERNAL function '" + funcName
+ "' which has not been bound (and ink fallbacks disabled).");
}
}
// Pop arguments
ArrayList<Object> arguments = new ArrayList<Object>();
for (int i = 0; i < numberOfArguments; ++i) {
Value<?> poppedObj = (Value<?>) state.popEvaluationStack();
Object valueObj = poppedObj.getValueObject();
arguments.add(valueObj);
}
// Reverse arguments from the order they were popped,
// so they're the right way round again.
Collections.reverse(arguments);
// Run the function!
Object funcResult = func.call(arguments.toArray());
// Convert return value (if any) to the a type that the ink engine can
// use
RTObject returnObj = null;
if (funcResult != null) {
returnObj = AbstractValue.create(funcResult);
Assert(returnObj != null, "Could not create ink value from returned Object of type "
+ funcResult.getClass().getCanonicalName());
} else {
returnObj = new Void();
}
state.pushEvaluationStack(returnObj);
}
/**
* Check whether more content is available if you were to call Continue() -
* i.e. are we mid story rather than at a choice point or at the end.
*
* @return true if it's possible to call Continue()
*/
public boolean canContinue() {
return state.getCurrentContentObject() != null && !state.hasError();
}
/**
* Chooses the Choice from the currentChoices list with the given index.
* Internally, this sets the current content path to that pointed to by the
* Choice, ready to continue story evaluation.
*/
public void chooseChoiceIndex(int choiceIdx) throws Exception {
List<Choice> choices = getCurrentChoices();
Assert(choiceIdx >= 0 && choiceIdx < choices.size(), "choice out of range");
// Replace callstack with the one from the thread at the choosing point,
// so that we can jump into the right place in the flow.
// This is important in case the flow was forked by a new thread, which
// can create multiple leading edges for the story, each of
// which has its own context.
Choice choiceToChoose = choices.get(choiceIdx);
state.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration());
choosePath(choiceToChoose.getchoicePoint().getChoiceTarget().getPath());
}
void choosePath(Path path) throws Exception {
state.setChosenPath(path);
// Take a note of newly visited containers for read counts etc
visitChangedContainersDueToDivert();
}
/**
* Change the current position of the story to the given path. From here you
* can call Continue() to evaluate the next line. The path String is a
* dot-separated path as used ly by the engine. These examples should work:
*
* myKnot myKnot.myStitch
*
* Note however that this won't necessarily work:
*
* myKnot.myStitch.myLabelledChoice
*
* ...because of the way that content is nested within a weave structure.
*
* @param A
* dot-separted path string, as specified above.
*/
public void choosePathString(String path) throws Exception {
choosePath(new Path(path));
}
RTObject contentAtPath(Path path) throws Exception {
return mainContentContainer().contentAtPath(path);
}
/**
* Continue the story for one line of content, if possible. If you're not
* sure if there's more content available, for example if you want to check
* whether you're at a choice point or at the end of the story, you should
* call canContinue before calling this function.
*
* @return The line of text content.
*/
public String Continue() throws StoryException, Exception {
// TODO: Should we leave this to the client, since it could be
// slow to iterate through all the content an extra time?
if (!hasValidatedExternals)
validateExternalBindings();
return continueInternal();
}
String continueInternal() throws StoryException, Exception {
if (!canContinue()) {
throw new StoryException("Can't continue - should check canContinue before calling Continue");
}
state.resetOutput();
state.setDidSafeExit(false);
state.getVariablesState().setbatchObservingVariableChanges(true);
// _previousContainer = null;
try {
StoryState stateAtLastNewline = null;
// The basic algorithm here is:
//
// do { Step() } while( canContinue && !outputStreamEndsInNewline );
//
// But the complexity comes from:
// - Stepping beyond the newline in case it'll be absorbed by glue
// later
// - Ensuring that non-text content beyond newlines are generated -
// i.e. choices,
// which are actually built out of text content.
// So we have to take a snapshot of the state, continue
// prospectively,
// and rewind if necessary.
// This code is slightly fragile :-/
//
do {
// Run main step function (walks through content)
step();
// Run out of content and we have a default invisible choice
// that we can follow?
if (!canContinue()) {
tryFollowDefaultInvisibleChoice();
}
// Don't save/rewind during String evaluation, which is e.g.
// used for choices
if (!getState().inStringEvaluation()) {
// We previously found a newline, but were we just double
// checking that
// it wouldn't immediately be removed by glue?
if (stateAtLastNewline != null) {
// Cover cases that non-text generated content was
// evaluated last step
String currText = getCurrentText();
int prevTextLength = stateAtLastNewline.currentText().length();
// Take tags into account too, so that a tag following a
// content line:
// Content
// # tag
// ... doesn't cause the tag to be wrongly associated
// with the content above.
int prevTagCount = stateAtLastNewline.getCurrentTags().size();
// Output has been extended?
if (!currText.equals(stateAtLastNewline.currentText())
|| prevTagCount != getCurrentTags().size()) {
// Original newline still exists?
if (currText.length() >= prevTextLength && currText.charAt(prevTextLength - 1) == '\n') {
restoreStateSnapshot(stateAtLastNewline);
break;
}
// Newline that previously existed is no longer
// valid - e.g.
// glue was encounted that caused it to be removed.
else {
stateAtLastNewline = null;
}
}
}
// Current content ends in a newline - approaching end of
// our evaluation
if (getState().outputStreamEndsInNewline()) {
// If we can continue evaluation for a bit:
// Create a snapshot in case we need to rewind.
// We're going to continue stepping in case we see glue
// or some
// non-text content such as choices.
if (canContinue()) {
stateAtLastNewline = stateSnapshot();
}
// Can't continue, so we're about to exit - make sure we
// don't have an old state hanging around.
else {
stateAtLastNewline = null;
}
}
}
} while (canContinue());
// Need to rewind, due to evaluating further than we should?
if (stateAtLastNewline != null) {
restoreStateSnapshot(stateAtLastNewline);
}
// Finished a section of content / reached a choice point?
if (!canContinue()) {
if (getState().getCallStack().canPopThread()) {
error("Thread available to pop, threads should always be flat by the end of evaluation?");
}
if (getCurrentChoices().size() == 0 && !getState().isDidSafeExit()
&& temporaryEvaluationContainer == null) {
if (getState().getCallStack().canPop(PushPopType.Tunnel)) {
error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?");
} else if (getState().getCallStack().canPop(PushPopType.Function)) {
error("unexpectedly reached end of content. Do you need a '~ return'?");
} else if (!getState().getCallStack().canPop()) {
error("ran out of content. Do you need a '-> DONE' or '-> END'?");
} else {
error("unexpectedly reached end of content for unknown reason. Please debug compiler!");
}
}
}
} catch (StoryException e) {
addError(e.getMessage(), e.useEndLineNumber);
} finally {
getState().setDidSafeExit(false);
state.getVariablesState().setbatchObservingVariableChanges(false);
}
return getCurrentText();
}
/**
* Continue the story until the next choice point or until it runs out of
* content. This is as opposed to the Continue() method which only evaluates
* one line of output at a time.
*
* @return The resulting text evaluated by the ink engine, concatenated
* together.
*/
public String continueMaximally() throws StoryException, Exception {
StringBuilder sb = new StringBuilder();
while (canContinue()) {
sb.append(Continue());
}
return sb.toString();
}
DebugMetadata currentDebugMetadata() {
DebugMetadata dm;
// Try to get from the current path first
RTObject currentContent = state.getCurrentContentObject();
if (currentContent != null) {
dm = currentContent.getDebugMetadata();
if (dm != null) {
return dm;
}
}
// Move up callstack if possible
for (int i = state.getCallStack().getElements().size() - 1; i >= 0; --i) {
RTObject currentObj = state.getCallStack().getElements().get(i).currentRTObject;
if (currentObj != null && currentObj.getDebugMetadata() != null) {
return currentObj.getDebugMetadata();
}
}
// Current/previous path may not be valid if we've just had an error,
// or if we've simply run out of content.
// As a last resort, try to grab something from the output stream
for (int i = state.getOutputStream().size() - 1; i >= 0; --i) {
RTObject outputObj = state.getOutputStream().get(i);
dm = outputObj.getDebugMetadata();
if (dm != null) {
return dm;
}
}
return null;
}
int currentLineNumber() throws Exception {
DebugMetadata dm = currentDebugMetadata();
if (dm != null) {
return dm.startLineNumber;
}
return 0;
}
void error(String message) throws Exception {
error(message, false);
}
// Throw an exception that gets caught and causes AddError to be called,
// then exits the flow.
void error(String message, boolean useEndLineNumber) throws Exception {
StoryException e = new StoryException(message);
e.useEndLineNumber = useEndLineNumber;
throw e;
}
// Evaluate a "hot compiled" piece of ink content, as used by the REPL-like
// CommandLinePlayer.
RTObject evaluateExpression(Container exprContainer) throws StoryException, Exception {
int startCallStackHeight = state.getCallStack().getElements().size();
state.getCallStack().push(PushPopType.Tunnel);
temporaryEvaluationContainer = exprContainer;
state.goToStart();
int evalStackHeight = state.getEvaluationStack().size();
Continue();
temporaryEvaluationContainer = null;
// Should have fallen off the end of the Container, which should
// have auto-popped, but just in case we didn't for some reason,
// manually pop to restore the state (including currentPath).
if (state.getCallStack().getElements().size() > startCallStackHeight) {
state.getCallStack().pop();
}
int endStackHeight = state.getEvaluationStack().size();
if (endStackHeight > evalStackHeight) {
return state.popEvaluationStack();
} else {
return null;
}
}
/**
* The list of Choice Objects available at the current point in the Story.
* This list will be populated as the Story is stepped through with the
* Continue() method. Once canContinue becomes false, this list will be
* fully populated, and is usually (but not always) on the final Continue()
* step.
*/
public List<Choice> getCurrentChoices() {
// Don't include invisible choices for external usage.
List<Choice> choices = new ArrayList<Choice>();
for (Choice c : state.getCurrentChoices()) {
if (!c.getchoicePoint().isInvisibleDefault()) {
c.setIndex(choices.size());
choices.add(c);
}
}
return choices;
}
/**
* Gets a list of tags as defined with '#' in source that were seen during
* the latest Continue() call.
*/
public List<String> getCurrentTags() {
return state.getCurrentTags();
}
/**
* Any errors generated during evaluation of the Story.
*/
public List<String> getCurrentErrors() {
return state.getCurrentErrors();
}
/**
* The latest line of text to be generated from a Continue() call.
*/
public String getCurrentText() {
return state.currentText();
}
/**
* The entire current state of the story including (but not limited to):
*
* * Global variables * Temporary variables * Read/visit and turn counts *
* The callstack and evaluation stacks * The current threads
*
*/
public StoryState getState() {
return state;
}
/**
* The VariablesState Object contains all the global variables in the story.
* However, note that there's more to the state of a Story than just the
* global variables. This is a convenience accessor to the full state
* Object.
*/
public VariablesState getVariablesState() {
return state.getVariablesState();
}
/**
* Whether the currentErrors list contains any errors.
*/
public boolean hasError() {
return state.hasError();
}
boolean incrementContentPointer() {
boolean successfulIncrement = true;
Element currEl = state.getCallStack().currentElement();
currEl.currentContentIndex++;
// Each time we step off the end, we fall out to the next container, all
// the
// while we're in indexed rather than named content
while (currEl.currentContentIndex >= currEl.currentContainer.getContent().size()) {
successfulIncrement = false;
Container nextAncestor = currEl.currentContainer.getParent() instanceof Container
? (Container) currEl.currentContainer.getParent() : null;
if (nextAncestor == null) {
break;
}
int indexInAncestor = nextAncestor.getContent().indexOf(currEl.currentContainer);
if (indexInAncestor == -1) {
break;
}
currEl.currentContainer = nextAncestor;
currEl.currentContentIndex = indexInAncestor + 1;
successfulIncrement = true;
}
if (!successfulIncrement)
currEl.currentContainer = null;
return successfulIncrement;
}
void incrementVisitCountForContainer(Container container) {
String containerPathStr = container.getPath().toString();
Integer count = state.getVisitCounts().get(containerPathStr);
if (count == null)
count = 0;
count++;
state.getVisitCounts().put(containerPathStr, count);
}
// Does the expression result represented by this Object evaluate to true?
// e.g. is it a Number that's not equal to 1?
boolean isTruthy(RTObject obj) throws Exception {
boolean truthy = false;
if (obj instanceof Value) {
Value<?> val = (Value<?>) obj;
if (val instanceof DivertTargetValue) {
DivertTargetValue divTarget = (DivertTargetValue) val;
error("Shouldn't use a divert target (to " + divTarget.getTargetPath()
+ ") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)");
return false;
}
return val.isTruthy();
}
return truthy;
}
/**
* When the named global variable changes it's value, the observer will be
* called to notify it of the change. Note that if the value changes
* multiple times within the ink, the observer will only be called once, at
* the end of the ink's evaluation. If, during the evaluation, it changes
* and then changes back again to its original value, it will still be
* called. Note that the observer will also be fired if the value of the
* variable is changed externally to the ink, by directly setting a value in
* story.variablesState.
*
* @param variableName
* The name of the global variable to observe.
* @param observer
* A delegate function to call when the variable changes.
*/
public void observeVariable(String variableName, VariableObserver observer) {
if (variableObservers == null)
variableObservers = new HashMap<String, List<VariableObserver>>();
if (variableObservers.containsKey(variableName)) {
variableObservers.get(variableName).add(observer);
} else {
List<VariableObserver> l = new ArrayList<VariableObserver>();
l.add(observer);
variableObservers.put(variableName, l);
}
}
/**
* Convenience function to allow multiple variables to be observed with the
* same observer delegate function. See the singular ObserveVariable for
* details. The observer will get one call for every variable that has
* changed.
*
* @param variableNames
* The set of variables to observe.
* @param The
* delegate function to call when any of the named variables
* change.
*/
public void observeVariables(List<String> variableNames, VariableObserver observer) {
for (String varName : variableNames) {
observeVariable(varName, observer);
}
}
/**
* Removes the variable observer, to stop getting variable change
* notifications. If you pass a specific variable name, it will stop
* observing that particular one. If you pass null (or leave it blank, since
* it's optional), then the observer will be removed from all variables that
* it's subscribed to.
*
* @param observer
* The observer to stop observing.
* @param specificVariableName
* (Optional) Specific variable name to stop observing.
*/
public void removeVariableObserver(VariableObserver observer, String specificVariableName) {
if (variableObservers == null)
return;
// Remove observer for this specific variable
if (specificVariableName != null) {
if (variableObservers.containsKey(specificVariableName)) {
variableObservers.get(specificVariableName).remove(observer);
}
} else {
// Remove observer for all variables
for (List<VariableObserver> obs : variableObservers.values()) {
obs.remove(observer);
}
}
}
public void removeVariableObserver(VariableObserver observer) {
removeVariableObserver(observer, null);
}
@Override
public void variableStateDidChangeEvent(String variableName, RTObject newValueObj) throws Exception {
if (variableObservers == null)
return;
List<VariableObserver> observers = variableObservers.get(variableName);
if (observers != null) {
if (!(newValueObj instanceof Value)) {
throw new Exception("Tried to get the value of a variable that isn't a standard type");
}
Value<?> val = (Value<?>) newValueObj;
for (VariableObserver o : observers) {
o.call(variableName, val.getValueObject());
}
}
}
Container mainContentContainer() {
if (temporaryEvaluationContainer != null) {
return temporaryEvaluationContainer;
} else {
return mainContentContainer;
}
}
private void nextContent() throws Exception {
// Setting previousContentObject is critical for
// VisitChangedContainersDueToDivert
state.setPreviousContentObject(state.getCurrentContentObject());
// Divert step?
if (state.getDivertedTargetObject() != null) {
state.setCurrentContentObject(state.getDivertedTargetObject());
state.setDivertedTargetObject(null);
// Internally uses state.previousContentObject and
// state.currentContentObject
visitChangedContainersDueToDivert();
// Diverted location has valid content?
if (state.getCurrentContentObject() != null) {
return;
}
// Otherwise, if diverted location doesn't have valid content,
// drop down and attempt to increment.
// This can happen if the diverted path is intentionally jumping
// to the end of a container - e.g. a Conditional that's re-joining
}
boolean successfulPointerIncrement = incrementContentPointer();
// Ran out of content? Try to auto-exit from a function,
// or finish evaluating the content of a thread
if (!successfulPointerIncrement) {
boolean didPop = false;
if (state.getCallStack().canPop(PushPopType.Function)) {
// Pop from the call stack
state.getCallStack().pop(PushPopType.Function);
// This pop was due to dropping off the end of a function that
// didn't return anything,
// so in this case, we make sure that the evaluator has
// something to chomp on if it needs it
if (state.getInExpressionEvaluation()) {
state.pushEvaluationStack(new Void());
}
didPop = true;
}
else if (state.getCallStack().canPopThread()) {
state.getCallStack().popThread();
didPop = true;
}
// Step past the point where we last called out
if (didPop && state.getCurrentContentObject() != null) {
nextContent();
}
}
}
// Note that this is O(n), since it re-evaluates the shuffle indices
// from a consistent seed each time.
// TODO: Is this the best algorithm it can be?
int nextSequenceShuffleIndex() throws Exception {
RTObject popEvaluationStack = state.popEvaluationStack();
IntValue numElementsIntVal = popEvaluationStack instanceof IntValue ? (IntValue) popEvaluationStack : null;
if (numElementsIntVal == null) {
error("expected number of elements in sequence for shuffle index");
return 0;
}
Container seqContainer = state.currentContainer();
int numElements = numElementsIntVal.value;
IntValue seqCountVal = (IntValue) state.popEvaluationStack();
int seqCount = seqCountVal.value;
int loopIndex = seqCount / numElements;
int iterationIndex = seqCount % numElements;
// Generate the same shuffle based on:
// - The hash of this container, to make sure it's consistent
// each time the runtime returns to the sequence
// - How many times the runtime has looped around this full shuffle
String seqPathStr = seqContainer.getPath().toString();
int sequenceHash = 0;
for (char c : seqPathStr.toCharArray()) {
sequenceHash += c;
}
int randomSeed = sequenceHash + loopIndex + state.getStorySeed();
Random random = new Random(randomSeed);
ArrayList<Integer> unpickedIndices = new ArrayList<Integer>();
for (int i = 0; i < numElements; ++i) {
unpickedIndices.add(i);
}
for (int i = 0; i <= iterationIndex; ++i) {
int chosen = random.nextInt(Integer.MAX_VALUE) % unpickedIndices.size();
int chosenIndex = unpickedIndices.get(chosen);
unpickedIndices.remove(chosen);
if (i == iterationIndex) {
return chosenIndex;
}
}
throw new Exception("Should never reach here");
}
/**
* Checks whether contentObj is a control or flow Object rather than a piece
* of content, and performs the required command if necessary.
*
* @return true if Object was logic or flow control, false if it's normal
* content.
* @param contentObj
* Content Object.
*/
boolean performLogicAndFlowControl(RTObject contentObj) throws Exception {
if (contentObj == null) {
return false;
}
// Divert
if (contentObj instanceof Divert) {
Divert currentDivert = (Divert) contentObj;
if (currentDivert.isConditional()) {
RTObject conditionValue = state.popEvaluationStack();
// False conditional? Cancel divert
if (!isTruthy(conditionValue))
return true;
}
if (currentDivert.hasVariableTarget()) {
String varName = currentDivert.getVariableDivertName();
RTObject varContents = state.getVariablesState().getVariableWithName(varName);
if (!(varContents instanceof DivertTargetValue)) {
IntValue intContent = varContents instanceof IntValue ? (IntValue) varContents : null;
String errorMessage = "Tried to divert to a target from a variable, but the variable (" + varName
+ ") didn't contain a divert target, it ";
if (intContent != null && intContent.value == 0) {
errorMessage += "was empty/null (the value 0).";
} else {
errorMessage += "contained '" + varContents + "'.";
}
error(errorMessage);
}
DivertTargetValue target = (DivertTargetValue) varContents;
state.setDivertedTargetObject(contentAtPath(target.getTargetPath()));
} else if (currentDivert.isExternal()) {
callExternalFunction(currentDivert.getTargetPathString(), currentDivert.getExternalArgs());
return true;
} else {
state.setDivertedTargetObject(currentDivert.getTargetContent());
}
if (currentDivert.getPushesToStack()) {
state.getCallStack().push(currentDivert.getStackPushType());
}
if (state.getDivertedTargetObject() == null && !currentDivert.isExternal()) {
// Human readable name available - runtime divert is part of a
// hard-written divert that to missing content
if (currentDivert != null && currentDivert.getDebugMetadata().sourceName != null) {
error("Divert target doesn't exist: " + currentDivert.getDebugMetadata().sourceName);
} else {
error("Divert resolution failed: " + currentDivert);
}
}
return true;
}
// Start/end an expression evaluation? Or print out the result?
else if (contentObj instanceof ControlCommand) {
ControlCommand evalCommand = (ControlCommand) contentObj;
int choiceCount;
switch (evalCommand.getcommandType()) {
case EvalStart:
Assert(state.getInExpressionEvaluation() == false, "Already in expression evaluation?");
state.setInExpressionEvaluation(true);
break;
case EvalEnd:
Assert(state.getInExpressionEvaluation() == true, "Not in expression evaluation mode");
state.setInExpressionEvaluation(false);
break;
case EvalOutput:
// If the expression turned out to be empty, there may not be
// anything on the stack
if (state.getEvaluationStack().size() > 0) {
RTObject output = state.popEvaluationStack();
// Functions may evaluate to Void, in which case we skip
// output
if (!(output instanceof Void)) {
// TODO: Should we really always blanket convert to
// string?
// It would be okay to have numbers in the output stream
// the
// only problem is when exporting text for viewing, it
// skips over numbers etc.
StringValue text = new StringValue(output.toString());
state.pushToOutputStream(text);
}
}
break;
case NoOp:
break;
case Duplicate:
state.pushEvaluationStack(state.peekEvaluationStack());
break;
case PopEvaluatedValue:
state.popEvaluationStack();
break;
case PopFunction:
case PopTunnel:
PushPopType popType = evalCommand.getcommandType() == ControlCommand.CommandType.PopFunction
? PushPopType.Function : PushPopType.Tunnel;
if (state.getCallStack().currentElement().type != popType || !state.getCallStack().canPop()) {
HashMap<PushPopType, String> names = new HashMap<PushPopType, String>();
names.put(PushPopType.Function, "function return statement (~ return)");
names.put(PushPopType.Tunnel, "tunnel onwards statement (->->)");
String expected = names.get(state.getCallStack().currentElement().type);
if (!state.getCallStack().canPop()) {
expected = "end of flow (-> END or choice)";
}
String errorMsg = String.format("Found %s, when expected %s", names.get(popType), expected);
error(errorMsg);
}
else {
state.getCallStack().pop();
}
break;
case BeginString:
state.pushToOutputStream(evalCommand);
Assert(state.getInExpressionEvaluation() == true,
"Expected to be in an expression when evaluating a string");
state.setInExpressionEvaluation(false);
break;
case EndString:
// Since we're iterating backward through the content,
// build a stack so that when we build the string,
// it's in the right order
Stack<RTObject> contentStackForString = new Stack<RTObject>();
int outputCountConsumed = 0;
for (int i = state.getOutputStream().size() - 1; i >= 0; --i) {
RTObject obj = state.getOutputStream().get(i);
outputCountConsumed++;
ControlCommand command = obj instanceof ControlCommand ? (ControlCommand) obj : null;
if (command != null && command.getcommandType() == ControlCommand.CommandType.BeginString) {
break;
}
if (obj instanceof StringValue)
contentStackForString.push(obj);
}
// Consume the content that was produced for this string
state.getOutputStream()
.subList(state.getOutputStream().size() - outputCountConsumed, state.getOutputStream().size())
.clear();
// Build String out of the content we collected
StringBuilder sb = new StringBuilder();
while (contentStackForString.size() > 0) {
RTObject c = contentStackForString.pop();
sb.append(c.toString());
}
// Return to expression evaluation (from content mode)
state.setInExpressionEvaluation(true);
state.pushEvaluationStack(new StringValue(sb.toString()));
break;
case ChoiceCount:
choiceCount = getCurrentChoices().size();
state.pushEvaluationStack(new IntValue(choiceCount));
break;
case TurnsSince:
RTObject target = state.popEvaluationStack();
if (!(target instanceof DivertTargetValue)) {
String extraNote = "";
if (target instanceof IntValue)
extraNote = ". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?";
error("TURNS_SINCE expected a divert target (knot, stitch, label name), but saw " + target
+ extraNote);
break;
}
DivertTargetValue divertTarget = target instanceof DivertTargetValue ? (DivertTargetValue) target
: null;
Container container = contentAtPath(divertTarget.getTargetPath()) instanceof Container
? (Container) contentAtPath(divertTarget.getTargetPath()) : null;
int turnCount = turnsSinceForContainer(container);
state.pushEvaluationStack(new IntValue(turnCount));
break;
case Random: {
IntValue maxInt = null;
RTObject o = state.popEvaluationStack();
if (o instanceof IntValue)
maxInt = (IntValue) o;
IntValue minInt = null;
o = state.popEvaluationStack();
if (o instanceof IntValue)
minInt = (IntValue) o;
if (minInt == null)
error("Invalid value for minimum parameter of RANDOM(min, max)");
if (maxInt == null)
error("Invalid value for maximum parameter of RANDOM(min, max)");
// +1 because it's inclusive of min and max, for e.g.
// RANDOM(1,6) for a dice roll.
int randomRange = maxInt.value - minInt.value + 1;
if (randomRange <= 0)
error("RANDOM was called with minimum as " + minInt.value + " and maximum as " + maxInt.value
+ ". The maximum must be larger");
int resultSeed = state.getStorySeed() + state.getPreviousRandom();
Random random = new Random(resultSeed);
int nextRandom = random.nextInt(Integer.MAX_VALUE);
int chosenValue = (nextRandom % randomRange) + minInt.value;
state.pushEvaluationStack(new IntValue(chosenValue));
// Next random number (rather than keeping the Random object
// around)
state.setPreviousRandom(state.getPreviousRandom() + 1);
break;
}
case SeedRandom:
IntValue seed = null;
RTObject o = state.popEvaluationStack();
if (o instanceof IntValue)
seed = (IntValue) o;
if (seed == null)
error("Invalid value passed to SEED_RANDOM");
// Story seed affects both RANDOM and shuffle behaviour
state.setStorySeed(seed.value);
state.setPreviousRandom(0);
// SEED_RANDOM returns nothing.
state.pushEvaluationStack(new Void());
break;
case VisitIndex:
int count = visitCountForContainer(state.currentContainer()) - 1; // index
// not
// count
state.pushEvaluationStack(new IntValue(count));
break;
case SequenceShuffleIndex:
int shuffleIndex = nextSequenceShuffleIndex();
state.pushEvaluationStack(new IntValue(shuffleIndex));
break;
case StartThread:
// Handled in main step function
break;
case Done:
// We may exist in the context of the initial
// act of creating the thread, or in the context of
// evaluating the content.
if (state.getCallStack().canPopThread()) {
state.getCallStack().popThread();
}
// In normal flow - allow safe exit without warning
else {
state.setDidSafeExit(true);
// Stop flow in current thread
state.setCurrentContentObject(null);
}
break;
// Force flow to end completely
case End:
state.forceEnd();
break;
default:
error("unhandled ControlCommand: " + evalCommand);
break;
}
return true;
}
// Variable assignment
else if (contentObj instanceof VariableAssignment) {
VariableAssignment varAss = (VariableAssignment) contentObj;
RTObject assignedVal = state.popEvaluationStack();
// When in temporary evaluation, don't create new variables purely
// within
// the temporary context, but attempt to create them globally
// var prioritiseHigherInCallStack = _temporaryEvaluationContainer
// != null;
state.getVariablesState().assign(varAss, assignedVal);
return true;
}
// Variable reference
else if (contentObj instanceof VariableReference) {
VariableReference varRef = (VariableReference) contentObj;
RTObject foundValue = null;
// Explicit read count value
if (varRef.getPathForCount() != null) {
Container container = varRef.getContainerForCount();
int count = visitCountForContainer(container);
foundValue = new IntValue(count);
}
// Normal variable reference
else {
foundValue = state.getVariablesState().getVariableWithName(varRef.getName());
if (foundValue == null) {
error("Uninitialised variable: " + varRef.getName());
foundValue = new IntValue(0);
}
}
state.getEvaluationStack().add(foundValue);
return true;
}
// Native function call
else if (contentObj instanceof NativeFunctionCall) {
NativeFunctionCall func = (NativeFunctionCall) contentObj;
List<RTObject> funcParams = state.popEvaluationStack(func.getNumberOfParameters());
RTObject result = func.call(funcParams);
state.getEvaluationStack().add(result);
return true;
}
// No control content, must be ordinary content
return false;
}
Choice processChoice(ChoicePoint choicePoint) throws Exception {
boolean showChoice = true;
// Don't create choice if choice point doesn't pass conditional
if (choicePoint.hasCondition()) {
RTObject conditionValue = state.popEvaluationStack();
if (!isTruthy(conditionValue)) {
showChoice = false;
}
}
String startText = "";
String choiceOnlyText = "";
if (choicePoint.hasChoiceOnlyContent()) {
StringValue choiceOnlyStrVal = (StringValue) state.popEvaluationStack();
choiceOnlyText = choiceOnlyStrVal.value;
}
if (choicePoint.hasStartContent()) {
StringValue startStrVal = (StringValue) state.popEvaluationStack();
startText = startStrVal.value;
}
// Don't create choice if player has already read this content
if (choicePoint.isOnceOnly()) {
int visitCount = visitCountForContainer(choicePoint.getChoiceTarget());
if (visitCount > 0) {
showChoice = false;
}
}
Choice choice = new Choice(choicePoint);
choice.setThreadAtGeneration(state.getCallStack().getcurrentThread().copy());
// We go through the full process of creating the choice above so
// that we consume the content for it, since otherwise it'll
// be shown on the output stream.
if (!showChoice) {
return null;
}
// Set final text for the choice
choice.setText(startText + choiceOnlyText);
return choice;
}
void recordTurnIndexVisitToContainer(Container container) {
String containerPathStr = container.getPath().toString();
state.getTurnIndices().put(containerPathStr, state.getCurrentTurnIndex());
}
/**
* Unwinds the callstack. Useful to reset the Story's evaluation without
* actually changing any meaningful state, for example if you want to exit a
* section of story prematurely and tell it to go elsewhere with a call to
* ChoosePathString(...). Doing so without calling ResetCallstack() could
* cause unexpected issues if, for example, the Story was in a tunnel
* already.
*/
public void resetCallstack() throws Exception {
state.forceEnd();
}
/**
* Reset the runtime error list within the state.
*/
public void resetErrors() {
state.resetErrors();
}
void resetGlobals() throws Exception {
if (mainContentContainer.getNamedContent().containsKey("global decl")) {
Path originalPath = getState().getCurrentPath();
choosePathString("global decl");
// Continue, but without validating external bindings,
// since we may be doing this reset at initialisation time.
continueInternal();
getState().setCurrentPath(originalPath);
}
}
/**
* Reset the Story back to its initial state as it was when it was first
* constructed.
*/
public void resetState() throws Exception {
state = new StoryState(this);
state.getVariablesState().setVariableChangedEvent(this);
resetGlobals();
}
void restoreStateSnapshot(StoryState state) {
this.state = state;
}
StoryState stateSnapshot() throws Exception {
return state.copy();
}
void step() throws Exception {
boolean shouldAddToStream = true;
// Get current content
RTObject currentContentObj = state.getCurrentContentObject();
if (currentContentObj == null) {
return;
}
// Step directly to the first element of content in a container (if
// necessary)
Container currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null;
while (currentContainer != null) {
// Mark container as being entered
visitContainer(currentContainer, true);
// No content? the most we can do is step past it
if (currentContainer.getContent().size() == 0)
break;
currentContentObj = currentContainer.getContent().get(0);
state.getCallStack().currentElement().currentContentIndex = 0;
state.getCallStack().currentElement().currentContainer = currentContainer;
currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null;
}
currentContainer = state.getCallStack().currentElement().currentContainer;
// Is the current content Object:
// - Normal content
// - Or a logic/flow statement - if so, do it
// Stop flow if we hit a stack pop when we're unable to pop (e.g.
// return/done statement in knot
// that was diverted to rather than called as a function)
boolean isLogicOrFlowControl = performLogicAndFlowControl(currentContentObj);
// Has flow been forced to end by flow control above?
if (state.getCurrentContentObject() == null) {
return;
}
if (isLogicOrFlowControl) {
shouldAddToStream = false;
}
// Choice with condition?
ChoicePoint choicePoint = currentContentObj instanceof ChoicePoint ? (ChoicePoint) currentContentObj : null;
if (choicePoint != null) {
Choice choice = processChoice(choicePoint);
if (choice != null) {
state.getCurrentChoices().add(choice);
}
currentContentObj = null;
shouldAddToStream = false;
}
// If the container has no content, then it will be
// the "content" itself, but we skip over it.
if (currentContentObj instanceof Container) {
shouldAddToStream = false;
}
// Content to add to evaluation stack or the output stream
if (shouldAddToStream) {
// If we're pushing a variable pointer onto the evaluation stack,
// ensure that it's specific
// to our current (possibly temporary) context index. And make a
// copy of the pointer
// so that we're not editing the original runtime Object.
VariablePointerValue varPointer = currentContentObj instanceof VariablePointerValue
? (VariablePointerValue) currentContentObj : null;
if (varPointer != null && varPointer.getContextIndex() == -1) {
// Create new Object so we're not overwriting the story's own
// data
int contextIdx = state.getCallStack().contextForVariableNamed(varPointer.getVariableName());
currentContentObj = new VariablePointerValue(varPointer.getVariableName(), contextIdx);
}
// Expression evaluation content
if (state.getInExpressionEvaluation()) {
state.pushEvaluationStack(currentContentObj);
}
// Output stream content (i.e. not expression evaluation)
else {
state.pushToOutputStream(currentContentObj);
}
}
// Increment the content pointer, following diverts if necessary
nextContent();
// Starting a thread should be done after the increment to the content
// pointer,
// so that when returning from the thread, it returns to the content
// after this instruction.
ControlCommand controlCmd = currentContentObj instanceof ControlCommand ? (ControlCommand) currentContentObj
: null;
if (controlCmd != null && controlCmd.getcommandType() == ControlCommand.CommandType.StartThread) {
state.getCallStack().pushThread();
}
}
/**
* The Story itself in JSON representation.
*/
public String toJsonString() throws Exception {
List<?> rootContainerJsonList = (List<?>) Json.runtimeObjectToJToken(mainContentContainer);
HashMap<String, Object> rootObject = new HashMap<String, Object>();
rootObject.put("inkVersion", inkVersionCurrent);
rootObject.put("root", rootContainerJsonList);
return SimpleJson.HashMapToText(rootObject);
}
boolean tryFollowDefaultInvisibleChoice() throws Exception {
List<Choice> allChoices = state.getCurrentChoices();
// Is a default invisible choice the ONLY choice?
// var invisibleChoices = allChoices.Where (c =>
// c.choicePoint.isInvisibleDefault).ToList();
ArrayList<Choice> invisibleChoices = new ArrayList<Choice>();
for (Choice c : allChoices) {
if (c.getchoicePoint().isInvisibleDefault()) {
invisibleChoices.add(c);
}
}
if (invisibleChoices.size() == 0 || allChoices.size() > invisibleChoices.size())
return false;
Choice choice = invisibleChoices.get(0);
choosePath(choice.getchoicePoint().getChoiceTarget().getPath());
return true;
}
int turnsSinceForContainer(Container container) throws Exception {
if (!container.getTurnIndexShouldBeCounted()) {
error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata()
+ ") unknown. The story may need to be compiled with countAllVisits flag (-c).");
}
String containerPathStr = container.getPath().toString();
Integer index = state.getTurnIndices().get(containerPathStr);
if (index != null) {
return state.getCurrentTurnIndex() - index;
} else {
return -1;
}
}
/**
* Remove a binding for a named EXTERNAL ink function.
*/
public void unbindExternalFunction(String funcName) throws Exception {
Assert(externals.containsKey(funcName), "Function '" + funcName + "' has not been bound.");
externals.remove(funcName);
}
/**
* Check that all EXTERNAL ink functions have a valid bound C# function.
* Note that this is automatically called on the first call to Continue().
*/
public void validateExternalBindings() throws Exception {
validateExternalBindings(mainContentContainer);
hasValidatedExternals = true;
}
void validateExternalBindings(Container c) throws Exception {
for (RTObject innerContent : c.getContent()) {
validateExternalBindings(innerContent);
}
for (INamedContent innerKeyValue : c.getNamedContent().values()) {
validateExternalBindings(innerKeyValue instanceof RTObject ? (RTObject) innerKeyValue : null);
}
}
void validateExternalBindings(RTObject o) throws Exception {
Container container = o instanceof Container ? (Container) o : null;
if (container != null) {
validateExternalBindings(container);
return;
}
Divert divert = o instanceof Divert ? (Divert) o : null;
if (divert != null && divert.isExternal()) {
String name = divert.getTargetPathString();
if (!externals.containsKey(name)) {
INamedContent fallbackFunction = mainContentContainer().getNamedContent().get(name);
String message = null;
if (!allowExternalFunctionFallbacks)
message = "Missing function binding for external '" + name + "' (ink fallbacks disabled)";
else if (fallbackFunction == null) {
message = "Missing function binding for external '" + name
+ "', and no fallback ink function found.";
}
if (message != null) {
String errorPreamble = "ERROR: ";
if (divert.getDebugMetadata() != null) {
errorPreamble += String.format("'%s' line %d: ", divert.getDebugMetadata().fileName,
divert.getDebugMetadata().startLineNumber);
}
throw new StoryException(errorPreamble + message);
}
}
}
}
void visitChangedContainersDueToDivert() {
RTObject previousContentObject = state.getPreviousContentObject();
RTObject newContentObject = state.getCurrentContentObject();
if (newContentObject == null)
return;
// First, find the previously open set of containers
HashSet<Container> prevContainerSet = new HashSet<Container>();
if (previousContentObject != null) {
Container prevAncestor = null;
if (previousContentObject instanceof Container) {
prevAncestor = (Container) previousContentObject;
} else if (previousContentObject.getParent() instanceof Container) {
prevAncestor = (Container) previousContentObject.getParent();
}
while (prevAncestor != null) {
prevContainerSet.add(prevAncestor);
prevAncestor = prevAncestor.getParent() instanceof Container ? (Container) prevAncestor.getParent()
: null;
}
}
// If the new Object is a container itself, it will be visited
// automatically at the next actual
// content step. However, we need to walk up the new ancestry to see if
// there are more new containers
RTObject currentChildOfContainer = newContentObject;
Container currentContainerAncestor = currentChildOfContainer.getParent() instanceof Container
? (Container) currentChildOfContainer.getParent() : null;
while (currentContainerAncestor != null && !prevContainerSet.contains(currentContainerAncestor)) {
// Check whether this ancestor container is being entered at the
// start,
// by checking whether the child Object is the first.
boolean enteringAtStart = currentContainerAncestor.getContent().size() > 0
&& currentChildOfContainer == currentContainerAncestor.getContent().get(0);
// Mark a visit to this container
visitContainer(currentContainerAncestor, enteringAtStart);
currentChildOfContainer = currentContainerAncestor;
currentContainerAncestor = currentContainerAncestor.getParent() instanceof Container
? (Container) currentContainerAncestor.getParent() : null;
}
}
// Mark a container as having been visited
void visitContainer(Container container, boolean atStart) {
if (!container.getCountingAtStartOnly() || atStart) {
if (container.getVisitsShouldBeCounted())
incrementVisitCountForContainer(container);
if (container.getTurnIndexShouldBeCounted())
recordTurnIndexVisitToContainer(container);
}
}
int visitCountForContainer(Container container) throws Exception {
if (!container.getVisitsShouldBeCounted()) {
error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata()
+ ") unknown. The story may need to be compiled with countAllVisits flag (-c).");
return 0;
}
String containerPathStr = container.getPath().toString();
Integer count = state.getVisitCounts().get(containerPathStr);
return count == null ? 0 : count;
}
public boolean allowExternalFunctionFallbacks() {
return allowExternalFunctionFallbacks;
}
public void setAllowExternalFunctionFallbacks(boolean allowExternalFunctionFallbacks) {
this.allowExternalFunctionFallbacks = allowExternalFunctionFallbacks;
}
/**
* Evaluates a function defined in ink.
*
* @param functionName
* The name of the function as declared in ink.
* @param arguments
* The arguments that the ink function takes, if any. Note that
* we don't (can't) do any validation on the number of arguments
* right now, so make sure you get it right!
* @return The return value as returned from the ink function with `~ return
* myValue`, or null if nothing is returned.
* @throws Exception
*/
public Object evaluateFunction(String functionName, Object[] arguments) throws Exception {
return evaluateFunction(functionName, null, arguments);
}
/**
* Checks if a function exists.
*
* @returns True if the function exists, else false.
* @param functionName
* The name of the function as declared in ink.
*/
public boolean hasFunction(String functionName) {
try {
return contentAtPath(new Path(functionName)) instanceof Container;
} catch (Exception e) {
return false;
}
}
/**
* Evaluates a function defined in ink, and gathers the possibly multi-line
* text as generated by the function.
*
* @param arguments
* The arguments that the ink function takes, if any. Note that
* we don't (can't) do any validation on the number of arguments
* right now, so make sure you get it right!
* @param functionName
* The name of the function as declared in ink.
* @param textOutput
* This text output is any text written as normal content within
* the function, as opposed to the return value, as returned with
* `~ return`.
* @return The return value as returned from the ink function with `~ return
* myValue`, or null if nothing is returned.
* @throws Exception
*/
public Object evaluateFunction(String functionName, StringBuffer textOutput, Object[] arguments) throws Exception {
Container funcContainer = null;
if (functionName == null) {
throw new Exception("Function is null");
} else if (functionName.trim().isEmpty()) {
throw new Exception("Function is empty or white space.");
}
try {
RTObject contentAtPath = contentAtPath(new Path(functionName));
if (contentAtPath instanceof Container)
funcContainer = (Container) contentAtPath;
} catch (StoryException e) {
if (e.getMessage().contains("not found"))
throw new Exception("Function doesn't exist: '" + functionName + "'");
else
throw e;
}
// We'll start a new callstack, so keep hold of the original,
// as well as the evaluation stack so we know if the function
// returned something
CallStack originalCallstack = state.getCallStack();
int originalEvaluationStackHeight = state.getEvaluationStack().size();
// Create a new base call stack element.
// By making it point at element 0 of the base, when NextContent is
// called, it'll actually step past the entire content of the game (!)
// and straight onto the Done. Bit of a hack :-/ We don't really have
// a better way of creating a temporary context that ends correctly.
state.setCallStack(new CallStack(mainContentContainer));
state.getCallStack().currentElement().currentContainer = mainContentContainer;
state.getCallStack().currentElement().currentContentIndex = 0;
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
if (!(arguments[i] instanceof Integer || arguments[i] instanceof Float
|| arguments[i] instanceof String)) {
throw new IllegalArgumentException(
"ink arguments when calling EvaluateFunction must be int, float or string");
}
state.getEvaluationStack().add(Value.create(arguments[i]));
}
}
// Jump into the function!
state.getCallStack().push(PushPopType.Function);
state.setCurrentContentObject(funcContainer);
// Evaluate the function, and collect the string output
while (canContinue()) {
String text = Continue();
if (textOutput != null)
textOutput.append(text);
}
// Restore original stack
state.setCallStack(originalCallstack);
// Do we have a returned value?
// Potentially pop multiple values off the stack, in case we need
// to clean up after ourselves (e.g. caller of EvaluateFunction may
// have passed too many arguments, and we currently have no way to check
// for that)
RTObject returnedObj = null;
while (state.getEvaluationStack().size() > originalEvaluationStackHeight) {
RTObject poppedObj = state.popEvaluationStack();
if (returnedObj == null)
returnedObj = poppedObj;
}
if (returnedObj != null) {
if (returnedObj instanceof Void)
return null;
// Some kind of value, if not void
Value<?> returnVal = (Value<?>) returnedObj;
// DivertTargets get returned as the string of components
// (rather than a Path, which isn't public)
if (returnVal.getValueType() == ValueType.DivertTarget) {
return returnVal.getValueObject().toString();
}
// Other types can just have their exact object type:
// int, float, string. VariablePointers get returned as strings.
return returnVal.getValueObject();
}
return null;
}
}
| src/main/java/com/bladecoder/ink/runtime/Story.java | package com.bladecoder.ink.runtime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Stack;
import com.bladecoder.ink.runtime.CallStack.Element;
/**
* A Story is the core class that represents a complete Ink narrative, and
* manages the evaluation and state of it.
*/
public class Story extends RTObject implements VariablesState.VariableChanged {
/**
* General purpose delegate definition for bound EXTERNAL function
* definitions from ink. Note that this version isn't necessary if you have
* a function with three arguments or less - see the overloads of
* BindExternalFunction.
*/
public interface ExternalFunction {
Object call(Object[] args) throws Exception;
}
// Version numbers are for engine itself and story file, rather
// than the story state save format (which is um, currently nonexistant)
// -- old engine, new format: always fail
// -- new engine, old format: possibly cope, based on this number
// When incrementing the version number above, the question you
// should ask yourself is:
// -- Will the engine be able to load an old story file from
// before I made these changes to the engine?
// If possible, you should support it, though it's not as
// critical as loading old save games, since it's an
// in-development problem only.
/**
* Delegate definition for variable observation - see ObserveVariable.
*/
public interface VariableObserver {
void call(String variableName, Object newValue);
}
/**
* The current version of the ink story file format.
*/
public static final int inkVersionCurrent = 15;
/**
* The minimum legacy version of ink that can be loaded by the current
* version of the code.
*/
public static final int inkVersionMinimumCompatible = 12;
private Container mainContentContainer;
/**
* An ink file can provide a fallback functions for when when an EXTERNAL
* has been left unbound by the client, and the fallback function will be
* called instead. Useful when testing a story in playmode, when it's not
* possible to write a client-side C# external function, but you don't want
* it to fail to run.
*/
private boolean allowExternalFunctionFallbacks;
private HashMap<String, ExternalFunction> externals;
private boolean hasValidatedExternals;
private StoryState state;
private Container temporaryEvaluationContainer;
private HashMap<String, List<VariableObserver>> variableObservers;
// Warning: When creating a Story using this constructor, you need to
// call ResetState on it before use. Intended for compiler use only.
// For normal use, use the constructor that takes a json string.
Story(Container contentContainer) {
mainContentContainer = contentContainer;
externals = new HashMap<String, ExternalFunction>();
}
/**
* Construct a Story Object using a JSON String compiled through inklecate.
*/
public Story(String jsonString) throws Exception {
this((Container) null);
HashMap<String, Object> rootObject = SimpleJson.textToHashMap(jsonString);
Object versionObj = rootObject.get("inkVersion");
if (versionObj == null)
throw new Exception("ink version number not found. Are you sure it's a valid .ink.json file?");
int formatFromFile = versionObj instanceof String ? Integer.parseInt((String) versionObj) : (int) versionObj;
if (formatFromFile > inkVersionCurrent) {
throw new Exception("Version of ink used to build story was newer than the current verison of the engine");
} else if (formatFromFile < inkVersionMinimumCompatible) {
throw new Exception(
"Version of ink used to build story is too old to be loaded by this version of the engine");
} else if (formatFromFile != inkVersionCurrent) {
System.out.println(
"WARNING: Version of ink used to build story doesn't match current version of engine. Non-critical, but recommend synchronising.");
}
Object rootToken = rootObject.get("root");
if (rootToken == null)
throw new Exception("Root node for ink not found. Are you sure it's a valid .ink.json file?");
mainContentContainer = Json.jTokenToRuntimeObject(rootToken) instanceof Container
? (Container) Json.jTokenToRuntimeObject(rootToken) : null;
resetState();
}
void addError(String message, boolean useEndLineNumber) throws Exception {
DebugMetadata dm = currentDebugMetadata();
if (dm != null) {
int lineNum = useEndLineNumber ? dm.endLineNumber : dm.startLineNumber;
message = String.format("RUNTIME ERROR: '%s' line %d: %s", dm.fileName, lineNum, message);
} else {
message = "RUNTIME ERROR: " + message;
}
state.addError(message);
// In a broken state don't need to know about any other errors.
state.forceEnd();
}
void Assert(boolean condition, Object... formatParams) throws Exception {
Assert(condition, null, formatParams);
}
void Assert(boolean condition, String message, Object... formatParams) throws Exception {
if (condition == false) {
if (message == null) {
message = "Story assert";
}
if (formatParams != null && formatParams.length > 0) {
message = String.format(message, formatParams);
}
throw new Exception(message + " " + currentDebugMetadata());
}
}
/**
* Most general form of function binding that returns an Object and takes an
* array of Object parameters. The only way to bind a function with more
* than 3 arguments.
*
* @param funcName
* EXTERNAL ink function name to bind to.
* @param func
* The Java function to bind.
*/
public void bindExternalFunction(String funcName, ExternalFunction func) throws Exception {
Assert(!externals.containsKey(funcName), "Function '" + funcName + "' has already been bound.");
externals.put(funcName, func);
}
@SuppressWarnings("unchecked")
public <T> T tryCoerce(Object value, Class<T> type) throws Exception {
if (value == null)
return null;
if (type.isAssignableFrom(value.getClass()))
return (T) value;
if (value instanceof Float && type == Integer.class) {
Integer intVal = (int) Math.round((Float) value);
return (T) intVal;
}
if (value instanceof Integer && type == Float.class) {
Float floatVal = Float.valueOf((Integer) value);
return (T) floatVal;
}
if (value instanceof Integer && type == Boolean.class) {
int intVal = (Integer) value;
return (T) (intVal == 0 ? new Boolean(false) : new Boolean(true));
}
if (type == String.class) {
return (T) value.toString();
}
Assert(false, "Failed to cast " + value.getClass().getCanonicalName() + " to " + type.getCanonicalName());
return null;
}
/**
* Get any global tags associated with the story. These are defined as hash
* tags defined at the very top of the story.
* @throws Exception
*/
public List<String> getGlobalTags() throws Exception {
return tagsAtStartOfFlowContainerWithPathString("");
}
/**
* Gets any tags associated with a particular knot or knot.stitch.
* These are defined as hash tags defined at the very top of a
* knot or stitch.
* @param path The path of the knot or stitch, in the form "knot" or
* "knot.stitch".
* @throws Exception
*/
public List<String> tagsForContentAtPath(String path) throws Exception {
return tagsAtStartOfFlowContainerWithPathString(path);
}
List<String> tagsAtStartOfFlowContainerWithPathString (String pathString) throws Exception {
Path path = new Path (pathString);
// Expected to be global story, knot or stitch
Container flowContainer = null;
RTObject c = contentAtPath(path);
if (c instanceof Container)
flowContainer = (Container)c;
// First element of the above constructs is a compiled weave
Container innerWeaveContainer = null;
if(flowContainer.getContent().get(0) instanceof Container)
innerWeaveContainer = (Container)flowContainer.getContent().get(0);
// Any initial tag objects count as the "main tags" associated with that story/knot/stitch
List<String> tags = null;
for ( RTObject c2 :innerWeaveContainer.getContent()) {
Tag tag = null;
if(c2 instanceof Tag)
tag = (Tag)c2;
if (tag != null) {
if (tags == null) tags = new ArrayList<String> ();
tags.add (tag.getText());
} else break;
}
return tags;
}
/**
* Useful when debugging a (very short) story, to visualise the state of the
* story. Add this call as a watch and open the extended text. A left-arrow
* mark will denote the current point of the story. It's only recommended
* that this is used on very short debug stories, since it can end up
* generate a large quantity of text otherwise.
*/
public String buildStringOfHierarchy() {
StringBuilder sb = new StringBuilder();
mainContentContainer.buildStringOfHierarchy(sb, 0, state.getCurrentContentObject());
return sb.toString();
}
void callExternalFunction(String funcName, int numberOfArguments) throws Exception {
Container fallbackFunctionContainer = null;
ExternalFunction func = externals.get(funcName);
// Try to use fallback function?
if (func == null) {
if (allowExternalFunctionFallbacks) {
RTObject contentAtPath = contentAtPath(new Path(funcName));
fallbackFunctionContainer = contentAtPath instanceof Container ? (Container) contentAtPath : null;
Assert(fallbackFunctionContainer != null, "Trying to call EXTERNAL function '" + funcName
+ "' which has not been bound, and fallback ink function could not be found.");
// Divert direct into fallback function and we're done
state.getCallStack().push(PushPopType.Function);
state.setDivertedTargetObject(fallbackFunctionContainer);
return;
} else {
Assert(false, "Trying to call EXTERNAL function '" + funcName
+ "' which has not been bound (and ink fallbacks disabled).");
}
}
// Pop arguments
ArrayList<Object> arguments = new ArrayList<Object>();
for (int i = 0; i < numberOfArguments; ++i) {
Value<?> poppedObj = (Value<?>) state.popEvaluationStack();
Object valueObj = poppedObj.getValueObject();
arguments.add(valueObj);
}
// Reverse arguments from the order they were popped,
// so they're the right way round again.
Collections.reverse(arguments);
// Run the function!
Object funcResult = func.call(arguments.toArray());
// Convert return value (if any) to the a type that the ink engine can
// use
RTObject returnObj = null;
if (funcResult != null) {
returnObj = AbstractValue.create(funcResult);
Assert(returnObj != null, "Could not create ink value from returned Object of type "
+ funcResult.getClass().getCanonicalName());
} else {
returnObj = new Void();
}
state.pushEvaluationStack(returnObj);
}
/**
* Check whether more content is available if you were to call Continue() -
* i.e. are we mid story rather than at a choice point or at the end.
*
* @return true if it's possible to call Continue()
*/
public boolean canContinue() {
return state.getCurrentContentObject() != null && !state.hasError();
}
/**
* Chooses the Choice from the currentChoices list with the given index.
* Internally, this sets the current content path to that pointed to by the
* Choice, ready to continue story evaluation.
*/
public void chooseChoiceIndex(int choiceIdx) throws Exception {
List<Choice> choices = getCurrentChoices();
Assert(choiceIdx >= 0 && choiceIdx < choices.size(), "choice out of range");
// Replace callstack with the one from the thread at the choosing point,
// so that we can jump into the right place in the flow.
// This is important in case the flow was forked by a new thread, which
// can create multiple leading edges for the story, each of
// which has its own context.
Choice choiceToChoose = choices.get(choiceIdx);
state.getCallStack().setCurrentThread(choiceToChoose.getThreadAtGeneration());
choosePath(choiceToChoose.getchoicePoint().getChoiceTarget().getPath());
}
void choosePath(Path path) throws Exception {
state.setChosenPath(path);
// Take a note of newly visited containers for read counts etc
visitChangedContainersDueToDivert();
}
/**
* Change the current position of the story to the given path. From here you
* can call Continue() to evaluate the next line. The path String is a
* dot-separated path as used ly by the engine. These examples should work:
*
* myKnot myKnot.myStitch
*
* Note however that this won't necessarily work:
*
* myKnot.myStitch.myLabelledChoice
*
* ...because of the way that content is nested within a weave structure.
*
* @param A
* dot-separted path string, as specified above.
*/
public void choosePathString(String path) throws Exception {
choosePath(new Path(path));
}
RTObject contentAtPath(Path path) throws Exception {
return mainContentContainer().contentAtPath(path);
}
/**
* Continue the story for one line of content, if possible. If you're not
* sure if there's more content available, for example if you want to check
* whether you're at a choice point or at the end of the story, you should
* call canContinue before calling this function.
*
* @return The line of text content.
*/
public String Continue() throws StoryException, Exception {
// TODO: Should we leave this to the client, since it could be
// slow to iterate through all the content an extra time?
if (!hasValidatedExternals)
validateExternalBindings();
return continueInternal();
}
String continueInternal() throws StoryException, Exception {
if (!canContinue()) {
throw new StoryException("Can't continue - should check canContinue before calling Continue");
}
state.resetOutput();
state.setDidSafeExit(false);
state.getVariablesState().setbatchObservingVariableChanges(true);
// _previousContainer = null;
try {
StoryState stateAtLastNewline = null;
// The basic algorithm here is:
//
// do { Step() } while( canContinue && !outputStreamEndsInNewline );
//
// But the complexity comes from:
// - Stepping beyond the newline in case it'll be absorbed by glue
// later
// - Ensuring that non-text content beyond newlines are generated -
// i.e. choices,
// which are actually built out of text content.
// So we have to take a snapshot of the state, continue
// prospectively,
// and rewind if necessary.
// This code is slightly fragile :-/
//
do {
// Run main step function (walks through content)
step();
// Run out of content and we have a default invisible choice
// that we can follow?
if (!canContinue()) {
tryFollowDefaultInvisibleChoice();
}
// Don't save/rewind during String evaluation, which is e.g.
// used for choices
if (!getState().inStringEvaluation()) {
// We previously found a newline, but were we just double
// checking that
// it wouldn't immediately be removed by glue?
if (stateAtLastNewline != null) {
// Cover cases that non-text generated content was
// evaluated last step
String currText = getCurrentText();
int prevTextLength = stateAtLastNewline.currentText().length();
// Output has been extended?
if (!currText.equals(stateAtLastNewline.currentText())) {
// Original newline still exists?
if (currText.length() >= prevTextLength && currText.charAt(prevTextLength - 1) == '\n') {
restoreStateSnapshot(stateAtLastNewline);
break;
}
// Newline that previously existed is no longer
// valid - e.g.
// glue was encounted that caused it to be removed.
else {
stateAtLastNewline = null;
}
}
}
// Current content ends in a newline - approaching end of
// our evaluation
if (getState().outputStreamEndsInNewline()) {
// If we can continue evaluation for a bit:
// Create a snapshot in case we need to rewind.
// We're going to continue stepping in case we see glue
// or some
// non-text content such as choices.
if (canContinue()) {
stateAtLastNewline = stateSnapshot();
}
// Can't continue, so we're about to exit - make sure we
// don't have an old state hanging around.
else {
stateAtLastNewline = null;
}
}
}
} while (canContinue());
// Need to rewind, due to evaluating further than we should?
if (stateAtLastNewline != null) {
restoreStateSnapshot(stateAtLastNewline);
}
// Finished a section of content / reached a choice point?
if (!canContinue()) {
if (getState().getCallStack().canPopThread()) {
error("Thread available to pop, threads should always be flat by the end of evaluation?");
}
if (getCurrentChoices().size() == 0 && !getState().isDidSafeExit()
&& temporaryEvaluationContainer == null) {
if (getState().getCallStack().canPop(PushPopType.Tunnel)) {
error("unexpectedly reached end of content. Do you need a '->->' to return from a tunnel?");
} else if (getState().getCallStack().canPop(PushPopType.Function)) {
error("unexpectedly reached end of content. Do you need a '~ return'?");
} else if (!getState().getCallStack().canPop()) {
error("ran out of content. Do you need a '-> DONE' or '-> END'?");
} else {
error("unexpectedly reached end of content for unknown reason. Please debug compiler!");
}
}
}
} catch (StoryException e) {
addError(e.getMessage(), e.useEndLineNumber);
} finally {
getState().setDidSafeExit(false);
state.getVariablesState().setbatchObservingVariableChanges(false);
}
return getCurrentText();
}
/**
* Continue the story until the next choice point or until it runs out of
* content. This is as opposed to the Continue() method which only evaluates
* one line of output at a time.
*
* @return The resulting text evaluated by the ink engine, concatenated
* together.
*/
public String continueMaximally() throws StoryException, Exception {
StringBuilder sb = new StringBuilder();
while (canContinue()) {
sb.append(Continue());
}
return sb.toString();
}
DebugMetadata currentDebugMetadata() {
DebugMetadata dm;
// Try to get from the current path first
RTObject currentContent = state.getCurrentContentObject();
if (currentContent != null) {
dm = currentContent.getDebugMetadata();
if (dm != null) {
return dm;
}
}
// Move up callstack if possible
for (int i = state.getCallStack().getElements().size() - 1; i >= 0; --i) {
RTObject currentObj = state.getCallStack().getElements().get(i).currentRTObject;
if (currentObj != null && currentObj.getDebugMetadata() != null) {
return currentObj.getDebugMetadata();
}
}
// Current/previous path may not be valid if we've just had an error,
// or if we've simply run out of content.
// As a last resort, try to grab something from the output stream
for (int i = state.getOutputStream().size() - 1; i >= 0; --i) {
RTObject outputObj = state.getOutputStream().get(i);
dm = outputObj.getDebugMetadata();
if (dm != null) {
return dm;
}
}
return null;
}
int currentLineNumber() throws Exception {
DebugMetadata dm = currentDebugMetadata();
if (dm != null) {
return dm.startLineNumber;
}
return 0;
}
void error(String message) throws Exception {
error(message, false);
}
// Throw an exception that gets caught and causes AddError to be called,
// then exits the flow.
void error(String message, boolean useEndLineNumber) throws Exception {
StoryException e = new StoryException(message);
e.useEndLineNumber = useEndLineNumber;
throw e;
}
// Evaluate a "hot compiled" piece of ink content, as used by the REPL-like
// CommandLinePlayer.
RTObject evaluateExpression(Container exprContainer) throws StoryException, Exception {
int startCallStackHeight = state.getCallStack().getElements().size();
state.getCallStack().push(PushPopType.Tunnel);
temporaryEvaluationContainer = exprContainer;
state.goToStart();
int evalStackHeight = state.getEvaluationStack().size();
Continue();
temporaryEvaluationContainer = null;
// Should have fallen off the end of the Container, which should
// have auto-popped, but just in case we didn't for some reason,
// manually pop to restore the state (including currentPath).
if (state.getCallStack().getElements().size() > startCallStackHeight) {
state.getCallStack().pop();
}
int endStackHeight = state.getEvaluationStack().size();
if (endStackHeight > evalStackHeight) {
return state.popEvaluationStack();
} else {
return null;
}
}
/**
* The list of Choice Objects available at the current point in the Story.
* This list will be populated as the Story is stepped through with the
* Continue() method. Once canContinue becomes false, this list will be
* fully populated, and is usually (but not always) on the final Continue()
* step.
*/
public List<Choice> getCurrentChoices() {
// Don't include invisible choices for external usage.
List<Choice> choices = new ArrayList<Choice>();
for (Choice c : state.getCurrentChoices()) {
if (!c.getchoicePoint().isInvisibleDefault()) {
c.setIndex(choices.size());
choices.add(c);
}
}
return choices;
}
/**
* Gets a list of tags as defined with '#' in source that were seen during
* the latest Continue() call.
*/
public List<String> getCurrentTags() {
return state.getCurrentTags();
}
/**
* Any errors generated during evaluation of the Story.
*/
public List<String> getCurrentErrors() {
return state.getCurrentErrors();
}
/**
* The latest line of text to be generated from a Continue() call.
*/
public String getCurrentText() {
return state.currentText();
}
/**
* The entire current state of the story including (but not limited to):
*
* * Global variables * Temporary variables * Read/visit and turn counts *
* The callstack and evaluation stacks * The current threads
*
*/
public StoryState getState() {
return state;
}
/**
* The VariablesState Object contains all the global variables in the story.
* However, note that there's more to the state of a Story than just the
* global variables. This is a convenience accessor to the full state
* Object.
*/
public VariablesState getVariablesState() {
return state.getVariablesState();
}
/**
* Whether the currentErrors list contains any errors.
*/
public boolean hasError() {
return state.hasError();
}
boolean incrementContentPointer() {
boolean successfulIncrement = true;
Element currEl = state.getCallStack().currentElement();
currEl.currentContentIndex++;
// Each time we step off the end, we fall out to the next container, all
// the
// while we're in indexed rather than named content
while (currEl.currentContentIndex >= currEl.currentContainer.getContent().size()) {
successfulIncrement = false;
Container nextAncestor = currEl.currentContainer.getParent() instanceof Container
? (Container) currEl.currentContainer.getParent() : null;
if (nextAncestor == null) {
break;
}
int indexInAncestor = nextAncestor.getContent().indexOf(currEl.currentContainer);
if (indexInAncestor == -1) {
break;
}
currEl.currentContainer = nextAncestor;
currEl.currentContentIndex = indexInAncestor + 1;
successfulIncrement = true;
}
if (!successfulIncrement)
currEl.currentContainer = null;
return successfulIncrement;
}
void incrementVisitCountForContainer(Container container) {
String containerPathStr = container.getPath().toString();
Integer count = state.getVisitCounts().get(containerPathStr);
if (count == null)
count = 0;
count++;
state.getVisitCounts().put(containerPathStr, count);
}
// Does the expression result represented by this Object evaluate to true?
// e.g. is it a Number that's not equal to 1?
boolean isTruthy(RTObject obj) throws Exception {
boolean truthy = false;
if (obj instanceof Value) {
Value<?> val = (Value<?>) obj;
if (val instanceof DivertTargetValue) {
DivertTargetValue divTarget = (DivertTargetValue) val;
error("Shouldn't use a divert target (to " + divTarget.getTargetPath()
+ ") as a conditional value. Did you intend a function call 'likeThis()' or a read count check 'likeThis'? (no arrows)");
return false;
}
return val.isTruthy();
}
return truthy;
}
/**
* When the named global variable changes it's value, the observer will be
* called to notify it of the change. Note that if the value changes
* multiple times within the ink, the observer will only be called once, at
* the end of the ink's evaluation. If, during the evaluation, it changes
* and then changes back again to its original value, it will still be
* called. Note that the observer will also be fired if the value of the
* variable is changed externally to the ink, by directly setting a value in
* story.variablesState.
*
* @param variableName
* The name of the global variable to observe.
* @param observer
* A delegate function to call when the variable changes.
*/
public void observeVariable(String variableName, VariableObserver observer) {
if (variableObservers == null)
variableObservers = new HashMap<String, List<VariableObserver>>();
if (variableObservers.containsKey(variableName)) {
variableObservers.get(variableName).add(observer);
} else {
List<VariableObserver> l = new ArrayList<VariableObserver>();
l.add(observer);
variableObservers.put(variableName, l);
}
}
/**
* Convenience function to allow multiple variables to be observed with the
* same observer delegate function. See the singular ObserveVariable for
* details. The observer will get one call for every variable that has
* changed.
*
* @param variableNames
* The set of variables to observe.
* @param The
* delegate function to call when any of the named variables
* change.
*/
public void observeVariables(List<String> variableNames, VariableObserver observer) {
for (String varName : variableNames) {
observeVariable(varName, observer);
}
}
/**
* Removes the variable observer, to stop getting variable change
* notifications. If you pass a specific variable name, it will stop
* observing that particular one. If you pass null (or leave it blank, since
* it's optional), then the observer will be removed from all variables that
* it's subscribed to.
*
* @param observer
* The observer to stop observing.
* @param specificVariableName
* (Optional) Specific variable name to stop observing.
*/
public void removeVariableObserver(VariableObserver observer, String specificVariableName) {
if (variableObservers == null)
return;
// Remove observer for this specific variable
if (specificVariableName != null) {
if (variableObservers.containsKey(specificVariableName)) {
variableObservers.get(specificVariableName).remove(observer);
}
} else {
// Remove observer for all variables
for (List<VariableObserver> obs : variableObservers.values()) {
obs.remove(observer);
}
}
}
public void removeVariableObserver(VariableObserver observer) {
removeVariableObserver(observer, null);
}
@Override
public void variableStateDidChangeEvent(String variableName, RTObject newValueObj) throws Exception {
if (variableObservers == null)
return;
List<VariableObserver> observers = variableObservers.get(variableName);
if (observers != null) {
if (!(newValueObj instanceof Value)) {
throw new Exception("Tried to get the value of a variable that isn't a standard type");
}
Value<?> val = (Value<?>) newValueObj;
for (VariableObserver o : observers) {
o.call(variableName, val.getValueObject());
}
}
}
Container mainContentContainer() {
if (temporaryEvaluationContainer != null) {
return temporaryEvaluationContainer;
} else {
return mainContentContainer;
}
}
private void nextContent() throws Exception {
// Setting previousContentObject is critical for
// VisitChangedContainersDueToDivert
state.setPreviousContentObject(state.getCurrentContentObject());
// Divert step?
if (state.getDivertedTargetObject() != null) {
state.setCurrentContentObject(state.getDivertedTargetObject());
state.setDivertedTargetObject(null);
// Internally uses state.previousContentObject and
// state.currentContentObject
visitChangedContainersDueToDivert();
// Diverted location has valid content?
if (state.getCurrentContentObject() != null) {
return;
}
// Otherwise, if diverted location doesn't have valid content,
// drop down and attempt to increment.
// This can happen if the diverted path is intentionally jumping
// to the end of a container - e.g. a Conditional that's re-joining
}
boolean successfulPointerIncrement = incrementContentPointer();
// Ran out of content? Try to auto-exit from a function,
// or finish evaluating the content of a thread
if (!successfulPointerIncrement) {
boolean didPop = false;
if (state.getCallStack().canPop(PushPopType.Function)) {
// Pop from the call stack
state.getCallStack().pop(PushPopType.Function);
// This pop was due to dropping off the end of a function that
// didn't return anything,
// so in this case, we make sure that the evaluator has
// something to chomp on if it needs it
if (state.getInExpressionEvaluation()) {
state.pushEvaluationStack(new Void());
}
didPop = true;
}
else if (state.getCallStack().canPopThread()) {
state.getCallStack().popThread();
didPop = true;
}
// Step past the point where we last called out
if (didPop && state.getCurrentContentObject() != null) {
nextContent();
}
}
}
// Note that this is O(n), since it re-evaluates the shuffle indices
// from a consistent seed each time.
// TODO: Is this the best algorithm it can be?
int nextSequenceShuffleIndex() throws Exception {
RTObject popEvaluationStack = state.popEvaluationStack();
IntValue numElementsIntVal = popEvaluationStack instanceof IntValue ? (IntValue) popEvaluationStack : null;
if (numElementsIntVal == null) {
error("expected number of elements in sequence for shuffle index");
return 0;
}
Container seqContainer = state.currentContainer();
int numElements = numElementsIntVal.value;
IntValue seqCountVal = (IntValue) state.popEvaluationStack();
int seqCount = seqCountVal.value;
int loopIndex = seqCount / numElements;
int iterationIndex = seqCount % numElements;
// Generate the same shuffle based on:
// - The hash of this container, to make sure it's consistent
// each time the runtime returns to the sequence
// - How many times the runtime has looped around this full shuffle
String seqPathStr = seqContainer.getPath().toString();
int sequenceHash = 0;
for (char c : seqPathStr.toCharArray()) {
sequenceHash += c;
}
int randomSeed = sequenceHash + loopIndex + state.getStorySeed();
Random random = new Random(randomSeed);
ArrayList<Integer> unpickedIndices = new ArrayList<Integer>();
for (int i = 0; i < numElements; ++i) {
unpickedIndices.add(i);
}
for (int i = 0; i <= iterationIndex; ++i) {
int chosen = random.nextInt(Integer.MAX_VALUE) % unpickedIndices.size();
int chosenIndex = unpickedIndices.get(chosen);
unpickedIndices.remove(chosen);
if (i == iterationIndex) {
return chosenIndex;
}
}
throw new Exception("Should never reach here");
}
/**
* Checks whether contentObj is a control or flow Object rather than a piece
* of content, and performs the required command if necessary.
*
* @return true if Object was logic or flow control, false if it's normal
* content.
* @param contentObj
* Content Object.
*/
boolean performLogicAndFlowControl(RTObject contentObj) throws Exception {
if (contentObj == null) {
return false;
}
// Divert
if (contentObj instanceof Divert) {
Divert currentDivert = (Divert) contentObj;
if (currentDivert.isConditional()) {
RTObject conditionValue = state.popEvaluationStack();
// False conditional? Cancel divert
if (!isTruthy(conditionValue))
return true;
}
if (currentDivert.hasVariableTarget()) {
String varName = currentDivert.getVariableDivertName();
RTObject varContents = state.getVariablesState().getVariableWithName(varName);
if (!(varContents instanceof DivertTargetValue)) {
IntValue intContent = varContents instanceof IntValue ? (IntValue) varContents : null;
String errorMessage = "Tried to divert to a target from a variable, but the variable (" + varName
+ ") didn't contain a divert target, it ";
if (intContent != null && intContent.value == 0) {
errorMessage += "was empty/null (the value 0).";
} else {
errorMessage += "contained '" + varContents + "'.";
}
error(errorMessage);
}
DivertTargetValue target = (DivertTargetValue) varContents;
state.setDivertedTargetObject(contentAtPath(target.getTargetPath()));
} else if (currentDivert.isExternal()) {
callExternalFunction(currentDivert.getTargetPathString(), currentDivert.getExternalArgs());
return true;
} else {
state.setDivertedTargetObject(currentDivert.getTargetContent());
}
if (currentDivert.getPushesToStack()) {
state.getCallStack().push(currentDivert.getStackPushType());
}
if (state.getDivertedTargetObject() == null && !currentDivert.isExternal()) {
// Human readable name available - runtime divert is part of a
// hard-written divert that to missing content
if (currentDivert != null && currentDivert.getDebugMetadata().sourceName != null) {
error("Divert target doesn't exist: " + currentDivert.getDebugMetadata().sourceName);
} else {
error("Divert resolution failed: " + currentDivert);
}
}
return true;
}
// Start/end an expression evaluation? Or print out the result?
else if (contentObj instanceof ControlCommand) {
ControlCommand evalCommand = (ControlCommand) contentObj;
int choiceCount;
switch (evalCommand.getcommandType()) {
case EvalStart:
Assert(state.getInExpressionEvaluation() == false, "Already in expression evaluation?");
state.setInExpressionEvaluation(true);
break;
case EvalEnd:
Assert(state.getInExpressionEvaluation() == true, "Not in expression evaluation mode");
state.setInExpressionEvaluation(false);
break;
case EvalOutput:
// If the expression turned out to be empty, there may not be
// anything on the stack
if (state.getEvaluationStack().size() > 0) {
RTObject output = state.popEvaluationStack();
// Functions may evaluate to Void, in which case we skip
// output
if (!(output instanceof Void)) {
// TODO: Should we really always blanket convert to
// string?
// It would be okay to have numbers in the output stream
// the
// only problem is when exporting text for viewing, it
// skips over numbers etc.
StringValue text = new StringValue(output.toString());
state.pushToOutputStream(text);
}
}
break;
case NoOp:
break;
case Duplicate:
state.pushEvaluationStack(state.peekEvaluationStack());
break;
case PopEvaluatedValue:
state.popEvaluationStack();
break;
case PopFunction:
case PopTunnel:
PushPopType popType = evalCommand.getcommandType() == ControlCommand.CommandType.PopFunction
? PushPopType.Function : PushPopType.Tunnel;
if (state.getCallStack().currentElement().type != popType || !state.getCallStack().canPop()) {
HashMap<PushPopType, String> names = new HashMap<PushPopType, String>();
names.put(PushPopType.Function, "function return statement (~ return)");
names.put(PushPopType.Tunnel, "tunnel onwards statement (->->)");
String expected = names.get(state.getCallStack().currentElement().type);
if (!state.getCallStack().canPop()) {
expected = "end of flow (-> END or choice)";
}
String errorMsg = String.format("Found %s, when expected %s", names.get(popType), expected);
error(errorMsg);
}
else {
state.getCallStack().pop();
}
break;
case BeginString:
state.pushToOutputStream(evalCommand);
Assert(state.getInExpressionEvaluation() == true,
"Expected to be in an expression when evaluating a string");
state.setInExpressionEvaluation(false);
break;
case EndString:
// Since we're iterating backward through the content,
// build a stack so that when we build the string,
// it's in the right order
Stack<RTObject> contentStackForString = new Stack<RTObject>();
int outputCountConsumed = 0;
for (int i = state.getOutputStream().size() - 1; i >= 0; --i) {
RTObject obj = state.getOutputStream().get(i);
outputCountConsumed++;
ControlCommand command = obj instanceof ControlCommand ? (ControlCommand) obj : null;
if (command != null && command.getcommandType() == ControlCommand.CommandType.BeginString) {
break;
}
if (obj instanceof StringValue)
contentStackForString.push(obj);
}
// Consume the content that was produced for this string
state.getOutputStream()
.subList(state.getOutputStream().size() - outputCountConsumed, state.getOutputStream().size())
.clear();
// Build String out of the content we collected
StringBuilder sb = new StringBuilder();
while (contentStackForString.size() > 0) {
RTObject c = contentStackForString.pop();
sb.append(c.toString());
}
// Return to expression evaluation (from content mode)
state.setInExpressionEvaluation(true);
state.pushEvaluationStack(new StringValue(sb.toString()));
break;
case ChoiceCount:
choiceCount = getCurrentChoices().size();
state.pushEvaluationStack(new IntValue(choiceCount));
break;
case TurnsSince:
RTObject target = state.popEvaluationStack();
if (!(target instanceof DivertTargetValue)) {
String extraNote = "";
if (target instanceof IntValue)
extraNote = ". Did you accidentally pass a read count ('knot_name') instead of a target ('-> knot_name')?";
error("TURNS_SINCE expected a divert target (knot, stitch, label name), but saw " + target
+ extraNote);
break;
}
DivertTargetValue divertTarget = target instanceof DivertTargetValue ? (DivertTargetValue) target
: null;
Container container = contentAtPath(divertTarget.getTargetPath()) instanceof Container
? (Container) contentAtPath(divertTarget.getTargetPath()) : null;
int turnCount = turnsSinceForContainer(container);
state.pushEvaluationStack(new IntValue(turnCount));
break;
case Random: {
IntValue maxInt = null;
RTObject o = state.popEvaluationStack();
if (o instanceof IntValue)
maxInt = (IntValue) o;
IntValue minInt = null;
o = state.popEvaluationStack();
if (o instanceof IntValue)
minInt = (IntValue) o;
if (minInt == null)
error("Invalid value for minimum parameter of RANDOM(min, max)");
if (maxInt == null)
error("Invalid value for maximum parameter of RANDOM(min, max)");
// +1 because it's inclusive of min and max, for e.g.
// RANDOM(1,6) for a dice roll.
int randomRange = maxInt.value - minInt.value + 1;
if (randomRange <= 0)
error("RANDOM was called with minimum as " + minInt.value + " and maximum as " + maxInt.value
+ ". The maximum must be larger");
int resultSeed = state.getStorySeed() + state.getPreviousRandom();
Random random = new Random(resultSeed);
int nextRandom = random.nextInt(Integer.MAX_VALUE);
int chosenValue = (nextRandom % randomRange) + minInt.value;
state.pushEvaluationStack(new IntValue(chosenValue));
// Next random number (rather than keeping the Random object
// around)
state.setPreviousRandom(state.getPreviousRandom() + 1);
break;
}
case SeedRandom:
IntValue seed = null;
RTObject o = state.popEvaluationStack();
if (o instanceof IntValue)
seed = (IntValue) o;
if (seed == null)
error("Invalid value passed to SEED_RANDOM");
// Story seed affects both RANDOM and shuffle behaviour
state.setStorySeed(seed.value);
state.setPreviousRandom(0);
// SEED_RANDOM returns nothing.
state.pushEvaluationStack(new Void());
break;
case VisitIndex:
int count = visitCountForContainer(state.currentContainer()) - 1; // index
// not
// count
state.pushEvaluationStack(new IntValue(count));
break;
case SequenceShuffleIndex:
int shuffleIndex = nextSequenceShuffleIndex();
state.pushEvaluationStack(new IntValue(shuffleIndex));
break;
case StartThread:
// Handled in main step function
break;
case Done:
// We may exist in the context of the initial
// act of creating the thread, or in the context of
// evaluating the content.
if (state.getCallStack().canPopThread()) {
state.getCallStack().popThread();
}
// In normal flow - allow safe exit without warning
else {
state.setDidSafeExit(true);
// Stop flow in current thread
state.setCurrentContentObject(null);
}
break;
// Force flow to end completely
case End:
state.forceEnd();
break;
default:
error("unhandled ControlCommand: " + evalCommand);
break;
}
return true;
}
// Variable assignment
else if (contentObj instanceof VariableAssignment) {
VariableAssignment varAss = (VariableAssignment) contentObj;
RTObject assignedVal = state.popEvaluationStack();
// When in temporary evaluation, don't create new variables purely
// within
// the temporary context, but attempt to create them globally
// var prioritiseHigherInCallStack = _temporaryEvaluationContainer
// != null;
state.getVariablesState().assign(varAss, assignedVal);
return true;
}
// Variable reference
else if (contentObj instanceof VariableReference) {
VariableReference varRef = (VariableReference) contentObj;
RTObject foundValue = null;
// Explicit read count value
if (varRef.getPathForCount() != null) {
Container container = varRef.getContainerForCount();
int count = visitCountForContainer(container);
foundValue = new IntValue(count);
}
// Normal variable reference
else {
foundValue = state.getVariablesState().getVariableWithName(varRef.getName());
if (foundValue == null) {
error("Uninitialised variable: " + varRef.getName());
foundValue = new IntValue(0);
}
}
state.getEvaluationStack().add(foundValue);
return true;
}
// Native function call
else if (contentObj instanceof NativeFunctionCall) {
NativeFunctionCall func = (NativeFunctionCall) contentObj;
List<RTObject> funcParams = state.popEvaluationStack(func.getNumberOfParameters());
RTObject result = func.call(funcParams);
state.getEvaluationStack().add(result);
return true;
}
// No control content, must be ordinary content
return false;
}
Choice processChoice(ChoicePoint choicePoint) throws Exception {
boolean showChoice = true;
// Don't create choice if choice point doesn't pass conditional
if (choicePoint.hasCondition()) {
RTObject conditionValue = state.popEvaluationStack();
if (!isTruthy(conditionValue)) {
showChoice = false;
}
}
String startText = "";
String choiceOnlyText = "";
if (choicePoint.hasChoiceOnlyContent()) {
StringValue choiceOnlyStrVal = (StringValue) state.popEvaluationStack();
choiceOnlyText = choiceOnlyStrVal.value;
}
if (choicePoint.hasStartContent()) {
StringValue startStrVal = (StringValue) state.popEvaluationStack();
startText = startStrVal.value;
}
// Don't create choice if player has already read this content
if (choicePoint.isOnceOnly()) {
int visitCount = visitCountForContainer(choicePoint.getChoiceTarget());
if (visitCount > 0) {
showChoice = false;
}
}
Choice choice = new Choice(choicePoint);
choice.setThreadAtGeneration(state.getCallStack().getcurrentThread().copy());
// We go through the full process of creating the choice above so
// that we consume the content for it, since otherwise it'll
// be shown on the output stream.
if (!showChoice) {
return null;
}
// Set final text for the choice
choice.setText(startText + choiceOnlyText);
return choice;
}
void recordTurnIndexVisitToContainer(Container container) {
String containerPathStr = container.getPath().toString();
state.getTurnIndices().put(containerPathStr, state.getCurrentTurnIndex());
}
/**
* Unwinds the callstack. Useful to reset the Story's evaluation without
* actually changing any meaningful state, for example if you want to exit a
* section of story prematurely and tell it to go elsewhere with a call to
* ChoosePathString(...). Doing so without calling ResetCallstack() could
* cause unexpected issues if, for example, the Story was in a tunnel
* already.
*/
public void resetCallstack() throws Exception {
state.forceEnd();
}
/**
* Reset the runtime error list within the state.
*/
public void resetErrors() {
state.resetErrors();
}
void resetGlobals() throws Exception {
if (mainContentContainer.getNamedContent().containsKey("global decl")) {
Path originalPath = getState().getCurrentPath();
choosePathString("global decl");
// Continue, but without validating external bindings,
// since we may be doing this reset at initialisation time.
continueInternal();
getState().setCurrentPath(originalPath);
}
}
/**
* Reset the Story back to its initial state as it was when it was first
* constructed.
*/
public void resetState() throws Exception {
state = new StoryState(this);
state.getVariablesState().setVariableChangedEvent(this);
resetGlobals();
}
void restoreStateSnapshot(StoryState state) {
this.state = state;
}
StoryState stateSnapshot() throws Exception {
return state.copy();
}
void step() throws Exception {
boolean shouldAddToStream = true;
// Get current content
RTObject currentContentObj = state.getCurrentContentObject();
if (currentContentObj == null) {
return;
}
// Step directly to the first element of content in a container (if
// necessary)
Container currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null;
while (currentContainer != null) {
// Mark container as being entered
visitContainer(currentContainer, true);
// No content? the most we can do is step past it
if (currentContainer.getContent().size() == 0)
break;
currentContentObj = currentContainer.getContent().get(0);
state.getCallStack().currentElement().currentContentIndex = 0;
state.getCallStack().currentElement().currentContainer = currentContainer;
currentContainer = currentContentObj instanceof Container ? (Container) currentContentObj : null;
}
currentContainer = state.getCallStack().currentElement().currentContainer;
// Is the current content Object:
// - Normal content
// - Or a logic/flow statement - if so, do it
// Stop flow if we hit a stack pop when we're unable to pop (e.g.
// return/done statement in knot
// that was diverted to rather than called as a function)
boolean isLogicOrFlowControl = performLogicAndFlowControl(currentContentObj);
// Has flow been forced to end by flow control above?
if (state.getCurrentContentObject() == null) {
return;
}
if (isLogicOrFlowControl) {
shouldAddToStream = false;
}
// Choice with condition?
ChoicePoint choicePoint = currentContentObj instanceof ChoicePoint ? (ChoicePoint) currentContentObj : null;
if (choicePoint != null) {
Choice choice = processChoice(choicePoint);
if (choice != null) {
state.getCurrentChoices().add(choice);
}
currentContentObj = null;
shouldAddToStream = false;
}
// If the container has no content, then it will be
// the "content" itself, but we skip over it.
if (currentContentObj instanceof Container) {
shouldAddToStream = false;
}
// Content to add to evaluation stack or the output stream
if (shouldAddToStream) {
// If we're pushing a variable pointer onto the evaluation stack,
// ensure that it's specific
// to our current (possibly temporary) context index. And make a
// copy of the pointer
// so that we're not editing the original runtime Object.
VariablePointerValue varPointer = currentContentObj instanceof VariablePointerValue
? (VariablePointerValue) currentContentObj : null;
if (varPointer != null && varPointer.getContextIndex() == -1) {
// Create new Object so we're not overwriting the story's own
// data
int contextIdx = state.getCallStack().contextForVariableNamed(varPointer.getVariableName());
currentContentObj = new VariablePointerValue(varPointer.getVariableName(), contextIdx);
}
// Expression evaluation content
if (state.getInExpressionEvaluation()) {
state.pushEvaluationStack(currentContentObj);
}
// Output stream content (i.e. not expression evaluation)
else {
state.pushToOutputStream(currentContentObj);
}
}
// Increment the content pointer, following diverts if necessary
nextContent();
// Starting a thread should be done after the increment to the content
// pointer,
// so that when returning from the thread, it returns to the content
// after this instruction.
ControlCommand controlCmd = currentContentObj instanceof ControlCommand ? (ControlCommand) currentContentObj
: null;
if (controlCmd != null && controlCmd.getcommandType() == ControlCommand.CommandType.StartThread) {
state.getCallStack().pushThread();
}
}
/**
* The Story itself in JSON representation.
*/
public String toJsonString() throws Exception {
List<?> rootContainerJsonList = (List<?>) Json.runtimeObjectToJToken(mainContentContainer);
HashMap<String, Object> rootObject = new HashMap<String, Object>();
rootObject.put("inkVersion", inkVersionCurrent);
rootObject.put("root", rootContainerJsonList);
return SimpleJson.HashMapToText(rootObject);
}
boolean tryFollowDefaultInvisibleChoice() throws Exception {
List<Choice> allChoices = state.getCurrentChoices();
// Is a default invisible choice the ONLY choice?
// var invisibleChoices = allChoices.Where (c =>
// c.choicePoint.isInvisibleDefault).ToList();
ArrayList<Choice> invisibleChoices = new ArrayList<Choice>();
for (Choice c : allChoices) {
if (c.getchoicePoint().isInvisibleDefault()) {
invisibleChoices.add(c);
}
}
if (invisibleChoices.size() == 0 || allChoices.size() > invisibleChoices.size())
return false;
Choice choice = invisibleChoices.get(0);
choosePath(choice.getchoicePoint().getChoiceTarget().getPath());
return true;
}
int turnsSinceForContainer(Container container) throws Exception {
if (!container.getTurnIndexShouldBeCounted()) {
error("TURNS_SINCE() for target (" + container.getName() + " - on " + container.getDebugMetadata()
+ ") unknown. The story may need to be compiled with countAllVisits flag (-c).");
}
String containerPathStr = container.getPath().toString();
Integer index = state.getTurnIndices().get(containerPathStr);
if (index != null) {
return state.getCurrentTurnIndex() - index;
} else {
return -1;
}
}
/**
* Remove a binding for a named EXTERNAL ink function.
*/
public void unbindExternalFunction(String funcName) throws Exception {
Assert(externals.containsKey(funcName), "Function '" + funcName + "' has not been bound.");
externals.remove(funcName);
}
/**
* Check that all EXTERNAL ink functions have a valid bound C# function.
* Note that this is automatically called on the first call to Continue().
*/
public void validateExternalBindings() throws Exception {
validateExternalBindings(mainContentContainer);
hasValidatedExternals = true;
}
void validateExternalBindings(Container c) throws Exception {
for (RTObject innerContent : c.getContent()) {
validateExternalBindings(innerContent);
}
for (INamedContent innerKeyValue : c.getNamedContent().values()) {
validateExternalBindings(innerKeyValue instanceof RTObject ? (RTObject) innerKeyValue : null);
}
}
void validateExternalBindings(RTObject o) throws Exception {
Container container = o instanceof Container ? (Container) o : null;
if (container != null) {
validateExternalBindings(container);
return;
}
Divert divert = o instanceof Divert ? (Divert) o : null;
if (divert != null && divert.isExternal()) {
String name = divert.getTargetPathString();
if (!externals.containsKey(name)) {
INamedContent fallbackFunction = mainContentContainer().getNamedContent().get(name);
String message = null;
if (!allowExternalFunctionFallbacks)
message = "Missing function binding for external '" + name + "' (ink fallbacks disabled)";
else if (fallbackFunction == null) {
message = "Missing function binding for external '" + name
+ "', and no fallback ink function found.";
}
if (message != null) {
String errorPreamble = "ERROR: ";
if (divert.getDebugMetadata() != null) {
errorPreamble += String.format("'%s' line %d: ", divert.getDebugMetadata().fileName,
divert.getDebugMetadata().startLineNumber);
}
throw new StoryException(errorPreamble + message);
}
}
}
}
void visitChangedContainersDueToDivert() {
RTObject previousContentObject = state.getPreviousContentObject();
RTObject newContentObject = state.getCurrentContentObject();
if (newContentObject == null)
return;
// First, find the previously open set of containers
HashSet<Container> prevContainerSet = new HashSet<Container>();
if (previousContentObject != null) {
Container prevAncestor = null;
if (previousContentObject instanceof Container) {
prevAncestor = (Container) previousContentObject;
} else if (previousContentObject.getParent() instanceof Container) {
prevAncestor = (Container) previousContentObject.getParent();
}
while (prevAncestor != null) {
prevContainerSet.add(prevAncestor);
prevAncestor = prevAncestor.getParent() instanceof Container ? (Container) prevAncestor.getParent()
: null;
}
}
// If the new Object is a container itself, it will be visited
// automatically at the next actual
// content step. However, we need to walk up the new ancestry to see if
// there are more new containers
RTObject currentChildOfContainer = newContentObject;
Container currentContainerAncestor = currentChildOfContainer.getParent() instanceof Container
? (Container) currentChildOfContainer.getParent() : null;
while (currentContainerAncestor != null && !prevContainerSet.contains(currentContainerAncestor)) {
// Check whether this ancestor container is being entered at the
// start,
// by checking whether the child Object is the first.
boolean enteringAtStart = currentContainerAncestor.getContent().size() > 0
&& currentChildOfContainer == currentContainerAncestor.getContent().get(0);
// Mark a visit to this container
visitContainer(currentContainerAncestor, enteringAtStart);
currentChildOfContainer = currentContainerAncestor;
currentContainerAncestor = currentContainerAncestor.getParent() instanceof Container
? (Container) currentContainerAncestor.getParent() : null;
}
}
// Mark a container as having been visited
void visitContainer(Container container, boolean atStart) {
if (!container.getCountingAtStartOnly() || atStart) {
if (container.getVisitsShouldBeCounted())
incrementVisitCountForContainer(container);
if (container.getTurnIndexShouldBeCounted())
recordTurnIndexVisitToContainer(container);
}
}
int visitCountForContainer(Container container) throws Exception {
if (!container.getVisitsShouldBeCounted()) {
error("Read count for target (" + container.getName() + " - on " + container.getDebugMetadata()
+ ") unknown. The story may need to be compiled with countAllVisits flag (-c).");
return 0;
}
String containerPathStr = container.getPath().toString();
Integer count = state.getVisitCounts().get(containerPathStr);
return count == null ? 0 : count;
}
public boolean allowExternalFunctionFallbacks() {
return allowExternalFunctionFallbacks;
}
public void setAllowExternalFunctionFallbacks(boolean allowExternalFunctionFallbacks) {
this.allowExternalFunctionFallbacks = allowExternalFunctionFallbacks;
}
/**
* Evaluates a function defined in ink.
*
* @param functionName
* The name of the function as declared in ink.
* @param arguments
* The arguments that the ink function takes, if any. Note that
* we don't (can't) do any validation on the number of arguments
* right now, so make sure you get it right!
* @return The return value as returned from the ink function with `~ return
* myValue`, or null if nothing is returned.
* @throws Exception
*/
public Object evaluateFunction(String functionName, Object[] arguments) throws Exception {
return evaluateFunction(functionName, null, arguments);
}
/**
* Checks if a function exists.
*
* @returns True if the function exists, else false.
* @param functionName
* The name of the function as declared in ink.
*/
public boolean hasFunction(String functionName) {
try {
return contentAtPath(new Path(functionName)) instanceof Container;
} catch (Exception e) {
return false;
}
}
/**
* Evaluates a function defined in ink, and gathers the possibly multi-line
* text as generated by the function.
*
* @param arguments
* The arguments that the ink function takes, if any. Note that
* we don't (can't) do any validation on the number of arguments
* right now, so make sure you get it right!
* @param functionName
* The name of the function as declared in ink.
* @param textOutput
* This text output is any text written as normal content within
* the function, as opposed to the return value, as returned with
* `~ return`.
* @return The return value as returned from the ink function with `~ return
* myValue`, or null if nothing is returned.
* @throws Exception
*/
public Object evaluateFunction(String functionName, StringBuffer textOutput, Object[] arguments) throws Exception {
Container funcContainer = null;
if (functionName == null) {
throw new Exception("Function is null");
} else if (functionName.trim().isEmpty()) {
throw new Exception("Function is empty or white space.");
}
try {
RTObject contentAtPath = contentAtPath(new Path(functionName));
if (contentAtPath instanceof Container)
funcContainer = (Container) contentAtPath;
} catch (StoryException e) {
if (e.getMessage().contains("not found"))
throw new Exception("Function doesn't exist: '" + functionName + "'");
else
throw e;
}
// We'll start a new callstack, so keep hold of the original,
// as well as the evaluation stack so we know if the function
// returned something
CallStack originalCallstack = state.getCallStack();
int originalEvaluationStackHeight = state.getEvaluationStack().size();
// Create a new base call stack element.
// By making it point at element 0 of the base, when NextContent is
// called, it'll actually step past the entire content of the game (!)
// and straight onto the Done. Bit of a hack :-/ We don't really have
// a better way of creating a temporary context that ends correctly.
state.setCallStack(new CallStack(mainContentContainer));
state.getCallStack().currentElement().currentContainer = mainContentContainer;
state.getCallStack().currentElement().currentContentIndex = 0;
if (arguments != null) {
for (int i = 0; i < arguments.length; i++) {
if (!(arguments[i] instanceof Integer || arguments[i] instanceof Float
|| arguments[i] instanceof String)) {
throw new IllegalArgumentException(
"ink arguments when calling EvaluateFunction must be int, float or string");
}
state.getEvaluationStack().add(Value.create(arguments[i]));
}
}
// Jump into the function!
state.getCallStack().push(PushPopType.Function);
state.setCurrentContentObject(funcContainer);
// Evaluate the function, and collect the string output
while (canContinue()) {
String text = Continue();
if (textOutput != null)
textOutput.append(text);
}
// Restore original stack
state.setCallStack(originalCallstack);
// Do we have a returned value?
// Potentially pop multiple values off the stack, in case we need
// to clean up after ourselves (e.g. caller of EvaluateFunction may
// have passed too many arguments, and we currently have no way to check
// for that)
RTObject returnedObj = null;
while (state.getEvaluationStack().size() > originalEvaluationStackHeight) {
RTObject poppedObj = state.popEvaluationStack();
if (returnedObj == null)
returnedObj = poppedObj;
}
if (returnedObj != null) {
if (returnedObj instanceof Void)
return null;
// Some kind of value, if not void
Value<?> returnVal = (Value<?>) returnedObj;
// DivertTargets get returned as the string of components
// (rather than a Path, which isn't public)
if (returnVal.getValueType() == ValueType.DivertTarget) {
return returnVal.getValueObject().toString();
}
// Other types can just have their exact object type:
// int, float, string. VariablePointers get returned as strings.
return returnVal.getValueObject();
}
return null;
}
}
| Seeing a tag after a new line counts as "new content", and therefore
causes the lookahead for glue to stop.
| src/main/java/com/bladecoder/ink/runtime/Story.java | Seeing a tag after a new line counts as "new content", and therefore causes the lookahead for glue to stop. | <ide><path>rc/main/java/com/bladecoder/ink/runtime/Story.java
<ide> /**
<ide> * Get any global tags associated with the story. These are defined as hash
<ide> * tags defined at the very top of the story.
<del> * @throws Exception
<add> *
<add> * @throws Exception
<ide> */
<ide> public List<String> getGlobalTags() throws Exception {
<ide> return tagsAtStartOfFlowContainerWithPathString("");
<ide> }
<ide>
<ide> /**
<del> * Gets any tags associated with a particular knot or knot.stitch.
<del> * These are defined as hash tags defined at the very top of a
<del> * knot or stitch.
<del> * @param path The path of the knot or stitch, in the form "knot" or
<del> * "knot.stitch".
<del> * @throws Exception
<add> * Gets any tags associated with a particular knot or knot.stitch. These are
<add> * defined as hash tags defined at the very top of a knot or stitch.
<add> *
<add> * @param path
<add> * The path of the knot or stitch, in the form "knot" or
<add> * "knot.stitch".
<add> * @throws Exception
<ide> */
<ide> public List<String> tagsForContentAtPath(String path) throws Exception {
<ide> return tagsAtStartOfFlowContainerWithPathString(path);
<ide> }
<ide>
<del> List<String> tagsAtStartOfFlowContainerWithPathString (String pathString) throws Exception {
<del> Path path = new Path (pathString);
<del>
<del> // Expected to be global story, knot or stitch
<del> Container flowContainer = null;
<del> RTObject c = contentAtPath(path);
<del>
<del> if (c instanceof Container)
<del> flowContainer = (Container)c;
<del>
<del> // First element of the above constructs is a compiled weave
<del> Container innerWeaveContainer = null;
<del>
<del> if(flowContainer.getContent().get(0) instanceof Container)
<del> innerWeaveContainer = (Container)flowContainer.getContent().get(0);
<del>
<del> // Any initial tag objects count as the "main tags" associated with that story/knot/stitch
<del> List<String> tags = null;
<del> for ( RTObject c2 :innerWeaveContainer.getContent()) {
<del> Tag tag = null;
<del>
<del> if(c2 instanceof Tag)
<del> tag = (Tag)c2;
<del>
<del> if (tag != null) {
<del> if (tags == null) tags = new ArrayList<String> ();
<del> tags.add (tag.getText());
<del> } else break;
<del> }
<del>
<del> return tags;
<del> }
<add> List<String> tagsAtStartOfFlowContainerWithPathString(String pathString) throws Exception {
<add> Path path = new Path(pathString);
<add>
<add> // Expected to be global story, knot or stitch
<add> Container flowContainer = null;
<add> RTObject c = contentAtPath(path);
<add>
<add> if (c instanceof Container)
<add> flowContainer = (Container) c;
<add>
<add> // First element of the above constructs is a compiled weave
<add> Container innerWeaveContainer = null;
<add>
<add> if (flowContainer.getContent().get(0) instanceof Container)
<add> innerWeaveContainer = (Container) flowContainer.getContent().get(0);
<add>
<add> // Any initial tag objects count as the "main tags" associated with that
<add> // story/knot/stitch
<add> List<String> tags = null;
<add> for (RTObject c2 : innerWeaveContainer.getContent()) {
<add> Tag tag = null;
<add>
<add> if (c2 instanceof Tag)
<add> tag = (Tag) c2;
<add>
<add> if (tag != null) {
<add> if (tags == null)
<add> tags = new ArrayList<String>();
<add> tags.add(tag.getText());
<add> } else
<add> break;
<add> }
<add>
<add> return tags;
<add> }
<ide>
<ide> /**
<ide> * Useful when debugging a (very short) story, to visualise the state of the
<ide> String currText = getCurrentText();
<ide> int prevTextLength = stateAtLastNewline.currentText().length();
<ide>
<add> // Take tags into account too, so that a tag following a
<add> // content line:
<add> // Content
<add> // # tag
<add> // ... doesn't cause the tag to be wrongly associated
<add> // with the content above.
<add> int prevTagCount = stateAtLastNewline.getCurrentTags().size();
<add>
<ide> // Output has been extended?
<del> if (!currText.equals(stateAtLastNewline.currentText())) {
<add> if (!currText.equals(stateAtLastNewline.currentText())
<add> || prevTagCount != getCurrentTags().size()) {
<ide>
<ide> // Original newline still exists?
<ide> if (currText.length() >= prevTextLength && currText.charAt(prevTextLength - 1) == '\n') { |
|
Java | mit | 4159f64ecc60ac8a9e7c0cfa441652cb7d6d3f71 | 0 | BP2014W1/JEngine,BP2014W1/JEngine,bptlab/JEngine,BP2014W1/JEngine,BP2014W1/JEngine,bptlab/JEngine,bptlab/JEngine,bptlab/JEngine | package de.uni_potsdam.hpi.bpt.bp2014.database;
import de.uni_potsdam.hpi.bpt.bp2014.jhistory.Log;
public class DbDataAttributeInstance extends DbObject{
/**
* This method creates and saves a new DataAttributeInstance to the database into the context of a DataObjectInstance and saves a log entry into the database.
*
* @param dataAttribute_id This is the database ID of the DataAttribute of which the new Instance is created, the ID can be found in the database.
* @param dataObjectInstance_id This is the database ID of the DataObjectInstance the AttributeInstance belongs to which is found in the database.
* @return an Integer which is -1 if something went wrong else it is the database ID of the newly created DataAttributeInstance.
*/
public int createNewDataAttributeInstance(int dataAttribute_id, int dataObjectInstance_id) {
String sql = "INSERT INTO dataattributeinstance (value, dataobjectinstance_id, dataattribute_id) VALUES ((SELECT dataattribute.default FROM dataattribute WHERE id = " + dataAttribute_id + "), " + dataObjectInstance_id + ", " + dataAttribute_id + ")";
int id = this.executeInsertStatement(sql);
Log log = new Log();
log.newDataAttributeInstance(id);
return id;
}
public Boolean existDataAttributeInstance(int dataAttribute_id, int dataObjectInstance_id) {
String sql = "SELECT id FROM dataattributeinstance WHERE dataobjectinstance_id = " + dataObjectInstance_id + " AND dataattribute_id = " + dataAttribute_id;
return this.executeExistStatement(sql);
}
public int getDataAttributeInstanceID(int dataAttribute_id, int dataObjectInstance_id) {
String sql = "SELECT id FROM dataattributeinstance WHERE dataobjectinstance_id = " + dataObjectInstance_id + " AND dataattribute_id = " + dataAttribute_id;
return this.executeStatementReturnsInt(sql, "id");
}
public String getType(int dataAttribute_id) {
String sql = "SELECT type FROM dataattribute WHERE id = " + dataAttribute_id;
return this.executeStatementReturnsString(sql, "type");
}
public Object getValue(int dataAttributeInstance_id) {
String sql = "SELECT value FROM dataattributeinstance WHERE id = " + dataAttributeInstance_id;
return this.executeStatementReturnsObject(sql, "value");
}
public String getName(int dataAttribute_id) {
String sql = "SELECT name FROM dataattribute WHERE id = " + dataAttribute_id;
return this.executeStatementReturnsString(sql, "name");
}
/**
* This method sets the DataAttributeinstance to a desired value and saves a log entry into the database.
*
* @param dataAttributeInstance_id This is the database ID of the DataAttributeinstance which is found in the database.
* @param value This is the value the DataAttributeinstance should have after executing setValue.
*/
public void setValue(int dataAttributeInstance_id, Object value){
Log log = new Log();
log.newDataAttributeInstanceValue(dataAttributeInstance_id, value);
String sql = "UPDATE dataattributeinstance SET value = '" + value + "' WHERE id = " + dataAttributeInstance_id;
executeUpdateStatement(sql);
}
}
| src/main/java/de/uni_potsdam/hpi/bpt/bp2014/database/DbDataAttributeInstance.java | package de.uni_potsdam.hpi.bpt.bp2014.database;
import de.uni_potsdam.hpi.bpt.bp2014.jhistory.Log;
public class DbDataAttributeInstance extends DbObject{
/**
* This method creates and saves a new DataAttributeInstance to the database into the context of a DataObjectInstance and saves a log entry into the database.
*
* @param dataAttribute_id This is the database ID of the DataAttribute of which the new Instance is created, the ID can be found in the database.
* @param dataObjectInstance_id This is the database ID of the DataObjectInstance the AttributeInstance belongs to which is found in the database.
* @return an Integer which is -1 if something went wrong else it is the database ID of the newly created DataAttributeInstance.
*/
public int createNewDataAttributeInstance(int dataAttribute_id, int dataObjectInstance_id) {
String sql = "INSERT INTO dataattributeinstance (value, dataobjectinstance_id, dataattribute_id) VALUES ((SELECT dataattribute.default FROM dataattribute WHERE id = " + dataAttribute_id + "), " + dataObjectInstance_id + ", " + dataAttribute_id + ")";
int id = this.executeInsertStatement(sql);
Log log = new Log();
log.newDataAttributeInstance(id);
return id;
}
public Boolean existDataAttributeInstance(int dataAttribute_id, int dataObjectInstance_id) {
String sql = "SELECT id FROM dataattributeinstance WHERE dataobjectinstance_id = " + dataObjectInstance_id + " AND dataattribute_id = " + dataAttribute_id;
return this.executeExistStatement(sql);
}
public int getDataAttributeInstanceID(int dataAttribute_id, int dataObjectInstance_id) {
String sql = "SELECT id FROM dataattributeinstance WHERE dataobjectinstance_id = " + dataObjectInstance_id + " AND dataattribute_id = " + dataAttribute_id;
return this.executeStatementReturnsInt(sql, "id");
}
public String getType(int dataAttribute_id) {
String sql = "SELECT type FROM dataattribute WHERE id = " + dataAttribute_id;
return this.executeStatementReturnsString(sql, "type");
}
public Object getValue(int dataAttributeInstance_id) {
String sql = "SELECT value FROM dataattributeinstance WHERE id = " + dataAttributeInstance_id;
return this.executeStatementReturnsObject(sql, "value");
}
public String getName(int dataAttribute_id) {
String sql = "SELECT name FROM dataattribute WHERE id = " + dataAttribute_id;
return this.executeStatementReturnsString(sql, "name");
}
/**
* This method sets the DataAttributeinstance to a desired value and saves a log entry into the database.
*
* @param dataAttributeInstance_id This is the database ID of the DataAttributeinstance which is found in the database.
* @param value This is the value the DataAttributeinstance should have after executing setValue.
*/
public void setValue(int dataAttributeInstance_id, Object value){
String sql = "UPDATE dataattributeinstance SET value = '" + value + "' WHERE id = " + dataAttributeInstance_id;
executeUpdateStatement(sql);
Log log = new Log();
log.newDataAttributeInstanceValue(dataAttributeInstance_id, value);
}
}
| small bug fix in dataattributeinstance logging
| src/main/java/de/uni_potsdam/hpi/bpt/bp2014/database/DbDataAttributeInstance.java | small bug fix in dataattributeinstance logging | <ide><path>rc/main/java/de/uni_potsdam/hpi/bpt/bp2014/database/DbDataAttributeInstance.java
<ide> * @param value This is the value the DataAttributeinstance should have after executing setValue.
<ide> */
<ide> public void setValue(int dataAttributeInstance_id, Object value){
<add> Log log = new Log();
<add> log.newDataAttributeInstanceValue(dataAttributeInstance_id, value);
<ide> String sql = "UPDATE dataattributeinstance SET value = '" + value + "' WHERE id = " + dataAttributeInstance_id;
<ide> executeUpdateStatement(sql);
<del> Log log = new Log();
<del> log.newDataAttributeInstanceValue(dataAttributeInstance_id, value);
<ide> }
<ide> } |
|
JavaScript | artistic-2.0 | a84e1cd5fd7f54b92f5df41a171bbbeeda40c0f7 | 0 | yibn2008/npm,princeofdarkness76/npm,kriskowal/npm,segment-boneyard/npm,midniteio/npm,rsp/npm,cchamberlain/npm,DaveEmmerson/npm,DIREKTSPEED-LTD/npm,chadnickbok/npm,yyx990803/npm,kriskowal/npm,kemitchell/npm,cchamberlain/npm-msys2,TimeToogo/npm,kriskowal/npm,xalopp/npm,yodeyer/npm,evocateur/npm,thomblake/npm,DIREKTSPEED-LTD/npm,midniteio/npm,yyx990803/npm,rsp/npm,kemitchell/npm,yodeyer/npm,lxe/npm,segrey/npm,ekmartin/npm,segrey/npm,TimeToogo/npm,misterbyrne/npm,chadnickbok/npm,ekmartin/npm,segmentio/npm,cchamberlain/npm-msys2,segmentio/npm,chadnickbok/npm,cchamberlain/npm-msys2,thomblake/npm,segment-boneyard/npm,thomblake/npm,kemitchell/npm,DIREKTSPEED-LTD/npm,kimshinelove/naver-npm,evocateur/npm,kimshinelove/naver-npm,rsp/npm,ekmartin/npm,princeofdarkness76/npm,cchamberlain/npm,xalopp/npm,Volune/npm,yibn2008/npm,haggholm/npm,xalopp/npm,misterbyrne/npm,yibn2008/npm,lxe/npm,princeofdarkness76/npm,evanlucas/npm,Volune/npm,haggholm/npm,yodeyer/npm,midniteio/npm,yyx990803/npm,lxe/npm,Volune/npm,cchamberlain/npm,evanlucas/npm,segrey/npm,haggholm/npm,kimshinelove/naver-npm,evanlucas/npm,TimeToogo/npm,DaveEmmerson/npm,segment-boneyard/npm,DaveEmmerson/npm,evocateur/npm,misterbyrne/npm,segmentio/npm |
// See http://semver.org/
// This implementation is a *hair* less strict in that it allows
// v1.2.3 things, and also tags that don't begin with a char.
var semver = "v?([0-9]+)\\.([0-9]+)\\.([0-9]+)(-[0-9]+-?)?([a-zA-Z-][a-zA-Z0-9-]*)?"
, expressions = exports.expressions =
{ parse : new RegExp("^\\s*"+semver+"\\s*$")
, parsePackage : new RegExp("^\\s*([^\/]+)[-@](" +semver+")\\s*$")
, parseRange : new RegExp(
"^\\s*(" + semver + ")\\s+-\\s+(" + semver + ")\\s*$")
, validComparator : new RegExp("((<|>)?=?)("+semver+")", "g")
}
Object.getOwnPropertyNames(expressions).forEach(function (i) {
exports[i] = function (str) { return str.match(expressions[i]) }
})
exports.rangeReplace = ">=$1 <=$7"
exports.compare = compare
exports.satisfies = satisfies
exports.gt = gt
exports.lt = lt
exports.valid = valid
exports.validPackage = validPackage
exports.validRange = validRange
exports.maxSatisfying = maxSatisfying
function valid (version) {
return exports.parse(version) && version.trim().replace(/^v/, '')
}
function validPackage (version) {
return version.match(expressions.parsePackage) && version.trim()
}
// range can be one of:
// "1.0.3 - 2.0.0" range, inclusive, like ">=1.0.3 <=2.0.0"
// ">1.0.2" like 1.0.3 - 9999.9999.9999
// ">=1.0.2" like 1.0.2 - 9999.9999.9999
// "<2.0.0" like 0.0.0 - 1.9999.9999
// ">1.0.2 <2.0.0" like 1.0.3 - 1.9999.9999
var starExpression = /(<|>)?=?\s*\*/g
, starReplace = ""
, compTrimExpression = new RegExp("((<|>)?=?)\\s*("+semver+")", "g")
, compTrimReplace = "$1$3"
function toComparators (range) {
return range.trim()
.replace(expressions.parseRange, exports.rangeReplace)
.replace(compTrimExpression, compTrimReplace)
.replace(starExpression, starReplace)
.split(/\s+/)
.filter(function (c) { return c.match(expressions.validComparator) })
}
function validRange (range) {
return toComparators(range).join(" ")
}
// returns the highest satisfying version in the list, or undefined
function maxSatisfying (versions, range) {
return versions
.filter(function (v) { return satisfies(v, range) })
.sort(compare)
.pop()
}
function satisfies (version, range) {
version = valid(version)
if (!version) return false
range = toComparators(range)
for (var i = 0, l = range.length; i < l; i ++) if (range[i]) {
var r = range[i]
, gtlt = r.charAt(0) === ">" ? gt : r.charAt(0) === "<" ? lt : false
, eq = r.charAt(!!gtlt) === "="
, sub = (!!eq) + (!!gtlt)
r = valid(r.substr(sub))
if (!r) return false
if (!gtlt) eq = true
if (eq && r === version) continue
if (gtlt && gtlt(version, r)) continue
return false
}
return true
}
// return v1 > v2 ? 1 : -1
function compare (v1, v2) {
return v1 === v2 ? 0 : gt(v1, v2) ? 1 : -1
}
function lt (v1, v2) { return gt(v2, v1) }
// return v1 > v2
function num (v) { return parseInt((v||"0").replace(/[^0-9]+/g, ''), 10) }
function gt (v1, v2) {
v1 = exports.parse(v1)
v2 = exports.parse(v2)
if (!v1 || !v2) return false
for (var i = 1; i < 5; i ++) {
v1[i] = num(v1[i])
v2[i] = num(v2[i])
if (v1[i] > v2[i]) return true
else if (v1[i] !== v2[i]) return false
}
// no tag is > than any tag, or use lexicographical order.
var tag1 = v1[5] || ""
, tag2 = v2[5] || ""
return tag2 && (!tag1 || tag1 > tag2)
}
if (module !== process.mainModule) return // tests below
var assert = require("assert")
; [ ["0.0.0", "0.0.0foo"]
, ["0.0.1", "0.0.0"]
, ["1.0.0", "0.9.9"]
, ["0.10.0", "0.9.0"]
, ["0.99.0", "0.10.0"]
, ["2.0.0", "1.2.3"]
, ["v0.0.0", "0.0.0foo"]
, ["v0.0.1", "0.0.0"]
, ["v1.0.0", "0.9.9"]
, ["v0.10.0", "0.9.0"]
, ["v0.99.0", "0.10.0"]
, ["v2.0.0", "1.2.3"]
, ["0.0.0", "v0.0.0foo"]
, ["0.0.1", "v0.0.0"]
, ["1.0.0", "v0.9.9"]
, ["0.10.0", "v0.9.0"]
, ["0.99.0", "v0.10.0"]
, ["2.0.0", "v1.2.3"]
, ["1.2.3", "1.2.3-asdf"]
, ["1.2.3-4", "1.2.3"]
, ["1.2.3-4-foo", "1.2.3"]
, ["1.2.3-5", "1.2.3-5-foo"]
, ["1.2.3-5", "1.2.3-4"]
].forEach(function (v) {
assert.ok(gt(v[0], v[1]), "gt('"+v[0]+"', '"+v[1]+"')")
assert.ok(lt(v[1], v[0]), "lt('"+v[1]+"', '"+v[0]+"')")
assert.ok(!gt(v[1], v[0]), "!gt('"+v[1]+"', '"+v[0]+"')")
assert.ok(!lt(v[0], v[1]), "!lt('"+v[0]+"', '"+v[1]+"')")
})
; [ ["1.0.0 - 2.0.0", "1.2.3"]
, ["1.0.0", "1.0.0"]
, [">=*", "0.2.4"]
, ["", "1.0.0"]
, ["*", "1.2.3"]
, ["*", "v1.2.3-foo"]
, [">=1.0.0", "1.0.0"]
, [">=1.0.0", "1.0.1"]
, [">=1.0.0", "1.1.0"]
, [">1.0.0", "1.0.1"]
, [">1.0.0", "1.1.0"]
, ["<=2.0.0", "2.0.0"]
, ["<=2.0.0", "1.9999.9999"]
, ["<=2.0.0", "0.2.9"]
, ["<2.0.0", "1.9999.9999"]
, ["<2.0.0", "0.2.9"]
, [">= 1.0.0", "1.0.0"]
, [">= 1.0.0", "1.0.1"]
, [">= 1.0.0", "1.1.0"]
, ["> 1.0.0", "1.0.1"]
, ["> 1.0.0", "1.1.0"]
, ["<= 2.0.0", "2.0.0"]
, ["<= 2.0.0", "1.9999.9999"]
, ["<= 2.0.0", "0.2.9"]
, ["< 2.0.0", "1.9999.9999"]
, ["<\t2.0.0", "0.2.9"]
, [">=0.1.97", "v0.1.97"]
, [">=0.1.97", "0.1.97"]
].forEach(function (v) {
assert.ok(satisfies(v[1], v[0]), v[0]+" satisfied by "+v[1])
})
| lib/utils/semver.js |
// See http://semver.org/
// This implementation is a *hair* less strict in that it allows
// v1.2.3 things, and also tags that don't begin with a char.
var semver = "v?([0-9]+)\\.([0-9]+)\\.([0-9]+)(-[0-9]+-?)?([a-zA-Z-][a-zA-Z0-9-]*)?"
, expressions = exports.expressions =
{ parse : new RegExp("^\\s*"+semver+"\\s*$")
, parsePackage : new RegExp("^\\s*([^\/]+)[-@](" +semver+")\\s*$")
, parseRange : new RegExp(
"^\\s*(" + semver + ")\\s+-\\s+(" + semver + ")\\s*$")
, validComparator : new RegExp("((<|>)?=?)("+semver+")", "g")
}
Object.getOwnPropertyNames(expressions).forEach(function (i) {
exports[i] = function (str) { return str.match(expressions[i]) }
})
exports.rangeReplace = ">=$1 <=$7"
exports.compare = compare
exports.satisfies = satisfies
exports.gt = gt
exports.lt = lt
exports.valid = valid
exports.validPackage = validPackage
exports.validRange = validRange
exports.maxSatisfying = maxSatisfying
function valid (version) { return exports.parse(version) && version.trim() }
function validPackage (version) {
return version.match(expressions.parsePackage) && version.trim()
}
// range can be one of:
// "1.0.3 - 2.0.0" range, inclusive, like ">=1.0.3 <=2.0.0"
// ">1.0.2" like 1.0.3 - 9999.9999.9999
// ">=1.0.2" like 1.0.2 - 9999.9999.9999
// "<2.0.0" like 0.0.0 - 1.9999.9999
// ">1.0.2 <2.0.0" like 1.0.3 - 1.9999.9999
var starExpression = /(<|>)?=?\s*\*/g
, starReplace = ""
, compTrimExpression = new RegExp("((<|>)?=?)\\s*("+semver+")", "g")
, compTrimReplace = "$1$3"
function toComparators (range) {
return range.trim()
.replace(expressions.parseRange, exports.rangeReplace)
.replace(compTrimExpression, compTrimReplace)
.replace(starExpression, starReplace)
.split(/\s+/)
.filter(function (c) { return c.match(expressions.validComparator) })
}
function validRange (range) {
return toComparators(range).join(" ")
}
// returns the highest satisfying version in the list, or undefined
function maxSatisfying (versions, range) {
return versions
.filter(function (v) { return satisfies(v, range) })
.sort(compare)
.pop()
}
function satisfies (version, range) {
version = valid(version)
if (!version) return false
range = toComparators(range)
for (var i = 0, l = range.length; i < l; i ++) if (range[i]) {
var r = range[i]
, gtlt = r.charAt(0) === ">" ? gt : r.charAt(0) === "<" ? lt : false
, eq = r.charAt(!!gtlt) === "="
, sub = (!!eq) + (!!gtlt)
r = valid(r.substr(sub))
if (!r) return false
if (!gtlt) eq = true
if (eq && r === version) continue
if (gtlt && gtlt(version, r)) continue
return false
}
return true
}
// return v1 > v2 ? 1 : -1
function compare (v1, v2) {
return v1 === v2 ? 0 : gt(v1, v2) ? 1 : -1
}
function lt (v1, v2) { return gt(v2, v1) }
// return v1 > v2
function num (v) { return parseInt((v||"0").replace(/[^0-9]+/g, ''), 10) }
function gt (v1, v2) {
v1 = exports.parse(v1)
v2 = exports.parse(v2)
if (!v1 || !v2) return false
for (var i = 1; i < 5; i ++) {
v1[i] = num(v1[i])
v2[i] = num(v2[i])
if (v1[i] > v2[i]) return true
else if (v1[i] !== v2[i]) return false
}
// no tag is > than any tag, or use lexicographical order.
var tag1 = v1[5] || ""
, tag2 = v2[5] || ""
return tag2 && (!tag1 || tag1 > tag2)
}
if (module !== process.mainModule) return // tests below
var assert = require("assert")
; [ ["0.0.0", "0.0.0foo"]
, ["0.0.1", "0.0.0"]
, ["1.0.0", "0.9.9"]
, ["0.10.0", "0.9.0"]
, ["0.99.0", "0.10.0"]
, ["2.0.0", "1.2.3"]
, ["v0.0.0", "0.0.0foo"]
, ["v0.0.1", "0.0.0"]
, ["v1.0.0", "0.9.9"]
, ["v0.10.0", "0.9.0"]
, ["v0.99.0", "0.10.0"]
, ["v2.0.0", "1.2.3"]
, ["0.0.0", "v0.0.0foo"]
, ["0.0.1", "v0.0.0"]
, ["1.0.0", "v0.9.9"]
, ["0.10.0", "v0.9.0"]
, ["0.99.0", "v0.10.0"]
, ["2.0.0", "v1.2.3"]
, ["1.2.3", "1.2.3-asdf"]
, ["1.2.3-4", "1.2.3"]
, ["1.2.3-4-foo", "1.2.3"]
, ["1.2.3-5", "1.2.3-5-foo"]
, ["1.2.3-5", "1.2.3-4"]
].forEach(function (v) {
assert.ok(gt(v[0], v[1]), "gt('"+v[0]+"', '"+v[1]+"')")
assert.ok(lt(v[1], v[0]), "lt('"+v[1]+"', '"+v[0]+"')")
assert.ok(!gt(v[1], v[0]), "!gt('"+v[1]+"', '"+v[0]+"')")
assert.ok(!lt(v[0], v[1]), "!lt('"+v[0]+"', '"+v[1]+"')")
})
; [ ["1.0.0 - 2.0.0", "1.2.3"]
, ["1.0.0", "1.0.0"]
, [">=*", "0.2.4"]
, ["", "1.0.0"]
, ["*", "1.2.3"]
, ["*", "v1.2.3-foo"]
, [">=1.0.0", "1.0.0"]
, [">=1.0.0", "1.0.1"]
, [">=1.0.0", "1.1.0"]
, [">1.0.0", "1.0.1"]
, [">1.0.0", "1.1.0"]
, ["<=2.0.0", "2.0.0"]
, ["<=2.0.0", "1.9999.9999"]
, ["<=2.0.0", "0.2.9"]
, ["<2.0.0", "1.9999.9999"]
, ["<2.0.0", "0.2.9"]
, [">= 1.0.0", "1.0.0"]
, [">= 1.0.0", "1.0.1"]
, [">= 1.0.0", "1.1.0"]
, ["> 1.0.0", "1.0.1"]
, ["> 1.0.0", "1.1.0"]
, ["<= 2.0.0", "2.0.0"]
, ["<= 2.0.0", "1.9999.9999"]
, ["<= 2.0.0", "0.2.9"]
, ["< 2.0.0", "1.9999.9999"]
, ["<\t2.0.0", "0.2.9"]
].forEach(function (v) {
assert.ok(satisfies(v[1], v[0]), v[0]+" satisfied by "+v[1])
})
| Add a test case, and make "v0.1.2" satisfy ">=0.1.2"
| lib/utils/semver.js | Add a test case, and make "v0.1.2" satisfy ">=0.1.2" | <ide><path>ib/utils/semver.js
<ide> exports.validRange = validRange
<ide> exports.maxSatisfying = maxSatisfying
<ide>
<del>function valid (version) { return exports.parse(version) && version.trim() }
<add>function valid (version) {
<add> return exports.parse(version) && version.trim().replace(/^v/, '')
<add>}
<ide> function validPackage (version) {
<ide> return version.match(expressions.parsePackage) && version.trim()
<ide> }
<ide> , ["<= 2.0.0", "0.2.9"]
<ide> , ["< 2.0.0", "1.9999.9999"]
<ide> , ["<\t2.0.0", "0.2.9"]
<add> , [">=0.1.97", "v0.1.97"]
<add> , [">=0.1.97", "0.1.97"]
<ide> ].forEach(function (v) {
<ide> assert.ok(satisfies(v[1], v[0]), v[0]+" satisfied by "+v[1])
<ide> }) |
|
Java | mit | error: pathspec 'app/src/main/java/de/christinecoenen/code/zapp/utils/ShortcutHelper.java' did not match any file(s) known to git
| 40c11c89f25da9e8c6709e863c37f0ebecb593f2 | 1 | cemrich/zapp | package de.christinecoenen.code.zapp.utils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.pm.ShortcutInfo;
import android.content.pm.ShortcutManager;
import android.graphics.drawable.Icon;
import android.os.Build;
import java.util.Collections;
import de.christinecoenen.code.zapp.ChannelDetailActivity;
import de.christinecoenen.code.zapp.model.ChannelModel;
/**
* Collection of helper functions to access the ShortcutManager API
* in a safe way.
*/
public class ShortcutHelper {
/**
* Adds the given channel as shortcut to the launcher icon.
* Only call on api level >= 25.
* @param context to access system services
* @param channel channel to create a shortcut for
* @return true if the channel could be added
*/
@TargetApi(25)
public boolean addShortcutForChannel(Context context, ChannelModel channel) {
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
ShortcutInfo shortcut = new ShortcutInfo.Builder(context, channel.getId())
.setShortLabel(channel.getName())
.setLongLabel(channel.getName())
.setIcon(Icon.createWithResource(context, channel.getDrawableId()))
.setIntent(ChannelDetailActivity.getStartIntent(context, channel.getId()))
.build();
return shortcutManager.addDynamicShortcuts(Collections.singletonList(shortcut));
}
/**
* Removes the given channel as shortcut from the launcher icon.
* Only call on api level >= 25.
* @param context to access system services
* @param channelId id of the channel you want to remove from shorcut menu
*/
@TargetApi(25)
public void removeShortcutForChannel(Context context, String channelId) {
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
shortcutManager.removeDynamicShortcuts(Collections.singletonList(channelId));
}
/**
* Call to report a shortcut used.
* You may call this using any api level.
* @param context to access system services
* @param channelId id of the channel that has been selected
*/
public void reportShortcutUsageGuarded(Context context, String channelId) {
if (areShortcutsSupported()) {
ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
shortcutManager.reportShortcutUsed(channelId);
}
}
/**
* @return true if the current api level supports shortcuts
*/
public boolean areShortcutsSupported() {
return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1;
}
}
| app/src/main/java/de/christinecoenen/code/zapp/utils/ShortcutHelper.java | Create helper class to easily use shortcuts
| app/src/main/java/de/christinecoenen/code/zapp/utils/ShortcutHelper.java | Create helper class to easily use shortcuts | <ide><path>pp/src/main/java/de/christinecoenen/code/zapp/utils/ShortcutHelper.java
<add>package de.christinecoenen.code.zapp.utils;
<add>
<add>
<add>import android.annotation.TargetApi;
<add>import android.content.Context;
<add>import android.content.pm.ShortcutInfo;
<add>import android.content.pm.ShortcutManager;
<add>import android.graphics.drawable.Icon;
<add>import android.os.Build;
<add>
<add>import java.util.Collections;
<add>
<add>import de.christinecoenen.code.zapp.ChannelDetailActivity;
<add>import de.christinecoenen.code.zapp.model.ChannelModel;
<add>
<add>/**
<add> * Collection of helper functions to access the ShortcutManager API
<add> * in a safe way.
<add> */
<add>public class ShortcutHelper {
<add>
<add> /**
<add> * Adds the given channel as shortcut to the launcher icon.
<add> * Only call on api level >= 25.
<add> * @param context to access system services
<add> * @param channel channel to create a shortcut for
<add> * @return true if the channel could be added
<add> */
<add> @TargetApi(25)
<add> public boolean addShortcutForChannel(Context context, ChannelModel channel) {
<add> ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
<add> ShortcutInfo shortcut = new ShortcutInfo.Builder(context, channel.getId())
<add> .setShortLabel(channel.getName())
<add> .setLongLabel(channel.getName())
<add> .setIcon(Icon.createWithResource(context, channel.getDrawableId()))
<add> .setIntent(ChannelDetailActivity.getStartIntent(context, channel.getId()))
<add> .build();
<add>
<add> return shortcutManager.addDynamicShortcuts(Collections.singletonList(shortcut));
<add> }
<add>
<add> /**
<add> * Removes the given channel as shortcut from the launcher icon.
<add> * Only call on api level >= 25.
<add> * @param context to access system services
<add> * @param channelId id of the channel you want to remove from shorcut menu
<add> */
<add> @TargetApi(25)
<add> public void removeShortcutForChannel(Context context, String channelId) {
<add> ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
<add> shortcutManager.removeDynamicShortcuts(Collections.singletonList(channelId));
<add> }
<add>
<add> /**
<add> * Call to report a shortcut used.
<add> * You may call this using any api level.
<add> * @param context to access system services
<add> * @param channelId id of the channel that has been selected
<add> */
<add> public void reportShortcutUsageGuarded(Context context, String channelId) {
<add> if (areShortcutsSupported()) {
<add> ShortcutManager shortcutManager = context.getSystemService(ShortcutManager.class);
<add> shortcutManager.reportShortcutUsed(channelId);
<add> }
<add> }
<add>
<add> /**
<add> * @return true if the current api level supports shortcuts
<add> */
<add> public boolean areShortcutsSupported() {
<add> return Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1;
<add> }
<add>} |
|
Java | mpl-2.0 | c255325868672041974b48639995f6efb039f625 | 0 | Pilarbrist/rhino,tntim96/rhino-apigee,ashwinrayaprolu1984/rhino,ashwinrayaprolu1984/rhino,AlexTrotsenko/rhino,Distrotech/rhino,Angelfirenze/rhino,Angelfirenze/rhino,jsdoc3/rhino,sam/htmlunit-rhino-fork,AlexTrotsenko/rhino,tntim96/rhino-jscover-repackaged,sam/htmlunit-rhino-fork,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,sam/htmlunit-rhino-fork,tntim96/rhino-jscover,qhanam/rhino,sam/htmlunit-rhino-fork,lv7777/egit_test,lv7777/egit_test,rasmuserik/rhino,Pilarbrist/rhino,swannodette/rhino,Pilarbrist/rhino,AlexTrotsenko/rhino,jsdoc3/rhino,lv7777/egit_test,tntim96/rhino-apigee,sainaen/rhino,sam/htmlunit-rhino-fork,tejassaoji/RhinoCoarseTainting,tuchida/rhino,sainaen/rhino,AlexTrotsenko/rhino,sainaen/rhino,tejassaoji/RhinoCoarseTainting,Angelfirenze/rhino,Angelfirenze/rhino,AlexTrotsenko/rhino,swannodette/rhino,tntim96/rhino-apigee,lv7777/egit_test,swannodette/rhino,rasmuserik/rhino,tntim96/rhino-jscover,tejassaoji/RhinoCoarseTainting,tntim96/htmlunit-rhino-fork,Angelfirenze/rhino,Pilarbrist/rhino,swannodette/rhino,tntim96/htmlunit-rhino-fork,tuchida/rhino,Angelfirenze/rhino,lv7777/egit_test,Distrotech/rhino,tejassaoji/RhinoCoarseTainting,InstantWebP2P/rhino-android,InstantWebP2P/rhino-android,sam/htmlunit-rhino-fork,qhanam/rhino,swannodette/rhino,sainaen/rhino,qhanam/rhino,sam/htmlunit-rhino-fork,tuchida/rhino,ashwinrayaprolu1984/rhino,tejassaoji/RhinoCoarseTainting,tuchida/rhino,sainaen/rhino,swannodette/rhino,tuchida/rhino,lv7777/egit_test,tejassaoji/RhinoCoarseTainting,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,lv7777/egit_test,jsdoc3/rhino,tejassaoji/RhinoCoarseTainting,Pilarbrist/rhino,ashwinrayaprolu1984/rhino,tuchida/rhino,Angelfirenze/rhino,qhanam/rhino,tuchida/rhino,swannodette/rhino,AlexTrotsenko/rhino,AlexTrotsenko/rhino,sainaen/rhino,tntim96/rhino-jscover-repackaged,sainaen/rhino,ashwinrayaprolu1984/rhino | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Mike Harm
* Ethan Hugg
* Bob Jervis
* Roger Lawrence
* Terry Lucas
* Frank Mitchell
* Milen Nankov
* Hannes Wallnoefer
* Andrew Wason
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.io.Serializable;
import java.lang.reflect.*;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import org.mozilla.javascript.ast.FunctionNode;
import org.mozilla.javascript.xml.XMLObject;
import org.mozilla.javascript.xml.XMLLib;
/**
* This is the class that implements the runtime.
*
* @author Norris Boyd
*/
public class ScriptRuntime {
/**
* No instances should be created.
*/
protected ScriptRuntime() {
}
/**
* Returns representation of the [[ThrowTypeError]] object.
* See ECMA 5 spec, 13.2.3
*/
public static BaseFunction typeErrorThrower() {
if (THROW_TYPE_ERROR == null) {
BaseFunction thrower = new BaseFunction() {
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
throw typeError0("msg.op.not.allowed");
}
@Override
public int getLength() {
return 0;
}
};
thrower.preventExtensions();
THROW_TYPE_ERROR = thrower;
}
return THROW_TYPE_ERROR;
}
private static BaseFunction THROW_TYPE_ERROR = null;
static class NoSuchMethodShim implements Callable {
String methodName;
Callable noSuchMethodMethod;
NoSuchMethodShim(Callable noSuchMethodMethod, String methodName)
{
this.noSuchMethodMethod = noSuchMethodMethod;
this.methodName = methodName;
}
/**
* Perform the call.
*
* @param cx the current Context for this thread
* @param scope the scope to use to resolve properties.
* @param thisObj the JavaScript <code>this</code> object
* @param args the array of arguments
* @return the result of the call
*/
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
{
Object[] nestedArgs = new Object[2];
nestedArgs[0] = methodName;
nestedArgs[1] = newArrayLiteral(args, null, cx, scope);
return noSuchMethodMethod.call(cx, scope, thisObj, nestedArgs);
}
}
/*
* There's such a huge space (and some time) waste for the Foo.class
* syntax: the compiler sticks in a test of a static field in the
* enclosing class for null and the code for creating the class value.
* It has to do this since the reference has to get pushed off until
* execution time (i.e. can't force an early load), but for the
* 'standard' classes - especially those in java.lang, we can trust
* that they won't cause problems by being loaded early.
*/
public final static Class<?>
BooleanClass = Kit.classOrNull("java.lang.Boolean"),
ByteClass = Kit.classOrNull("java.lang.Byte"),
CharacterClass = Kit.classOrNull("java.lang.Character"),
ClassClass = Kit.classOrNull("java.lang.Class"),
DoubleClass = Kit.classOrNull("java.lang.Double"),
FloatClass = Kit.classOrNull("java.lang.Float"),
IntegerClass = Kit.classOrNull("java.lang.Integer"),
LongClass = Kit.classOrNull("java.lang.Long"),
NumberClass = Kit.classOrNull("java.lang.Number"),
ObjectClass = Kit.classOrNull("java.lang.Object"),
ShortClass = Kit.classOrNull("java.lang.Short"),
StringClass = Kit.classOrNull("java.lang.String"),
DateClass = Kit.classOrNull("java.util.Date");
public final static Class<?>
ContextClass
= Kit.classOrNull("org.mozilla.javascript.Context"),
ContextFactoryClass
= Kit.classOrNull("org.mozilla.javascript.ContextFactory"),
FunctionClass
= Kit.classOrNull("org.mozilla.javascript.Function"),
ScriptableObjectClass
= Kit.classOrNull("org.mozilla.javascript.ScriptableObject");
public static final Class<Scriptable> ScriptableClass =
Scriptable.class;
private static final String[] lazilyNames = {
"RegExp", "org.mozilla.javascript.regexp.NativeRegExp",
"Packages", "org.mozilla.javascript.NativeJavaTopPackage",
"java", "org.mozilla.javascript.NativeJavaTopPackage",
"javax", "org.mozilla.javascript.NativeJavaTopPackage",
"org", "org.mozilla.javascript.NativeJavaTopPackage",
"com", "org.mozilla.javascript.NativeJavaTopPackage",
"edu", "org.mozilla.javascript.NativeJavaTopPackage",
"net", "org.mozilla.javascript.NativeJavaTopPackage",
"getClass", "org.mozilla.javascript.NativeJavaTopPackage",
"JavaAdapter", "org.mozilla.javascript.JavaAdapter",
"JavaImporter", "org.mozilla.javascript.ImporterTopLevel",
"Continuation", "org.mozilla.javascript.NativeContinuation",
// TODO Grotesque hack using literal string (xml) just to minimize
// changes for now
"XML", "(xml)",
"XMLList", "(xml)",
"Namespace", "(xml)",
"QName", "(xml)",
};
// Locale object used to request locale-neutral operations.
public static Locale ROOT_LOCALE = new Locale("");
private static final Object LIBRARY_SCOPE_KEY = "LIBRARY_SCOPE";
public static boolean isRhinoRuntimeType(Class<?> cl)
{
if (cl.isPrimitive()) {
return (cl != Character.TYPE);
} else {
return (cl == StringClass || cl == BooleanClass
|| NumberClass.isAssignableFrom(cl)
|| ScriptableClass.isAssignableFrom(cl));
}
}
public static ScriptableObject initStandardObjects(Context cx,
ScriptableObject scope,
boolean sealed)
{
if (scope == null) {
scope = new NativeObject();
}
scope.associateValue(LIBRARY_SCOPE_KEY, scope);
(new ClassCache()).associate(scope);
BaseFunction.init(scope, sealed);
NativeObject.init(scope, sealed);
Scriptable objectProto = ScriptableObject.getObjectPrototype(scope);
// Function.prototype.__proto__ should be Object.prototype
Scriptable functionProto = ScriptableObject.getClassPrototype(scope, "Function");
functionProto.setPrototype(objectProto);
// Set the prototype of the object passed in if need be
if (scope.getPrototype() == null)
scope.setPrototype(objectProto);
// must precede NativeGlobal since it's needed therein
NativeError.init(scope, sealed);
NativeGlobal.init(cx, scope, sealed);
NativeArray.init(scope, sealed);
if (cx.getOptimizationLevel() > 0) {
// When optimizing, attempt to fulfill all requests for new Array(N)
// with a higher threshold before switching to a sparse
// representation
NativeArray.setMaximumInitialCapacity(200000);
}
NativeString.init(scope, sealed);
NativeBoolean.init(scope, sealed);
NativeNumber.init(scope, sealed);
NativeDate.init(scope, sealed);
NativeMath.init(scope, sealed);
NativeJSON.init(scope, sealed);
NativeWith.init(scope, sealed);
NativeCall.init(scope, sealed);
NativeScript.init(scope, sealed);
NativeIterator.init(scope, sealed); // Also initializes NativeGenerator
boolean withXml = cx.hasFeature(Context.FEATURE_E4X) &&
cx.getE4xImplementationFactory() != null;
for (int i = 0; i != lazilyNames.length; i += 2) {
String topProperty = lazilyNames[i];
String className = lazilyNames[i + 1];
if (!withXml && className.equals("(xml)")) {
continue;
} else if (withXml && className.equals("(xml)")) {
className = cx.getE4xImplementationFactory().
getImplementationClassName();
}
new LazilyLoadedCtor(scope, topProperty, className, sealed, true);
}
if (scope instanceof TopLevel) {
((TopLevel)scope).cacheBuiltins();
}
return scope;
}
public static ScriptableObject getLibraryScopeOrNull(Scriptable scope)
{
ScriptableObject libScope;
libScope = (ScriptableObject)ScriptableObject.
getTopScopeValue(scope, LIBRARY_SCOPE_KEY);
return libScope;
}
// It is public so NativeRegExp can access it.
public static boolean isJSLineTerminator(int c)
{
// Optimization for faster check for eol character:
// they do not have 0xDFD0 bits set
if ((c & 0xDFD0) != 0) {
return false;
}
return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
}
public static boolean isJSWhitespaceOrLineTerminator(int c) {
return (isStrWhiteSpaceChar(c) || isJSLineTerminator(c));
}
/**
* Indicates if the character is a Str whitespace char according to ECMA spec:
* StrWhiteSpaceChar :::
<TAB>
<SP>
<NBSP>
<FF>
<VT>
<CR>
<LF>
<LS>
<PS>
<USP>
<BOM>
*/
static boolean isStrWhiteSpaceChar(int c)
{
switch (c) {
case ' ': // <SP>
case '\n': // <LF>
case '\r': // <CR>
case '\t': // <TAB>
case '\u00A0': // <NBSP>
case '\u000C': // <FF>
case '\u000B': // <VT>
case '\u2028': // <LS>
case '\u2029': // <PS>
case '\uFEFF': // <BOM>
return true;
default:
return Character.getType(c) == Character.SPACE_SEPARATOR;
}
}
public static Boolean wrapBoolean(boolean b)
{
return b ? Boolean.TRUE : Boolean.FALSE;
}
public static Integer wrapInt(int i)
{
return Integer.valueOf(i);
}
public static Number wrapNumber(double x)
{
if (x != x) {
return ScriptRuntime.NaNobj;
}
return new Double(x);
}
/**
* Convert the value to a boolean.
*
* See ECMA 9.2.
*/
public static boolean toBoolean(Object val)
{
for (;;) {
if (val instanceof Boolean)
return ((Boolean) val).booleanValue();
if (val == null || val == Undefined.instance)
return false;
if (val instanceof CharSequence)
return ((CharSequence) val).length() != 0;
if (val instanceof Number) {
double d = ((Number) val).doubleValue();
return (d == d && d != 0.0);
}
if (val instanceof Scriptable) {
if (val instanceof ScriptableObject &&
((ScriptableObject) val).avoidObjectDetection())
{
return false;
}
if (Context.getContext().isVersionECMA1()) {
// pure ECMA
return true;
}
// ECMA extension
val = ((Scriptable) val).getDefaultValue(BooleanClass);
if (val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
continue;
}
warnAboutNonJSObject(val);
return true;
}
}
/**
* Convert the value to a number.
*
* See ECMA 9.3.
*/
public static double toNumber(Object val)
{
for (;;) {
if (val instanceof Number)
return ((Number) val).doubleValue();
if (val == null)
return +0.0;
if (val == Undefined.instance)
return NaN;
if (val instanceof String)
return toNumber((String) val);
if (val instanceof CharSequence)
return toNumber(val.toString());
if (val instanceof Boolean)
return ((Boolean) val).booleanValue() ? 1 : +0.0;
if (val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(NumberClass);
if (val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
continue;
}
warnAboutNonJSObject(val);
return NaN;
}
}
public static double toNumber(Object[] args, int index) {
return (index < args.length) ? toNumber(args[index]) : NaN;
}
// Can not use Double.NaN defined as 0.0d / 0.0 as under the Microsoft VM,
// versions 2.01 and 3.0P1, that causes some uses (returns at least) of
// Double.NaN to be converted to 1.0.
// So we use ScriptRuntime.NaN instead of Double.NaN.
public static final double
NaN = Double.longBitsToDouble(0x7ff8000000000000L);
// A similar problem exists for negative zero.
public static final double
negativeZero = Double.longBitsToDouble(0x8000000000000000L);
public static final Double NaNobj = new Double(NaN);
/*
* Helper function for toNumber, parseInt, and TokenStream.getToken.
*/
static double stringToNumber(String s, int start, int radix) {
char digitMax = '9';
char lowerCaseBound = 'a';
char upperCaseBound = 'A';
int len = s.length();
if (radix < 10) {
digitMax = (char) ('0' + radix - 1);
}
if (radix > 10) {
lowerCaseBound = (char) ('a' + radix - 10);
upperCaseBound = (char) ('A' + radix - 10);
}
int end;
double sum = 0.0;
for (end=start; end < len; end++) {
char c = s.charAt(end);
int newDigit;
if ('0' <= c && c <= digitMax)
newDigit = c - '0';
else if ('a' <= c && c < lowerCaseBound)
newDigit = c - 'a' + 10;
else if ('A' <= c && c < upperCaseBound)
newDigit = c - 'A' + 10;
else
break;
sum = sum*radix + newDigit;
}
if (start == end) {
return NaN;
}
if (sum >= 9007199254740992.0) {
if (radix == 10) {
/* If we're accumulating a decimal number and the number
* is >= 2^53, then the result from the repeated multiply-add
* above may be inaccurate. Call Java to get the correct
* answer.
*/
try {
return Double.valueOf(s.substring(start, end)).doubleValue();
} catch (NumberFormatException nfe) {
return NaN;
}
} else if (radix == 2 || radix == 4 || radix == 8 ||
radix == 16 || radix == 32)
{
/* The number may also be inaccurate for one of these bases.
* This happens if the addition in value*radix + digit causes
* a round-down to an even least significant mantissa bit
* when the first dropped bit is a one. If any of the
* following digits in the number (which haven't been added
* in yet) are nonzero then the correct action would have
* been to round up instead of down. An example of this
* occurs when reading the number 0x1000000000000081, which
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
*/
int bitShiftInChar = 1;
int digit = 0;
final int SKIP_LEADING_ZEROS = 0;
final int FIRST_EXACT_53_BITS = 1;
final int AFTER_BIT_53 = 2;
final int ZEROS_AFTER_54 = 3;
final int MIXED_AFTER_54 = 4;
int state = SKIP_LEADING_ZEROS;
int exactBitsLimit = 53;
double factor = 0.0;
boolean bit53 = false;
// bit54 is the 54th bit (the first dropped from the mantissa)
boolean bit54 = false;
for (;;) {
if (bitShiftInChar == 1) {
if (start == end)
break;
digit = s.charAt(start++);
if ('0' <= digit && digit <= '9')
digit -= '0';
else if ('a' <= digit && digit <= 'z')
digit -= 'a' - 10;
else
digit -= 'A' - 10;
bitShiftInChar = radix;
}
bitShiftInChar >>= 1;
boolean bit = (digit & bitShiftInChar) != 0;
switch (state) {
case SKIP_LEADING_ZEROS:
if (bit) {
--exactBitsLimit;
sum = 1.0;
state = FIRST_EXACT_53_BITS;
}
break;
case FIRST_EXACT_53_BITS:
sum *= 2.0;
if (bit)
sum += 1.0;
--exactBitsLimit;
if (exactBitsLimit == 0) {
bit53 = bit;
state = AFTER_BIT_53;
}
break;
case AFTER_BIT_53:
bit54 = bit;
factor = 2.0;
state = ZEROS_AFTER_54;
break;
case ZEROS_AFTER_54:
if (bit) {
state = MIXED_AFTER_54;
}
// fallthrough
case MIXED_AFTER_54:
factor *= 2;
break;
}
}
switch (state) {
case SKIP_LEADING_ZEROS:
sum = 0.0;
break;
case FIRST_EXACT_53_BITS:
case AFTER_BIT_53:
// do nothing
break;
case ZEROS_AFTER_54:
// x1.1 -> x1 + 1 (round up)
// x0.1 -> x0 (round down)
if (bit54 & bit53)
sum += 1.0;
sum *= factor;
break;
case MIXED_AFTER_54:
// x.100...1.. -> x + 1 (round up)
// x.0anything -> x (round down)
if (bit54)
sum += 1.0;
sum *= factor;
break;
}
}
/* We don't worry about inaccurate numbers for any other base. */
}
return sum;
}
/**
* ToNumber applied to the String type
*
* See ECMA 9.3.1
*/
public static double toNumber(String s) {
int len = s.length();
int start = 0;
char startChar;
for (;;) {
if (start == len) {
// Empty or contains only whitespace
return +0.0;
}
startChar = s.charAt(start);
if (!ScriptRuntime.isStrWhiteSpaceChar(startChar))
break;
start++;
}
if (startChar == '0') {
if (start + 2 < len) {
int c1 = s.charAt(start + 1);
if (c1 == 'x' || c1 == 'X') {
// A hexadecimal number
return stringToNumber(s, start + 2, 16);
}
}
} else if (startChar == '+' || startChar == '-') {
if (start + 3 < len && s.charAt(start + 1) == '0') {
int c2 = s.charAt(start + 2);
if (c2 == 'x' || c2 == 'X') {
// A hexadecimal number with sign
double val = stringToNumber(s, start + 3, 16);
return startChar == '-' ? -val : val;
}
}
}
int end = len - 1;
char endChar;
while (ScriptRuntime.isStrWhiteSpaceChar(endChar = s.charAt(end)))
end--;
if (endChar == 'y') {
// check for "Infinity"
if (startChar == '+' || startChar == '-')
start++;
if (start + 7 == end && s.regionMatches(start, "Infinity", 0, 8))
return startChar == '-'
? Double.NEGATIVE_INFINITY
: Double.POSITIVE_INFINITY;
return NaN;
}
// A non-hexadecimal, non-infinity number:
// just try a normal floating point conversion
String sub = s.substring(start, end+1);
if (MSJVM_BUG_WORKAROUNDS) {
// The MS JVM will accept non-conformant strings
// rather than throwing a NumberFormatException
// as it should.
for (int i=sub.length()-1; i >= 0; i--) {
char c = sub.charAt(i);
if (('0' <= c && c <= '9') || c == '.' ||
c == 'e' || c == 'E' ||
c == '+' || c == '-')
continue;
return NaN;
}
}
try {
return Double.valueOf(sub).doubleValue();
} catch (NumberFormatException ex) {
return NaN;
}
}
/**
* Helper function for builtin objects that use the varargs form.
* ECMA function formal arguments are undefined if not supplied;
* this function pads the argument array out to the expected
* length, if necessary.
*/
public static Object[] padArguments(Object[] args, int count) {
if (count < args.length)
return args;
int i;
Object[] result = new Object[count];
for (i = 0; i < args.length; i++) {
result[i] = args[i];
}
for (; i < count; i++) {
result[i] = Undefined.instance;
}
return result;
}
/* Work around Microsoft Java VM bugs. */
private final static boolean MSJVM_BUG_WORKAROUNDS = true;
public static String escapeString(String s)
{
return escapeString(s, '"');
}
/**
* For escaping strings printed by object and array literals; not quite
* the same as 'escape.'
*/
public static String escapeString(String s, char escapeQuote)
{
if (!(escapeQuote == '"' || escapeQuote == '\'')) Kit.codeBug();
StringBuffer sb = null;
for(int i = 0, L = s.length(); i != L; ++i) {
int c = s.charAt(i);
if (' ' <= c && c <= '~' && c != escapeQuote && c != '\\') {
// an ordinary print character (like C isprint()) and not "
// or \ .
if (sb != null) {
sb.append((char)c);
}
continue;
}
if (sb == null) {
sb = new StringBuffer(L + 3);
sb.append(s);
sb.setLength(i);
}
int escape = -1;
switch (c) {
case '\b': escape = 'b'; break;
case '\f': escape = 'f'; break;
case '\n': escape = 'n'; break;
case '\r': escape = 'r'; break;
case '\t': escape = 't'; break;
case 0xb: escape = 'v'; break; // Java lacks \v.
case ' ': escape = ' '; break;
case '\\': escape = '\\'; break;
}
if (escape >= 0) {
// an \escaped sort of character
sb.append('\\');
sb.append((char)escape);
} else if (c == escapeQuote) {
sb.append('\\');
sb.append(escapeQuote);
} else {
int hexSize;
if (c < 256) {
// 2-digit hex
sb.append("\\x");
hexSize = 2;
} else {
// Unicode.
sb.append("\\u");
hexSize = 4;
}
// append hexadecimal form of c left-padded with 0
for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) {
int digit = 0xf & (c >> shift);
int hc = (digit < 10) ? '0' + digit : 'a' - 10 + digit;
sb.append((char)hc);
}
}
}
return (sb == null) ? s : sb.toString();
}
static boolean isValidIdentifierName(String s)
{
int L = s.length();
if (L == 0)
return false;
if (!Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i != L; ++i) {
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
}
return !TokenStream.isKeyword(s);
}
public static CharSequence toCharSequence(Object val) {
if (val instanceof NativeString) {
return ((NativeString)val).toCharSequence();
}
return val instanceof CharSequence ? (CharSequence) val : toString(val);
}
/**
* Convert the value to a string.
*
* See ECMA 9.8.
*/
public static String toString(Object val) {
for (;;) {
if (val == null) {
return "null";
}
if (val == Undefined.instance) {
return "undefined";
}
if (val instanceof String) {
return (String)val;
}
if (val instanceof CharSequence) {
return val.toString();
}
if (val instanceof Number) {
// XXX should we just teach NativeNumber.stringValue()
// about Numbers?
return numberToString(((Number)val).doubleValue(), 10);
}
if (val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(StringClass);
if (val instanceof Scriptable) {
throw errorWithClassName("msg.primitive.expected", val);
}
continue;
}
return val.toString();
}
}
static String defaultObjectToString(Scriptable obj)
{
return "[object " + obj.getClassName() + ']';
}
public static String toString(Object[] args, int index)
{
return (index < args.length) ? toString(args[index]) : "undefined";
}
/**
* Optimized version of toString(Object) for numbers.
*/
public static String toString(double val) {
return numberToString(val, 10);
}
public static String numberToString(double d, int base) {
if (d != d)
return "NaN";
if (d == Double.POSITIVE_INFINITY)
return "Infinity";
if (d == Double.NEGATIVE_INFINITY)
return "-Infinity";
if (d == 0.0)
return "0";
if ((base < 2) || (base > 36)) {
throw Context.reportRuntimeError1(
"msg.bad.radix", Integer.toString(base));
}
if (base != 10) {
return DToA.JS_dtobasestr(base, d);
} else {
StringBuffer result = new StringBuffer();
DToA.JS_dtostr(result, DToA.DTOSTR_STANDARD, 0, d);
return result.toString();
}
}
static String uneval(Context cx, Scriptable scope, Object value)
{
if (value == null) {
return "null";
}
if (value == Undefined.instance) {
return "undefined";
}
if (value instanceof CharSequence) {
String escaped = escapeString(value.toString());
StringBuffer sb = new StringBuffer(escaped.length() + 2);
sb.append('\"');
sb.append(escaped);
sb.append('\"');
return sb.toString();
}
if (value instanceof Number) {
double d = ((Number)value).doubleValue();
if (d == 0 && 1 / d < 0) {
return "-0";
}
return toString(d);
}
if (value instanceof Boolean) {
return toString(value);
}
if (value instanceof Scriptable) {
Scriptable obj = (Scriptable)value;
// Wrapped Java objects won't have "toSource" and will report
// errors for get()s of nonexistent name, so use has() first
if (ScriptableObject.hasProperty(obj, "toSource")) {
Object v = ScriptableObject.getProperty(obj, "toSource");
if (v instanceof Function) {
Function f = (Function)v;
return toString(f.call(cx, scope, obj, emptyArgs));
}
}
return toString(value);
}
warnAboutNonJSObject(value);
return value.toString();
}
static String defaultObjectToSource(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap(31);
} else {
toplevel = false;
iterating = cx.iterating.has(thisObj);
}
StringBuffer result = new StringBuffer(128);
if (toplevel) {
result.append("(");
}
result.append('{');
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.intern(thisObj); // stop recursion.
Object[] ids = thisObj.getIds();
for (int i=0; i < ids.length; i++) {
Object id = ids[i];
Object value;
if (id instanceof Integer) {
int intId = ((Integer)id).intValue();
value = thisObj.get(intId, thisObj);
if (value == Scriptable.NOT_FOUND)
continue; // a property has been removed
if (i > 0)
result.append(", ");
result.append(intId);
} else {
String strId = (String)id;
value = thisObj.get(strId, thisObj);
if (value == Scriptable.NOT_FOUND)
continue; // a property has been removed
if (i > 0)
result.append(", ");
if (ScriptRuntime.isValidIdentifierName(strId)) {
result.append(strId);
} else {
result.append('\'');
result.append(
ScriptRuntime.escapeString(strId, '\''));
result.append('\'');
}
}
result.append(':');
result.append(ScriptRuntime.uneval(cx, scope, value));
}
}
} finally {
if (toplevel) {
cx.iterating = null;
}
}
result.append('}');
if (toplevel) {
result.append(')');
}
return result.toString();
}
public static Scriptable toObject(Scriptable scope, Object val)
{
if (val instanceof Scriptable) {
return (Scriptable)val;
}
return toObject(Context.getContext(), scope, val);
}
/**
* Warning: this doesn't allow to resolve primitive prototype properly when many top scopes are involved
*/
public static Scriptable toObjectOrNull(Context cx, Object obj)
{
if (obj instanceof Scriptable) {
return (Scriptable)obj;
} else if (obj != null && obj != Undefined.instance) {
return toObject(cx, getTopCallScope(cx), obj);
}
return null;
}
/**
* @param scope the scope that should be used to resolve primitive prototype
*/
public static Scriptable toObjectOrNull(Context cx, Object obj,
final Scriptable scope)
{
if (obj instanceof Scriptable) {
return (Scriptable)obj;
} else if (obj != null && obj != Undefined.instance) {
return toObject(cx, scope, obj);
}
return null;
}
/**
* @deprecated Use {@link #toObject(Scriptable, Object)} instead.
*/
public static Scriptable toObject(Scriptable scope, Object val,
Class<?> staticClass)
{
if (val instanceof Scriptable) {
return (Scriptable)val;
}
return toObject(Context.getContext(), scope, val);
}
/**
* Convert the value to an object.
*
* See ECMA 9.9.
*/
public static Scriptable toObject(Context cx, Scriptable scope, Object val)
{
if (val instanceof Scriptable) {
return (Scriptable) val;
}
if (val instanceof CharSequence) {
// FIXME we want to avoid toString() here, especially for concat()
NativeString result = new NativeString((CharSequence)val);
setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.String);
return result;
}
if (val instanceof Number) {
NativeNumber result = new NativeNumber(((Number)val).doubleValue());
setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Number);
return result;
}
if (val instanceof Boolean) {
NativeBoolean result = new NativeBoolean(((Boolean)val).booleanValue());
setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Boolean);
return result;
}
if (val == null) {
throw typeError0("msg.null.to.object");
}
if (val == Undefined.instance) {
throw typeError0("msg.undef.to.object");
}
// Extension: Wrap as a LiveConnect object.
Object wrapped = cx.getWrapFactory().wrap(cx, scope, val, null);
if (wrapped instanceof Scriptable)
return (Scriptable) wrapped;
throw errorWithClassName("msg.invalid.type", val);
}
/**
* @deprecated Use {@link #toObject(Context, Scriptable, Object)} instead.
*/
public static Scriptable toObject(Context cx, Scriptable scope, Object val,
Class<?> staticClass)
{
return toObject(cx, scope, val);
}
/**
* @deprecated The method is only present for compatibility.
*/
public static Object call(Context cx, Object fun, Object thisArg,
Object[] args, Scriptable scope)
{
if (!(fun instanceof Function)) {
throw notFunctionError(toString(fun));
}
Function function = (Function)fun;
Scriptable thisObj = toObjectOrNull(cx, thisArg);
if (thisObj == null) {
throw undefCallError(thisObj, "function");
}
return function.call(cx, scope, thisObj, args);
}
public static Scriptable newObject(Context cx, Scriptable scope,
String constructorName, Object[] args)
{
scope = ScriptableObject.getTopLevelScope(scope);
Function ctor = getExistingCtor(cx, scope, constructorName);
if (args == null) { args = ScriptRuntime.emptyArgs; }
return ctor.construct(cx, scope, args);
}
public static Scriptable newBuiltinObject(Context cx, Scriptable scope,
TopLevel.Builtins type,
Object[] args)
{
scope = ScriptableObject.getTopLevelScope(scope);
Function ctor = TopLevel.getBuiltinCtor(cx, scope, type);
if (args == null) { args = ScriptRuntime.emptyArgs; }
return ctor.construct(cx, scope, args);
}
/**
*
* See ECMA 9.4.
*/
public static double toInteger(Object val) {
return toInteger(toNumber(val));
}
// convenience method
public static double toInteger(double d) {
// if it's NaN
if (d != d)
return +0.0;
if (d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return d;
if (d > 0.0)
return Math.floor(d);
else
return Math.ceil(d);
}
public static double toInteger(Object[] args, int index) {
return (index < args.length) ? toInteger(args[index]) : +0.0;
}
/**
*
* See ECMA 9.5.
*/
public static int toInt32(Object val)
{
// short circuit for common integer values
if (val instanceof Integer)
return ((Integer)val).intValue();
return toInt32(toNumber(val));
}
public static int toInt32(Object[] args, int index) {
return (index < args.length) ? toInt32(args[index]) : 0;
}
public static int toInt32(double d) {
int id = (int)d;
if (id == d) {
// This covers -0.0 as well
return id;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
double two32 = 4294967296.0;
d = Math.IEEEremainder(d, two32);
// (double)(long)d == d should hold here
long l = (long)d;
// returning (int)d does not work as d can be outside int range
// but the result must always be 32 lower bits of l
return (int)l;
}
/**
* See ECMA 9.6.
* @return long value representing 32 bits unsigned integer
*/
public static long toUint32(double d) {
long l = (long)d;
if (l == d) {
// This covers -0.0 as well
return l & 0xffffffffL;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
l = (long)Math.IEEEremainder(d, two32);
return l & 0xffffffffL;
}
public static long toUint32(Object val) {
return toUint32(toNumber(val));
}
/**
*
* See ECMA 9.7.
*/
public static char toUint16(Object val) {
double d = toNumber(val);
int i = (int)d;
if (i == d) {
return (char)i;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
int int16 = 0x10000;
i = (int)Math.IEEEremainder(d, int16);
return (char)i;
}
// XXX: this is until setDefaultNamespace will learn how to store NS
// properly and separates namespace form Scriptable.get etc.
private static final String DEFAULT_NS_TAG = "__default_namespace__";
public static Object setDefaultNamespace(Object namespace, Context cx)
{
Scriptable scope = cx.currentActivationCall;
if (scope == null) {
scope = getTopCallScope(cx);
}
XMLLib xmlLib = currentXMLLib(cx);
Object ns = xmlLib.toDefaultXmlNamespace(cx, namespace);
// XXX : this should be in separated namesapce from Scriptable.get/put
if (!scope.has(DEFAULT_NS_TAG, scope)) {
// XXX: this is racy of cause
ScriptableObject.defineProperty(scope, DEFAULT_NS_TAG, ns,
ScriptableObject.PERMANENT
| ScriptableObject.DONTENUM);
} else {
scope.put(DEFAULT_NS_TAG, scope, ns);
}
return Undefined.instance;
}
public static Object searchDefaultNamespace(Context cx)
{
Scriptable scope = cx.currentActivationCall;
if (scope == null) {
scope = getTopCallScope(cx);
}
Object nsObject;
for (;;) {
Scriptable parent = scope.getParentScope();
if (parent == null) {
nsObject = ScriptableObject.getProperty(scope, DEFAULT_NS_TAG);
if (nsObject == Scriptable.NOT_FOUND) {
return null;
}
break;
}
nsObject = scope.get(DEFAULT_NS_TAG, scope);
if (nsObject != Scriptable.NOT_FOUND) {
break;
}
scope = parent;
}
return nsObject;
}
public static Object getTopLevelProp(Scriptable scope, String id) {
scope = ScriptableObject.getTopLevelScope(scope);
return ScriptableObject.getProperty(scope, id);
}
static Function getExistingCtor(Context cx, Scriptable scope,
String constructorName)
{
Object ctorVal = ScriptableObject.getProperty(scope, constructorName);
if (ctorVal instanceof Function) {
return (Function)ctorVal;
}
if (ctorVal == Scriptable.NOT_FOUND) {
throw Context.reportRuntimeError1(
"msg.ctor.not.found", constructorName);
} else {
throw Context.reportRuntimeError1(
"msg.not.ctor", constructorName);
}
}
/**
* Return -1L if str is not an index, or the index value as lower 32
* bits of the result. Note that the result needs to be cast to an int
* in order to produce the actual index, which may be negative.
*/
public static long indexFromString(String str)
{
// The length of the decimal string representation of
// Integer.MAX_VALUE, 2147483647
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (len > 0) {
int i = 0;
boolean negate = false;
int c = str.charAt(0);
if (c == '-') {
if (len > 1) {
c = str.charAt(1);
i = 1;
negate = true;
}
}
c -= '0';
if (0 <= c && c <= 9
&& len <= (negate ? MAX_VALUE_LENGTH + 1 : MAX_VALUE_LENGTH))
{
// Use negative numbers to accumulate index to handle
// Integer.MIN_VALUE that is greater by 1 in absolute value
// then Integer.MAX_VALUE
int index = -c;
int oldIndex = 0;
i++;
if (index != 0) {
// Note that 00, 01, 000 etc. are not indexes
while (i != len && 0 <= (c = str.charAt(i) - '0') && c <= 9)
{
oldIndex = index;
index = 10 * index - c;
i++;
}
}
// Make sure all characters were consumed and that it couldn't
// have overflowed.
if (i == len &&
(oldIndex > (Integer.MIN_VALUE / 10) ||
(oldIndex == (Integer.MIN_VALUE / 10) &&
c <= (negate ? -(Integer.MIN_VALUE % 10)
: (Integer.MAX_VALUE % 10)))))
{
return 0xFFFFFFFFL & (negate ? index : -index);
}
}
}
return -1L;
}
/**
* If str is a decimal presentation of Uint32 value, return it as long.
* Othewise return -1L;
*/
public static long testUint32String(String str)
{
// The length of the decimal string representation of
// UINT32_MAX_VALUE, 4294967296
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (1 <= len && len <= MAX_VALUE_LENGTH) {
int c = str.charAt(0);
c -= '0';
if (c == 0) {
// Note that 00,01 etc. are not valid Uint32 presentations
return (len == 1) ? 0L : -1L;
}
if (1 <= c && c <= 9) {
long v = c;
for (int i = 1; i != len; ++i) {
c = str.charAt(i) - '0';
if (!(0 <= c && c <= 9)) {
return -1;
}
v = 10 * v + c;
}
// Check for overflow
if ((v >>> 32) == 0) {
return v;
}
}
}
return -1;
}
/**
* If s represents index, then return index value wrapped as Integer
* and othewise return s.
*/
static Object getIndexObject(String s)
{
long indexTest = indexFromString(s);
if (indexTest >= 0) {
return Integer.valueOf((int)indexTest);
}
return s;
}
/**
* If d is exact int value, return its value wrapped as Integer
* and othewise return d converted to String.
*/
static Object getIndexObject(double d)
{
int i = (int)d;
if (i == d) {
return Integer.valueOf(i);
}
return toString(d);
}
/**
* If toString(id) is a decimal presentation of int32 value, then id
* is index. In this case return null and make the index available
* as ScriptRuntime.lastIndexResult(cx). Otherwise return toString(id).
*/
static String toStringIdOrIndex(Context cx, Object id)
{
if (id instanceof Number) {
double d = ((Number)id).doubleValue();
int index = (int)d;
if (index == d) {
storeIndexResult(cx, index);
return null;
}
return toString(id);
} else {
String s;
if (id instanceof String) {
s = (String)id;
} else {
s = toString(id);
}
long indexTest = indexFromString(s);
if (indexTest >= 0) {
storeIndexResult(cx, (int)indexTest);
return null;
}
return s;
}
}
/**
* Call obj.[[Get]](id)
*/
public static Object getObjectElem(Object obj, Object elem, Context cx)
{
return getObjectElem(obj, elem, cx, getTopCallScope(cx));
}
/**
* Call obj.[[Get]](id)
*/
public static Object getObjectElem(Object obj, Object elem, Context cx, final Scriptable scope)
{
Scriptable sobj = toObjectOrNull(cx, obj, scope);
if (sobj == null) {
throw undefReadError(obj, elem);
}
return getObjectElem(sobj, elem, cx);
}
public static Object getObjectElem(Scriptable obj, Object elem,
Context cx)
{
Object result;
if (obj instanceof XMLObject) {
result = ((XMLObject)obj).get(cx, elem);
} else {
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
result = ScriptableObject.getProperty(obj, index);
} else {
result = ScriptableObject.getProperty(obj, s);
}
}
if (result == Scriptable.NOT_FOUND) {
result = Undefined.instance;
}
return result;
}
/**
* Version of getObjectElem when elem is a valid JS identifier name.
*/
public static Object getObjectProp(Object obj, String property,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefReadError(obj, property);
}
return getObjectProp(sobj, property, cx);
}
/**
* @param scope the scope that should be used to resolve primitive prototype
*/
public static Object getObjectProp(Object obj, String property,
Context cx, final Scriptable scope)
{
Scriptable sobj = toObjectOrNull(cx, obj, scope);
if (sobj == null) {
throw undefReadError(obj, property);
}
return getObjectProp(sobj, property, cx);
}
public static Object getObjectProp(Scriptable obj, String property,
Context cx)
{
Object result = ScriptableObject.getProperty(obj, property);
if (result == Scriptable.NOT_FOUND) {
if (cx.hasFeature(Context.FEATURE_STRICT_MODE)) {
Context.reportWarning(ScriptRuntime.getMessage1(
"msg.ref.undefined.prop", property));
}
result = Undefined.instance;
}
return result;
}
public static Object getObjectPropNoWarn(Object obj, String property,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefReadError(obj, property);
}
Object result = ScriptableObject.getProperty(sobj, property);
if (result == Scriptable.NOT_FOUND) {
return Undefined.instance;
}
return result;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object getObjectIndex(Object obj, double dblIndex,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefReadError(obj, toString(dblIndex));
}
int index = (int)dblIndex;
if (index == dblIndex) {
return getObjectIndex(sobj, index, cx);
} else {
String s = toString(dblIndex);
return getObjectProp(sobj, s, cx);
}
}
public static Object getObjectIndex(Scriptable obj, int index,
Context cx)
{
Object result = ScriptableObject.getProperty(obj, index);
if (result == Scriptable.NOT_FOUND) {
result = Undefined.instance;
}
return result;
}
/*
* Call obj.[[Put]](id, value)
*/
public static Object setObjectElem(Object obj, Object elem, Object value,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefWriteError(obj, elem, value);
}
return setObjectElem(sobj, elem, value, cx);
}
public static Object setObjectElem(Scriptable obj, Object elem,
Object value, Context cx)
{
if (obj instanceof XMLObject) {
((XMLObject)obj).put(cx, elem, value);
} else {
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
ScriptableObject.putProperty(obj, index, value);
} else {
ScriptableObject.putProperty(obj, s, value);
}
}
return value;
}
/**
* Version of setObjectElem when elem is a valid JS identifier name.
*/
public static Object setObjectProp(Object obj, String property,
Object value, Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefWriteError(obj, property, value);
}
return setObjectProp(sobj, property, value, cx);
}
public static Object setObjectProp(Scriptable obj, String property,
Object value, Context cx)
{
ScriptableObject.putProperty(obj, property, value);
return value;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object setObjectIndex(Object obj, double dblIndex,
Object value, Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefWriteError(obj, String.valueOf(dblIndex), value);
}
int index = (int)dblIndex;
if (index == dblIndex) {
return setObjectIndex(sobj, index, value, cx);
} else {
String s = toString(dblIndex);
return setObjectProp(sobj, s, value, cx);
}
}
public static Object setObjectIndex(Scriptable obj, int index, Object value,
Context cx)
{
ScriptableObject.putProperty(obj, index, value);
return value;
}
public static boolean deleteObjectElem(Scriptable target, Object elem,
Context cx)
{
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
target.delete(index);
return !target.has(index, target);
} else {
target.delete(s);
return !target.has(s, target);
}
}
public static boolean hasObjectElem(Scriptable target, Object elem,
Context cx)
{
boolean result;
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
result = ScriptableObject.hasProperty(target, index);
} else {
result = ScriptableObject.hasProperty(target, s);
}
return result;
}
public static Object refGet(Ref ref, Context cx)
{
return ref.get(cx);
}
public static Object refSet(Ref ref, Object value, Context cx)
{
return ref.set(cx, value);
}
public static Object refDel(Ref ref, Context cx)
{
return wrapBoolean(ref.delete(cx));
}
static boolean isSpecialProperty(String s)
{
return s.equals("__proto__") || s.equals("__parent__");
}
public static Ref specialRef(Object obj, String specialProperty,
Context cx)
{
return SpecialRef.createSpecial(cx, obj, specialProperty);
}
/**
* The delete operator
*
* See ECMA 11.4.1
*
* In ECMA 0.19, the description of the delete operator (11.4.1)
* assumes that the [[Delete]] method returns a value. However,
* the definition of the [[Delete]] operator (8.6.2.5) does not
* define a return value. Here we assume that the [[Delete]]
* method doesn't return a value.
*/
public static Object delete(Object obj, Object id, Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
String idStr = (id == null) ? "null" : id.toString();
throw typeError2("msg.undef.prop.delete", toString(obj), idStr);
}
boolean result = deleteObjectElem(sobj, id, cx);
return wrapBoolean(result);
}
/**
* Looks up a name in the scope chain and returns its value.
*/
public static Object name(Context cx, Scriptable scope, String name)
{
Scriptable parent = scope.getParentScope();
if (parent == null) {
Object result = topScopeName(cx, scope, name);
if (result == Scriptable.NOT_FOUND) {
throw notFoundError(scope, name);
}
return result;
}
return nameOrFunction(cx, scope, parent, name, false);
}
private static Object nameOrFunction(Context cx, Scriptable scope,
Scriptable parentScope, String name,
boolean asFunctionCall)
{
Object result;
Scriptable thisObj = scope; // It is used only if asFunctionCall==true.
XMLObject firstXMLObject = null;
for (;;) {
if (scope instanceof NativeWith) {
Scriptable withObj = scope.getPrototype();
if (withObj instanceof XMLObject) {
XMLObject xmlObj = (XMLObject)withObj;
if (xmlObj.has(name, xmlObj)) {
// function this should be the target object of with
thisObj = xmlObj;
result = xmlObj.get(name, xmlObj);
break;
}
if (firstXMLObject == null) {
firstXMLObject = xmlObj;
}
} else {
result = ScriptableObject.getProperty(withObj, name);
if (result != Scriptable.NOT_FOUND) {
// function this should be the target object of with
thisObj = withObj;
break;
}
}
} else if (scope instanceof NativeCall) {
// NativeCall does not prototype chain and Scriptable.get
// can be called directly.
result = scope.get(name, scope);
if (result != Scriptable.NOT_FOUND) {
if (asFunctionCall) {
// ECMA 262 requires that this for nested funtions
// should be top scope
thisObj = ScriptableObject.
getTopLevelScope(parentScope);
}
break;
}
} else {
// Can happen if Rhino embedding decided that nested
// scopes are useful for what ever reasons.
result = ScriptableObject.getProperty(scope, name);
if (result != Scriptable.NOT_FOUND) {
thisObj = scope;
break;
}
}
scope = parentScope;
parentScope = parentScope.getParentScope();
if (parentScope == null) {
result = topScopeName(cx, scope, name);
if (result == Scriptable.NOT_FOUND) {
if (firstXMLObject == null || asFunctionCall) {
throw notFoundError(scope, name);
}
// The name was not found, but we did find an XML
// object in the scope chain and we are looking for name,
// not function. The result should be an empty XMLList
// in name context.
result = firstXMLObject.get(name, firstXMLObject);
}
// For top scope thisObj for functions is always scope itself.
thisObj = scope;
break;
}
}
if (asFunctionCall) {
if (!(result instanceof Callable)) {
throw notFunctionError(result, name);
}
storeScriptable(cx, thisObj);
}
return result;
}
private static Object topScopeName(Context cx, Scriptable scope,
String name)
{
if (cx.useDynamicScope) {
scope = checkDynamicScope(cx.topCallScope, scope);
}
return ScriptableObject.getProperty(scope, name);
}
/**
* Returns the object in the scope chain that has a given property.
*
* The order of evaluation of an assignment expression involves
* evaluating the lhs to a reference, evaluating the rhs, and then
* modifying the reference with the rhs value. This method is used
* to 'bind' the given name to an object containing that property
* so that the side effects of evaluating the rhs do not affect
* which property is modified.
* Typically used in conjunction with setName.
*
* See ECMA 10.1.4
*/
public static Scriptable bind(Context cx, Scriptable scope, String id)
{
Scriptable firstXMLObject = null;
Scriptable parent = scope.getParentScope();
childScopesChecks: if (parent != null) {
// Check for possibly nested "with" scopes first
while (scope instanceof NativeWith) {
Scriptable withObj = scope.getPrototype();
if (withObj instanceof XMLObject) {
XMLObject xmlObject = (XMLObject)withObj;
if (xmlObject.has(cx, id)) {
return xmlObject;
}
if (firstXMLObject == null) {
firstXMLObject = xmlObject;
}
} else {
if (ScriptableObject.hasProperty(withObj, id)) {
return withObj;
}
}
scope = parent;
parent = parent.getParentScope();
if (parent == null) {
break childScopesChecks;
}
}
for (;;) {
if (ScriptableObject.hasProperty(scope, id)) {
return scope;
}
scope = parent;
parent = parent.getParentScope();
if (parent == null) {
break childScopesChecks;
}
}
}
// scope here is top scope
if (cx.useDynamicScope) {
scope = checkDynamicScope(cx.topCallScope, scope);
}
if (ScriptableObject.hasProperty(scope, id)) {
return scope;
}
// Nothing was found, but since XML objects always bind
// return one if found
return firstXMLObject;
}
public static Object setName(Scriptable bound, Object value,
Context cx, Scriptable scope, String id)
{
if (bound != null) {
// TODO: we used to special-case XMLObject here, but putProperty
// seems to work for E4X and it's better to optimize the common case
ScriptableObject.putProperty(bound, id, value);
} else {
// "newname = 7;", where 'newname' has not yet
// been defined, creates a new property in the
// top scope unless strict mode is specified.
if (cx.hasFeature(Context.FEATURE_STRICT_MODE) ||
cx.hasFeature(Context.FEATURE_STRICT_VARS))
{
Context.reportWarning(
ScriptRuntime.getMessage1("msg.assn.create.strict", id));
}
// Find the top scope by walking up the scope chain.
bound = ScriptableObject.getTopLevelScope(scope);
if (cx.useDynamicScope) {
bound = checkDynamicScope(cx.topCallScope, bound);
}
bound.put(id, bound, value);
}
return value;
}
public static Object strictSetName(Scriptable bound, Object value,
Context cx, Scriptable scope, String id) {
if (bound != null) {
// TODO: The LeftHandSide also may not be a reference to a
// data property with the attribute value {[[Writable]]:false},
// to an accessor property with the attribute value
// {[[Put]]:undefined}, nor to a non-existent property of an
// object whose [[Extensible]] internal property has the value
// false. In these cases a TypeError exception is thrown (11.13.1).
// TODO: we used to special-case XMLObject here, but putProperty
// seems to work for E4X and we should optimize the common case
ScriptableObject.putProperty(bound, id, value);
return value;
} else {
// See ES5 8.7.2
String msg = "Assignment to undefined \"" + id + "\" in strict mode";
throw constructError("ReferenceError", msg);
}
}
public static Object setConst(Scriptable bound, Object value,
Context cx, String id)
{
if (bound instanceof XMLObject) {
bound.put(id, bound, value);
} else {
ScriptableObject.putConstProperty(bound, id, value);
}
return value;
}
/**
* This is the enumeration needed by the for..in statement.
*
* See ECMA 12.6.3.
*
* IdEnumeration maintains a ObjToIntMap to make sure a given
* id is enumerated only once across multiple objects in a
* prototype chain.
*
* XXX - ECMA delete doesn't hide properties in the prototype,
* but js/ref does. This means that the js/ref for..in can
* avoid maintaining a hash table and instead perform lookups
* to see if a given property has already been enumerated.
*
*/
private static class IdEnumeration implements Serializable
{
private static final long serialVersionUID = 1L;
Scriptable obj;
Object[] ids;
int index;
ObjToIntMap used;
Object currentId;
int enumType; /* one of ENUM_INIT_KEYS, ENUM_INIT_VALUES,
ENUM_INIT_ARRAY */
// if true, integer ids will be returned as numbers rather than strings
boolean enumNumbers;
Scriptable iterator;
}
public static Scriptable toIterator(Context cx, Scriptable scope,
Scriptable obj, boolean keyOnly)
{
if (ScriptableObject.hasProperty(obj,
NativeIterator.ITERATOR_PROPERTY_NAME))
{
Object v = ScriptableObject.getProperty(obj,
NativeIterator.ITERATOR_PROPERTY_NAME);
if (!(v instanceof Callable)) {
throw typeError0("msg.invalid.iterator");
}
Callable f = (Callable) v;
Object[] args = new Object[] { keyOnly ? Boolean.TRUE
: Boolean.FALSE };
v = f.call(cx, scope, obj, args);
if (!(v instanceof Scriptable)) {
throw typeError0("msg.iterator.primitive");
}
return (Scriptable) v;
}
return null;
}
// for backwards compatibility with generated class files
public static Object enumInit(Object value, Context cx, boolean enumValues)
{
return enumInit(value, cx, enumValues ? ENUMERATE_VALUES
: ENUMERATE_KEYS);
}
public static final int ENUMERATE_KEYS = 0;
public static final int ENUMERATE_VALUES = 1;
public static final int ENUMERATE_ARRAY = 2;
public static final int ENUMERATE_KEYS_NO_ITERATOR = 3;
public static final int ENUMERATE_VALUES_NO_ITERATOR = 4;
public static final int ENUMERATE_ARRAY_NO_ITERATOR = 5;
public static Object enumInit(Object value, Context cx, int enumType)
{
IdEnumeration x = new IdEnumeration();
x.obj = toObjectOrNull(cx, value);
if (x.obj == null) {
// null or undefined do not cause errors but rather lead to empty
// "for in" loop
return x;
}
x.enumType = enumType;
x.iterator = null;
if (enumType != ENUMERATE_KEYS_NO_ITERATOR &&
enumType != ENUMERATE_VALUES_NO_ITERATOR &&
enumType != ENUMERATE_ARRAY_NO_ITERATOR)
{
x.iterator = toIterator(cx, x.obj.getParentScope(), x.obj,
enumType == ScriptRuntime.ENUMERATE_KEYS);
}
if (x.iterator == null) {
// enumInit should read all initial ids before returning
// or "for (a.i in a)" would wrongly enumerate i in a as well
enumChangeObject(x);
}
return x;
}
public static void setEnumNumbers(Object enumObj, boolean enumNumbers) {
((IdEnumeration)enumObj).enumNumbers = enumNumbers;
}
public static Boolean enumNext(Object enumObj)
{
IdEnumeration x = (IdEnumeration)enumObj;
if (x.iterator != null) {
Object v = ScriptableObject.getProperty(x.iterator, "next");
if (!(v instanceof Callable))
return Boolean.FALSE;
Callable f = (Callable) v;
Context cx = Context.getContext();
try {
x.currentId = f.call(cx, x.iterator.getParentScope(),
x.iterator, emptyArgs);
return Boolean.TRUE;
} catch (JavaScriptException e) {
if (e.getValue() instanceof NativeIterator.StopIteration) {
return Boolean.FALSE;
}
throw e;
}
}
for (;;) {
if (x.obj == null) {
return Boolean.FALSE;
}
if (x.index == x.ids.length) {
x.obj = x.obj.getPrototype();
enumChangeObject(x);
continue;
}
Object id = x.ids[x.index++];
if (x.used != null && x.used.has(id)) {
continue;
}
if (id instanceof String) {
String strId = (String)id;
if (!x.obj.has(strId, x.obj))
continue; // must have been deleted
x.currentId = strId;
} else {
int intId = ((Number)id).intValue();
if (!x.obj.has(intId, x.obj))
continue; // must have been deleted
x.currentId = x.enumNumbers ? (Object) (Integer.valueOf(intId))
: String.valueOf(intId);
}
return Boolean.TRUE;
}
}
public static Object enumId(Object enumObj, Context cx)
{
IdEnumeration x = (IdEnumeration)enumObj;
if (x.iterator != null) {
return x.currentId;
}
switch (x.enumType) {
case ENUMERATE_KEYS:
case ENUMERATE_KEYS_NO_ITERATOR:
return x.currentId;
case ENUMERATE_VALUES:
case ENUMERATE_VALUES_NO_ITERATOR:
return enumValue(enumObj, cx);
case ENUMERATE_ARRAY:
case ENUMERATE_ARRAY_NO_ITERATOR:
Object[] elements = { x.currentId, enumValue(enumObj, cx) };
return cx.newArray(ScriptableObject.getTopLevelScope(x.obj), elements);
default:
throw Kit.codeBug();
}
}
public static Object enumValue(Object enumObj, Context cx) {
IdEnumeration x = (IdEnumeration)enumObj;
Object result;
String s = toStringIdOrIndex(cx, x.currentId);
if (s == null) {
int index = lastIndexResult(cx);
result = x.obj.get(index, x.obj);
} else {
result = x.obj.get(s, x.obj);
}
return result;
}
private static void enumChangeObject(IdEnumeration x)
{
Object[] ids = null;
while (x.obj != null) {
ids = x.obj.getIds();
if (ids.length != 0) {
break;
}
x.obj = x.obj.getPrototype();
}
if (x.obj != null && x.ids != null) {
Object[] previous = x.ids;
int L = previous.length;
if (x.used == null) {
x.used = new ObjToIntMap(L);
}
for (int i = 0; i != L; ++i) {
x.used.intern(previous[i]);
}
}
x.ids = ids;
x.index = 0;
}
/**
* Prepare for calling name(...): return function corresponding to
* name and make current top scope available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getNameFunctionAndThis(String name,
Context cx,
Scriptable scope)
{
Scriptable parent = scope.getParentScope();
if (parent == null) {
Object result = topScopeName(cx, scope, name);
if (!(result instanceof Callable)) {
if (result == Scriptable.NOT_FOUND) {
throw notFoundError(scope, name);
} else {
throw notFunctionError(result, name);
}
}
// Top scope is not NativeWith or NativeCall => thisObj == scope
Scriptable thisObj = scope;
storeScriptable(cx, thisObj);
return (Callable)result;
}
// name will call storeScriptable(cx, thisObj);
return (Callable)nameOrFunction(cx, scope, parent, name, true);
}
/**
* Prepare for calling obj[id](...): return function corresponding to
* obj[id] and make obj properly converted to Scriptable available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getElemFunctionAndThis(Object obj,
Object elem,
Context cx)
{
String str = toStringIdOrIndex(cx, elem);
if (str != null) {
return getPropFunctionAndThis(obj, str, cx);
}
int index = lastIndexResult(cx);
Scriptable thisObj = toObjectOrNull(cx, obj);
if (thisObj == null) {
throw undefCallError(obj, String.valueOf(index));
}
Object value;
if (thisObj instanceof XMLObject) {
Scriptable sobj = thisObj;
do {
XMLObject xmlObject = (XMLObject)sobj;
value = xmlObject.getFunctionProperty(cx, index);
if (value != Scriptable.NOT_FOUND) {
break;
}
sobj = xmlObject.getExtraMethodSource(cx);
if (sobj != null) {
thisObj = sobj;
if (!(sobj instanceof XMLObject)) {
value = ScriptableObject.getProperty(sobj, index);
}
}
} while (sobj instanceof XMLObject);
} else {
value = ScriptableObject.getProperty(thisObj, index);
}
if (!(value instanceof Callable)) {
throw notFunctionError(value, elem);
}
storeScriptable(cx, thisObj);
return (Callable)value;
}
/**
* Prepare for calling obj.property(...): return function corresponding to
* obj.property and make obj properly converted to Scriptable available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
* Warning: this doesn't allow to resolve primitive prototype properly when
* many top scopes are involved.
*/
public static Callable getPropFunctionAndThis(Object obj,
String property,
Context cx)
{
Scriptable thisObj = toObjectOrNull(cx, obj);
return getPropFunctionAndThisHelper(obj, property, cx, thisObj);
}
/**
* Prepare for calling obj.property(...): return function corresponding to
* obj.property and make obj properly converted to Scriptable available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getPropFunctionAndThis(Object obj,
String property,
Context cx, final Scriptable scope)
{
Scriptable thisObj = toObjectOrNull(cx, obj, scope);
return getPropFunctionAndThisHelper(obj, property, cx, thisObj);
}
private static Callable getPropFunctionAndThisHelper(Object obj,
String property, Context cx, Scriptable thisObj)
{
if (thisObj == null) {
throw undefCallError(obj, property);
}
Object value;
if (thisObj instanceof XMLObject) {
Scriptable sobj = thisObj;
do {
XMLObject xmlObject = (XMLObject)sobj;
value = xmlObject.getFunctionProperty(cx, property);
if (value != Scriptable.NOT_FOUND) {
break;
}
sobj = xmlObject.getExtraMethodSource(cx);
if (sobj != null) {
thisObj = sobj;
if (!(sobj instanceof XMLObject)) {
value = ScriptableObject.getProperty(sobj, property);
}
}
} while (sobj instanceof XMLObject);
} else {
value = ScriptableObject.getProperty(thisObj, property);
if (!(value instanceof Callable)) {
Object noSuchMethod = ScriptableObject.getProperty(thisObj, "__noSuchMethod__");
if (noSuchMethod instanceof Callable)
value = new NoSuchMethodShim((Callable)noSuchMethod, property);
}
}
if (!(value instanceof Callable)) {
throw notFunctionError(thisObj, value, property);
}
storeScriptable(cx, thisObj);
return (Callable)value;
}
/**
* Prepare for calling <expression>(...): return function corresponding to
* <expression> and make parent scope of the function available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getValueFunctionAndThis(Object value, Context cx)
{
if (!(value instanceof Callable)) {
throw notFunctionError(value);
}
Callable f = (Callable)value;
Scriptable thisObj = null;
if (f instanceof Scriptable) {
thisObj = ((Scriptable)f).getParentScope();
}
if (thisObj == null) {
if (cx.topCallScope == null) throw new IllegalStateException();
thisObj = cx.topCallScope;
}
if (thisObj.getParentScope() != null) {
if (thisObj instanceof NativeWith) {
// functions defined inside with should have with target
// as their thisObj
} else if (thisObj instanceof NativeCall) {
// nested functions should have top scope as their thisObj
thisObj = ScriptableObject.getTopLevelScope(thisObj);
}
}
storeScriptable(cx, thisObj);
return f;
}
/**
* Perform function call in reference context. Should always
* return value that can be passed to
* {@link #refGet(Ref, Context)} or {@link #refSet(Ref, Object, Context)}
* arbitrary number of times.
* The args array reference should not be stored in any object that is
* can be GC-reachable after this method returns. If this is necessary,
* store args.clone(), not args array itself.
*/
public static Ref callRef(Callable function, Scriptable thisObj,
Object[] args, Context cx)
{
if (function instanceof RefCallable) {
RefCallable rfunction = (RefCallable)function;
Ref ref = rfunction.refCall(cx, thisObj, args);
if (ref == null) {
throw new IllegalStateException(rfunction.getClass().getName()+".refCall() returned null");
}
return ref;
}
// No runtime support for now
String msg = getMessage1("msg.no.ref.from.function",
toString(function));
throw constructError("ReferenceError", msg);
}
/**
* Operator new.
*
* See ECMA 11.2.2
*/
public static Scriptable newObject(Object fun, Context cx,
Scriptable scope, Object[] args)
{
if (!(fun instanceof Function)) {
throw notFunctionError(fun);
}
Function function = (Function)fun;
return function.construct(cx, scope, args);
}
public static Object callSpecial(Context cx, Callable fun,
Scriptable thisObj,
Object[] args, Scriptable scope,
Scriptable callerThis, int callType,
String filename, int lineNumber)
{
if (callType == Node.SPECIALCALL_EVAL) {
if (thisObj.getParentScope() == null && NativeGlobal.isEvalFunction(fun)) {
return evalSpecial(cx, scope, callerThis, args,
filename, lineNumber);
}
} else if (callType == Node.SPECIALCALL_WITH) {
if (NativeWith.isWithFunction(fun)) {
throw Context.reportRuntimeError1("msg.only.from.new",
"With");
}
} else {
throw Kit.codeBug();
}
return fun.call(cx, scope, thisObj, args);
}
public static Object newSpecial(Context cx, Object fun,
Object[] args, Scriptable scope,
int callType)
{
if (callType == Node.SPECIALCALL_EVAL) {
if (NativeGlobal.isEvalFunction(fun)) {
throw typeError1("msg.not.ctor", "eval");
}
} else if (callType == Node.SPECIALCALL_WITH) {
if (NativeWith.isWithFunction(fun)) {
return NativeWith.newWithSpecial(cx, scope, args);
}
} else {
throw Kit.codeBug();
}
return newObject(fun, cx, scope, args);
}
/**
* Function.prototype.apply and Function.prototype.call
*
* See Ecma 15.3.4.[34]
*/
public static Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
int L = args.length;
Callable function = getCallable(thisObj);
Scriptable callThis = null;
if (L != 0) {
callThis = toObjectOrNull(cx, args[0]);
}
if (callThis == null) {
// This covers the case of args[0] == (null|undefined) as well.
callThis = getTopCallScope(cx);
}
Object[] callArgs;
if (isApply) {
// Follow Ecma 15.3.4.3
callArgs = L <= 1 ? ScriptRuntime.emptyArgs :
getApplyArguments(cx, args[1]);
} else {
// Follow Ecma 15.3.4.4
if (L <= 1) {
callArgs = ScriptRuntime.emptyArgs;
} else {
callArgs = new Object[L - 1];
System.arraycopy(args, 1, callArgs, 0, L - 1);
}
}
return function.call(cx, scope, callThis, callArgs);
}
static Object[] getApplyArguments(Context cx, Object arg1)
{
if (arg1 == null || arg1 == Undefined.instance) {
return ScriptRuntime.emptyArgs;
} else if (arg1 instanceof NativeArray || arg1 instanceof Arguments) {
return cx.getElements((Scriptable) arg1);
} else {
throw ScriptRuntime.typeError0("msg.arg.isnt.array");
}
}
static Callable getCallable(Scriptable thisObj)
{
Callable function;
if (thisObj instanceof Callable) {
function = (Callable)thisObj;
} else {
Object value = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
if (!(value instanceof Callable)) {
throw ScriptRuntime.notFunctionError(value, thisObj);
}
function = (Callable)value;
}
return function;
}
/**
* The eval function property of the global object.
*
* See ECMA 15.1.2.1
*/
public static Object evalSpecial(Context cx, Scriptable scope,
Object thisArg, Object[] args,
String filename, int lineNumber)
{
if (args.length < 1)
return Undefined.instance;
Object x = args[0];
if (!(x instanceof CharSequence)) {
if (cx.hasFeature(Context.FEATURE_STRICT_MODE) ||
cx.hasFeature(Context.FEATURE_STRICT_EVAL))
{
throw Context.reportRuntimeError0("msg.eval.nonstring.strict");
}
String message = ScriptRuntime.getMessage0("msg.eval.nonstring");
Context.reportWarning(message);
return x;
}
if (filename == null) {
int[] linep = new int[1];
filename = Context.getSourcePositionFromStack(linep);
if (filename != null) {
lineNumber = linep[0];
} else {
filename = "";
}
}
String sourceName = ScriptRuntime.
makeUrlForGeneratedScript(true, filename, lineNumber);
ErrorReporter reporter;
reporter = DefaultErrorReporter.forEval(cx.getErrorReporter());
Evaluator evaluator = Context.createInterpreter();
if (evaluator == null) {
throw new JavaScriptException("Interpreter not present",
filename, lineNumber);
}
// Compile with explicit interpreter instance to force interpreter
// mode.
Script script = cx.compileString(x.toString(), evaluator,
reporter, sourceName, 1, null);
evaluator.setEvalScriptFlag(script);
Callable c = (Callable)script;
return c.call(cx, scope, (Scriptable)thisArg, ScriptRuntime.emptyArgs);
}
/**
* The typeof operator
*/
public static String typeof(Object value)
{
if (value == null)
return "object";
if (value == Undefined.instance)
return "undefined";
if (value instanceof ScriptableObject)
return ((ScriptableObject) value).getTypeOf();
if (value instanceof Scriptable)
return (value instanceof Callable) ? "function" : "object";
if (value instanceof CharSequence)
return "string";
if (value instanceof Number)
return "number";
if (value instanceof Boolean)
return "boolean";
throw errorWithClassName("msg.invalid.type", value);
}
/**
* The typeof operator that correctly handles the undefined case
*/
public static String typeofName(Scriptable scope, String id)
{
Context cx = Context.getContext();
Scriptable val = bind(cx, scope, id);
if (val == null)
return "undefined";
return typeof(getObjectProp(val, id, cx));
}
// neg:
// implement the '-' operator inline in the caller
// as "-toNumber(val)"
// not:
// implement the '!' operator inline in the caller
// as "!toBoolean(val)"
// bitnot:
// implement the '~' operator inline in the caller
// as "~toInt32(val)"
public static Object add(Object val1, Object val2, Context cx)
{
if(val1 instanceof Number && val2 instanceof Number) {
return wrapNumber(((Number)val1).doubleValue() +
((Number)val2).doubleValue());
}
if (val1 instanceof XMLObject) {
Object test = ((XMLObject)val1).addValues(cx, true, val2);
if (test != Scriptable.NOT_FOUND) {
return test;
}
}
if (val2 instanceof XMLObject) {
Object test = ((XMLObject)val2).addValues(cx, false, val1);
if (test != Scriptable.NOT_FOUND) {
return test;
}
}
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(null);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(null);
if (!(val1 instanceof CharSequence) && !(val2 instanceof CharSequence))
if ((val1 instanceof Number) && (val2 instanceof Number))
return wrapNumber(((Number)val1).doubleValue() +
((Number)val2).doubleValue());
else
return wrapNumber(toNumber(val1) + toNumber(val2));
return new ConsString(toCharSequence(val1), toCharSequence(val2));
}
public static CharSequence add(CharSequence val1, Object val2) {
return new ConsString(val1, toCharSequence(val2));
}
public static CharSequence add(Object val1, CharSequence val2) {
return new ConsString(toCharSequence(val1), val2);
}
/**
* @deprecated The method is only present for compatibility.
*/
public static Object nameIncrDecr(Scriptable scopeChain, String id,
int incrDecrMask)
{
return nameIncrDecr(scopeChain, id, Context.getContext(), incrDecrMask);
}
public static Object nameIncrDecr(Scriptable scopeChain, String id,
Context cx, int incrDecrMask)
{
Scriptable target;
Object value;
search: {
do {
if (cx.useDynamicScope && scopeChain.getParentScope() == null) {
scopeChain = checkDynamicScope(cx.topCallScope, scopeChain);
}
target = scopeChain;
do {
if (target instanceof NativeWith &&
target.getPrototype() instanceof XMLObject) {
break;
}
value = target.get(id, scopeChain);
if (value != Scriptable.NOT_FOUND) {
break search;
}
target = target.getPrototype();
} while (target != null);
scopeChain = scopeChain.getParentScope();
} while (scopeChain != null);
throw notFoundError(scopeChain, id);
}
return doScriptableIncrDecr(target, id, scopeChain, value,
incrDecrMask);
}
public static Object propIncrDecr(Object obj, String id,
Context cx, int incrDecrMask)
{
Scriptable start = toObjectOrNull(cx, obj);
if (start == null) {
throw undefReadError(obj, id);
}
Scriptable target = start;
Object value;
search: {
do {
value = target.get(id, start);
if (value != Scriptable.NOT_FOUND) {
break search;
}
target = target.getPrototype();
} while (target != null);
start.put(id, start, NaNobj);
return NaNobj;
}
return doScriptableIncrDecr(target, id, start, value,
incrDecrMask);
}
private static Object doScriptableIncrDecr(Scriptable target,
String id,
Scriptable protoChainStart,
Object value,
int incrDecrMask)
{
boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
double number;
if (value instanceof Number) {
number = ((Number)value).doubleValue();
} else {
number = toNumber(value);
if (post) {
// convert result to number
value = wrapNumber(number);
}
}
if ((incrDecrMask & Node.DECR_FLAG) == 0) {
++number;
} else {
--number;
}
Number result = wrapNumber(number);
target.put(id, protoChainStart, result);
if (post) {
return value;
} else {
return result;
}
}
public static Object elemIncrDecr(Object obj, Object index,
Context cx, int incrDecrMask)
{
Object value = getObjectElem(obj, index, cx);
boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
double number;
if (value instanceof Number) {
number = ((Number)value).doubleValue();
} else {
number = toNumber(value);
if (post) {
// convert result to number
value = wrapNumber(number);
}
}
if ((incrDecrMask & Node.DECR_FLAG) == 0) {
++number;
} else {
--number;
}
Number result = wrapNumber(number);
setObjectElem(obj, index, result, cx);
if (post) {
return value;
} else {
return result;
}
}
public static Object refIncrDecr(Ref ref, Context cx, int incrDecrMask)
{
Object value = ref.get(cx);
boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
double number;
if (value instanceof Number) {
number = ((Number)value).doubleValue();
} else {
number = toNumber(value);
if (post) {
// convert result to number
value = wrapNumber(number);
}
}
if ((incrDecrMask & Node.DECR_FLAG) == 0) {
++number;
} else {
--number;
}
Number result = wrapNumber(number);
ref.set(cx, result);
if (post) {
return value;
} else {
return result;
}
}
public static Object toPrimitive(Object val) {
return toPrimitive(val, null);
}
public static Object toPrimitive(Object val, Class<?> typeHint)
{
if (!(val instanceof Scriptable)) {
return val;
}
Scriptable s = (Scriptable)val;
Object result = s.getDefaultValue(typeHint);
if (result instanceof Scriptable)
throw typeError0("msg.bad.default.value");
return result;
}
/**
* Equality
*
* See ECMA 11.9
*/
public static boolean eq(Object x, Object y)
{
if (x == y && !(x instanceof Number)) {
return true;
} else if (x == null || x == Undefined.instance) {
if (y == null || y == Undefined.instance) {
return true;
}
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
return false;
} else if (x instanceof Number) {
return eqNumber(((Number)x).doubleValue(), y);
} else if (x instanceof CharSequence) {
return eqString(x.toString(), y);
} else if (x instanceof Boolean) {
boolean b = ((Boolean)x).booleanValue();
if (y instanceof Boolean) {
return b == ((Boolean)y).booleanValue();
}
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
return eqNumber(b ? 1.0 : 0.0, y);
} else if (x instanceof Scriptable) {
if (y instanceof Scriptable) {
if (x == y) {
return true;
}
if (x instanceof ScriptableObject) {
Object test = ((ScriptableObject)x).equivalentValues(y);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
if (x instanceof Wrapper && y instanceof Wrapper) {
// See bug 413838. Effectively an extension to ECMA for
// the LiveConnect case.
Object unwrappedX = ((Wrapper)x).unwrap();
Object unwrappedY = ((Wrapper)y).unwrap();
return unwrappedX == unwrappedY ||
(isPrimitive(unwrappedX) &&
isPrimitive(unwrappedY) &&
eq(unwrappedX, unwrappedY));
}
return false;
} else if (y instanceof Boolean) {
if (x instanceof ScriptableObject) {
Object test = ((ScriptableObject)x).equivalentValues(y);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
double d = ((Boolean)y).booleanValue() ? 1.0 : 0.0;
return eqNumber(d, x);
} else if (y instanceof Number) {
return eqNumber(((Number)y).doubleValue(), x);
} else if (y instanceof String) {
return eqString((String)y, x);
}
// covers the case when y == Undefined.instance as well
return false;
} else {
warnAboutNonJSObject(x);
return x == y;
}
}
public static boolean isPrimitive(Object obj) {
return obj == null || obj == Undefined.instance ||
(obj instanceof Number) || (obj instanceof String) ||
(obj instanceof Boolean);
}
static boolean eqNumber(double x, Object y)
{
for (;;) {
if (y == null || y == Undefined.instance) {
return false;
} else if (y instanceof Number) {
return x == ((Number)y).doubleValue();
} else if (y instanceof CharSequence) {
return x == toNumber(y);
} else if (y instanceof Boolean) {
return x == (((Boolean)y).booleanValue() ? 1.0 : +0.0);
} else if (y instanceof Scriptable) {
if (y instanceof ScriptableObject) {
Object xval = wrapNumber(x);
Object test = ((ScriptableObject)y).equivalentValues(xval);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
y = toPrimitive(y);
} else {
warnAboutNonJSObject(y);
return false;
}
}
}
private static boolean eqString(String x, Object y)
{
for (;;) {
if (y == null || y == Undefined.instance) {
return false;
} else if (y instanceof CharSequence) {
return x.equals(y.toString());
} else if (y instanceof Number) {
return toNumber(x) == ((Number)y).doubleValue();
} else if (y instanceof Boolean) {
return toNumber(x) == (((Boolean)y).booleanValue() ? 1.0 : 0.0);
} else if (y instanceof Scriptable) {
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
y = toPrimitive(y);
continue;
} else {
warnAboutNonJSObject(y);
return false;
}
}
}
public static boolean shallowEq(Object x, Object y)
{
if (x == y) {
if (!(x instanceof Number)) {
return true;
}
// NaN check
double d = ((Number)x).doubleValue();
return d == d;
}
if (x == null || x == Undefined.instance) {
return false;
} else if (x instanceof Number) {
if (y instanceof Number) {
return ((Number)x).doubleValue() == ((Number)y).doubleValue();
}
} else if (x instanceof CharSequence) {
if (y instanceof CharSequence) {
return x.toString().equals(y.toString());
}
} else if (x instanceof Boolean) {
if (y instanceof Boolean) {
return x.equals(y);
}
} else if (x instanceof Scriptable) {
if (x instanceof Wrapper && y instanceof Wrapper) {
return ((Wrapper)x).unwrap() == ((Wrapper)y).unwrap();
}
} else {
warnAboutNonJSObject(x);
return x == y;
}
return false;
}
/**
* The instanceof operator.
*
* @return a instanceof b
*/
public static boolean instanceOf(Object a, Object b, Context cx)
{
// Check RHS is an object
if (! (b instanceof Scriptable)) {
throw typeError0("msg.instanceof.not.object");
}
// for primitive values on LHS, return false
if (! (a instanceof Scriptable))
return false;
return ((Scriptable)b).hasInstance((Scriptable)a);
}
/**
* Delegates to
*
* @return true iff rhs appears in lhs' proto chain
*/
public static boolean jsDelegatesTo(Scriptable lhs, Scriptable rhs) {
Scriptable proto = lhs.getPrototype();
while (proto != null) {
if (proto.equals(rhs)) return true;
proto = proto.getPrototype();
}
return false;
}
/**
* The in operator.
*
* This is a new JS 1.3 language feature. The in operator mirrors
* the operation of the for .. in construct, and tests whether the
* rhs has the property given by the lhs. It is different from the
* for .. in construct in that:
* <BR> - it doesn't perform ToObject on the right hand side
* <BR> - it returns true for DontEnum properties.
* @param a the left hand operand
* @param b the right hand operand
*
* @return true if property name or element number a is a property of b
*/
public static boolean in(Object a, Object b, Context cx)
{
if (!(b instanceof Scriptable)) {
throw typeError0("msg.instanceof.not.object");
}
return hasObjectElem((Scriptable)b, a, cx);
}
public static boolean cmp_LT(Object val1, Object val2)
{
double d1, d2;
if (val1 instanceof Number && val2 instanceof Number) {
d1 = ((Number)val1).doubleValue();
d2 = ((Number)val2).doubleValue();
} else {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (val1 instanceof CharSequence && val2 instanceof CharSequence) {
return val1.toString().compareTo(val2.toString()) < 0;
}
d1 = toNumber(val1);
d2 = toNumber(val2);
}
return d1 < d2;
}
public static boolean cmp_LE(Object val1, Object val2)
{
double d1, d2;
if (val1 instanceof Number && val2 instanceof Number) {
d1 = ((Number)val1).doubleValue();
d2 = ((Number)val2).doubleValue();
} else {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (val1 instanceof CharSequence && val2 instanceof CharSequence) {
return val1.toString().compareTo(val2.toString()) <= 0;
}
d1 = toNumber(val1);
d2 = toNumber(val2);
}
return d1 <= d2;
}
// ------------------
// Statements
// ------------------
public static ScriptableObject getGlobal(Context cx) {
final String GLOBAL_CLASS = "org.mozilla.javascript.tools.shell.Global";
Class<?> globalClass = Kit.classOrNull(GLOBAL_CLASS);
if (globalClass != null) {
try {
Class<?>[] parm = { ScriptRuntime.ContextClass };
Constructor<?> globalClassCtor = globalClass.getConstructor(parm);
Object[] arg = { cx };
return (ScriptableObject) globalClassCtor.newInstance(arg);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
// fall through...
}
}
return new ImporterTopLevel(cx);
}
public static boolean hasTopCall(Context cx)
{
return (cx.topCallScope != null);
}
public static Scriptable getTopCallScope(Context cx)
{
Scriptable scope = cx.topCallScope;
if (scope == null) {
throw new IllegalStateException();
}
return scope;
}
public static Object doTopCall(Callable callable,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (scope == null)
throw new IllegalArgumentException();
if (cx.topCallScope != null) throw new IllegalStateException();
Object result;
cx.topCallScope = ScriptableObject.getTopLevelScope(scope);
cx.useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE);
ContextFactory f = cx.getFactory();
try {
result = f.doTopCall(callable, cx, scope, thisObj, args);
} finally {
cx.topCallScope = null;
// Cleanup cached references
cx.cachedXMLLib = null;
if (cx.currentActivationCall != null) {
// Function should always call exitActivationFunction
// if it creates activation record
throw new IllegalStateException();
}
}
return result;
}
/**
* Return <tt>possibleDynamicScope</tt> if <tt>staticTopScope</tt>
* is present on its prototype chain and return <tt>staticTopScope</tt>
* otherwise.
* Should only be called when <tt>staticTopScope</tt> is top scope.
*/
static Scriptable checkDynamicScope(Scriptable possibleDynamicScope,
Scriptable staticTopScope)
{
// Return cx.topCallScope if scope
if (possibleDynamicScope == staticTopScope) {
return possibleDynamicScope;
}
Scriptable proto = possibleDynamicScope;
for (;;) {
proto = proto.getPrototype();
if (proto == staticTopScope) {
return possibleDynamicScope;
}
if (proto == null) {
return staticTopScope;
}
}
}
public static void addInstructionCount(Context cx, int instructionsToAdd)
{
cx.instructionCount += instructionsToAdd;
if (cx.instructionCount > cx.instructionThreshold)
{
cx.observeInstructionCount(cx.instructionCount);
cx.instructionCount = 0;
}
}
public static void initScript(NativeFunction funObj, Scriptable thisObj,
Context cx, Scriptable scope,
boolean evalScript)
{
if (cx.topCallScope == null)
throw new IllegalStateException();
int varCount = funObj.getParamAndVarCount();
if (varCount != 0) {
Scriptable varScope = scope;
// Never define any variables from var statements inside with
// object. See bug 38590.
while (varScope instanceof NativeWith) {
varScope = varScope.getParentScope();
}
for (int i = varCount; i-- != 0;) {
String name = funObj.getParamOrVarName(i);
boolean isConst = funObj.getParamOrVarConst(i);
// Don't overwrite existing def if already defined in object
// or prototypes of object.
if (!ScriptableObject.hasProperty(scope, name)) {
if (!evalScript) {
// Global var definitions are supposed to be DONTDELETE
if (isConst)
ScriptableObject.defineConstProperty(varScope, name);
else
ScriptableObject.defineProperty(
varScope, name, Undefined.instance,
ScriptableObject.PERMANENT);
} else {
varScope.put(name, varScope, Undefined.instance);
}
} else {
ScriptableObject.redefineProperty(scope, name, isConst);
}
}
}
}
public static Scriptable createFunctionActivation(NativeFunction funObj,
Scriptable scope,
Object[] args)
{
return new NativeCall(funObj, scope, args);
}
public static void enterActivationFunction(Context cx,
Scriptable scope)
{
if (cx.topCallScope == null)
throw new IllegalStateException();
NativeCall call = (NativeCall)scope;
call.parentActivationCall = cx.currentActivationCall;
cx.currentActivationCall = call;
}
public static void exitActivationFunction(Context cx)
{
NativeCall call = cx.currentActivationCall;
cx.currentActivationCall = call.parentActivationCall;
call.parentActivationCall = null;
}
static NativeCall findFunctionActivation(Context cx, Function f)
{
NativeCall call = cx.currentActivationCall;
while (call != null) {
if (call.function == f)
return call;
call = call.parentActivationCall;
}
return null;
}
public static Scriptable newCatchScope(Throwable t,
Scriptable lastCatchScope,
String exceptionName,
Context cx, Scriptable scope)
{
Object obj;
boolean cacheObj;
getObj:
if (t instanceof JavaScriptException) {
cacheObj = false;
obj = ((JavaScriptException)t).getValue();
} else {
cacheObj = true;
// Create wrapper object unless it was associated with
// the previous scope object
if (lastCatchScope != null) {
NativeObject last = (NativeObject)lastCatchScope;
obj = last.getAssociatedValue(t);
if (obj == null) Kit.codeBug();
break getObj;
}
RhinoException re;
String errorName;
String errorMsg;
Throwable javaException = null;
if (t instanceof EcmaError) {
EcmaError ee = (EcmaError)t;
re = ee;
errorName = ee.getName();
errorMsg = ee.getErrorMessage();
} else if (t instanceof WrappedException) {
WrappedException we = (WrappedException)t;
re = we;
javaException = we.getWrappedException();
errorName = "JavaException";
errorMsg = javaException.getClass().getName()
+": "+javaException.getMessage();
} else if (t instanceof EvaluatorException) {
// Pure evaluator exception, nor WrappedException instance
EvaluatorException ee = (EvaluatorException)t;
re = ee;
errorName = "InternalError";
errorMsg = ee.getMessage();
} else if (cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) {
// With FEATURE_ENHANCED_JAVA_ACCESS, scripts can catch
// all exception types
re = new WrappedException(t);
errorName = "JavaException";
errorMsg = t.toString();
} else {
// Script can catch only instances of JavaScriptException,
// EcmaError and EvaluatorException
throw Kit.codeBug();
}
String sourceUri = re.sourceName();
if (sourceUri == null) {
sourceUri = "";
}
int line = re.lineNumber();
Object args[];
if (line > 0) {
args = new Object[] { errorMsg, sourceUri, Integer.valueOf(line) };
} else {
args = new Object[] { errorMsg, sourceUri };
}
Scriptable errorObject = cx.newObject(scope, errorName, args);
ScriptableObject.putProperty(errorObject, "name", errorName);
// set exception in Error objects to enable non-ECMA "stack" property
if (errorObject instanceof NativeError) {
((NativeError) errorObject).setStackProvider(re);
}
if (javaException != null && isVisible(cx, javaException)) {
Object wrap = cx.getWrapFactory().wrap(cx, scope, javaException,
null);
ScriptableObject.defineProperty(
errorObject, "javaException", wrap,
ScriptableObject.PERMANENT | ScriptableObject.READONLY);
}
if (isVisible(cx, re)) {
Object wrap = cx.getWrapFactory().wrap(cx, scope, re, null);
ScriptableObject.defineProperty(
errorObject, "rhinoException", wrap,
ScriptableObject.PERMANENT | ScriptableObject.READONLY);
}
obj = errorObject;
}
NativeObject catchScopeObject = new NativeObject();
// See ECMA 12.4
catchScopeObject.defineProperty(
exceptionName, obj, ScriptableObject.PERMANENT);
if (isVisible(cx, t)) {
// Add special Rhino object __exception__ defined in the catch
// scope that can be used to retrieve the Java exception associated
// with the JavaScript exception (to get stack trace info, etc.)
catchScopeObject.defineProperty(
"__exception__", Context.javaToJS(t, scope),
ScriptableObject.PERMANENT|ScriptableObject.DONTENUM);
}
if (cacheObj) {
catchScopeObject.associateValue(t, obj);
}
return catchScopeObject;
}
private static boolean isVisible(Context cx, Object obj) {
ClassShutter shutter = cx.getClassShutter();
return shutter == null ||
shutter.visibleToScripts(obj.getClass().getName());
}
public static Scriptable enterWith(Object obj, Context cx,
Scriptable scope)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw typeError1("msg.undef.with", toString(obj));
}
if (sobj instanceof XMLObject) {
XMLObject xmlObject = (XMLObject)sobj;
return xmlObject.enterWith(scope);
}
return new NativeWith(scope, sobj);
}
public static Scriptable leaveWith(Scriptable scope)
{
NativeWith nw = (NativeWith)scope;
return nw.getParentScope();
}
public static Scriptable enterDotQuery(Object value, Scriptable scope)
{
if (!(value instanceof XMLObject)) {
throw notXmlError(value);
}
XMLObject object = (XMLObject)value;
return object.enterDotQuery(scope);
}
public static Object updateDotQuery(boolean value, Scriptable scope)
{
// Return null to continue looping
NativeWith nw = (NativeWith)scope;
return nw.updateDotQuery(value);
}
public static Scriptable leaveDotQuery(Scriptable scope)
{
NativeWith nw = (NativeWith)scope;
return nw.getParentScope();
}
public static void setFunctionProtoAndParent(BaseFunction fn,
Scriptable scope)
{
fn.setParentScope(scope);
fn.setPrototype(ScriptableObject.getFunctionPrototype(scope));
}
public static void setObjectProtoAndParent(ScriptableObject object,
Scriptable scope)
{
// Compared with function it always sets the scope to top scope
scope = ScriptableObject.getTopLevelScope(scope);
object.setParentScope(scope);
Scriptable proto
= ScriptableObject.getClassPrototype(scope, object.getClassName());
object.setPrototype(proto);
}
public static void setBuiltinProtoAndParent(ScriptableObject object,
Scriptable scope,
TopLevel.Builtins type)
{
scope = ScriptableObject.getTopLevelScope(scope);
object.setParentScope(scope);
object.setPrototype(TopLevel.getBuiltinPrototype(scope, type));
}
public static void initFunction(Context cx, Scriptable scope,
NativeFunction function, int type,
boolean fromEvalCode)
{
if (type == FunctionNode.FUNCTION_STATEMENT) {
String name = function.getFunctionName();
if (name != null && name.length() != 0) {
if (!fromEvalCode) {
// ECMA specifies that functions defined in global and
// function scope outside eval should have DONTDELETE set.
ScriptableObject.defineProperty
(scope, name, function, ScriptableObject.PERMANENT);
} else {
scope.put(name, scope, function);
}
}
} else if (type == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) {
String name = function.getFunctionName();
if (name != null && name.length() != 0) {
// Always put function expression statements into initial
// activation object ignoring the with statement to follow
// SpiderMonkey
while (scope instanceof NativeWith) {
scope = scope.getParentScope();
}
scope.put(name, scope, function);
}
} else {
throw Kit.codeBug();
}
}
public static Scriptable newArrayLiteral(Object[] objects,
int[] skipIndices,
Context cx, Scriptable scope)
{
final int SKIP_DENSITY = 2;
int count = objects.length;
int skipCount = 0;
if (skipIndices != null) {
skipCount = skipIndices.length;
}
int length = count + skipCount;
if (length > 1 && skipCount * SKIP_DENSITY < length) {
// If not too sparse, create whole array for constructor
Object[] sparse;
if (skipCount == 0) {
sparse = objects;
} else {
sparse = new Object[length];
int skip = 0;
for (int i = 0, j = 0; i != length; ++i) {
if (skip != skipCount && skipIndices[skip] == i) {
sparse[i] = Scriptable.NOT_FOUND;
++skip;
continue;
}
sparse[i] = objects[j];
++j;
}
}
return cx.newArray(scope, sparse);
}
Scriptable array = cx.newArray(scope, length);
int skip = 0;
for (int i = 0, j = 0; i != length; ++i) {
if (skip != skipCount && skipIndices[skip] == i) {
++skip;
continue;
}
ScriptableObject.putProperty(array, i, objects[j]);
++j;
}
return array;
}
/**
* This method is here for backward compat with existing compiled code. It
* is called when an object literal is compiled. The next instance will be
* the version called from new code.
* @deprecated This method only present for compatibility.
*/
public static Scriptable newObjectLiteral(Object[] propertyIds,
Object[] propertyValues,
Context cx, Scriptable scope)
{
// This will initialize to all zeros, exactly what we need for old-style
// getterSetters values (no getters or setters in the list)
int [] getterSetters = new int[propertyIds.length];
return newObjectLiteral(propertyIds, propertyValues, getterSetters,
cx, scope);
}
public static Scriptable newObjectLiteral(Object[] propertyIds,
Object[] propertyValues,
int [] getterSetters,
Context cx, Scriptable scope)
{
Scriptable object = cx.newObject(scope);
for (int i = 0, end = propertyIds.length; i != end; ++i) {
Object id = propertyIds[i];
int getterSetter = getterSetters[i];
Object value = propertyValues[i];
if (id instanceof String) {
if (getterSetter == 0) {
if (isSpecialProperty((String)id)) {
specialRef(object, (String)id, cx).set(cx, value);
} else {
ScriptableObject.putProperty(object, (String)id, value);
}
} else {
Callable fun;
String definer;
if (getterSetter < 0) // < 0 means get foo() ...
definer = "__defineGetter__";
else
definer = "__defineSetter__";
fun = getPropFunctionAndThis(object, definer, cx);
// Must consume the last scriptable object in cx
lastStoredScriptable(cx);
Object[] outArgs = new Object[2];
outArgs[0] = id;
outArgs[1] = value;
fun.call(cx, scope, object, outArgs);
}
} else {
int index = ((Integer)id).intValue();
ScriptableObject.putProperty(object, index, value);
}
}
return object;
}
public static boolean isArrayObject(Object obj)
{
return obj instanceof NativeArray || obj instanceof Arguments;
}
public static Object[] getArrayElements(Scriptable object)
{
Context cx = Context.getContext();
long longLen = NativeArray.getLengthProperty(cx, object);
if (longLen > Integer.MAX_VALUE) {
// arrays beyond MAX_INT is not in Java in any case
throw new IllegalArgumentException();
}
int len = (int) longLen;
if (len == 0) {
return ScriptRuntime.emptyArgs;
} else {
Object[] result = new Object[len];
for (int i=0; i < len; i++) {
Object elem = ScriptableObject.getProperty(object, i);
result[i] = (elem == Scriptable.NOT_FOUND) ? Undefined.instance
: elem;
}
return result;
}
}
static void checkDeprecated(Context cx, String name) {
int version = cx.getLanguageVersion();
if (version >= Context.VERSION_1_4 || version == Context.VERSION_DEFAULT) {
String msg = getMessage1("msg.deprec.ctor", name);
if (version == Context.VERSION_DEFAULT)
Context.reportWarning(msg);
else
throw Context.reportRuntimeError(msg);
}
}
public static String getMessage0(String messageId)
{
return getMessage(messageId, null);
}
public static String getMessage1(String messageId, Object arg1)
{
Object[] arguments = {arg1};
return getMessage(messageId, arguments);
}
public static String getMessage2(
String messageId, Object arg1, Object arg2)
{
Object[] arguments = {arg1, arg2};
return getMessage(messageId, arguments);
}
public static String getMessage3(
String messageId, Object arg1, Object arg2, Object arg3)
{
Object[] arguments = {arg1, arg2, arg3};
return getMessage(messageId, arguments);
}
public static String getMessage4(
String messageId, Object arg1, Object arg2, Object arg3, Object arg4)
{
Object[] arguments = {arg1, arg2, arg3, arg4};
return getMessage(messageId, arguments);
}
/**
* This is an interface defining a message provider. Create your
* own implementation to override the default error message provider.
*
* @author Mike Harm
*/
public interface MessageProvider {
/**
* Returns a textual message identified by the given messageId,
* parameterized by the given arguments.
*
* @param messageId the identifier of the message
* @param arguments the arguments to fill into the message
*/
String getMessage(String messageId, Object[] arguments);
}
public static MessageProvider messageProvider = new DefaultMessageProvider();
public static String getMessage(String messageId, Object[] arguments)
{
return messageProvider.getMessage(messageId, arguments);
}
/* OPT there's a noticable delay for the first error! Maybe it'd
* make sense to use a ListResourceBundle instead of a properties
* file to avoid (synchronized) text parsing.
*/
private static class DefaultMessageProvider implements MessageProvider {
public String getMessage(String messageId, Object[] arguments) {
final String defaultResource
= "org.mozilla.javascript.resources.Messages";
Context cx = Context.getCurrentContext();
Locale locale = cx != null ? cx.getLocale() : Locale.getDefault();
// ResourceBundle does caching.
ResourceBundle rb = ResourceBundle.getBundle(defaultResource, locale);
String formatString;
try {
formatString = rb.getString(messageId);
} catch (java.util.MissingResourceException mre) {
throw new RuntimeException
("no message resource found for message property "+ messageId);
}
/*
* It's OK to format the string, even if 'arguments' is null;
* we need to format it anyway, to make double ''s collapse to
* single 's.
*/
MessageFormat formatter = new MessageFormat(formatString);
return formatter.format(arguments);
}
}
public static EcmaError constructError(String error, String message)
{
int[] linep = new int[1];
String filename = Context.getSourcePositionFromStack(linep);
return constructError(error, message, filename, linep[0], null, 0);
}
public static EcmaError constructError(String error,
String message,
int lineNumberDelta)
{
int[] linep = new int[1];
String filename = Context.getSourcePositionFromStack(linep);
if (linep[0] != 0) {
linep[0] += lineNumberDelta;
}
return constructError(error, message, filename, linep[0], null, 0);
}
public static EcmaError constructError(String error,
String message,
String sourceName,
int lineNumber,
String lineSource,
int columnNumber)
{
return new EcmaError(error, message, sourceName,
lineNumber, lineSource, columnNumber);
}
public static EcmaError typeError(String message)
{
return constructError("TypeError", message);
}
public static EcmaError typeError0(String messageId)
{
String msg = getMessage0(messageId);
return typeError(msg);
}
public static EcmaError typeError1(String messageId, String arg1)
{
String msg = getMessage1(messageId, arg1);
return typeError(msg);
}
public static EcmaError typeError2(String messageId, String arg1,
String arg2)
{
String msg = getMessage2(messageId, arg1, arg2);
return typeError(msg);
}
public static EcmaError typeError3(String messageId, String arg1,
String arg2, String arg3)
{
String msg = getMessage3(messageId, arg1, arg2, arg3);
return typeError(msg);
}
public static RuntimeException undefReadError(Object object, Object id)
{
String idStr = (id == null) ? "null" : id.toString();
return typeError2("msg.undef.prop.read", toString(object), idStr);
}
public static RuntimeException undefCallError(Object object, Object id)
{
String idStr = (id == null) ? "null" : id.toString();
return typeError2("msg.undef.method.call", toString(object), idStr);
}
public static RuntimeException undefWriteError(Object object,
Object id,
Object value)
{
String idStr = (id == null) ? "null" : id.toString();
String valueStr = (value instanceof Scriptable)
? value.toString() : toString(value);
return typeError3("msg.undef.prop.write", toString(object), idStr,
valueStr);
}
public static RuntimeException notFoundError(Scriptable object,
String property)
{
// XXX: use object to improve the error message
String msg = getMessage1("msg.is.not.defined", property);
throw constructError("ReferenceError", msg);
}
public static RuntimeException notFunctionError(Object value)
{
return notFunctionError(value, value);
}
public static RuntimeException notFunctionError(Object value,
Object messageHelper)
{
// Use value for better error reporting
String msg = (messageHelper == null)
? "null" : messageHelper.toString();
if (value == Scriptable.NOT_FOUND) {
return typeError1("msg.function.not.found", msg);
}
return typeError2("msg.isnt.function", msg, typeof(value));
}
public static RuntimeException notFunctionError(Object obj, Object value,
String propertyName)
{
// Use obj and value for better error reporting
String objString = toString(obj);
if (obj instanceof NativeFunction) {
// Omit function body in string representations of functions
int curly = objString.indexOf('{');
if (curly > -1) {
objString = objString.substring(0, curly + 1) + "...}";
}
}
if (value == Scriptable.NOT_FOUND) {
return typeError2("msg.function.not.found.in", propertyName,
objString);
}
return typeError3("msg.isnt.function.in", propertyName, objString,
typeof(value));
}
private static RuntimeException notXmlError(Object value)
{
throw typeError1("msg.isnt.xml.object", toString(value));
}
private static void warnAboutNonJSObject(Object nonJSObject)
{
String message =
"RHINO USAGE WARNING: Missed Context.javaToJS() conversion:\n"
+"Rhino runtime detected object "+nonJSObject+" of class "+nonJSObject.getClass().getName()+" where it expected String, Number, Boolean or Scriptable instance. Please check your code for missing Context.javaToJS() call.";
Context.reportWarning(message);
// Just to be sure that it would be noticed
System.err.println(message);
}
public static RegExpProxy getRegExpProxy(Context cx)
{
return cx.getRegExpProxy();
}
public static void setRegExpProxy(Context cx, RegExpProxy proxy)
{
if (proxy == null) throw new IllegalArgumentException();
cx.regExpProxy = proxy;
}
public static RegExpProxy checkRegExpProxy(Context cx)
{
RegExpProxy result = getRegExpProxy(cx);
if (result == null) {
throw Context.reportRuntimeError0("msg.no.regexp");
}
return result;
}
private static XMLLib currentXMLLib(Context cx)
{
// Scripts should be running to access this
if (cx.topCallScope == null)
throw new IllegalStateException();
XMLLib xmlLib = cx.cachedXMLLib;
if (xmlLib == null) {
xmlLib = XMLLib.extractFromScope(cx.topCallScope);
if (xmlLib == null)
throw new IllegalStateException();
cx.cachedXMLLib = xmlLib;
}
return xmlLib;
}
/**
* Escapes the reserved characters in a value of an attribute
*
* @param value Unescaped text
* @return The escaped text
*/
public static String escapeAttributeValue(Object value, Context cx)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.escapeAttributeValue(value);
}
/**
* Escapes the reserved characters in a value of a text node
*
* @param value Unescaped text
* @return The escaped text
*/
public static String escapeTextValue(Object value, Context cx)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.escapeTextValue(value);
}
public static Ref memberRef(Object obj, Object elem,
Context cx, int memberTypeFlags)
{
if (!(obj instanceof XMLObject)) {
throw notXmlError(obj);
}
XMLObject xmlObject = (XMLObject)obj;
return xmlObject.memberRef(cx, elem, memberTypeFlags);
}
public static Ref memberRef(Object obj, Object namespace, Object elem,
Context cx, int memberTypeFlags)
{
if (!(obj instanceof XMLObject)) {
throw notXmlError(obj);
}
XMLObject xmlObject = (XMLObject)obj;
return xmlObject.memberRef(cx, namespace, elem, memberTypeFlags);
}
public static Ref nameRef(Object name, Context cx,
Scriptable scope, int memberTypeFlags)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.nameRef(cx, name, scope, memberTypeFlags);
}
public static Ref nameRef(Object namespace, Object name, Context cx,
Scriptable scope, int memberTypeFlags)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.nameRef(cx, namespace, name, scope, memberTypeFlags);
}
private static void storeIndexResult(Context cx, int index)
{
cx.scratchIndex = index;
}
static int lastIndexResult(Context cx)
{
return cx.scratchIndex;
}
public static void storeUint32Result(Context cx, long value)
{
if ((value >>> 32) != 0)
throw new IllegalArgumentException();
cx.scratchUint32 = value;
}
public static long lastUint32Result(Context cx)
{
long value = cx.scratchUint32;
if ((value >>> 32) != 0)
throw new IllegalStateException();
return value;
}
private static void storeScriptable(Context cx, Scriptable value)
{
// The previously stored scratchScriptable should be consumed
if (cx.scratchScriptable != null)
throw new IllegalStateException();
cx.scratchScriptable = value;
}
public static Scriptable lastStoredScriptable(Context cx)
{
Scriptable result = cx.scratchScriptable;
cx.scratchScriptable = null;
return result;
}
static String makeUrlForGeneratedScript
(boolean isEval, String masterScriptUrl, int masterScriptLine)
{
if (isEval) {
return masterScriptUrl+'#'+masterScriptLine+"(eval)";
} else {
return masterScriptUrl+'#'+masterScriptLine+"(Function)";
}
}
static boolean isGeneratedScript(String sourceUrl) {
// ALERT: this may clash with a valid URL containing (eval) or
// (Function)
return sourceUrl.indexOf("(eval)") >= 0
|| sourceUrl.indexOf("(Function)") >= 0;
}
private static RuntimeException errorWithClassName(String msg, Object val)
{
return Context.reportRuntimeError1(msg, val.getClass().getName());
}
/**
* Equivalent to executing "new Error(message)" from JavaScript.
* @param cx the current context
* @param scope the current scope
* @param message the message
* @return a JavaScriptException you should throw
*/
public static JavaScriptException throwError(Context cx, Scriptable scope,
String message) {
int[] linep = { 0 };
String filename = Context.getSourcePositionFromStack(linep);
final Scriptable error = newBuiltinObject(cx, scope,
TopLevel.Builtins.Error, new Object[] { message, filename, Integer.valueOf(linep[0]) });
return new JavaScriptException(error, filename, linep[0]);
}
public static final Object[] emptyArgs = new Object[0];
public static final String[] emptyStrings = new String[0];
}
| src/org/mozilla/javascript/ScriptRuntime.java | /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Patrick Beard
* Norris Boyd
* Igor Bukanov
* Mike Harm
* Ethan Hugg
* Bob Jervis
* Roger Lawrence
* Terry Lucas
* Frank Mitchell
* Milen Nankov
* Hannes Wallnoefer
* Andrew Wason
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript;
import java.io.Serializable;
import java.lang.reflect.*;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
import org.mozilla.javascript.ast.FunctionNode;
import org.mozilla.javascript.xml.XMLObject;
import org.mozilla.javascript.xml.XMLLib;
/**
* This is the class that implements the runtime.
*
* @author Norris Boyd
*/
public class ScriptRuntime {
/**
* No instances should be created.
*/
protected ScriptRuntime() {
}
/**
* Returns representation of the [[ThrowTypeError]] object.
* See ECMA 5 spec, 13.2.3
*/
public static BaseFunction typeErrorThrower() {
if (THROW_TYPE_ERROR == null) {
BaseFunction thrower = new BaseFunction() {
@Override
public Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args) {
throw typeError0("msg.op.not.allowed");
}
@Override
public int getLength() {
return 0;
}
};
thrower.preventExtensions();
THROW_TYPE_ERROR = thrower;
}
return THROW_TYPE_ERROR;
}
private static BaseFunction THROW_TYPE_ERROR = null;
static class NoSuchMethodShim implements Callable {
String methodName;
Callable noSuchMethodMethod;
NoSuchMethodShim(Callable noSuchMethodMethod, String methodName)
{
this.noSuchMethodMethod = noSuchMethodMethod;
this.methodName = methodName;
}
/**
* Perform the call.
*
* @param cx the current Context for this thread
* @param scope the scope to use to resolve properties.
* @param thisObj the JavaScript <code>this</code> object
* @param args the array of arguments
* @return the result of the call
*/
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args)
{
Object[] nestedArgs = new Object[2];
nestedArgs[0] = methodName;
nestedArgs[1] = newArrayLiteral(args, null, cx, scope);
return noSuchMethodMethod.call(cx, scope, thisObj, nestedArgs);
}
}
/*
* There's such a huge space (and some time) waste for the Foo.class
* syntax: the compiler sticks in a test of a static field in the
* enclosing class for null and the code for creating the class value.
* It has to do this since the reference has to get pushed off until
* execution time (i.e. can't force an early load), but for the
* 'standard' classes - especially those in java.lang, we can trust
* that they won't cause problems by being loaded early.
*/
public final static Class<?>
BooleanClass = Kit.classOrNull("java.lang.Boolean"),
ByteClass = Kit.classOrNull("java.lang.Byte"),
CharacterClass = Kit.classOrNull("java.lang.Character"),
ClassClass = Kit.classOrNull("java.lang.Class"),
DoubleClass = Kit.classOrNull("java.lang.Double"),
FloatClass = Kit.classOrNull("java.lang.Float"),
IntegerClass = Kit.classOrNull("java.lang.Integer"),
LongClass = Kit.classOrNull("java.lang.Long"),
NumberClass = Kit.classOrNull("java.lang.Number"),
ObjectClass = Kit.classOrNull("java.lang.Object"),
ShortClass = Kit.classOrNull("java.lang.Short"),
StringClass = Kit.classOrNull("java.lang.String"),
DateClass = Kit.classOrNull("java.util.Date");
public final static Class<?>
ContextClass
= Kit.classOrNull("org.mozilla.javascript.Context"),
ContextFactoryClass
= Kit.classOrNull("org.mozilla.javascript.ContextFactory"),
FunctionClass
= Kit.classOrNull("org.mozilla.javascript.Function"),
ScriptableObjectClass
= Kit.classOrNull("org.mozilla.javascript.ScriptableObject");
public static final Class<Scriptable> ScriptableClass =
Scriptable.class;
private static final String[] lazilyNames = {
"RegExp", "org.mozilla.javascript.regexp.NativeRegExp",
"Packages", "org.mozilla.javascript.NativeJavaTopPackage",
"java", "org.mozilla.javascript.NativeJavaTopPackage",
"javax", "org.mozilla.javascript.NativeJavaTopPackage",
"org", "org.mozilla.javascript.NativeJavaTopPackage",
"com", "org.mozilla.javascript.NativeJavaTopPackage",
"edu", "org.mozilla.javascript.NativeJavaTopPackage",
"net", "org.mozilla.javascript.NativeJavaTopPackage",
"getClass", "org.mozilla.javascript.NativeJavaTopPackage",
"JavaAdapter", "org.mozilla.javascript.JavaAdapter",
"JavaImporter", "org.mozilla.javascript.ImporterTopLevel",
"Continuation", "org.mozilla.javascript.NativeContinuation",
// TODO Grotesque hack using literal string (xml) just to minimize
// changes for now
"XML", "(xml)",
"XMLList", "(xml)",
"Namespace", "(xml)",
"QName", "(xml)",
};
// Locale object used to request locale-neutral operations.
public static Locale ROOT_LOCALE = new Locale("");
private static final Object LIBRARY_SCOPE_KEY = "LIBRARY_SCOPE";
public static boolean isRhinoRuntimeType(Class<?> cl)
{
if (cl.isPrimitive()) {
return (cl != Character.TYPE);
} else {
return (cl == StringClass || cl == BooleanClass
|| NumberClass.isAssignableFrom(cl)
|| ScriptableClass.isAssignableFrom(cl));
}
}
public static ScriptableObject initStandardObjects(Context cx,
ScriptableObject scope,
boolean sealed)
{
if (scope == null) {
scope = new NativeObject();
}
scope.associateValue(LIBRARY_SCOPE_KEY, scope);
(new ClassCache()).associate(scope);
BaseFunction.init(scope, sealed);
NativeObject.init(scope, sealed);
Scriptable objectProto = ScriptableObject.getObjectPrototype(scope);
// Function.prototype.__proto__ should be Object.prototype
Scriptable functionProto = ScriptableObject.getClassPrototype(scope, "Function");
functionProto.setPrototype(objectProto);
// Set the prototype of the object passed in if need be
if (scope.getPrototype() == null)
scope.setPrototype(objectProto);
// must precede NativeGlobal since it's needed therein
NativeError.init(scope, sealed);
NativeGlobal.init(cx, scope, sealed);
NativeArray.init(scope, sealed);
if (cx.getOptimizationLevel() > 0) {
// When optimizing, attempt to fulfill all requests for new Array(N)
// with a higher threshold before switching to a sparse
// representation
NativeArray.setMaximumInitialCapacity(200000);
}
NativeString.init(scope, sealed);
NativeBoolean.init(scope, sealed);
NativeNumber.init(scope, sealed);
NativeDate.init(scope, sealed);
NativeMath.init(scope, sealed);
NativeJSON.init(scope, sealed);
NativeWith.init(scope, sealed);
NativeCall.init(scope, sealed);
NativeScript.init(scope, sealed);
NativeIterator.init(scope, sealed); // Also initializes NativeGenerator
boolean withXml = cx.hasFeature(Context.FEATURE_E4X) &&
cx.getE4xImplementationFactory() != null;
for (int i = 0; i != lazilyNames.length; i += 2) {
String topProperty = lazilyNames[i];
String className = lazilyNames[i + 1];
if (!withXml && className.equals("(xml)")) {
continue;
} else if (withXml && className.equals("(xml)")) {
className = cx.getE4xImplementationFactory().
getImplementationClassName();
}
new LazilyLoadedCtor(scope, topProperty, className, sealed, true);
}
if (scope instanceof TopLevel) {
((TopLevel)scope).cacheBuiltins();
}
return scope;
}
public static ScriptableObject getLibraryScopeOrNull(Scriptable scope)
{
ScriptableObject libScope;
libScope = (ScriptableObject)ScriptableObject.
getTopScopeValue(scope, LIBRARY_SCOPE_KEY);
return libScope;
}
// It is public so NativeRegExp can access it.
public static boolean isJSLineTerminator(int c)
{
// Optimization for faster check for eol character:
// they do not have 0xDFD0 bits set
if ((c & 0xDFD0) != 0) {
return false;
}
return c == '\n' || c == '\r' || c == 0x2028 || c == 0x2029;
}
public static boolean isJSWhitespaceOrLineTerminator(int c) {
return (isStrWhiteSpaceChar(c) || isJSLineTerminator(c));
}
/**
* Indicates if the character is a Str whitespace char according to ECMA spec:
* StrWhiteSpaceChar :::
<TAB>
<SP>
<NBSP>
<FF>
<VT>
<CR>
<LF>
<LS>
<PS>
<USP>
<BOM>
*/
static boolean isStrWhiteSpaceChar(int c)
{
switch (c) {
case ' ': // <SP>
case '\n': // <LF>
case '\r': // <CR>
case '\t': // <TAB>
case '\u00A0': // <NBSP>
case '\u000C': // <FF>
case '\u000B': // <VT>
case '\u2028': // <LS>
case '\u2029': // <PS>
case '\uFEFF': // <BOM>
return true;
default:
return Character.getType(c) == Character.SPACE_SEPARATOR;
}
}
public static Boolean wrapBoolean(boolean b)
{
return b ? Boolean.TRUE : Boolean.FALSE;
}
public static Integer wrapInt(int i)
{
return Integer.valueOf(i);
}
public static Number wrapNumber(double x)
{
if (x != x) {
return ScriptRuntime.NaNobj;
}
return new Double(x);
}
/**
* Convert the value to a boolean.
*
* See ECMA 9.2.
*/
public static boolean toBoolean(Object val)
{
for (;;) {
if (val instanceof Boolean)
return ((Boolean) val).booleanValue();
if (val == null || val == Undefined.instance)
return false;
if (val instanceof CharSequence)
return ((CharSequence) val).length() != 0;
if (val instanceof Number) {
double d = ((Number) val).doubleValue();
return (d == d && d != 0.0);
}
if (val instanceof Scriptable) {
if (val instanceof ScriptableObject &&
((ScriptableObject) val).avoidObjectDetection())
{
return false;
}
if (Context.getContext().isVersionECMA1()) {
// pure ECMA
return true;
}
// ECMA extension
val = ((Scriptable) val).getDefaultValue(BooleanClass);
if (val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
continue;
}
warnAboutNonJSObject(val);
return true;
}
}
/**
* Convert the value to a number.
*
* See ECMA 9.3.
*/
public static double toNumber(Object val)
{
for (;;) {
if (val instanceof Number)
return ((Number) val).doubleValue();
if (val == null)
return +0.0;
if (val == Undefined.instance)
return NaN;
if (val instanceof CharSequence)
return toNumber(val.toString());
if (val instanceof Boolean)
return ((Boolean) val).booleanValue() ? 1 : +0.0;
if (val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(NumberClass);
if (val instanceof Scriptable)
throw errorWithClassName("msg.primitive.expected", val);
continue;
}
warnAboutNonJSObject(val);
return NaN;
}
}
public static double toNumber(Object[] args, int index) {
return (index < args.length) ? toNumber(args[index]) : NaN;
}
// Can not use Double.NaN defined as 0.0d / 0.0 as under the Microsoft VM,
// versions 2.01 and 3.0P1, that causes some uses (returns at least) of
// Double.NaN to be converted to 1.0.
// So we use ScriptRuntime.NaN instead of Double.NaN.
public static final double
NaN = Double.longBitsToDouble(0x7ff8000000000000L);
// A similar problem exists for negative zero.
public static final double
negativeZero = Double.longBitsToDouble(0x8000000000000000L);
public static final Double NaNobj = new Double(NaN);
/*
* Helper function for toNumber, parseInt, and TokenStream.getToken.
*/
static double stringToNumber(String s, int start, int radix) {
char digitMax = '9';
char lowerCaseBound = 'a';
char upperCaseBound = 'A';
int len = s.length();
if (radix < 10) {
digitMax = (char) ('0' + radix - 1);
}
if (radix > 10) {
lowerCaseBound = (char) ('a' + radix - 10);
upperCaseBound = (char) ('A' + radix - 10);
}
int end;
double sum = 0.0;
for (end=start; end < len; end++) {
char c = s.charAt(end);
int newDigit;
if ('0' <= c && c <= digitMax)
newDigit = c - '0';
else if ('a' <= c && c < lowerCaseBound)
newDigit = c - 'a' + 10;
else if ('A' <= c && c < upperCaseBound)
newDigit = c - 'A' + 10;
else
break;
sum = sum*radix + newDigit;
}
if (start == end) {
return NaN;
}
if (sum >= 9007199254740992.0) {
if (radix == 10) {
/* If we're accumulating a decimal number and the number
* is >= 2^53, then the result from the repeated multiply-add
* above may be inaccurate. Call Java to get the correct
* answer.
*/
try {
return Double.valueOf(s.substring(start, end)).doubleValue();
} catch (NumberFormatException nfe) {
return NaN;
}
} else if (radix == 2 || radix == 4 || radix == 8 ||
radix == 16 || radix == 32)
{
/* The number may also be inaccurate for one of these bases.
* This happens if the addition in value*radix + digit causes
* a round-down to an even least significant mantissa bit
* when the first dropped bit is a one. If any of the
* following digits in the number (which haven't been added
* in yet) are nonzero then the correct action would have
* been to round up instead of down. An example of this
* occurs when reading the number 0x1000000000000081, which
* rounds to 0x1000000000000000 instead of 0x1000000000000100.
*/
int bitShiftInChar = 1;
int digit = 0;
final int SKIP_LEADING_ZEROS = 0;
final int FIRST_EXACT_53_BITS = 1;
final int AFTER_BIT_53 = 2;
final int ZEROS_AFTER_54 = 3;
final int MIXED_AFTER_54 = 4;
int state = SKIP_LEADING_ZEROS;
int exactBitsLimit = 53;
double factor = 0.0;
boolean bit53 = false;
// bit54 is the 54th bit (the first dropped from the mantissa)
boolean bit54 = false;
for (;;) {
if (bitShiftInChar == 1) {
if (start == end)
break;
digit = s.charAt(start++);
if ('0' <= digit && digit <= '9')
digit -= '0';
else if ('a' <= digit && digit <= 'z')
digit -= 'a' - 10;
else
digit -= 'A' - 10;
bitShiftInChar = radix;
}
bitShiftInChar >>= 1;
boolean bit = (digit & bitShiftInChar) != 0;
switch (state) {
case SKIP_LEADING_ZEROS:
if (bit) {
--exactBitsLimit;
sum = 1.0;
state = FIRST_EXACT_53_BITS;
}
break;
case FIRST_EXACT_53_BITS:
sum *= 2.0;
if (bit)
sum += 1.0;
--exactBitsLimit;
if (exactBitsLimit == 0) {
bit53 = bit;
state = AFTER_BIT_53;
}
break;
case AFTER_BIT_53:
bit54 = bit;
factor = 2.0;
state = ZEROS_AFTER_54;
break;
case ZEROS_AFTER_54:
if (bit) {
state = MIXED_AFTER_54;
}
// fallthrough
case MIXED_AFTER_54:
factor *= 2;
break;
}
}
switch (state) {
case SKIP_LEADING_ZEROS:
sum = 0.0;
break;
case FIRST_EXACT_53_BITS:
case AFTER_BIT_53:
// do nothing
break;
case ZEROS_AFTER_54:
// x1.1 -> x1 + 1 (round up)
// x0.1 -> x0 (round down)
if (bit54 & bit53)
sum += 1.0;
sum *= factor;
break;
case MIXED_AFTER_54:
// x.100...1.. -> x + 1 (round up)
// x.0anything -> x (round down)
if (bit54)
sum += 1.0;
sum *= factor;
break;
}
}
/* We don't worry about inaccurate numbers for any other base. */
}
return sum;
}
/**
* ToNumber applied to the String type
*
* See ECMA 9.3.1
*/
public static double toNumber(String s) {
int len = s.length();
int start = 0;
char startChar;
for (;;) {
if (start == len) {
// Empty or contains only whitespace
return +0.0;
}
startChar = s.charAt(start);
if (!ScriptRuntime.isStrWhiteSpaceChar(startChar))
break;
start++;
}
if (startChar == '0') {
if (start + 2 < len) {
int c1 = s.charAt(start + 1);
if (c1 == 'x' || c1 == 'X') {
// A hexadecimal number
return stringToNumber(s, start + 2, 16);
}
}
} else if (startChar == '+' || startChar == '-') {
if (start + 3 < len && s.charAt(start + 1) == '0') {
int c2 = s.charAt(start + 2);
if (c2 == 'x' || c2 == 'X') {
// A hexadecimal number with sign
double val = stringToNumber(s, start + 3, 16);
return startChar == '-' ? -val : val;
}
}
}
int end = len - 1;
char endChar;
while (ScriptRuntime.isStrWhiteSpaceChar(endChar = s.charAt(end)))
end--;
if (endChar == 'y') {
// check for "Infinity"
if (startChar == '+' || startChar == '-')
start++;
if (start + 7 == end && s.regionMatches(start, "Infinity", 0, 8))
return startChar == '-'
? Double.NEGATIVE_INFINITY
: Double.POSITIVE_INFINITY;
return NaN;
}
// A non-hexadecimal, non-infinity number:
// just try a normal floating point conversion
String sub = s.substring(start, end+1);
if (MSJVM_BUG_WORKAROUNDS) {
// The MS JVM will accept non-conformant strings
// rather than throwing a NumberFormatException
// as it should.
for (int i=sub.length()-1; i >= 0; i--) {
char c = sub.charAt(i);
if (('0' <= c && c <= '9') || c == '.' ||
c == 'e' || c == 'E' ||
c == '+' || c == '-')
continue;
return NaN;
}
}
try {
return Double.valueOf(sub).doubleValue();
} catch (NumberFormatException ex) {
return NaN;
}
}
/**
* Helper function for builtin objects that use the varargs form.
* ECMA function formal arguments are undefined if not supplied;
* this function pads the argument array out to the expected
* length, if necessary.
*/
public static Object[] padArguments(Object[] args, int count) {
if (count < args.length)
return args;
int i;
Object[] result = new Object[count];
for (i = 0; i < args.length; i++) {
result[i] = args[i];
}
for (; i < count; i++) {
result[i] = Undefined.instance;
}
return result;
}
/* Work around Microsoft Java VM bugs. */
private final static boolean MSJVM_BUG_WORKAROUNDS = true;
public static String escapeString(String s)
{
return escapeString(s, '"');
}
/**
* For escaping strings printed by object and array literals; not quite
* the same as 'escape.'
*/
public static String escapeString(String s, char escapeQuote)
{
if (!(escapeQuote == '"' || escapeQuote == '\'')) Kit.codeBug();
StringBuffer sb = null;
for(int i = 0, L = s.length(); i != L; ++i) {
int c = s.charAt(i);
if (' ' <= c && c <= '~' && c != escapeQuote && c != '\\') {
// an ordinary print character (like C isprint()) and not "
// or \ .
if (sb != null) {
sb.append((char)c);
}
continue;
}
if (sb == null) {
sb = new StringBuffer(L + 3);
sb.append(s);
sb.setLength(i);
}
int escape = -1;
switch (c) {
case '\b': escape = 'b'; break;
case '\f': escape = 'f'; break;
case '\n': escape = 'n'; break;
case '\r': escape = 'r'; break;
case '\t': escape = 't'; break;
case 0xb: escape = 'v'; break; // Java lacks \v.
case ' ': escape = ' '; break;
case '\\': escape = '\\'; break;
}
if (escape >= 0) {
// an \escaped sort of character
sb.append('\\');
sb.append((char)escape);
} else if (c == escapeQuote) {
sb.append('\\');
sb.append(escapeQuote);
} else {
int hexSize;
if (c < 256) {
// 2-digit hex
sb.append("\\x");
hexSize = 2;
} else {
// Unicode.
sb.append("\\u");
hexSize = 4;
}
// append hexadecimal form of c left-padded with 0
for (int shift = (hexSize - 1) * 4; shift >= 0; shift -= 4) {
int digit = 0xf & (c >> shift);
int hc = (digit < 10) ? '0' + digit : 'a' - 10 + digit;
sb.append((char)hc);
}
}
}
return (sb == null) ? s : sb.toString();
}
static boolean isValidIdentifierName(String s)
{
int L = s.length();
if (L == 0)
return false;
if (!Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i != L; ++i) {
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
}
return !TokenStream.isKeyword(s);
}
public static CharSequence toCharSequence(Object val) {
if (val instanceof NativeString) {
return ((NativeString)val).toCharSequence();
}
return val instanceof CharSequence ? (CharSequence) val : toString(val);
}
/**
* Convert the value to a string.
*
* See ECMA 9.8.
*/
public static String toString(Object val) {
for (;;) {
if (val == null) {
return "null";
}
if (val == Undefined.instance) {
return "undefined";
}
if (val instanceof CharSequence) {
return val.toString();
}
if (val instanceof Number) {
// XXX should we just teach NativeNumber.stringValue()
// about Numbers?
return numberToString(((Number)val).doubleValue(), 10);
}
if (val instanceof Scriptable) {
val = ((Scriptable) val).getDefaultValue(StringClass);
if (val instanceof Scriptable) {
throw errorWithClassName("msg.primitive.expected", val);
}
continue;
}
return val.toString();
}
}
static String defaultObjectToString(Scriptable obj)
{
return "[object " + obj.getClassName() + ']';
}
public static String toString(Object[] args, int index)
{
return (index < args.length) ? toString(args[index]) : "undefined";
}
/**
* Optimized version of toString(Object) for numbers.
*/
public static String toString(double val) {
return numberToString(val, 10);
}
public static String numberToString(double d, int base) {
if (d != d)
return "NaN";
if (d == Double.POSITIVE_INFINITY)
return "Infinity";
if (d == Double.NEGATIVE_INFINITY)
return "-Infinity";
if (d == 0.0)
return "0";
if ((base < 2) || (base > 36)) {
throw Context.reportRuntimeError1(
"msg.bad.radix", Integer.toString(base));
}
if (base != 10) {
return DToA.JS_dtobasestr(base, d);
} else {
StringBuffer result = new StringBuffer();
DToA.JS_dtostr(result, DToA.DTOSTR_STANDARD, 0, d);
return result.toString();
}
}
static String uneval(Context cx, Scriptable scope, Object value)
{
if (value == null) {
return "null";
}
if (value == Undefined.instance) {
return "undefined";
}
if (value instanceof CharSequence) {
String escaped = escapeString(value.toString());
StringBuffer sb = new StringBuffer(escaped.length() + 2);
sb.append('\"');
sb.append(escaped);
sb.append('\"');
return sb.toString();
}
if (value instanceof Number) {
double d = ((Number)value).doubleValue();
if (d == 0 && 1 / d < 0) {
return "-0";
}
return toString(d);
}
if (value instanceof Boolean) {
return toString(value);
}
if (value instanceof Scriptable) {
Scriptable obj = (Scriptable)value;
// Wrapped Java objects won't have "toSource" and will report
// errors for get()s of nonexistent name, so use has() first
if (ScriptableObject.hasProperty(obj, "toSource")) {
Object v = ScriptableObject.getProperty(obj, "toSource");
if (v instanceof Function) {
Function f = (Function)v;
return toString(f.call(cx, scope, obj, emptyArgs));
}
}
return toString(value);
}
warnAboutNonJSObject(value);
return value.toString();
}
static String defaultObjectToSource(Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
boolean toplevel, iterating;
if (cx.iterating == null) {
toplevel = true;
iterating = false;
cx.iterating = new ObjToIntMap(31);
} else {
toplevel = false;
iterating = cx.iterating.has(thisObj);
}
StringBuffer result = new StringBuffer(128);
if (toplevel) {
result.append("(");
}
result.append('{');
// Make sure cx.iterating is set to null when done
// so we don't leak memory
try {
if (!iterating) {
cx.iterating.intern(thisObj); // stop recursion.
Object[] ids = thisObj.getIds();
for (int i=0; i < ids.length; i++) {
Object id = ids[i];
Object value;
if (id instanceof Integer) {
int intId = ((Integer)id).intValue();
value = thisObj.get(intId, thisObj);
if (value == Scriptable.NOT_FOUND)
continue; // a property has been removed
if (i > 0)
result.append(", ");
result.append(intId);
} else {
String strId = (String)id;
value = thisObj.get(strId, thisObj);
if (value == Scriptable.NOT_FOUND)
continue; // a property has been removed
if (i > 0)
result.append(", ");
if (ScriptRuntime.isValidIdentifierName(strId)) {
result.append(strId);
} else {
result.append('\'');
result.append(
ScriptRuntime.escapeString(strId, '\''));
result.append('\'');
}
}
result.append(':');
result.append(ScriptRuntime.uneval(cx, scope, value));
}
}
} finally {
if (toplevel) {
cx.iterating = null;
}
}
result.append('}');
if (toplevel) {
result.append(')');
}
return result.toString();
}
public static Scriptable toObject(Scriptable scope, Object val)
{
if (val instanceof Scriptable) {
return (Scriptable)val;
}
return toObject(Context.getContext(), scope, val);
}
/**
* Warning: this doesn't allow to resolve primitive prototype properly when many top scopes are involved
*/
public static Scriptable toObjectOrNull(Context cx, Object obj)
{
if (obj instanceof Scriptable) {
return (Scriptable)obj;
} else if (obj != null && obj != Undefined.instance) {
return toObject(cx, getTopCallScope(cx), obj);
}
return null;
}
/**
* @param scope the scope that should be used to resolve primitive prototype
*/
public static Scriptable toObjectOrNull(Context cx, Object obj,
final Scriptable scope)
{
if (obj instanceof Scriptable) {
return (Scriptable)obj;
} else if (obj != null && obj != Undefined.instance) {
return toObject(cx, scope, obj);
}
return null;
}
/**
* @deprecated Use {@link #toObject(Scriptable, Object)} instead.
*/
public static Scriptable toObject(Scriptable scope, Object val,
Class<?> staticClass)
{
if (val instanceof Scriptable) {
return (Scriptable)val;
}
return toObject(Context.getContext(), scope, val);
}
/**
* Convert the value to an object.
*
* See ECMA 9.9.
*/
public static Scriptable toObject(Context cx, Scriptable scope, Object val)
{
if (val instanceof Scriptable) {
return (Scriptable) val;
}
if (val instanceof CharSequence) {
// FIXME we want to avoid toString() here, especially for concat()
NativeString result = new NativeString((CharSequence)val);
setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.String);
return result;
}
if (val instanceof Number) {
NativeNumber result = new NativeNumber(((Number)val).doubleValue());
setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Number);
return result;
}
if (val instanceof Boolean) {
NativeBoolean result = new NativeBoolean(((Boolean)val).booleanValue());
setBuiltinProtoAndParent(result, scope, TopLevel.Builtins.Boolean);
return result;
}
if (val == null) {
throw typeError0("msg.null.to.object");
}
if (val == Undefined.instance) {
throw typeError0("msg.undef.to.object");
}
// Extension: Wrap as a LiveConnect object.
Object wrapped = cx.getWrapFactory().wrap(cx, scope, val, null);
if (wrapped instanceof Scriptable)
return (Scriptable) wrapped;
throw errorWithClassName("msg.invalid.type", val);
}
/**
* @deprecated Use {@link #toObject(Context, Scriptable, Object)} instead.
*/
public static Scriptable toObject(Context cx, Scriptable scope, Object val,
Class<?> staticClass)
{
return toObject(cx, scope, val);
}
/**
* @deprecated The method is only present for compatibility.
*/
public static Object call(Context cx, Object fun, Object thisArg,
Object[] args, Scriptable scope)
{
if (!(fun instanceof Function)) {
throw notFunctionError(toString(fun));
}
Function function = (Function)fun;
Scriptable thisObj = toObjectOrNull(cx, thisArg);
if (thisObj == null) {
throw undefCallError(thisObj, "function");
}
return function.call(cx, scope, thisObj, args);
}
public static Scriptable newObject(Context cx, Scriptable scope,
String constructorName, Object[] args)
{
scope = ScriptableObject.getTopLevelScope(scope);
Function ctor = getExistingCtor(cx, scope, constructorName);
if (args == null) { args = ScriptRuntime.emptyArgs; }
return ctor.construct(cx, scope, args);
}
public static Scriptable newBuiltinObject(Context cx, Scriptable scope,
TopLevel.Builtins type,
Object[] args)
{
scope = ScriptableObject.getTopLevelScope(scope);
Function ctor = TopLevel.getBuiltinCtor(cx, scope, type);
if (args == null) { args = ScriptRuntime.emptyArgs; }
return ctor.construct(cx, scope, args);
}
/**
*
* See ECMA 9.4.
*/
public static double toInteger(Object val) {
return toInteger(toNumber(val));
}
// convenience method
public static double toInteger(double d) {
// if it's NaN
if (d != d)
return +0.0;
if (d == 0.0 ||
d == Double.POSITIVE_INFINITY ||
d == Double.NEGATIVE_INFINITY)
return d;
if (d > 0.0)
return Math.floor(d);
else
return Math.ceil(d);
}
public static double toInteger(Object[] args, int index) {
return (index < args.length) ? toInteger(args[index]) : +0.0;
}
/**
*
* See ECMA 9.5.
*/
public static int toInt32(Object val)
{
// short circuit for common integer values
if (val instanceof Integer)
return ((Integer)val).intValue();
return toInt32(toNumber(val));
}
public static int toInt32(Object[] args, int index) {
return (index < args.length) ? toInt32(args[index]) : 0;
}
public static int toInt32(double d) {
int id = (int)d;
if (id == d) {
// This covers -0.0 as well
return id;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
double two32 = 4294967296.0;
d = Math.IEEEremainder(d, two32);
// (double)(long)d == d should hold here
long l = (long)d;
// returning (int)d does not work as d can be outside int range
// but the result must always be 32 lower bits of l
return (int)l;
}
/**
* See ECMA 9.6.
* @return long value representing 32 bits unsigned integer
*/
public static long toUint32(double d) {
long l = (long)d;
if (l == d) {
// This covers -0.0 as well
return l & 0xffffffffL;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
// 0x100000000 gives me a numeric overflow...
double two32 = 4294967296.0;
l = (long)Math.IEEEremainder(d, two32);
return l & 0xffffffffL;
}
public static long toUint32(Object val) {
return toUint32(toNumber(val));
}
/**
*
* See ECMA 9.7.
*/
public static char toUint16(Object val) {
double d = toNumber(val);
int i = (int)d;
if (i == d) {
return (char)i;
}
if (d != d
|| d == Double.POSITIVE_INFINITY
|| d == Double.NEGATIVE_INFINITY)
{
return 0;
}
d = (d >= 0) ? Math.floor(d) : Math.ceil(d);
int int16 = 0x10000;
i = (int)Math.IEEEremainder(d, int16);
return (char)i;
}
// XXX: this is until setDefaultNamespace will learn how to store NS
// properly and separates namespace form Scriptable.get etc.
private static final String DEFAULT_NS_TAG = "__default_namespace__";
public static Object setDefaultNamespace(Object namespace, Context cx)
{
Scriptable scope = cx.currentActivationCall;
if (scope == null) {
scope = getTopCallScope(cx);
}
XMLLib xmlLib = currentXMLLib(cx);
Object ns = xmlLib.toDefaultXmlNamespace(cx, namespace);
// XXX : this should be in separated namesapce from Scriptable.get/put
if (!scope.has(DEFAULT_NS_TAG, scope)) {
// XXX: this is racy of cause
ScriptableObject.defineProperty(scope, DEFAULT_NS_TAG, ns,
ScriptableObject.PERMANENT
| ScriptableObject.DONTENUM);
} else {
scope.put(DEFAULT_NS_TAG, scope, ns);
}
return Undefined.instance;
}
public static Object searchDefaultNamespace(Context cx)
{
Scriptable scope = cx.currentActivationCall;
if (scope == null) {
scope = getTopCallScope(cx);
}
Object nsObject;
for (;;) {
Scriptable parent = scope.getParentScope();
if (parent == null) {
nsObject = ScriptableObject.getProperty(scope, DEFAULT_NS_TAG);
if (nsObject == Scriptable.NOT_FOUND) {
return null;
}
break;
}
nsObject = scope.get(DEFAULT_NS_TAG, scope);
if (nsObject != Scriptable.NOT_FOUND) {
break;
}
scope = parent;
}
return nsObject;
}
public static Object getTopLevelProp(Scriptable scope, String id) {
scope = ScriptableObject.getTopLevelScope(scope);
return ScriptableObject.getProperty(scope, id);
}
static Function getExistingCtor(Context cx, Scriptable scope,
String constructorName)
{
Object ctorVal = ScriptableObject.getProperty(scope, constructorName);
if (ctorVal instanceof Function) {
return (Function)ctorVal;
}
if (ctorVal == Scriptable.NOT_FOUND) {
throw Context.reportRuntimeError1(
"msg.ctor.not.found", constructorName);
} else {
throw Context.reportRuntimeError1(
"msg.not.ctor", constructorName);
}
}
/**
* Return -1L if str is not an index, or the index value as lower 32
* bits of the result. Note that the result needs to be cast to an int
* in order to produce the actual index, which may be negative.
*/
public static long indexFromString(String str)
{
// The length of the decimal string representation of
// Integer.MAX_VALUE, 2147483647
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (len > 0) {
int i = 0;
boolean negate = false;
int c = str.charAt(0);
if (c == '-') {
if (len > 1) {
c = str.charAt(1);
i = 1;
negate = true;
}
}
c -= '0';
if (0 <= c && c <= 9
&& len <= (negate ? MAX_VALUE_LENGTH + 1 : MAX_VALUE_LENGTH))
{
// Use negative numbers to accumulate index to handle
// Integer.MIN_VALUE that is greater by 1 in absolute value
// then Integer.MAX_VALUE
int index = -c;
int oldIndex = 0;
i++;
if (index != 0) {
// Note that 00, 01, 000 etc. are not indexes
while (i != len && 0 <= (c = str.charAt(i) - '0') && c <= 9)
{
oldIndex = index;
index = 10 * index - c;
i++;
}
}
// Make sure all characters were consumed and that it couldn't
// have overflowed.
if (i == len &&
(oldIndex > (Integer.MIN_VALUE / 10) ||
(oldIndex == (Integer.MIN_VALUE / 10) &&
c <= (negate ? -(Integer.MIN_VALUE % 10)
: (Integer.MAX_VALUE % 10)))))
{
return 0xFFFFFFFFL & (negate ? index : -index);
}
}
}
return -1L;
}
/**
* If str is a decimal presentation of Uint32 value, return it as long.
* Othewise return -1L;
*/
public static long testUint32String(String str)
{
// The length of the decimal string representation of
// UINT32_MAX_VALUE, 4294967296
final int MAX_VALUE_LENGTH = 10;
int len = str.length();
if (1 <= len && len <= MAX_VALUE_LENGTH) {
int c = str.charAt(0);
c -= '0';
if (c == 0) {
// Note that 00,01 etc. are not valid Uint32 presentations
return (len == 1) ? 0L : -1L;
}
if (1 <= c && c <= 9) {
long v = c;
for (int i = 1; i != len; ++i) {
c = str.charAt(i) - '0';
if (!(0 <= c && c <= 9)) {
return -1;
}
v = 10 * v + c;
}
// Check for overflow
if ((v >>> 32) == 0) {
return v;
}
}
}
return -1;
}
/**
* If s represents index, then return index value wrapped as Integer
* and othewise return s.
*/
static Object getIndexObject(String s)
{
long indexTest = indexFromString(s);
if (indexTest >= 0) {
return Integer.valueOf((int)indexTest);
}
return s;
}
/**
* If d is exact int value, return its value wrapped as Integer
* and othewise return d converted to String.
*/
static Object getIndexObject(double d)
{
int i = (int)d;
if (i == d) {
return Integer.valueOf(i);
}
return toString(d);
}
/**
* If toString(id) is a decimal presentation of int32 value, then id
* is index. In this case return null and make the index available
* as ScriptRuntime.lastIndexResult(cx). Otherwise return toString(id).
*/
static String toStringIdOrIndex(Context cx, Object id)
{
if (id instanceof Number) {
double d = ((Number)id).doubleValue();
int index = (int)d;
if (index == d) {
storeIndexResult(cx, index);
return null;
}
return toString(id);
} else {
String s;
if (id instanceof String) {
s = (String)id;
} else {
s = toString(id);
}
long indexTest = indexFromString(s);
if (indexTest >= 0) {
storeIndexResult(cx, (int)indexTest);
return null;
}
return s;
}
}
/**
* Call obj.[[Get]](id)
*/
public static Object getObjectElem(Object obj, Object elem, Context cx)
{
return getObjectElem(obj, elem, cx, getTopCallScope(cx));
}
/**
* Call obj.[[Get]](id)
*/
public static Object getObjectElem(Object obj, Object elem, Context cx, final Scriptable scope)
{
Scriptable sobj = toObjectOrNull(cx, obj, scope);
if (sobj == null) {
throw undefReadError(obj, elem);
}
return getObjectElem(sobj, elem, cx);
}
public static Object getObjectElem(Scriptable obj, Object elem,
Context cx)
{
Object result;
if (obj instanceof XMLObject) {
result = ((XMLObject)obj).get(cx, elem);
} else {
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
result = ScriptableObject.getProperty(obj, index);
} else {
result = ScriptableObject.getProperty(obj, s);
}
}
if (result == Scriptable.NOT_FOUND) {
result = Undefined.instance;
}
return result;
}
/**
* Version of getObjectElem when elem is a valid JS identifier name.
*/
public static Object getObjectProp(Object obj, String property,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefReadError(obj, property);
}
return getObjectProp(sobj, property, cx);
}
/**
* @param scope the scope that should be used to resolve primitive prototype
*/
public static Object getObjectProp(Object obj, String property,
Context cx, final Scriptable scope)
{
Scriptable sobj = toObjectOrNull(cx, obj, scope);
if (sobj == null) {
throw undefReadError(obj, property);
}
return getObjectProp(sobj, property, cx);
}
public static Object getObjectProp(Scriptable obj, String property,
Context cx)
{
Object result = ScriptableObject.getProperty(obj, property);
if (result == Scriptable.NOT_FOUND) {
if (cx.hasFeature(Context.FEATURE_STRICT_MODE)) {
Context.reportWarning(ScriptRuntime.getMessage1(
"msg.ref.undefined.prop", property));
}
result = Undefined.instance;
}
return result;
}
public static Object getObjectPropNoWarn(Object obj, String property,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefReadError(obj, property);
}
Object result = ScriptableObject.getProperty(sobj, property);
if (result == Scriptable.NOT_FOUND) {
return Undefined.instance;
}
return result;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object getObjectIndex(Object obj, double dblIndex,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefReadError(obj, toString(dblIndex));
}
int index = (int)dblIndex;
if (index == dblIndex) {
return getObjectIndex(sobj, index, cx);
} else {
String s = toString(dblIndex);
return getObjectProp(sobj, s, cx);
}
}
public static Object getObjectIndex(Scriptable obj, int index,
Context cx)
{
Object result = ScriptableObject.getProperty(obj, index);
if (result == Scriptable.NOT_FOUND) {
result = Undefined.instance;
}
return result;
}
/*
* Call obj.[[Put]](id, value)
*/
public static Object setObjectElem(Object obj, Object elem, Object value,
Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefWriteError(obj, elem, value);
}
return setObjectElem(sobj, elem, value, cx);
}
public static Object setObjectElem(Scriptable obj, Object elem,
Object value, Context cx)
{
if (obj instanceof XMLObject) {
((XMLObject)obj).put(cx, elem, value);
} else {
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
ScriptableObject.putProperty(obj, index, value);
} else {
ScriptableObject.putProperty(obj, s, value);
}
}
return value;
}
/**
* Version of setObjectElem when elem is a valid JS identifier name.
*/
public static Object setObjectProp(Object obj, String property,
Object value, Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefWriteError(obj, property, value);
}
return setObjectProp(sobj, property, value, cx);
}
public static Object setObjectProp(Scriptable obj, String property,
Object value, Context cx)
{
ScriptableObject.putProperty(obj, property, value);
return value;
}
/*
* A cheaper and less general version of the above for well-known argument
* types.
*/
public static Object setObjectIndex(Object obj, double dblIndex,
Object value, Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw undefWriteError(obj, String.valueOf(dblIndex), value);
}
int index = (int)dblIndex;
if (index == dblIndex) {
return setObjectIndex(sobj, index, value, cx);
} else {
String s = toString(dblIndex);
return setObjectProp(sobj, s, value, cx);
}
}
public static Object setObjectIndex(Scriptable obj, int index, Object value,
Context cx)
{
ScriptableObject.putProperty(obj, index, value);
return value;
}
public static boolean deleteObjectElem(Scriptable target, Object elem,
Context cx)
{
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
target.delete(index);
return !target.has(index, target);
} else {
target.delete(s);
return !target.has(s, target);
}
}
public static boolean hasObjectElem(Scriptable target, Object elem,
Context cx)
{
boolean result;
String s = toStringIdOrIndex(cx, elem);
if (s == null) {
int index = lastIndexResult(cx);
result = ScriptableObject.hasProperty(target, index);
} else {
result = ScriptableObject.hasProperty(target, s);
}
return result;
}
public static Object refGet(Ref ref, Context cx)
{
return ref.get(cx);
}
public static Object refSet(Ref ref, Object value, Context cx)
{
return ref.set(cx, value);
}
public static Object refDel(Ref ref, Context cx)
{
return wrapBoolean(ref.delete(cx));
}
static boolean isSpecialProperty(String s)
{
return s.equals("__proto__") || s.equals("__parent__");
}
public static Ref specialRef(Object obj, String specialProperty,
Context cx)
{
return SpecialRef.createSpecial(cx, obj, specialProperty);
}
/**
* The delete operator
*
* See ECMA 11.4.1
*
* In ECMA 0.19, the description of the delete operator (11.4.1)
* assumes that the [[Delete]] method returns a value. However,
* the definition of the [[Delete]] operator (8.6.2.5) does not
* define a return value. Here we assume that the [[Delete]]
* method doesn't return a value.
*/
public static Object delete(Object obj, Object id, Context cx)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
String idStr = (id == null) ? "null" : id.toString();
throw typeError2("msg.undef.prop.delete", toString(obj), idStr);
}
boolean result = deleteObjectElem(sobj, id, cx);
return wrapBoolean(result);
}
/**
* Looks up a name in the scope chain and returns its value.
*/
public static Object name(Context cx, Scriptable scope, String name)
{
Scriptable parent = scope.getParentScope();
if (parent == null) {
Object result = topScopeName(cx, scope, name);
if (result == Scriptable.NOT_FOUND) {
throw notFoundError(scope, name);
}
return result;
}
return nameOrFunction(cx, scope, parent, name, false);
}
private static Object nameOrFunction(Context cx, Scriptable scope,
Scriptable parentScope, String name,
boolean asFunctionCall)
{
Object result;
Scriptable thisObj = scope; // It is used only if asFunctionCall==true.
XMLObject firstXMLObject = null;
for (;;) {
if (scope instanceof NativeWith) {
Scriptable withObj = scope.getPrototype();
if (withObj instanceof XMLObject) {
XMLObject xmlObj = (XMLObject)withObj;
if (xmlObj.has(name, xmlObj)) {
// function this should be the target object of with
thisObj = xmlObj;
result = xmlObj.get(name, xmlObj);
break;
}
if (firstXMLObject == null) {
firstXMLObject = xmlObj;
}
} else {
result = ScriptableObject.getProperty(withObj, name);
if (result != Scriptable.NOT_FOUND) {
// function this should be the target object of with
thisObj = withObj;
break;
}
}
} else if (scope instanceof NativeCall) {
// NativeCall does not prototype chain and Scriptable.get
// can be called directly.
result = scope.get(name, scope);
if (result != Scriptable.NOT_FOUND) {
if (asFunctionCall) {
// ECMA 262 requires that this for nested funtions
// should be top scope
thisObj = ScriptableObject.
getTopLevelScope(parentScope);
}
break;
}
} else {
// Can happen if Rhino embedding decided that nested
// scopes are useful for what ever reasons.
result = ScriptableObject.getProperty(scope, name);
if (result != Scriptable.NOT_FOUND) {
thisObj = scope;
break;
}
}
scope = parentScope;
parentScope = parentScope.getParentScope();
if (parentScope == null) {
result = topScopeName(cx, scope, name);
if (result == Scriptable.NOT_FOUND) {
if (firstXMLObject == null || asFunctionCall) {
throw notFoundError(scope, name);
}
// The name was not found, but we did find an XML
// object in the scope chain and we are looking for name,
// not function. The result should be an empty XMLList
// in name context.
result = firstXMLObject.get(name, firstXMLObject);
}
// For top scope thisObj for functions is always scope itself.
thisObj = scope;
break;
}
}
if (asFunctionCall) {
if (!(result instanceof Callable)) {
throw notFunctionError(result, name);
}
storeScriptable(cx, thisObj);
}
return result;
}
private static Object topScopeName(Context cx, Scriptable scope,
String name)
{
if (cx.useDynamicScope) {
scope = checkDynamicScope(cx.topCallScope, scope);
}
return ScriptableObject.getProperty(scope, name);
}
/**
* Returns the object in the scope chain that has a given property.
*
* The order of evaluation of an assignment expression involves
* evaluating the lhs to a reference, evaluating the rhs, and then
* modifying the reference with the rhs value. This method is used
* to 'bind' the given name to an object containing that property
* so that the side effects of evaluating the rhs do not affect
* which property is modified.
* Typically used in conjunction with setName.
*
* See ECMA 10.1.4
*/
public static Scriptable bind(Context cx, Scriptable scope, String id)
{
Scriptable firstXMLObject = null;
Scriptable parent = scope.getParentScope();
childScopesChecks: if (parent != null) {
// Check for possibly nested "with" scopes first
while (scope instanceof NativeWith) {
Scriptable withObj = scope.getPrototype();
if (withObj instanceof XMLObject) {
XMLObject xmlObject = (XMLObject)withObj;
if (xmlObject.has(cx, id)) {
return xmlObject;
}
if (firstXMLObject == null) {
firstXMLObject = xmlObject;
}
} else {
if (ScriptableObject.hasProperty(withObj, id)) {
return withObj;
}
}
scope = parent;
parent = parent.getParentScope();
if (parent == null) {
break childScopesChecks;
}
}
for (;;) {
if (ScriptableObject.hasProperty(scope, id)) {
return scope;
}
scope = parent;
parent = parent.getParentScope();
if (parent == null) {
break childScopesChecks;
}
}
}
// scope here is top scope
if (cx.useDynamicScope) {
scope = checkDynamicScope(cx.topCallScope, scope);
}
if (ScriptableObject.hasProperty(scope, id)) {
return scope;
}
// Nothing was found, but since XML objects always bind
// return one if found
return firstXMLObject;
}
public static Object setName(Scriptable bound, Object value,
Context cx, Scriptable scope, String id)
{
if (bound != null) {
// TODO: we used to special-case XMLObject here, but putProperty
// seems to work for E4X and it's better to optimize the common case
ScriptableObject.putProperty(bound, id, value);
} else {
// "newname = 7;", where 'newname' has not yet
// been defined, creates a new property in the
// top scope unless strict mode is specified.
if (cx.hasFeature(Context.FEATURE_STRICT_MODE) ||
cx.hasFeature(Context.FEATURE_STRICT_VARS))
{
Context.reportWarning(
ScriptRuntime.getMessage1("msg.assn.create.strict", id));
}
// Find the top scope by walking up the scope chain.
bound = ScriptableObject.getTopLevelScope(scope);
if (cx.useDynamicScope) {
bound = checkDynamicScope(cx.topCallScope, bound);
}
bound.put(id, bound, value);
}
return value;
}
public static Object strictSetName(Scriptable bound, Object value,
Context cx, Scriptable scope, String id) {
if (bound != null) {
// TODO: The LeftHandSide also may not be a reference to a
// data property with the attribute value {[[Writable]]:false},
// to an accessor property with the attribute value
// {[[Put]]:undefined}, nor to a non-existent property of an
// object whose [[Extensible]] internal property has the value
// false. In these cases a TypeError exception is thrown (11.13.1).
// TODO: we used to special-case XMLObject here, but putProperty
// seems to work for E4X and we should optimize the common case
ScriptableObject.putProperty(bound, id, value);
return value;
} else {
// See ES5 8.7.2
String msg = "Assignment to undefined \"" + id + "\" in strict mode";
throw constructError("ReferenceError", msg);
}
}
public static Object setConst(Scriptable bound, Object value,
Context cx, String id)
{
if (bound instanceof XMLObject) {
bound.put(id, bound, value);
} else {
ScriptableObject.putConstProperty(bound, id, value);
}
return value;
}
/**
* This is the enumeration needed by the for..in statement.
*
* See ECMA 12.6.3.
*
* IdEnumeration maintains a ObjToIntMap to make sure a given
* id is enumerated only once across multiple objects in a
* prototype chain.
*
* XXX - ECMA delete doesn't hide properties in the prototype,
* but js/ref does. This means that the js/ref for..in can
* avoid maintaining a hash table and instead perform lookups
* to see if a given property has already been enumerated.
*
*/
private static class IdEnumeration implements Serializable
{
private static final long serialVersionUID = 1L;
Scriptable obj;
Object[] ids;
int index;
ObjToIntMap used;
Object currentId;
int enumType; /* one of ENUM_INIT_KEYS, ENUM_INIT_VALUES,
ENUM_INIT_ARRAY */
// if true, integer ids will be returned as numbers rather than strings
boolean enumNumbers;
Scriptable iterator;
}
public static Scriptable toIterator(Context cx, Scriptable scope,
Scriptable obj, boolean keyOnly)
{
if (ScriptableObject.hasProperty(obj,
NativeIterator.ITERATOR_PROPERTY_NAME))
{
Object v = ScriptableObject.getProperty(obj,
NativeIterator.ITERATOR_PROPERTY_NAME);
if (!(v instanceof Callable)) {
throw typeError0("msg.invalid.iterator");
}
Callable f = (Callable) v;
Object[] args = new Object[] { keyOnly ? Boolean.TRUE
: Boolean.FALSE };
v = f.call(cx, scope, obj, args);
if (!(v instanceof Scriptable)) {
throw typeError0("msg.iterator.primitive");
}
return (Scriptable) v;
}
return null;
}
// for backwards compatibility with generated class files
public static Object enumInit(Object value, Context cx, boolean enumValues)
{
return enumInit(value, cx, enumValues ? ENUMERATE_VALUES
: ENUMERATE_KEYS);
}
public static final int ENUMERATE_KEYS = 0;
public static final int ENUMERATE_VALUES = 1;
public static final int ENUMERATE_ARRAY = 2;
public static final int ENUMERATE_KEYS_NO_ITERATOR = 3;
public static final int ENUMERATE_VALUES_NO_ITERATOR = 4;
public static final int ENUMERATE_ARRAY_NO_ITERATOR = 5;
public static Object enumInit(Object value, Context cx, int enumType)
{
IdEnumeration x = new IdEnumeration();
x.obj = toObjectOrNull(cx, value);
if (x.obj == null) {
// null or undefined do not cause errors but rather lead to empty
// "for in" loop
return x;
}
x.enumType = enumType;
x.iterator = null;
if (enumType != ENUMERATE_KEYS_NO_ITERATOR &&
enumType != ENUMERATE_VALUES_NO_ITERATOR &&
enumType != ENUMERATE_ARRAY_NO_ITERATOR)
{
x.iterator = toIterator(cx, x.obj.getParentScope(), x.obj,
enumType == ScriptRuntime.ENUMERATE_KEYS);
}
if (x.iterator == null) {
// enumInit should read all initial ids before returning
// or "for (a.i in a)" would wrongly enumerate i in a as well
enumChangeObject(x);
}
return x;
}
public static void setEnumNumbers(Object enumObj, boolean enumNumbers) {
((IdEnumeration)enumObj).enumNumbers = enumNumbers;
}
public static Boolean enumNext(Object enumObj)
{
IdEnumeration x = (IdEnumeration)enumObj;
if (x.iterator != null) {
Object v = ScriptableObject.getProperty(x.iterator, "next");
if (!(v instanceof Callable))
return Boolean.FALSE;
Callable f = (Callable) v;
Context cx = Context.getContext();
try {
x.currentId = f.call(cx, x.iterator.getParentScope(),
x.iterator, emptyArgs);
return Boolean.TRUE;
} catch (JavaScriptException e) {
if (e.getValue() instanceof NativeIterator.StopIteration) {
return Boolean.FALSE;
}
throw e;
}
}
for (;;) {
if (x.obj == null) {
return Boolean.FALSE;
}
if (x.index == x.ids.length) {
x.obj = x.obj.getPrototype();
enumChangeObject(x);
continue;
}
Object id = x.ids[x.index++];
if (x.used != null && x.used.has(id)) {
continue;
}
if (id instanceof String) {
String strId = (String)id;
if (!x.obj.has(strId, x.obj))
continue; // must have been deleted
x.currentId = strId;
} else {
int intId = ((Number)id).intValue();
if (!x.obj.has(intId, x.obj))
continue; // must have been deleted
x.currentId = x.enumNumbers ? (Object) (Integer.valueOf(intId))
: String.valueOf(intId);
}
return Boolean.TRUE;
}
}
public static Object enumId(Object enumObj, Context cx)
{
IdEnumeration x = (IdEnumeration)enumObj;
if (x.iterator != null) {
return x.currentId;
}
switch (x.enumType) {
case ENUMERATE_KEYS:
case ENUMERATE_KEYS_NO_ITERATOR:
return x.currentId;
case ENUMERATE_VALUES:
case ENUMERATE_VALUES_NO_ITERATOR:
return enumValue(enumObj, cx);
case ENUMERATE_ARRAY:
case ENUMERATE_ARRAY_NO_ITERATOR:
Object[] elements = { x.currentId, enumValue(enumObj, cx) };
return cx.newArray(ScriptableObject.getTopLevelScope(x.obj), elements);
default:
throw Kit.codeBug();
}
}
public static Object enumValue(Object enumObj, Context cx) {
IdEnumeration x = (IdEnumeration)enumObj;
Object result;
String s = toStringIdOrIndex(cx, x.currentId);
if (s == null) {
int index = lastIndexResult(cx);
result = x.obj.get(index, x.obj);
} else {
result = x.obj.get(s, x.obj);
}
return result;
}
private static void enumChangeObject(IdEnumeration x)
{
Object[] ids = null;
while (x.obj != null) {
ids = x.obj.getIds();
if (ids.length != 0) {
break;
}
x.obj = x.obj.getPrototype();
}
if (x.obj != null && x.ids != null) {
Object[] previous = x.ids;
int L = previous.length;
if (x.used == null) {
x.used = new ObjToIntMap(L);
}
for (int i = 0; i != L; ++i) {
x.used.intern(previous[i]);
}
}
x.ids = ids;
x.index = 0;
}
/**
* Prepare for calling name(...): return function corresponding to
* name and make current top scope available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getNameFunctionAndThis(String name,
Context cx,
Scriptable scope)
{
Scriptable parent = scope.getParentScope();
if (parent == null) {
Object result = topScopeName(cx, scope, name);
if (!(result instanceof Callable)) {
if (result == Scriptable.NOT_FOUND) {
throw notFoundError(scope, name);
} else {
throw notFunctionError(result, name);
}
}
// Top scope is not NativeWith or NativeCall => thisObj == scope
Scriptable thisObj = scope;
storeScriptable(cx, thisObj);
return (Callable)result;
}
// name will call storeScriptable(cx, thisObj);
return (Callable)nameOrFunction(cx, scope, parent, name, true);
}
/**
* Prepare for calling obj[id](...): return function corresponding to
* obj[id] and make obj properly converted to Scriptable available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getElemFunctionAndThis(Object obj,
Object elem,
Context cx)
{
String str = toStringIdOrIndex(cx, elem);
if (str != null) {
return getPropFunctionAndThis(obj, str, cx);
}
int index = lastIndexResult(cx);
Scriptable thisObj = toObjectOrNull(cx, obj);
if (thisObj == null) {
throw undefCallError(obj, String.valueOf(index));
}
Object value;
if (thisObj instanceof XMLObject) {
Scriptable sobj = thisObj;
do {
XMLObject xmlObject = (XMLObject)sobj;
value = xmlObject.getFunctionProperty(cx, index);
if (value != Scriptable.NOT_FOUND) {
break;
}
sobj = xmlObject.getExtraMethodSource(cx);
if (sobj != null) {
thisObj = sobj;
if (!(sobj instanceof XMLObject)) {
value = ScriptableObject.getProperty(sobj, index);
}
}
} while (sobj instanceof XMLObject);
} else {
value = ScriptableObject.getProperty(thisObj, index);
}
if (!(value instanceof Callable)) {
throw notFunctionError(value, elem);
}
storeScriptable(cx, thisObj);
return (Callable)value;
}
/**
* Prepare for calling obj.property(...): return function corresponding to
* obj.property and make obj properly converted to Scriptable available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
* Warning: this doesn't allow to resolve primitive prototype properly when
* many top scopes are involved.
*/
public static Callable getPropFunctionAndThis(Object obj,
String property,
Context cx)
{
Scriptable thisObj = toObjectOrNull(cx, obj);
return getPropFunctionAndThisHelper(obj, property, cx, thisObj);
}
/**
* Prepare for calling obj.property(...): return function corresponding to
* obj.property and make obj properly converted to Scriptable available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getPropFunctionAndThis(Object obj,
String property,
Context cx, final Scriptable scope)
{
Scriptable thisObj = toObjectOrNull(cx, obj, scope);
return getPropFunctionAndThisHelper(obj, property, cx, thisObj);
}
private static Callable getPropFunctionAndThisHelper(Object obj,
String property, Context cx, Scriptable thisObj)
{
if (thisObj == null) {
throw undefCallError(obj, property);
}
Object value;
if (thisObj instanceof XMLObject) {
Scriptable sobj = thisObj;
do {
XMLObject xmlObject = (XMLObject)sobj;
value = xmlObject.getFunctionProperty(cx, property);
if (value != Scriptable.NOT_FOUND) {
break;
}
sobj = xmlObject.getExtraMethodSource(cx);
if (sobj != null) {
thisObj = sobj;
if (!(sobj instanceof XMLObject)) {
value = ScriptableObject.getProperty(sobj, property);
}
}
} while (sobj instanceof XMLObject);
} else {
value = ScriptableObject.getProperty(thisObj, property);
if (!(value instanceof Callable)) {
Object noSuchMethod = ScriptableObject.getProperty(thisObj, "__noSuchMethod__");
if (noSuchMethod instanceof Callable)
value = new NoSuchMethodShim((Callable)noSuchMethod, property);
}
}
if (!(value instanceof Callable)) {
throw notFunctionError(thisObj, value, property);
}
storeScriptable(cx, thisObj);
return (Callable)value;
}
/**
* Prepare for calling <expression>(...): return function corresponding to
* <expression> and make parent scope of the function available
* as ScriptRuntime.lastStoredScriptable() for consumption as thisObj.
* The caller must call ScriptRuntime.lastStoredScriptable() immediately
* after calling this method.
*/
public static Callable getValueFunctionAndThis(Object value, Context cx)
{
if (!(value instanceof Callable)) {
throw notFunctionError(value);
}
Callable f = (Callable)value;
Scriptable thisObj = null;
if (f instanceof Scriptable) {
thisObj = ((Scriptable)f).getParentScope();
}
if (thisObj == null) {
if (cx.topCallScope == null) throw new IllegalStateException();
thisObj = cx.topCallScope;
}
if (thisObj.getParentScope() != null) {
if (thisObj instanceof NativeWith) {
// functions defined inside with should have with target
// as their thisObj
} else if (thisObj instanceof NativeCall) {
// nested functions should have top scope as their thisObj
thisObj = ScriptableObject.getTopLevelScope(thisObj);
}
}
storeScriptable(cx, thisObj);
return f;
}
/**
* Perform function call in reference context. Should always
* return value that can be passed to
* {@link #refGet(Ref, Context)} or {@link #refSet(Ref, Object, Context)}
* arbitrary number of times.
* The args array reference should not be stored in any object that is
* can be GC-reachable after this method returns. If this is necessary,
* store args.clone(), not args array itself.
*/
public static Ref callRef(Callable function, Scriptable thisObj,
Object[] args, Context cx)
{
if (function instanceof RefCallable) {
RefCallable rfunction = (RefCallable)function;
Ref ref = rfunction.refCall(cx, thisObj, args);
if (ref == null) {
throw new IllegalStateException(rfunction.getClass().getName()+".refCall() returned null");
}
return ref;
}
// No runtime support for now
String msg = getMessage1("msg.no.ref.from.function",
toString(function));
throw constructError("ReferenceError", msg);
}
/**
* Operator new.
*
* See ECMA 11.2.2
*/
public static Scriptable newObject(Object fun, Context cx,
Scriptable scope, Object[] args)
{
if (!(fun instanceof Function)) {
throw notFunctionError(fun);
}
Function function = (Function)fun;
return function.construct(cx, scope, args);
}
public static Object callSpecial(Context cx, Callable fun,
Scriptable thisObj,
Object[] args, Scriptable scope,
Scriptable callerThis, int callType,
String filename, int lineNumber)
{
if (callType == Node.SPECIALCALL_EVAL) {
if (thisObj.getParentScope() == null && NativeGlobal.isEvalFunction(fun)) {
return evalSpecial(cx, scope, callerThis, args,
filename, lineNumber);
}
} else if (callType == Node.SPECIALCALL_WITH) {
if (NativeWith.isWithFunction(fun)) {
throw Context.reportRuntimeError1("msg.only.from.new",
"With");
}
} else {
throw Kit.codeBug();
}
return fun.call(cx, scope, thisObj, args);
}
public static Object newSpecial(Context cx, Object fun,
Object[] args, Scriptable scope,
int callType)
{
if (callType == Node.SPECIALCALL_EVAL) {
if (NativeGlobal.isEvalFunction(fun)) {
throw typeError1("msg.not.ctor", "eval");
}
} else if (callType == Node.SPECIALCALL_WITH) {
if (NativeWith.isWithFunction(fun)) {
return NativeWith.newWithSpecial(cx, scope, args);
}
} else {
throw Kit.codeBug();
}
return newObject(fun, cx, scope, args);
}
/**
* Function.prototype.apply and Function.prototype.call
*
* See Ecma 15.3.4.[34]
*/
public static Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
int L = args.length;
Callable function = getCallable(thisObj);
Scriptable callThis = null;
if (L != 0) {
callThis = toObjectOrNull(cx, args[0]);
}
if (callThis == null) {
// This covers the case of args[0] == (null|undefined) as well.
callThis = getTopCallScope(cx);
}
Object[] callArgs;
if (isApply) {
// Follow Ecma 15.3.4.3
callArgs = L <= 1 ? ScriptRuntime.emptyArgs :
getApplyArguments(cx, args[1]);
} else {
// Follow Ecma 15.3.4.4
if (L <= 1) {
callArgs = ScriptRuntime.emptyArgs;
} else {
callArgs = new Object[L - 1];
System.arraycopy(args, 1, callArgs, 0, L - 1);
}
}
return function.call(cx, scope, callThis, callArgs);
}
static Object[] getApplyArguments(Context cx, Object arg1)
{
if (arg1 == null || arg1 == Undefined.instance) {
return ScriptRuntime.emptyArgs;
} else if (arg1 instanceof NativeArray || arg1 instanceof Arguments) {
return cx.getElements((Scriptable) arg1);
} else {
throw ScriptRuntime.typeError0("msg.arg.isnt.array");
}
}
static Callable getCallable(Scriptable thisObj)
{
Callable function;
if (thisObj instanceof Callable) {
function = (Callable)thisObj;
} else {
Object value = thisObj.getDefaultValue(ScriptRuntime.FunctionClass);
if (!(value instanceof Callable)) {
throw ScriptRuntime.notFunctionError(value, thisObj);
}
function = (Callable)value;
}
return function;
}
/**
* The eval function property of the global object.
*
* See ECMA 15.1.2.1
*/
public static Object evalSpecial(Context cx, Scriptable scope,
Object thisArg, Object[] args,
String filename, int lineNumber)
{
if (args.length < 1)
return Undefined.instance;
Object x = args[0];
if (!(x instanceof CharSequence)) {
if (cx.hasFeature(Context.FEATURE_STRICT_MODE) ||
cx.hasFeature(Context.FEATURE_STRICT_EVAL))
{
throw Context.reportRuntimeError0("msg.eval.nonstring.strict");
}
String message = ScriptRuntime.getMessage0("msg.eval.nonstring");
Context.reportWarning(message);
return x;
}
if (filename == null) {
int[] linep = new int[1];
filename = Context.getSourcePositionFromStack(linep);
if (filename != null) {
lineNumber = linep[0];
} else {
filename = "";
}
}
String sourceName = ScriptRuntime.
makeUrlForGeneratedScript(true, filename, lineNumber);
ErrorReporter reporter;
reporter = DefaultErrorReporter.forEval(cx.getErrorReporter());
Evaluator evaluator = Context.createInterpreter();
if (evaluator == null) {
throw new JavaScriptException("Interpreter not present",
filename, lineNumber);
}
// Compile with explicit interpreter instance to force interpreter
// mode.
Script script = cx.compileString(x.toString(), evaluator,
reporter, sourceName, 1, null);
evaluator.setEvalScriptFlag(script);
Callable c = (Callable)script;
return c.call(cx, scope, (Scriptable)thisArg, ScriptRuntime.emptyArgs);
}
/**
* The typeof operator
*/
public static String typeof(Object value)
{
if (value == null)
return "object";
if (value == Undefined.instance)
return "undefined";
if (value instanceof ScriptableObject)
return ((ScriptableObject) value).getTypeOf();
if (value instanceof Scriptable)
return (value instanceof Callable) ? "function" : "object";
if (value instanceof CharSequence)
return "string";
if (value instanceof Number)
return "number";
if (value instanceof Boolean)
return "boolean";
throw errorWithClassName("msg.invalid.type", value);
}
/**
* The typeof operator that correctly handles the undefined case
*/
public static String typeofName(Scriptable scope, String id)
{
Context cx = Context.getContext();
Scriptable val = bind(cx, scope, id);
if (val == null)
return "undefined";
return typeof(getObjectProp(val, id, cx));
}
// neg:
// implement the '-' operator inline in the caller
// as "-toNumber(val)"
// not:
// implement the '!' operator inline in the caller
// as "!toBoolean(val)"
// bitnot:
// implement the '~' operator inline in the caller
// as "~toInt32(val)"
public static Object add(Object val1, Object val2, Context cx)
{
if(val1 instanceof Number && val2 instanceof Number) {
return wrapNumber(((Number)val1).doubleValue() +
((Number)val2).doubleValue());
}
if (val1 instanceof XMLObject) {
Object test = ((XMLObject)val1).addValues(cx, true, val2);
if (test != Scriptable.NOT_FOUND) {
return test;
}
}
if (val2 instanceof XMLObject) {
Object test = ((XMLObject)val2).addValues(cx, false, val1);
if (test != Scriptable.NOT_FOUND) {
return test;
}
}
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(null);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(null);
if (!(val1 instanceof CharSequence) && !(val2 instanceof CharSequence))
if ((val1 instanceof Number) && (val2 instanceof Number))
return wrapNumber(((Number)val1).doubleValue() +
((Number)val2).doubleValue());
else
return wrapNumber(toNumber(val1) + toNumber(val2));
return new ConsString(toCharSequence(val1), toCharSequence(val2));
}
public static CharSequence add(CharSequence val1, Object val2) {
return new ConsString(val1, toCharSequence(val2));
}
public static CharSequence add(Object val1, CharSequence val2) {
return new ConsString(toCharSequence(val1), val2);
}
/**
* @deprecated The method is only present for compatibility.
*/
public static Object nameIncrDecr(Scriptable scopeChain, String id,
int incrDecrMask)
{
return nameIncrDecr(scopeChain, id, Context.getContext(), incrDecrMask);
}
public static Object nameIncrDecr(Scriptable scopeChain, String id,
Context cx, int incrDecrMask)
{
Scriptable target;
Object value;
search: {
do {
if (cx.useDynamicScope && scopeChain.getParentScope() == null) {
scopeChain = checkDynamicScope(cx.topCallScope, scopeChain);
}
target = scopeChain;
do {
if (target instanceof NativeWith &&
target.getPrototype() instanceof XMLObject) {
break;
}
value = target.get(id, scopeChain);
if (value != Scriptable.NOT_FOUND) {
break search;
}
target = target.getPrototype();
} while (target != null);
scopeChain = scopeChain.getParentScope();
} while (scopeChain != null);
throw notFoundError(scopeChain, id);
}
return doScriptableIncrDecr(target, id, scopeChain, value,
incrDecrMask);
}
public static Object propIncrDecr(Object obj, String id,
Context cx, int incrDecrMask)
{
Scriptable start = toObjectOrNull(cx, obj);
if (start == null) {
throw undefReadError(obj, id);
}
Scriptable target = start;
Object value;
search: {
do {
value = target.get(id, start);
if (value != Scriptable.NOT_FOUND) {
break search;
}
target = target.getPrototype();
} while (target != null);
start.put(id, start, NaNobj);
return NaNobj;
}
return doScriptableIncrDecr(target, id, start, value,
incrDecrMask);
}
private static Object doScriptableIncrDecr(Scriptable target,
String id,
Scriptable protoChainStart,
Object value,
int incrDecrMask)
{
boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
double number;
if (value instanceof Number) {
number = ((Number)value).doubleValue();
} else {
number = toNumber(value);
if (post) {
// convert result to number
value = wrapNumber(number);
}
}
if ((incrDecrMask & Node.DECR_FLAG) == 0) {
++number;
} else {
--number;
}
Number result = wrapNumber(number);
target.put(id, protoChainStart, result);
if (post) {
return value;
} else {
return result;
}
}
public static Object elemIncrDecr(Object obj, Object index,
Context cx, int incrDecrMask)
{
Object value = getObjectElem(obj, index, cx);
boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
double number;
if (value instanceof Number) {
number = ((Number)value).doubleValue();
} else {
number = toNumber(value);
if (post) {
// convert result to number
value = wrapNumber(number);
}
}
if ((incrDecrMask & Node.DECR_FLAG) == 0) {
++number;
} else {
--number;
}
Number result = wrapNumber(number);
setObjectElem(obj, index, result, cx);
if (post) {
return value;
} else {
return result;
}
}
public static Object refIncrDecr(Ref ref, Context cx, int incrDecrMask)
{
Object value = ref.get(cx);
boolean post = ((incrDecrMask & Node.POST_FLAG) != 0);
double number;
if (value instanceof Number) {
number = ((Number)value).doubleValue();
} else {
number = toNumber(value);
if (post) {
// convert result to number
value = wrapNumber(number);
}
}
if ((incrDecrMask & Node.DECR_FLAG) == 0) {
++number;
} else {
--number;
}
Number result = wrapNumber(number);
ref.set(cx, result);
if (post) {
return value;
} else {
return result;
}
}
public static Object toPrimitive(Object val) {
return toPrimitive(val, null);
}
public static Object toPrimitive(Object val, Class<?> typeHint)
{
if (!(val instanceof Scriptable)) {
return val;
}
Scriptable s = (Scriptable)val;
Object result = s.getDefaultValue(typeHint);
if (result instanceof Scriptable)
throw typeError0("msg.bad.default.value");
return result;
}
/**
* Equality
*
* See ECMA 11.9
*/
public static boolean eq(Object x, Object y)
{
if (x == y && !(x instanceof Number)) {
return true;
} else if (x == null || x == Undefined.instance) {
if (y == null || y == Undefined.instance) {
return true;
}
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
return false;
} else if (x instanceof Number) {
return eqNumber(((Number)x).doubleValue(), y);
} else if (x instanceof CharSequence) {
return eqString(x.toString(), y);
} else if (x instanceof Boolean) {
boolean b = ((Boolean)x).booleanValue();
if (y instanceof Boolean) {
return b == ((Boolean)y).booleanValue();
}
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
return eqNumber(b ? 1.0 : 0.0, y);
} else if (x instanceof Scriptable) {
if (y instanceof Scriptable) {
if (x == y) {
return true;
}
if (x instanceof ScriptableObject) {
Object test = ((ScriptableObject)x).equivalentValues(y);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
if (x instanceof Wrapper && y instanceof Wrapper) {
// See bug 413838. Effectively an extension to ECMA for
// the LiveConnect case.
Object unwrappedX = ((Wrapper)x).unwrap();
Object unwrappedY = ((Wrapper)y).unwrap();
return unwrappedX == unwrappedY ||
(isPrimitive(unwrappedX) &&
isPrimitive(unwrappedY) &&
eq(unwrappedX, unwrappedY));
}
return false;
} else if (y instanceof Boolean) {
if (x instanceof ScriptableObject) {
Object test = ((ScriptableObject)x).equivalentValues(y);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
double d = ((Boolean)y).booleanValue() ? 1.0 : 0.0;
return eqNumber(d, x);
} else if (y instanceof Number) {
return eqNumber(((Number)y).doubleValue(), x);
} else if (y instanceof String) {
return eqString((String)y, x);
}
// covers the case when y == Undefined.instance as well
return false;
} else {
warnAboutNonJSObject(x);
return x == y;
}
}
public static boolean isPrimitive(Object obj) {
return obj == null || obj == Undefined.instance ||
(obj instanceof Number) || (obj instanceof String) ||
(obj instanceof Boolean);
}
static boolean eqNumber(double x, Object y)
{
for (;;) {
if (y == null || y == Undefined.instance) {
return false;
} else if (y instanceof Number) {
return x == ((Number)y).doubleValue();
} else if (y instanceof CharSequence) {
return x == toNumber(y);
} else if (y instanceof Boolean) {
return x == (((Boolean)y).booleanValue() ? 1.0 : +0.0);
} else if (y instanceof Scriptable) {
if (y instanceof ScriptableObject) {
Object xval = wrapNumber(x);
Object test = ((ScriptableObject)y).equivalentValues(xval);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
y = toPrimitive(y);
} else {
warnAboutNonJSObject(y);
return false;
}
}
}
private static boolean eqString(String x, Object y)
{
for (;;) {
if (y == null || y == Undefined.instance) {
return false;
} else if (y instanceof CharSequence) {
return x.equals(y.toString());
} else if (y instanceof Number) {
return toNumber(x) == ((Number)y).doubleValue();
} else if (y instanceof Boolean) {
return toNumber(x) == (((Boolean)y).booleanValue() ? 1.0 : 0.0);
} else if (y instanceof Scriptable) {
if (y instanceof ScriptableObject) {
Object test = ((ScriptableObject)y).equivalentValues(x);
if (test != Scriptable.NOT_FOUND) {
return ((Boolean)test).booleanValue();
}
}
y = toPrimitive(y);
continue;
} else {
warnAboutNonJSObject(y);
return false;
}
}
}
public static boolean shallowEq(Object x, Object y)
{
if (x == y) {
if (!(x instanceof Number)) {
return true;
}
// NaN check
double d = ((Number)x).doubleValue();
return d == d;
}
if (x == null || x == Undefined.instance) {
return false;
} else if (x instanceof Number) {
if (y instanceof Number) {
return ((Number)x).doubleValue() == ((Number)y).doubleValue();
}
} else if (x instanceof CharSequence) {
if (y instanceof CharSequence) {
return x.toString().equals(y.toString());
}
} else if (x instanceof Boolean) {
if (y instanceof Boolean) {
return x.equals(y);
}
} else if (x instanceof Scriptable) {
if (x instanceof Wrapper && y instanceof Wrapper) {
return ((Wrapper)x).unwrap() == ((Wrapper)y).unwrap();
}
} else {
warnAboutNonJSObject(x);
return x == y;
}
return false;
}
/**
* The instanceof operator.
*
* @return a instanceof b
*/
public static boolean instanceOf(Object a, Object b, Context cx)
{
// Check RHS is an object
if (! (b instanceof Scriptable)) {
throw typeError0("msg.instanceof.not.object");
}
// for primitive values on LHS, return false
if (! (a instanceof Scriptable))
return false;
return ((Scriptable)b).hasInstance((Scriptable)a);
}
/**
* Delegates to
*
* @return true iff rhs appears in lhs' proto chain
*/
public static boolean jsDelegatesTo(Scriptable lhs, Scriptable rhs) {
Scriptable proto = lhs.getPrototype();
while (proto != null) {
if (proto.equals(rhs)) return true;
proto = proto.getPrototype();
}
return false;
}
/**
* The in operator.
*
* This is a new JS 1.3 language feature. The in operator mirrors
* the operation of the for .. in construct, and tests whether the
* rhs has the property given by the lhs. It is different from the
* for .. in construct in that:
* <BR> - it doesn't perform ToObject on the right hand side
* <BR> - it returns true for DontEnum properties.
* @param a the left hand operand
* @param b the right hand operand
*
* @return true if property name or element number a is a property of b
*/
public static boolean in(Object a, Object b, Context cx)
{
if (!(b instanceof Scriptable)) {
throw typeError0("msg.instanceof.not.object");
}
return hasObjectElem((Scriptable)b, a, cx);
}
public static boolean cmp_LT(Object val1, Object val2)
{
double d1, d2;
if (val1 instanceof Number && val2 instanceof Number) {
d1 = ((Number)val1).doubleValue();
d2 = ((Number)val2).doubleValue();
} else {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (val1 instanceof CharSequence && val2 instanceof CharSequence) {
return val1.toString().compareTo(val2.toString()) < 0;
}
d1 = toNumber(val1);
d2 = toNumber(val2);
}
return d1 < d2;
}
public static boolean cmp_LE(Object val1, Object val2)
{
double d1, d2;
if (val1 instanceof Number && val2 instanceof Number) {
d1 = ((Number)val1).doubleValue();
d2 = ((Number)val2).doubleValue();
} else {
if (val1 instanceof Scriptable)
val1 = ((Scriptable) val1).getDefaultValue(NumberClass);
if (val2 instanceof Scriptable)
val2 = ((Scriptable) val2).getDefaultValue(NumberClass);
if (val1 instanceof CharSequence && val2 instanceof CharSequence) {
return val1.toString().compareTo(val2.toString()) <= 0;
}
d1 = toNumber(val1);
d2 = toNumber(val2);
}
return d1 <= d2;
}
// ------------------
// Statements
// ------------------
public static ScriptableObject getGlobal(Context cx) {
final String GLOBAL_CLASS = "org.mozilla.javascript.tools.shell.Global";
Class<?> globalClass = Kit.classOrNull(GLOBAL_CLASS);
if (globalClass != null) {
try {
Class<?>[] parm = { ScriptRuntime.ContextClass };
Constructor<?> globalClassCtor = globalClass.getConstructor(parm);
Object[] arg = { cx };
return (ScriptableObject) globalClassCtor.newInstance(arg);
}
catch (RuntimeException e) {
throw e;
}
catch (Exception e) {
// fall through...
}
}
return new ImporterTopLevel(cx);
}
public static boolean hasTopCall(Context cx)
{
return (cx.topCallScope != null);
}
public static Scriptable getTopCallScope(Context cx)
{
Scriptable scope = cx.topCallScope;
if (scope == null) {
throw new IllegalStateException();
}
return scope;
}
public static Object doTopCall(Callable callable,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args)
{
if (scope == null)
throw new IllegalArgumentException();
if (cx.topCallScope != null) throw new IllegalStateException();
Object result;
cx.topCallScope = ScriptableObject.getTopLevelScope(scope);
cx.useDynamicScope = cx.hasFeature(Context.FEATURE_DYNAMIC_SCOPE);
ContextFactory f = cx.getFactory();
try {
result = f.doTopCall(callable, cx, scope, thisObj, args);
} finally {
cx.topCallScope = null;
// Cleanup cached references
cx.cachedXMLLib = null;
if (cx.currentActivationCall != null) {
// Function should always call exitActivationFunction
// if it creates activation record
throw new IllegalStateException();
}
}
return result;
}
/**
* Return <tt>possibleDynamicScope</tt> if <tt>staticTopScope</tt>
* is present on its prototype chain and return <tt>staticTopScope</tt>
* otherwise.
* Should only be called when <tt>staticTopScope</tt> is top scope.
*/
static Scriptable checkDynamicScope(Scriptable possibleDynamicScope,
Scriptable staticTopScope)
{
// Return cx.topCallScope if scope
if (possibleDynamicScope == staticTopScope) {
return possibleDynamicScope;
}
Scriptable proto = possibleDynamicScope;
for (;;) {
proto = proto.getPrototype();
if (proto == staticTopScope) {
return possibleDynamicScope;
}
if (proto == null) {
return staticTopScope;
}
}
}
public static void addInstructionCount(Context cx, int instructionsToAdd)
{
cx.instructionCount += instructionsToAdd;
if (cx.instructionCount > cx.instructionThreshold)
{
cx.observeInstructionCount(cx.instructionCount);
cx.instructionCount = 0;
}
}
public static void initScript(NativeFunction funObj, Scriptable thisObj,
Context cx, Scriptable scope,
boolean evalScript)
{
if (cx.topCallScope == null)
throw new IllegalStateException();
int varCount = funObj.getParamAndVarCount();
if (varCount != 0) {
Scriptable varScope = scope;
// Never define any variables from var statements inside with
// object. See bug 38590.
while (varScope instanceof NativeWith) {
varScope = varScope.getParentScope();
}
for (int i = varCount; i-- != 0;) {
String name = funObj.getParamOrVarName(i);
boolean isConst = funObj.getParamOrVarConst(i);
// Don't overwrite existing def if already defined in object
// or prototypes of object.
if (!ScriptableObject.hasProperty(scope, name)) {
if (!evalScript) {
// Global var definitions are supposed to be DONTDELETE
if (isConst)
ScriptableObject.defineConstProperty(varScope, name);
else
ScriptableObject.defineProperty(
varScope, name, Undefined.instance,
ScriptableObject.PERMANENT);
} else {
varScope.put(name, varScope, Undefined.instance);
}
} else {
ScriptableObject.redefineProperty(scope, name, isConst);
}
}
}
}
public static Scriptable createFunctionActivation(NativeFunction funObj,
Scriptable scope,
Object[] args)
{
return new NativeCall(funObj, scope, args);
}
public static void enterActivationFunction(Context cx,
Scriptable scope)
{
if (cx.topCallScope == null)
throw new IllegalStateException();
NativeCall call = (NativeCall)scope;
call.parentActivationCall = cx.currentActivationCall;
cx.currentActivationCall = call;
}
public static void exitActivationFunction(Context cx)
{
NativeCall call = cx.currentActivationCall;
cx.currentActivationCall = call.parentActivationCall;
call.parentActivationCall = null;
}
static NativeCall findFunctionActivation(Context cx, Function f)
{
NativeCall call = cx.currentActivationCall;
while (call != null) {
if (call.function == f)
return call;
call = call.parentActivationCall;
}
return null;
}
public static Scriptable newCatchScope(Throwable t,
Scriptable lastCatchScope,
String exceptionName,
Context cx, Scriptable scope)
{
Object obj;
boolean cacheObj;
getObj:
if (t instanceof JavaScriptException) {
cacheObj = false;
obj = ((JavaScriptException)t).getValue();
} else {
cacheObj = true;
// Create wrapper object unless it was associated with
// the previous scope object
if (lastCatchScope != null) {
NativeObject last = (NativeObject)lastCatchScope;
obj = last.getAssociatedValue(t);
if (obj == null) Kit.codeBug();
break getObj;
}
RhinoException re;
String errorName;
String errorMsg;
Throwable javaException = null;
if (t instanceof EcmaError) {
EcmaError ee = (EcmaError)t;
re = ee;
errorName = ee.getName();
errorMsg = ee.getErrorMessage();
} else if (t instanceof WrappedException) {
WrappedException we = (WrappedException)t;
re = we;
javaException = we.getWrappedException();
errorName = "JavaException";
errorMsg = javaException.getClass().getName()
+": "+javaException.getMessage();
} else if (t instanceof EvaluatorException) {
// Pure evaluator exception, nor WrappedException instance
EvaluatorException ee = (EvaluatorException)t;
re = ee;
errorName = "InternalError";
errorMsg = ee.getMessage();
} else if (cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS)) {
// With FEATURE_ENHANCED_JAVA_ACCESS, scripts can catch
// all exception types
re = new WrappedException(t);
errorName = "JavaException";
errorMsg = t.toString();
} else {
// Script can catch only instances of JavaScriptException,
// EcmaError and EvaluatorException
throw Kit.codeBug();
}
String sourceUri = re.sourceName();
if (sourceUri == null) {
sourceUri = "";
}
int line = re.lineNumber();
Object args[];
if (line > 0) {
args = new Object[] { errorMsg, sourceUri, Integer.valueOf(line) };
} else {
args = new Object[] { errorMsg, sourceUri };
}
Scriptable errorObject = cx.newObject(scope, errorName, args);
ScriptableObject.putProperty(errorObject, "name", errorName);
// set exception in Error objects to enable non-ECMA "stack" property
if (errorObject instanceof NativeError) {
((NativeError) errorObject).setStackProvider(re);
}
if (javaException != null && isVisible(cx, javaException)) {
Object wrap = cx.getWrapFactory().wrap(cx, scope, javaException,
null);
ScriptableObject.defineProperty(
errorObject, "javaException", wrap,
ScriptableObject.PERMANENT | ScriptableObject.READONLY);
}
if (isVisible(cx, re)) {
Object wrap = cx.getWrapFactory().wrap(cx, scope, re, null);
ScriptableObject.defineProperty(
errorObject, "rhinoException", wrap,
ScriptableObject.PERMANENT | ScriptableObject.READONLY);
}
obj = errorObject;
}
NativeObject catchScopeObject = new NativeObject();
// See ECMA 12.4
catchScopeObject.defineProperty(
exceptionName, obj, ScriptableObject.PERMANENT);
if (isVisible(cx, t)) {
// Add special Rhino object __exception__ defined in the catch
// scope that can be used to retrieve the Java exception associated
// with the JavaScript exception (to get stack trace info, etc.)
catchScopeObject.defineProperty(
"__exception__", Context.javaToJS(t, scope),
ScriptableObject.PERMANENT|ScriptableObject.DONTENUM);
}
if (cacheObj) {
catchScopeObject.associateValue(t, obj);
}
return catchScopeObject;
}
private static boolean isVisible(Context cx, Object obj) {
ClassShutter shutter = cx.getClassShutter();
return shutter == null ||
shutter.visibleToScripts(obj.getClass().getName());
}
public static Scriptable enterWith(Object obj, Context cx,
Scriptable scope)
{
Scriptable sobj = toObjectOrNull(cx, obj);
if (sobj == null) {
throw typeError1("msg.undef.with", toString(obj));
}
if (sobj instanceof XMLObject) {
XMLObject xmlObject = (XMLObject)sobj;
return xmlObject.enterWith(scope);
}
return new NativeWith(scope, sobj);
}
public static Scriptable leaveWith(Scriptable scope)
{
NativeWith nw = (NativeWith)scope;
return nw.getParentScope();
}
public static Scriptable enterDotQuery(Object value, Scriptable scope)
{
if (!(value instanceof XMLObject)) {
throw notXmlError(value);
}
XMLObject object = (XMLObject)value;
return object.enterDotQuery(scope);
}
public static Object updateDotQuery(boolean value, Scriptable scope)
{
// Return null to continue looping
NativeWith nw = (NativeWith)scope;
return nw.updateDotQuery(value);
}
public static Scriptable leaveDotQuery(Scriptable scope)
{
NativeWith nw = (NativeWith)scope;
return nw.getParentScope();
}
public static void setFunctionProtoAndParent(BaseFunction fn,
Scriptable scope)
{
fn.setParentScope(scope);
fn.setPrototype(ScriptableObject.getFunctionPrototype(scope));
}
public static void setObjectProtoAndParent(ScriptableObject object,
Scriptable scope)
{
// Compared with function it always sets the scope to top scope
scope = ScriptableObject.getTopLevelScope(scope);
object.setParentScope(scope);
Scriptable proto
= ScriptableObject.getClassPrototype(scope, object.getClassName());
object.setPrototype(proto);
}
public static void setBuiltinProtoAndParent(ScriptableObject object,
Scriptable scope,
TopLevel.Builtins type)
{
scope = ScriptableObject.getTopLevelScope(scope);
object.setParentScope(scope);
object.setPrototype(TopLevel.getBuiltinPrototype(scope, type));
}
public static void initFunction(Context cx, Scriptable scope,
NativeFunction function, int type,
boolean fromEvalCode)
{
if (type == FunctionNode.FUNCTION_STATEMENT) {
String name = function.getFunctionName();
if (name != null && name.length() != 0) {
if (!fromEvalCode) {
// ECMA specifies that functions defined in global and
// function scope outside eval should have DONTDELETE set.
ScriptableObject.defineProperty
(scope, name, function, ScriptableObject.PERMANENT);
} else {
scope.put(name, scope, function);
}
}
} else if (type == FunctionNode.FUNCTION_EXPRESSION_STATEMENT) {
String name = function.getFunctionName();
if (name != null && name.length() != 0) {
// Always put function expression statements into initial
// activation object ignoring the with statement to follow
// SpiderMonkey
while (scope instanceof NativeWith) {
scope = scope.getParentScope();
}
scope.put(name, scope, function);
}
} else {
throw Kit.codeBug();
}
}
public static Scriptable newArrayLiteral(Object[] objects,
int[] skipIndices,
Context cx, Scriptable scope)
{
final int SKIP_DENSITY = 2;
int count = objects.length;
int skipCount = 0;
if (skipIndices != null) {
skipCount = skipIndices.length;
}
int length = count + skipCount;
if (length > 1 && skipCount * SKIP_DENSITY < length) {
// If not too sparse, create whole array for constructor
Object[] sparse;
if (skipCount == 0) {
sparse = objects;
} else {
sparse = new Object[length];
int skip = 0;
for (int i = 0, j = 0; i != length; ++i) {
if (skip != skipCount && skipIndices[skip] == i) {
sparse[i] = Scriptable.NOT_FOUND;
++skip;
continue;
}
sparse[i] = objects[j];
++j;
}
}
return cx.newArray(scope, sparse);
}
Scriptable array = cx.newArray(scope, length);
int skip = 0;
for (int i = 0, j = 0; i != length; ++i) {
if (skip != skipCount && skipIndices[skip] == i) {
++skip;
continue;
}
ScriptableObject.putProperty(array, i, objects[j]);
++j;
}
return array;
}
/**
* This method is here for backward compat with existing compiled code. It
* is called when an object literal is compiled. The next instance will be
* the version called from new code.
* @deprecated This method only present for compatibility.
*/
public static Scriptable newObjectLiteral(Object[] propertyIds,
Object[] propertyValues,
Context cx, Scriptable scope)
{
// This will initialize to all zeros, exactly what we need for old-style
// getterSetters values (no getters or setters in the list)
int [] getterSetters = new int[propertyIds.length];
return newObjectLiteral(propertyIds, propertyValues, getterSetters,
cx, scope);
}
public static Scriptable newObjectLiteral(Object[] propertyIds,
Object[] propertyValues,
int [] getterSetters,
Context cx, Scriptable scope)
{
Scriptable object = cx.newObject(scope);
for (int i = 0, end = propertyIds.length; i != end; ++i) {
Object id = propertyIds[i];
int getterSetter = getterSetters[i];
Object value = propertyValues[i];
if (id instanceof String) {
if (getterSetter == 0) {
if (isSpecialProperty((String)id)) {
specialRef(object, (String)id, cx).set(cx, value);
} else {
ScriptableObject.putProperty(object, (String)id, value);
}
} else {
Callable fun;
String definer;
if (getterSetter < 0) // < 0 means get foo() ...
definer = "__defineGetter__";
else
definer = "__defineSetter__";
fun = getPropFunctionAndThis(object, definer, cx);
// Must consume the last scriptable object in cx
lastStoredScriptable(cx);
Object[] outArgs = new Object[2];
outArgs[0] = id;
outArgs[1] = value;
fun.call(cx, scope, object, outArgs);
}
} else {
int index = ((Integer)id).intValue();
ScriptableObject.putProperty(object, index, value);
}
}
return object;
}
public static boolean isArrayObject(Object obj)
{
return obj instanceof NativeArray || obj instanceof Arguments;
}
public static Object[] getArrayElements(Scriptable object)
{
Context cx = Context.getContext();
long longLen = NativeArray.getLengthProperty(cx, object);
if (longLen > Integer.MAX_VALUE) {
// arrays beyond MAX_INT is not in Java in any case
throw new IllegalArgumentException();
}
int len = (int) longLen;
if (len == 0) {
return ScriptRuntime.emptyArgs;
} else {
Object[] result = new Object[len];
for (int i=0; i < len; i++) {
Object elem = ScriptableObject.getProperty(object, i);
result[i] = (elem == Scriptable.NOT_FOUND) ? Undefined.instance
: elem;
}
return result;
}
}
static void checkDeprecated(Context cx, String name) {
int version = cx.getLanguageVersion();
if (version >= Context.VERSION_1_4 || version == Context.VERSION_DEFAULT) {
String msg = getMessage1("msg.deprec.ctor", name);
if (version == Context.VERSION_DEFAULT)
Context.reportWarning(msg);
else
throw Context.reportRuntimeError(msg);
}
}
public static String getMessage0(String messageId)
{
return getMessage(messageId, null);
}
public static String getMessage1(String messageId, Object arg1)
{
Object[] arguments = {arg1};
return getMessage(messageId, arguments);
}
public static String getMessage2(
String messageId, Object arg1, Object arg2)
{
Object[] arguments = {arg1, arg2};
return getMessage(messageId, arguments);
}
public static String getMessage3(
String messageId, Object arg1, Object arg2, Object arg3)
{
Object[] arguments = {arg1, arg2, arg3};
return getMessage(messageId, arguments);
}
public static String getMessage4(
String messageId, Object arg1, Object arg2, Object arg3, Object arg4)
{
Object[] arguments = {arg1, arg2, arg3, arg4};
return getMessage(messageId, arguments);
}
/**
* This is an interface defining a message provider. Create your
* own implementation to override the default error message provider.
*
* @author Mike Harm
*/
public interface MessageProvider {
/**
* Returns a textual message identified by the given messageId,
* parameterized by the given arguments.
*
* @param messageId the identifier of the message
* @param arguments the arguments to fill into the message
*/
String getMessage(String messageId, Object[] arguments);
}
public static MessageProvider messageProvider = new DefaultMessageProvider();
public static String getMessage(String messageId, Object[] arguments)
{
return messageProvider.getMessage(messageId, arguments);
}
/* OPT there's a noticable delay for the first error! Maybe it'd
* make sense to use a ListResourceBundle instead of a properties
* file to avoid (synchronized) text parsing.
*/
private static class DefaultMessageProvider implements MessageProvider {
public String getMessage(String messageId, Object[] arguments) {
final String defaultResource
= "org.mozilla.javascript.resources.Messages";
Context cx = Context.getCurrentContext();
Locale locale = cx != null ? cx.getLocale() : Locale.getDefault();
// ResourceBundle does caching.
ResourceBundle rb = ResourceBundle.getBundle(defaultResource, locale);
String formatString;
try {
formatString = rb.getString(messageId);
} catch (java.util.MissingResourceException mre) {
throw new RuntimeException
("no message resource found for message property "+ messageId);
}
/*
* It's OK to format the string, even if 'arguments' is null;
* we need to format it anyway, to make double ''s collapse to
* single 's.
*/
MessageFormat formatter = new MessageFormat(formatString);
return formatter.format(arguments);
}
}
public static EcmaError constructError(String error, String message)
{
int[] linep = new int[1];
String filename = Context.getSourcePositionFromStack(linep);
return constructError(error, message, filename, linep[0], null, 0);
}
public static EcmaError constructError(String error,
String message,
int lineNumberDelta)
{
int[] linep = new int[1];
String filename = Context.getSourcePositionFromStack(linep);
if (linep[0] != 0) {
linep[0] += lineNumberDelta;
}
return constructError(error, message, filename, linep[0], null, 0);
}
public static EcmaError constructError(String error,
String message,
String sourceName,
int lineNumber,
String lineSource,
int columnNumber)
{
return new EcmaError(error, message, sourceName,
lineNumber, lineSource, columnNumber);
}
public static EcmaError typeError(String message)
{
return constructError("TypeError", message);
}
public static EcmaError typeError0(String messageId)
{
String msg = getMessage0(messageId);
return typeError(msg);
}
public static EcmaError typeError1(String messageId, String arg1)
{
String msg = getMessage1(messageId, arg1);
return typeError(msg);
}
public static EcmaError typeError2(String messageId, String arg1,
String arg2)
{
String msg = getMessage2(messageId, arg1, arg2);
return typeError(msg);
}
public static EcmaError typeError3(String messageId, String arg1,
String arg2, String arg3)
{
String msg = getMessage3(messageId, arg1, arg2, arg3);
return typeError(msg);
}
public static RuntimeException undefReadError(Object object, Object id)
{
String idStr = (id == null) ? "null" : id.toString();
return typeError2("msg.undef.prop.read", toString(object), idStr);
}
public static RuntimeException undefCallError(Object object, Object id)
{
String idStr = (id == null) ? "null" : id.toString();
return typeError2("msg.undef.method.call", toString(object), idStr);
}
public static RuntimeException undefWriteError(Object object,
Object id,
Object value)
{
String idStr = (id == null) ? "null" : id.toString();
String valueStr = (value instanceof Scriptable)
? value.toString() : toString(value);
return typeError3("msg.undef.prop.write", toString(object), idStr,
valueStr);
}
public static RuntimeException notFoundError(Scriptable object,
String property)
{
// XXX: use object to improve the error message
String msg = getMessage1("msg.is.not.defined", property);
throw constructError("ReferenceError", msg);
}
public static RuntimeException notFunctionError(Object value)
{
return notFunctionError(value, value);
}
public static RuntimeException notFunctionError(Object value,
Object messageHelper)
{
// Use value for better error reporting
String msg = (messageHelper == null)
? "null" : messageHelper.toString();
if (value == Scriptable.NOT_FOUND) {
return typeError1("msg.function.not.found", msg);
}
return typeError2("msg.isnt.function", msg, typeof(value));
}
public static RuntimeException notFunctionError(Object obj, Object value,
String propertyName)
{
// Use obj and value for better error reporting
String objString = toString(obj);
if (obj instanceof NativeFunction) {
// Omit function body in string representations of functions
int curly = objString.indexOf('{');
if (curly > -1) {
objString = objString.substring(0, curly + 1) + "...}";
}
}
if (value == Scriptable.NOT_FOUND) {
return typeError2("msg.function.not.found.in", propertyName,
objString);
}
return typeError3("msg.isnt.function.in", propertyName, objString,
typeof(value));
}
private static RuntimeException notXmlError(Object value)
{
throw typeError1("msg.isnt.xml.object", toString(value));
}
private static void warnAboutNonJSObject(Object nonJSObject)
{
String message =
"RHINO USAGE WARNING: Missed Context.javaToJS() conversion:\n"
+"Rhino runtime detected object "+nonJSObject+" of class "+nonJSObject.getClass().getName()+" where it expected String, Number, Boolean or Scriptable instance. Please check your code for missing Context.javaToJS() call.";
Context.reportWarning(message);
// Just to be sure that it would be noticed
System.err.println(message);
}
public static RegExpProxy getRegExpProxy(Context cx)
{
return cx.getRegExpProxy();
}
public static void setRegExpProxy(Context cx, RegExpProxy proxy)
{
if (proxy == null) throw new IllegalArgumentException();
cx.regExpProxy = proxy;
}
public static RegExpProxy checkRegExpProxy(Context cx)
{
RegExpProxy result = getRegExpProxy(cx);
if (result == null) {
throw Context.reportRuntimeError0("msg.no.regexp");
}
return result;
}
private static XMLLib currentXMLLib(Context cx)
{
// Scripts should be running to access this
if (cx.topCallScope == null)
throw new IllegalStateException();
XMLLib xmlLib = cx.cachedXMLLib;
if (xmlLib == null) {
xmlLib = XMLLib.extractFromScope(cx.topCallScope);
if (xmlLib == null)
throw new IllegalStateException();
cx.cachedXMLLib = xmlLib;
}
return xmlLib;
}
/**
* Escapes the reserved characters in a value of an attribute
*
* @param value Unescaped text
* @return The escaped text
*/
public static String escapeAttributeValue(Object value, Context cx)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.escapeAttributeValue(value);
}
/**
* Escapes the reserved characters in a value of a text node
*
* @param value Unescaped text
* @return The escaped text
*/
public static String escapeTextValue(Object value, Context cx)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.escapeTextValue(value);
}
public static Ref memberRef(Object obj, Object elem,
Context cx, int memberTypeFlags)
{
if (!(obj instanceof XMLObject)) {
throw notXmlError(obj);
}
XMLObject xmlObject = (XMLObject)obj;
return xmlObject.memberRef(cx, elem, memberTypeFlags);
}
public static Ref memberRef(Object obj, Object namespace, Object elem,
Context cx, int memberTypeFlags)
{
if (!(obj instanceof XMLObject)) {
throw notXmlError(obj);
}
XMLObject xmlObject = (XMLObject)obj;
return xmlObject.memberRef(cx, namespace, elem, memberTypeFlags);
}
public static Ref nameRef(Object name, Context cx,
Scriptable scope, int memberTypeFlags)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.nameRef(cx, name, scope, memberTypeFlags);
}
public static Ref nameRef(Object namespace, Object name, Context cx,
Scriptable scope, int memberTypeFlags)
{
XMLLib xmlLib = currentXMLLib(cx);
return xmlLib.nameRef(cx, namespace, name, scope, memberTypeFlags);
}
private static void storeIndexResult(Context cx, int index)
{
cx.scratchIndex = index;
}
static int lastIndexResult(Context cx)
{
return cx.scratchIndex;
}
public static void storeUint32Result(Context cx, long value)
{
if ((value >>> 32) != 0)
throw new IllegalArgumentException();
cx.scratchUint32 = value;
}
public static long lastUint32Result(Context cx)
{
long value = cx.scratchUint32;
if ((value >>> 32) != 0)
throw new IllegalStateException();
return value;
}
private static void storeScriptable(Context cx, Scriptable value)
{
// The previously stored scratchScriptable should be consumed
if (cx.scratchScriptable != null)
throw new IllegalStateException();
cx.scratchScriptable = value;
}
public static Scriptable lastStoredScriptable(Context cx)
{
Scriptable result = cx.scratchScriptable;
cx.scratchScriptable = null;
return result;
}
static String makeUrlForGeneratedScript
(boolean isEval, String masterScriptUrl, int masterScriptLine)
{
if (isEval) {
return masterScriptUrl+'#'+masterScriptLine+"(eval)";
} else {
return masterScriptUrl+'#'+masterScriptLine+"(Function)";
}
}
static boolean isGeneratedScript(String sourceUrl) {
// ALERT: this may clash with a valid URL containing (eval) or
// (Function)
return sourceUrl.indexOf("(eval)") >= 0
|| sourceUrl.indexOf("(Function)") >= 0;
}
private static RuntimeException errorWithClassName(String msg, Object val)
{
return Context.reportRuntimeError1(msg, val.getClass().getName());
}
/**
* Equivalent to executing "new Error(message)" from JavaScript.
* @param cx the current context
* @param scope the current scope
* @param message the message
* @return a JavaScriptException you should throw
*/
public static JavaScriptException throwError(Context cx, Scriptable scope,
String message) {
int[] linep = { 0 };
String filename = Context.getSourcePositionFromStack(linep);
final Scriptable error = newBuiltinObject(cx, scope,
TopLevel.Builtins.Error, new Object[] { message, filename, Integer.valueOf(linep[0]) });
return new JavaScriptException(error, filename, linep[0]);
}
public static final Object[] emptyArgs = new Object[0];
public static final String[] emptyStrings = new String[0];
}
| Avoid calling String.toString() on some hot paths
| src/org/mozilla/javascript/ScriptRuntime.java | Avoid calling String.toString() on some hot paths | <ide><path>rc/org/mozilla/javascript/ScriptRuntime.java
<ide> return +0.0;
<ide> if (val == Undefined.instance)
<ide> return NaN;
<add> if (val instanceof String)
<add> return toNumber((String) val);
<ide> if (val instanceof CharSequence)
<ide> return toNumber(val.toString());
<ide> if (val instanceof Boolean)
<ide> }
<ide> if (val == Undefined.instance) {
<ide> return "undefined";
<add> }
<add> if (val instanceof String) {
<add> return (String)val;
<ide> }
<ide> if (val instanceof CharSequence) {
<ide> return val.toString(); |
|
Java | apache-2.0 | 6b879df6055de821459f7bb5aacdaa7a16565f90 | 0 | MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab,MyRobotLab/myrobotlab | package org.myrobotlab.service;
import java.io.IOException;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.openni.OpenNiData;
import org.myrobotlab.openni.Skeleton;
import org.slf4j.Logger;
// TODO set pir sensor
/**
*
* Sweety - The sweety robot service. Maintained by \@beetlejuice
*
*/
public class Sweety extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Sweety.class);
transient public Arduino arduino;
transient public Adafruit16CServoDriver adaFruit16cRight;
transient public Adafruit16CServoDriver adaFruit16cLeft;
transient public WebkitSpeechRecognition ear;
transient public WebGui webGui;
transient public MarySpeech mouth;
transient public static Tracking tracker;
transient public ProgramAB chatBot;
transient public static OpenNi openni;
transient public Pid pid;
transient public Pir pir;
transient public HtmlFilter htmlFilter;
// Right arm Servomotors
transient public Servo rightShoulderServo;
transient public Servo rightArmServo;
transient public Servo rightBicepsServo;
transient public Servo rightElbowServo;
transient public Servo rightWristServo;
// Left arm Servomotors
transient public Servo leftShoulderServo;
transient public Servo leftArmServo;
transient public Servo leftBicepsServo;
transient public Servo leftElbowServo;
transient public Servo leftWristServo;
// Right hand Servomotors
transient public Servo rightThumbServo;
transient public Servo rightIndexServo;
transient public Servo rightMiddleServo;
transient public Servo rightRingServo;
transient public Servo rightPinkyServo;
// Left hand Servomotors
transient public Servo leftThumbServo;
transient public Servo leftIndexServo;
transient public Servo leftMiddleServo;
transient public Servo leftRingServo;
transient public Servo leftPinkyServo;
// Head Servomotors
transient public Servo neckTiltServo;
transient public Servo neckPanServo;
// Ultrasonic sensors
transient public UltrasonicSensor USfront;
transient public UltrasonicSensor USfrontRight;
transient public UltrasonicSensor USfrontLeft;
transient public UltrasonicSensor USback;
transient public UltrasonicSensor USbackRight;
transient public UltrasonicSensor USbackLeft;
boolean copyGesture = false;
boolean firstSkeleton = true;
boolean saveSkeletonFrame = false;
// Adafruit16CServoDriver setup
String i2cBus = "0";
String i2cAdressRight = "0x40";
String i2cAdressLeft = "0x41";
// arduino pins variables
int rightMotorDirPin = 2;
int rightMotorPwmPin = 3;
int leftMotorDirPin = 4;
int leftMotorPwmPin = 5;
int backUltrasonicTrig = 22;
int backUltrasonicEcho = 23;
int back_leftUltrasonicTrig = 24;
int back_leftUltrasonicEcho = 25;
int back_rightUltrasonicTrig = 26;
int back_rightUltrasonicEcho = 27;
int front_leftUltrasonicTrig = 28;
int front_leftUltrasonicEcho = 29;
int frontUltrasonicTrig = 30;
int frontUltrasonicEcho = 31;
int front_rightUltrasonicTrig = 32;
int front_rightUltrasonicEcho = 33;
int SHIFT = 14;
int LATCH = 15;
int DATA = 16;
int pirSensorPin = 17;
int pin = 0;
int min = 1;
int max = 2;
int rest = 3;
// for arms and hands, the values are pin,min,max,rest
//Right arm
int rightShoulder[] = {34,0,180,0};
int rightArm[] = {1,45,155,140};
int rightBiceps[] = {2,12,90,12};
int rightElbow[] = {3,8,90,8};
int rightWrist[] = {4,0,140,140};
// Left arm
int leftShoulder[] = {35,0,150,148};
int leftArm[] = {1,0,85,0};
int leftBiceps[] = {2,60,140,140};
int leftElbow[] = {3,0,75,0};
int leftWrist[] = {4,0,168,0};
// Right hand
int rightThumb[] = {5,170,75,170};
int rightIndex[] = {6,70,180,180};
int rightMiddle[] = {7,1,2,3};
int rightRing[] = {8,15,130,15};
int rightPinky[] = {9,25,180,25};
// Left hand
int leftThumb[] = {5,40,105,40};
int leftIndex[] = {6,0,180,0};
int leftMiddle[] = {7,0,180,0};
int leftRing[] = {8,10,180,180};
int leftPinky[] = {9,65,180,180};
// Head
int neckTilt[] = {6,15,50,30};
int neckPan[] = {7,20,130,75};
/**
* Replace the values of an array , if a value == -1 the old value is keep
* Exemple if rightArm[]={35,1,2,3} and user ask to change by {-1,1,2,3}, this method will return {35,1,2,3}
* This method must receive an array of ten arrays.
* If one of these arrays is less or more than four numbers length , it doesn't will be changed.
*/
int[][] changeArrayValues(int[][] valuesArray){
// valuesArray contain first the news values and after, the old values
for (int i = 0; i < (valuesArray.length / 2 ); i++) {
if (valuesArray[i].length ==4 ){
for (int j = 0; j < 3; j++) {
if (valuesArray[i][j] == -1){
valuesArray[i][j] = valuesArray[i+5][j];
}
}
}
else{
valuesArray[i]=valuesArray[i+(valuesArray.length / 2 )];
}
}
return valuesArray;
}
/**
* Set pin, min, max, and rest for each servos. -1 in an array mean "no change"
* Exemple setRightArm({39,1,2,3},{40,1,2,3},{41,1,2,3},{-1,1,2,3},{-1,1,2,3})
* Python exemple : sweety.setRightArm([1,0,180,90],[2,0,180,0],[3,180,90,90],[7,7,4,4],[8,5,8,1])
*/
public void setRightArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){
int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,rightShoulder,rightArm,rightBiceps,rightElbow,rightWrist};
valuesArray = changeArrayValues(valuesArray);
rightShoulder = valuesArray[0];
rightArm = valuesArray[1];
rightBiceps = valuesArray[2];
rightElbow = valuesArray[3];
rightWrist = valuesArray[4];
}
/**
* Same as setRightArm
*/
public void setLefttArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){
int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,leftShoulder,leftArm,leftBiceps,leftElbow,leftWrist};
valuesArray = changeArrayValues(valuesArray);
leftShoulder = valuesArray[0];
leftArm = valuesArray[1];
leftBiceps = valuesArray[2];
leftElbow = valuesArray[3];
leftWrist = valuesArray[4];
}
/**
* Same as setRightArm
*/
public void setLeftHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){
int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, leftThumb, leftIndex, leftMiddle, leftRing, leftPinky};
valuesArray = changeArrayValues(valuesArray);
leftThumb = valuesArray[0];
leftIndex = valuesArray[1];
leftMiddle = valuesArray[2];
leftRing = valuesArray[3];
leftPinky = valuesArray[4];
}
/**
* Same as setRightArm
*/
public void setRightHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){
int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, rightThumb, rightIndex, rightMiddle, rightRing, rightPinky};
valuesArray = changeArrayValues(valuesArray);
rightThumb = valuesArray[0];
rightIndex = valuesArray[1];
rightMiddle = valuesArray[2];
rightRing = valuesArray[3];
rightPinky = valuesArray[4];
}
/**
* Set pin, min, max, and rest for head tilt and pan . -1 in an array mean "no change"
* Exemple setHead({39,1,2,3},{40,1,2,3})
* Python exemple : sweety.setHead([1,0,180,90],[2,0,180,0])
*/
public void setHead(int[] tilt, int[] pan){
int[][] valuesArray = new int[][]{tilt, pan,neckTilt,neckPan};
valuesArray = changeArrayValues(valuesArray);
neckTilt = valuesArray[0];
neckPan = valuesArray[1];
}
// set Adafruit16CServoDriver setup
public void setadafruitServoDriver(String i2cBusValue, String i2cAdressRightValue, String i2cAdressLeftValue) {
i2cBus = i2cBusValue;
i2cAdressRight = i2cAdressRightValue;
i2cAdressLeft = i2cAdressLeftValue;
}
// variables for speak / mouth sync
public int delaytime = 3;
public int delaytimestop = 5;
public int delaytimeletter = 1;
String lang;
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
Runtime.start("sweety", "Sweety");
} catch (Exception e) {
Logging.logError(e);
}
}
public Sweety(String n) {
super(n);
}
/**
* Attach the servos to arduino and adafruitServoDriver pins
* @throws Exception e
*/
public void attach() throws Exception {
adaFruit16cLeft.attach("arduino",i2cBus,i2cAdressLeft);
adaFruit16cRight.attach("arduino",i2cBus,i2cAdressRight);
rightElbowServo.attach(adaFruit16cRight, rightElbow[pin]);
rightShoulderServo.attach(adaFruit16cRight, rightShoulder[pin]);
rightArmServo.attach(adaFruit16cRight, rightArm[pin]);
rightBicepsServo.attach(adaFruit16cRight, rightBiceps[pin]);
rightElbowServo.attach(adaFruit16cRight, rightElbow[pin]);
rightWristServo.attach(adaFruit16cRight, rightWrist[pin]);
leftShoulderServo.attach(adaFruit16cLeft, leftShoulder[pin]);
leftArmServo.attach(adaFruit16cLeft, leftArm[pin]);
leftBicepsServo.attach(adaFruit16cLeft, leftBiceps[pin]);
leftElbowServo.attach(adaFruit16cLeft, leftElbow[pin]);
leftWristServo.attach(adaFruit16cLeft, leftWrist[pin]);
rightThumbServo.attach(adaFruit16cRight, rightThumb[pin]);
rightIndexServo.attach(adaFruit16cRight, rightIndex[pin]);
rightMiddleServo.attach(adaFruit16cRight, rightMiddle[pin]);
rightRingServo.attach(adaFruit16cRight, rightRing[pin]);
rightPinkyServo.attach(adaFruit16cRight, rightPinky[pin]);
leftThumbServo.attach(adaFruit16cLeft, leftThumb[pin]);
leftIndexServo.attach(adaFruit16cLeft, leftIndex[pin]);
leftMiddleServo.attach(adaFruit16cLeft, leftMiddle[pin]);
leftRingServo.attach(adaFruit16cLeft, leftRing[pin]);
leftPinkyServo.attach(adaFruit16cLeft, leftPinky[pin]);
neckTiltServo.attach(arduino, neckTilt[pin]);
neckPanServo.attach(arduino, neckPan[pin]);
// Inverted servos
neckTiltServo.setInverted(true);
}
/**
* Connect the arduino to a COM port . Exemple : connect("COM8")
* @param port port
* @throws IOException e
*/
public void connect(String port) throws IOException {
arduino.connect(port);
sleep(2000);
arduino.pinMode(SHIFT, Arduino.OUTPUT);
arduino.pinMode(LATCH, Arduino.OUTPUT);
arduino.pinMode(DATA, Arduino.OUTPUT);
arduino.pinMode(pirSensorPin, Arduino.INPUT);
}
/**
* detach the servos from arduino pins
*/
public void detach() {
if (rightElbowServo != null)
rightElbowServo.detach();
if (rightShoulderServo != null)
rightShoulderServo.detach();
if (rightArmServo != null)
rightArmServo.detach();
if (rightBicepsServo != null)
rightBicepsServo.detach();
if (rightElbowServo != null)
rightElbowServo.detach();
if (rightWristServo != null)
rightWristServo.detach();
if (leftShoulderServo != null)
leftShoulderServo.detach();
if (leftShoulderServo != null)
leftShoulderServo.detach();
if (leftBicepsServo != null)
leftBicepsServo.detach();
if (leftElbowServo != null)
leftElbowServo.detach();
if (leftWristServo != null)
leftWristServo.detach();
if (rightThumbServo != null)
rightThumbServo.detach();
if (rightIndexServo != null)
rightIndexServo.detach();
if (rightMiddleServo != null)
rightMiddleServo.detach();
if (rightRingServo != null)
rightRingServo.detach();
if (rightPinkyServo != null)
rightPinkyServo.detach();
if (leftThumbServo != null)
leftThumbServo.detach();
if (leftIndexServo != null)
leftIndexServo.detach();
if (leftMiddleServo != null)
leftMiddleServo.detach();
if (leftRingServo != null)
leftRingServo.detach();
if (leftPinkyServo != null)
leftPinkyServo.detach();
if (neckTiltServo != null)
neckTiltServo.detach();
if (neckPanServo != null)
neckPanServo.detach();
}
/**
* Move the head . Use : head(neckTiltAngle, neckPanAngle -1 mean
* "no change"
* @param neckTiltAngle tilt
* @param neckPanAngle pan
*/
public void setHeadPosition(double neckTiltAngle, double neckPanAngle) {
if (neckTiltAngle == -1) {
neckTiltAngle = neckTiltServo.getPos();
}
if (neckPanAngle == -1) {
neckPanAngle = neckPanServo.getPos();
}
neckTiltServo.moveTo(neckTiltAngle);
neckPanServo.moveTo(neckPanAngle);
}
/**
* Move the right arm . Use : setRightArm(shoulder angle, arm angle, biceps angle,
* Elbow angle, wrist angle) -1 mean "no change"
* @param shoulderAngle s
* @param armAngle a
* @param bicepsAngle b
* @param ElbowAngle f
* @param wristAngle w
*/
public void setRightArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) {
// TODO protect against self collision
if (shoulderAngle == -1) {
shoulderAngle = rightShoulderServo.getPos();
}
if (armAngle == -1) {
armAngle = rightArmServo.getPos();
}
if (bicepsAngle == -1) {
armAngle = rightBicepsServo.getPos();
}
if (ElbowAngle == -1) {
ElbowAngle = rightElbowServo.getPos();
}
if (wristAngle == -1) {
wristAngle = rightWristServo.getPos();
}
rightShoulderServo.moveTo(shoulderAngle);
rightArmServo.moveTo(armAngle);
rightBicepsServo.moveTo(bicepsAngle);
rightElbowServo.moveTo(ElbowAngle);
rightWristServo.moveTo(wristAngle);
}
/*
* Move the left arm . Use : setLeftArm(shoulder angle, arm angle, biceps angle, Elbow angle,
* Elbow angle,wrist angle) -1 mean "no change"
* @param shoulderAngle s
* @param armAngle a
* @param bicepsAngle b
* @param ElbowAngle f
* @param wristAngle w
*/
public void setLeftArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) {
// TODO protect against self collision with -> servoName.getPos()
if (shoulderAngle == -1) {
shoulderAngle = leftShoulderServo.getPos();
}
if (armAngle == -1) {
armAngle = leftArmServo.getPos();
}
if (bicepsAngle == -1) {
armAngle = leftBicepsServo.getPos();
}
if (ElbowAngle == -1) {
ElbowAngle = leftElbowServo.getPos();
}
if (wristAngle == -1) {
wristAngle = leftWristServo.getPos();
}
leftShoulderServo.moveTo(shoulderAngle);
leftArmServo.moveTo(armAngle);
leftBicepsServo.moveTo(bicepsAngle);
leftElbowServo.moveTo(ElbowAngle);
leftWristServo.moveTo(wristAngle);
}
/*
* Move the left hand . Use : setLeftHand(thumb angle, index angle, middle angle, ring angle,
* pinky angle) -1 mean "no change"
*/
public void setLeftHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) {
if (thumbAngle == -1) {
thumbAngle = leftThumbServo.getPos();
}
if (indexAngle == -1) {
indexAngle = leftIndexServo.getPos();
}
if (middleAngle == -1) {
middleAngle = leftMiddleServo.getPos();
}
if (ringAngle == -1) {
ringAngle = leftRingServo.getPos();
}
if (pinkyAngle == -1) {
pinkyAngle = leftPinkyServo.getPos();
}
leftThumbServo.moveTo(thumbAngle);
leftIndexServo.moveTo(indexAngle);
leftMiddleServo.moveTo(middleAngle);
leftRingServo.moveTo(ringAngle);
leftPinkyServo.moveTo(pinkyAngle);
}
/*
* Move the right hand . Use : setrightHand(thumb angle, index angle, middle angle, ring angle,
* pinky angle) -1 mean "no change"
*/
public void setRightHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) {
if (thumbAngle == -1) {
thumbAngle = rightThumbServo.getPos();
}
if (indexAngle == -1) {
indexAngle = rightIndexServo.getPos();
}
if (middleAngle == -1) {
middleAngle = rightMiddleServo.getPos();
}
if (ringAngle == -1) {
ringAngle = rightRingServo.getPos();
}
if (pinkyAngle == -1) {
pinkyAngle = rightPinkyServo.getPos();
}
rightThumbServo.moveTo(thumbAngle);
rightIndexServo.moveTo(indexAngle);
rightMiddleServo.moveTo(middleAngle);
rightRingServo.moveTo(ringAngle);
rightPinkyServo.moveTo(pinkyAngle);
}
/*
* Set the mouth attitude . choose : smile, notHappy, speechLess, empty.
*/
public void mouthState(String value) {
if (value == "smile") {
myShiftOut("11011100");
} else if (value == "notHappy") {
myShiftOut("00111110");
} else if (value == "speechLess") {
myShiftOut("10111100");
} else if (value == "empty") {
myShiftOut("00000000");
}
}
/*
* drive the motors . Speed > 0 go forward . Speed < 0 go backward . Direction
* > 0 go right . Direction < 0 go left
*/
public void moveMotors(int speed, int direction) {
int speedMin = 50; // min PWM needed for the motors
boolean isMoving = false;
int rightCurrentSpeed = 0;
int leftCurrentSpeed = 0;
if (speed < 0) { // Go backward
arduino.analogWrite(rightMotorDirPin, 0);
arduino.analogWrite(leftMotorDirPin, 0);
speed = speed * -1;
} else {// Go forward
arduino.analogWrite(rightMotorDirPin, 255);
arduino.analogWrite(leftMotorDirPin, 255);
}
if (direction > speedMin && speed > speedMin) {// move and turn to the
// right
if (isMoving) {
arduino.analogWrite(rightMotorPwmPin, direction);
arduino.analogWrite(leftMotorPwmPin, speed);
} else {
rightCurrentSpeed = speedMin;
leftCurrentSpeed = speedMin;
while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) {
if (rightCurrentSpeed < direction) {
rightCurrentSpeed++;
}
if (leftCurrentSpeed < speed) {
leftCurrentSpeed++;
}
arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed);
arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed);
sleep(20);
}
isMoving = true;
}
} else if (direction < (speedMin * -1) && speed > speedMin) {// move and
// turn
// to
// the
// left
direction *= -1;
if (isMoving) {
arduino.analogWrite(leftMotorPwmPin, direction);
arduino.analogWrite(rightMotorPwmPin, speed);
} else {
rightCurrentSpeed = speedMin;
leftCurrentSpeed = speedMin;
while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) {
if (rightCurrentSpeed < speed) {
rightCurrentSpeed++;
}
if (leftCurrentSpeed < direction) {
leftCurrentSpeed++;
}
arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed);
arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed);
sleep(20);
}
isMoving = true;
}
} else if (speed > speedMin) { // Go strait
if (isMoving) {
arduino.analogWrite(leftMotorPwmPin, speed);
arduino.analogWrite(rightMotorPwmPin, speed);
} else {
int CurrentSpeed = speedMin;
while (CurrentSpeed < speed) {
CurrentSpeed++;
arduino.analogWrite(rightMotorPwmPin, CurrentSpeed);
arduino.analogWrite(leftMotorPwmPin, CurrentSpeed);
sleep(20);
}
isMoving = true;
}
} else if (speed < speedMin && direction < speedMin * -1) {// turn left
arduino.analogWrite(rightMotorDirPin, 255);
arduino.analogWrite(leftMotorDirPin, 0);
arduino.analogWrite(leftMotorPwmPin, speedMin);
arduino.analogWrite(rightMotorPwmPin, speedMin);
}
else if (speed < speedMin && direction > speedMin) {// turn right
arduino.analogWrite(rightMotorDirPin, 0);
arduino.analogWrite(leftMotorDirPin, 255);
arduino.analogWrite(leftMotorPwmPin, speedMin);
arduino.analogWrite(rightMotorPwmPin, speedMin);
} else {// stop
arduino.analogWrite(leftMotorPwmPin, 0);
arduino.analogWrite(rightMotorPwmPin, 0);
isMoving = false;
}
}
/**
* Used to manage a shift register
*/
private void myShiftOut(String value) {
arduino.digitalWrite(LATCH, 0); // Stop the copy
for (int i = 0; i < 8; i++) { // Store the data
if (value.charAt(i) == '1') {
arduino.digitalWrite(DATA, 1);
} else {
arduino.digitalWrite(DATA, 0);
}
arduino.digitalWrite(SHIFT, 1);
arduino.digitalWrite(SHIFT, 0);
}
arduino.digitalWrite(LATCH, 1); // copy
}
/**
* Move the servos to show asked posture
* @param pos pos
*/
public void posture(String pos) {
if (pos == "rest") {
setLeftArmPosition(leftShoulder[rest], leftArm[rest], leftBiceps[rest], leftElbow[rest], leftWrist[rest]);
setRightArmPosition(rightShoulder[rest], rightArm[rest], rightBiceps[rest], rightElbow[rest], rightWrist[rest]);
setLeftHandPosition(leftThumb[rest], leftIndex[rest], leftMiddle[rest], leftRing[rest], leftPinky[rest]);
setRightHandPosition(rightThumb[rest], rightIndex[rest], rightMiddle[rest], rightRing[rest], rightPinky[rest]);
setHeadPosition(neckTilt[rest], neckPan[rest]);
}
/*
* Template else if (pos == ""){ setLeftArmPosition(, , , 85, 150);
* setRightArmPosition(, , , 116, 10); setHeadPosition(75, 127, 75); }
*/
// TODO correct angles for posture
else if (pos == "yes") {
setLeftArmPosition(0, 95, 136, 85, 150);
setRightArmPosition(155, 55, 5, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "concenter") {
setLeftArmPosition(37, 116, 85, 85, 150);
setRightArmPosition(109, 43, 54, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "showLeft") {
setLeftArmPosition(68, 63, 160, 85, 150);
setRightArmPosition(2, 76, 40, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "showRight") {
setLeftArmPosition(145, 79, 93, 85, 150);
setRightArmPosition(80, 110, 5, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "handsUp") {
setLeftArmPosition(0, 79, 93, 85, 150);
setRightArmPosition(155, 76, 40, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "carryBags") {
setLeftArmPosition(145, 79, 93, 85, 150);
setRightArmPosition(2, 76, 40, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
}
}
@Override
public Sweety publishState() {
super.publishState();
if (arduino != null)arduino.publishState();
if (rightShoulderServo != null)rightShoulderServo.publishState();
if (rightArmServo != null)rightArmServo.publishState();
if (rightBicepsServo != null) rightBicepsServo.publishState();
if (rightElbowServo != null) rightElbowServo.publishState();
if (rightWristServo != null)rightWristServo.publishState();
if (leftShoulderServo != null)leftShoulderServo.publishState();
if (leftArmServo != null)leftArmServo.publishState();
if (leftElbowServo != null)leftElbowServo.publishState();
if (leftBicepsServo != null)leftBicepsServo.publishState();
if (leftWristServo != null)leftWristServo.publishState();
if (rightThumbServo != null)rightThumbServo.publishState();
if (rightIndexServo != null)rightIndexServo.publishState();
if (rightMiddleServo != null)rightMiddleServo.publishState();
if (rightRingServo != null)rightRingServo.publishState();
if (rightPinkyServo != null)rightPinkyServo.publishState();
if (leftThumbServo != null)leftThumbServo.publishState();
if (leftIndexServo != null)leftIndexServo.publishState();
if (leftMiddleServo != null)leftMiddleServo.publishState();
if (leftRingServo != null)leftRingServo.publishState();
if (leftPinkyServo != null)leftPinkyServo.publishState();
if (neckTiltServo != null)neckTiltServo.publishState();
if (neckPanServo != null)neckPanServo.publishState();
return this;
}
/**
* Say text and move mouth leds
* @param text text being said
*/
public synchronized void saying(String text) { // Adapt mouth leds to words
log.info("Saying :" + text);
try {
mouth.speak(text);
} catch (Exception e) {
Logging.logError(e);
}
}
public synchronized void onStartSpeaking(String text) {
sleep(15);
boolean ison = false;
String testword;
String[] a = text.split(" ");
for (int w = 0; w < a.length; w++) {
testword = a[w];
char[] c = testword.toCharArray();
for (int x = 0; x < c.length; x++) {
char s = c[x];
if ((s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'y') && !ison) {
myShiftOut("00011100");
ison = true;
sleep(delaytime);
myShiftOut("00000100");
} else if (s == '.') {
ison = false;
myShiftOut("00000000");
sleep(delaytimestop);
} else {
ison = false;
sleep(delaytimeletter); //
}
}
}
}
public synchronized void onEndSpeaking(String utterance) {
myShiftOut("00000000");
}
public void setdelays(Integer d1, Integer d2, Integer d3) {
delaytime = d1;
delaytimestop = d2;
delaytimeletter = d3;
}
public void setLanguage(String lang){
this.lang = lang;
}
public void setVoice(String voice){
mouth.setVoice(voice);
}
@Override
public void startService() {
super.startService();
arduino = (Arduino) Runtime.start("arduino","Arduino");
adaFruit16cLeft = (Adafruit16CServoDriver) Runtime.start("I2cServoControlLeft","Adafruit16CServoDriver");
adaFruit16cRight = (Adafruit16CServoDriver) Runtime.start("I2cServoControlRight","Adafruit16CServoDriver");
chatBot = (ProgramAB) Runtime.start("chatBot","ProgramAB");
htmlFilter = (HtmlFilter) Runtime.start("htmlFilter","HtmlFilter");
mouth = (MarySpeech) Runtime.start("mouth","MarySpeech");
ear = (WebkitSpeechRecognition) Runtime.start("ear","WebkitSpeechRecognition");
webGui = (WebGui) Runtime.start("webGui","WebGui");
pir = (Pir) Runtime.start("pir","Pir");
// configure services
pir.attach(arduino,pirSensorPin );
// FIXME - there is likely an "attach" that does this...
subscribe(mouth.getName(), "publishStartSpeaking");
subscribe(mouth.getName(), "publishEndSpeaking");
}
public void startServos() {
rightShoulderServo = (Servo) Runtime.start("rightShoulderServo","Servo");
rightArmServo = (Servo) Runtime.start("rightArmServo","Servo");
rightBicepsServo = (Servo) Runtime.start("rightBicepsServo","Servo");
rightElbowServo = (Servo) Runtime.start("rightElbowServo","Servo");
rightWristServo = (Servo) Runtime.start("rightWristServo","Servo");
leftShoulderServo = (Servo) Runtime.start("leftShoulderServo","Servo");
leftArmServo = (Servo) Runtime.start("leftArmServo","Servo");
leftBicepsServo = (Servo) Runtime.start("leftBicepsServo","Servo");
leftElbowServo = (Servo) Runtime.start("leftElbowServo","Servo");
leftWristServo = (Servo) Runtime.start("leftWristServo","Servo");
rightThumbServo = (Servo) Runtime.start("rightThumbServo","Servo");
rightIndexServo = (Servo) Runtime.start("rightIndexServo","Servo");
rightMiddleServo = (Servo) Runtime.start("rightMiddleServo","Servo");
rightRingServo = (Servo) Runtime.start("rightRingServo","Servo");
rightPinkyServo = (Servo) Runtime.start("rightPinkyServo","Servo");
leftThumbServo = (Servo) Runtime.start("leftThumbServo","Servo");
leftIndexServo = (Servo) Runtime.start("leftIndexServo","Servo");
leftMiddleServo = (Servo) Runtime.start("leftMiddleServo","Servo");
leftRingServo = (Servo) Runtime.start("leftRingServo","Servo");
leftPinkyServo = (Servo) Runtime.start("leftPinkyServo","Servo");
neckTiltServo = (Servo) Runtime.start("neckTiltServo","Servo");
neckPanServo = (Servo) Runtime.start("neckPanServo","Servo");
// Set min and max angle for each servos
rightShoulderServo.setMinMax(rightShoulder[min], rightShoulder[max]);
rightArmServo.setMinMax(rightArm[min], rightArm[max]);
rightBicepsServo.setMinMax(rightBiceps[min], rightBiceps[max]);
rightElbowServo.setMinMax(rightElbow[min], rightElbow[max]);
rightWristServo.setMinMax(rightWrist[min], rightWrist[max]);
leftShoulderServo.setMinMax(leftShoulder[min], leftShoulder[max]);
leftArmServo.setMinMax(leftArm[min], leftArm[max]);
leftBicepsServo.setMinMax(leftBiceps[min], leftBiceps[max]);
leftElbowServo.setMinMax(leftElbow[min], leftElbow[max]);
leftWristServo.setMinMax(leftWrist[min], leftWrist[max]);
rightThumbServo.setMinMax(rightThumb[min], rightThumb[max]);
rightIndexServo.setMinMax(rightIndex[min], rightIndex[max]);
rightMiddleServo.setMinMax(rightMiddle[min], rightMiddle[max]);
rightRingServo.setMinMax(rightRing[min], rightRing[max]);
rightPinkyServo.setMinMax(rightPinky[min], rightPinky[max]);
leftThumbServo.setMinMax(leftThumb[min], leftThumb[max]);
leftIndexServo.setMinMax(leftIndex[min], leftIndex[max]);
leftMiddleServo.setMinMax(leftMiddle[min], leftMiddle[max]);
leftRingServo.setMinMax(leftRing[min], leftRing[max]);
leftPinkyServo.setMinMax(leftPinky[min], leftPinky[max]);
neckTiltServo.setMinMax(neckTilt[min], neckTilt[max]);
neckPanServo.setMinMax(neckPan[min], neckPan[max]);
// Set rest for each servos
rightShoulderServo.setRest(rightShoulder[rest]);
rightArmServo.setRest(rightArm[rest]);
rightBicepsServo.setRest(rightBiceps[rest]);
rightElbowServo.setRest(rightElbow[rest]);
rightWristServo.setRest(rightWrist[rest]);
leftShoulderServo.setRest(leftShoulder[rest]);
leftArmServo.setRest(leftArm[rest]);
leftBicepsServo.setRest(leftBiceps[rest]);
leftElbowServo.setRest(leftElbow[rest]);
leftWristServo.setRest(leftWrist[rest]);
rightThumbServo.setRest(rightThumb[rest]);
rightIndexServo.setRest(rightIndex[rest]);
rightMiddleServo.setRest(rightMiddle[rest]);
rightRingServo.setRest(rightRing[rest]);
rightPinkyServo.setRest(rightPinky[rest]);
leftThumbServo.setRest(leftThumb[rest]);
leftIndexServo.setRest(leftIndex[rest]);
leftMiddleServo.setRest(leftMiddle[rest]);
leftRingServo.setRest(leftRing[rest]);
leftPinkyServo.setRest(leftPinky[rest]);
neckTiltServo.setRest(neckTilt[rest]);
neckPanServo.setRest(neckPan[rest]);
setVelocity(75);
}
void setVelocity(int value) {
rightShoulderServo.setVelocity(value);
rightArmServo.setVelocity(value);
rightBicepsServo.setVelocity(value);
rightElbowServo.setVelocity(value);
rightWristServo.setVelocity(value);
leftShoulderServo.setVelocity(value);
leftArmServo.setVelocity(value);
leftBicepsServo.setVelocity(value);
leftElbowServo.setVelocity(value);
leftWristServo.setVelocity(value);
rightThumbServo.setVelocity(value);
rightIndexServo.setVelocity(value);
rightMiddleServo.setVelocity(value);
rightRingServo.setVelocity(value);
rightPinkyServo.setVelocity(value);
leftThumbServo.setVelocity(value);
leftIndexServo.setVelocity(value);
leftMiddleServo.setVelocity(value);
leftRingServo.setVelocity(value);
leftPinkyServo.setVelocity(value);
neckTiltServo.setVelocity(value);
neckPanServo.setVelocity(value);
}
/**
* Start the tracking services
*/
public void startTrack() throws Exception {
tracker = (Tracking) Runtime.start("tracker","Tracking");
sleep(1000);
tracker.connect(tracker.getOpenCV(),neckPanServo ,neckTiltServo);
//tracker.pid.invert("y");
//tracker.clearPreFilters();
}
/**
* Start the ultrasonic sensors services
* @param port port
* @throws Exception e
*/
public void startUltraSonic(String port) throws Exception {
USfront = (UltrasonicSensor) Runtime.start("USfront","UltrasonicSensor");
USfrontRight = (UltrasonicSensor) Runtime.start("USfrontRight","UltrasonicSensor");
USfrontLeft = (UltrasonicSensor) Runtime.start("USfrontLeft","UltrasonicSensor");
USback = (UltrasonicSensor) Runtime.start("USback","UltrasonicSensor");
USbackRight = (UltrasonicSensor) Runtime.start("USbackRight","UltrasonicSensor");
USbackLeft = (UltrasonicSensor) Runtime.start("USbackLeft","UltrasonicSensor");
USfront.attach(arduino, frontUltrasonicTrig, frontUltrasonicEcho);
USfrontRight.attach(arduino, front_rightUltrasonicTrig, front_rightUltrasonicEcho);
USfrontLeft.attach(arduino, front_leftUltrasonicTrig, front_leftUltrasonicEcho);
USback.attach(arduino, backUltrasonicTrig, backUltrasonicEcho);
USbackRight.attach(arduino, back_rightUltrasonicTrig, back_rightUltrasonicEcho);
USbackLeft.attach(arduino, back_leftUltrasonicTrig, back_leftUltrasonicEcho);
}
/**
* Stop the tracking services
* @throws Exception e
*/
public void stopTrack() throws Exception {
tracker.opencv.stopCapture();
tracker.releaseService();
}
public OpenNi startOpenNI() throws Exception {
// TODO modify this function to fit new sweety
/*
* Start the Kinect service
*/
if (openni == null) {
System.out.println("starting kinect");
openni = (OpenNi) Runtime.start("openni","OpenNi");
pid = (Pid) Runtime.start("pid","Pid");
pid.setMode("kinect", Pid.MODE_AUTOMATIC);
pid.setOutputRange("kinect", -1, 1);
pid.setPID("kinect", 10.0, 0.0, 1.0);
pid.setControllerDirection("kinect", 0);
// re-mapping of skeleton !
// openni.skeleton.leftElbow.mapXY(0, 180, 180, 0);
openni.skeleton.rightElbow.mapXY(0, 180, 180, 0);
// openni.skeleton.leftShoulder.mapYZ(0, 180, 180, 0);
openni.skeleton.rightShoulder.mapYZ(0, 180, 180, 0);
openni.skeleton.leftShoulder.mapXY(0, 180, 180, 0);
// openni.skeleton.rightShoulder.mapXY(0, 180, 180, 0);
openni.addListener("publishOpenNIData", this.getName(), "onOpenNIData");
// openni.addOpenNIData(this);
}
return openni;
}
public boolean copyGesture(boolean b) throws Exception {
log.info("copyGesture {}", b);
if (b) {
if (openni == null) {
openni = startOpenNI();
}
System.out.println("copying gestures");
openni.startUserTracking();
} else {
System.out.println("stop copying gestures");
if (openni != null) {
openni.stopCapture();
firstSkeleton = true;
}
}
copyGesture = b;
return b;
}
public String captureGesture() {
return captureGesture(null);
}
public String captureGesture(String gestureName) {
StringBuffer script = new StringBuffer();
String indentSpace = "";
if (gestureName != null) {
indentSpace = " ";
script.append(String.format("def %s():\n", gestureName));
}
script.append(indentSpace);
script.append(
String.format("Sweety.setRightArmPosition(%d,%d,%d,%d,%d)\n", rightShoulderServo.getPos(), rightArmServo.getPos(), rightBicepsServo.getPos(), rightElbowServo.getPos(), rightWristServo.getPos()));
script.append(indentSpace);
script
.append(String.format("Sweety.setLeftArmPosition(%d,%d,%d,%d,%d)\n", leftShoulderServo.getPos(), leftArmServo.getPos(), leftBicepsServo.getPos(), leftElbowServo.getPos(), leftWristServo.getPos()));
script.append(indentSpace);
script.append(String.format("Sweety.setHeadPosition(%d,%d)\n", neckTiltServo.getPos(), neckPanServo.getPos()));
send("python", "appendScript", script.toString());
return script.toString();
}
public void onOpenNIData(OpenNiData data) {
Skeleton skeleton = data.skeleton;
if (firstSkeleton) {
System.out.println("i see you");
firstSkeleton = false;
}
// TODO adapt for new design
int LElbow = Math.round(skeleton.leftElbow.getAngleXY()) - (180 - leftElbow[max]);
int Larm = Math.round(skeleton.leftShoulder.getAngleXY()) - (180 - leftArm[max]);
int Lshoulder = Math.round(skeleton.leftShoulder.getAngleYZ()) + leftShoulder[min];
int RElbow = Math.round(skeleton.rightElbow.getAngleXY()) + rightElbow[min];
int Rarm = Math.round(skeleton.rightShoulder.getAngleXY()) + rightArm[min];
int Rshoulder = Math.round(skeleton.rightShoulder.getAngleYZ()) - (180 - rightShoulder[max]);
// Move the left side
setLeftArmPosition(Lshoulder, Larm, LElbow, -1, -1);
// Move the right side
setRightArmPosition(Rshoulder, Rarm, RElbow, -1, -1);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, and dependencies
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Sweety.class.getCanonicalName());
meta.addDescription("service for the Sweety robot");
meta.addCategory("robot");
return meta;
}
}
| src/main/java/org/myrobotlab/service/Sweety.java | package org.myrobotlab.service;
import java.io.IOException;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.Logging;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.openni.OpenNiData;
import org.myrobotlab.openni.Skeleton;
import org.slf4j.Logger;
// TODO set pir sensor
/**
*
* Sweety - The sweety robot service. Maintained by \@beetlejuice
*
*/
public class Sweety extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Sweety.class);
transient public Arduino arduino;
transient public Adafruit16CServoDriver adaFruit16cRight;
transient public Adafruit16CServoDriver adaFruit16cLeft;
transient public WebkitSpeechRecognition ear;
transient public WebGui webGui;
transient public MarySpeech mouth;
transient public static Tracking tracker;
transient public ProgramAB chatBot;
transient public static OpenNi openni;
transient public Pid pid;
transient public Pir pir;
transient public HtmlFilter htmlFilter;
// Right arm Servomotors
transient public Servo rightShoulderServo;
transient public Servo rightArmServo;
transient public Servo rightBicepsServo;
transient public Servo rightElbowServo;
transient public Servo rightWristServo;
// Left arm Servomotors
transient public Servo leftShoulderServo;
transient public Servo leftArmServo;
transient public Servo leftBicepsServo;
transient public Servo leftElbowServo;
transient public Servo leftWristServo;
// Right hand Servomotors
transient public Servo rightThumbServo;
transient public Servo rightIndexServo;
transient public Servo rightMiddleServo;
transient public Servo rightRingServo;
transient public Servo rightPinkyServo;
// Left hand Servomotors
transient public Servo leftThumbServo;
transient public Servo leftIndexServo;
transient public Servo leftMiddleServo;
transient public Servo leftRingServo;
transient public Servo leftPinkyServo;
// Head Servomotors
transient public Servo neckTiltServo;
transient public Servo neckPanServo;
// Ultrasonic sensors
transient public UltrasonicSensor USfront;
transient public UltrasonicSensor USfrontRight;
transient public UltrasonicSensor USfrontLeft;
transient public UltrasonicSensor USback;
transient public UltrasonicSensor USbackRight;
transient public UltrasonicSensor USbackLeft;
boolean copyGesture = false;
boolean firstSkeleton = true;
boolean saveSkeletonFrame = false;
// Adafruit16CServoDriver setup
String i2cBus = "0";
String i2cAdressRight = "0x40";
String i2cAdressLeft = "0x41";
// arduino pins variables
int rightMotorDirPin = 2;
int rightMotorPwmPin = 3;
int leftMotorDirPin = 4;
int leftMotorPwmPin = 5;
int backUltrasonicTrig = 22;
int backUltrasonicEcho = 23;
int back_leftUltrasonicTrig = 24;
int back_leftUltrasonicEcho = 25;
int back_rightUltrasonicTrig = 26;
int back_rightUltrasonicEcho = 27;
int front_leftUltrasonicTrig = 28;
int front_leftUltrasonicEcho = 29;
int frontUltrasonicTrig = 30;
int frontUltrasonicEcho = 31;
int front_rightUltrasonicTrig = 32;
int front_rightUltrasonicEcho = 33;
int SHIFT = 14;
int LATCH = 15;
int DATA = 16;
int pirSensorPin = 17;
int pin = 0;
int min = 1;
int max = 2;
int rest = 3;
// for arms and hands, the values are pin,min,max,rest
//Right arm
int rightShoulder[] = {34,0,180,0};
int rightArm[] = {1,45,155,140};
int rightBiceps[] = {2,12,90,12};
int rightElbow[] = {3,8,90,8};
int rightWrist[] = {4,0,140,140};
// Left arm
int leftShoulder[] = {35,0,150,148};
int leftArm[] = {1,0,85,0};
int leftBiceps[] = {2,60,140,140};
int leftElbow[] = {3,0,75,0};
int leftWrist[] = {4,0,168,0};
// Right hand
int rightThumb[] = {5,170,75,170};
int rightIndex[] = {6,70,180,180};
int rightMiddle[] = {7,1,2,3};
int rightRing[] = {8,15,130,15};
int rightPinky[] = {9,25,180,25};
// Left hand
int leftThumb[] = {5,40,105,40};
int leftIndex[] = {6,0,180,0};
int leftMiddle[] = {7,0,180,0};
int leftRing[] = {8,10,180,180};
int leftPinky[] = {9,65,180,180};
// Head
int neckTilt[] = {6,15,50,30};
int neckPan[] = {7,20,130,75};
/**
* Replace the values of an array , if a value == -1 the old value is keep
* Exemple if rightArm[]={35,1,2,3} and user ask to change by {-1,1,2,3}, this method will return {35,1,2,3}
* This method must receive an array of ten arrays.
* If one of these arrays is less or more than four numbers length , it doesn't will be changed.
*/
int[][] changeArrayValues(int[][] valuesArray){
// valuesArray contain first the news values and after, the old values
for (int i = 0; i < (valuesArray.length / 2 ); i++) {
if (valuesArray[i].length ==4 ){
for (int j = 0; j < 3; j++) {
if (valuesArray[i][j] == -1){
valuesArray[i][j] = valuesArray[i+5][j];
}
}
}
else{
valuesArray[i]=valuesArray[i+(valuesArray.length / 2 )];
}
}
return valuesArray;
}
/**
* Set pin, min, max, and rest for each servos. -1 in an array mean "no change"
* Exemple setRightArm({39,1,2,3},{40,1,2,3},{41,1,2,3},{-1,1,2,3},{-1,1,2,3})
* Python exemple : sweety.setRightArm([1,0,180,90],[2,0,180,0],[3,180,90,90],[7,7,4,4],[8,5,8,1])
*/
public void setRightArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){
int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,rightShoulder,rightArm,rightBiceps,rightElbow,rightWrist};
valuesArray = changeArrayValues(valuesArray);
rightShoulder = valuesArray[0];
rightArm = valuesArray[1];
rightBiceps = valuesArray[2];
rightElbow = valuesArray[3];
rightWrist = valuesArray[4];
}
/**
* Same as setRightArm
*/
public void setLefttArm(int[] shoulder, int[] arm, int[] biceps, int[] elbow, int[] wrist){
int[][] valuesArray = new int[][]{shoulder, arm, biceps, elbow,wrist,leftShoulder,leftArm,leftBiceps,leftElbow,leftWrist};
valuesArray = changeArrayValues(valuesArray);
leftShoulder = valuesArray[0];
leftArm = valuesArray[1];
leftBiceps = valuesArray[2];
leftElbow = valuesArray[3];
leftWrist = valuesArray[4];
}
/**
* Same as setRightArm
*/
public void setLeftHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){
int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, leftThumb, leftIndex, leftMiddle, leftRing, leftPinky};
valuesArray = changeArrayValues(valuesArray);
leftThumb = valuesArray[0];
leftIndex = valuesArray[1];
leftMiddle = valuesArray[2];
leftRing = valuesArray[3];
leftPinky = valuesArray[4];
}
/**
* Same as setRightArm
*/
public void setRightHand(int[] thumb, int[] index, int[] middle, int[] ring, int[] pinky){
int[][] valuesArray = new int[][]{thumb, index, middle, ring, pinky, rightThumb, rightIndex, rightMiddle, rightRing, rightPinky};
valuesArray = changeArrayValues(valuesArray);
rightThumb = valuesArray[0];
rightIndex = valuesArray[1];
rightMiddle = valuesArray[2];
rightRing = valuesArray[3];
rightPinky = valuesArray[4];
}
/**
* Set pin, min, max, and rest for head tilt and pan . -1 in an array mean "no change"
* Exemple setHead({39,1,2,3},{40,1,2,3})
* Python exemple : sweety.setHead([1,0,180,90],[2,0,180,0])
*/
public void setHead(int[] tilt, int[] pan){
int[][] valuesArray = new int[][]{tilt, pan,neckTilt,neckPan};
valuesArray = changeArrayValues(valuesArray);
neckTilt = valuesArray[0];
neckPan = valuesArray[1];
}
// set Adafruit16CServoDriver setup
public void setadafruitServoDriver(String i2cBusValue, String i2cAdressRightValue, String i2cAdressLeftValue) {
i2cBus = i2cBusValue;
i2cAdressRight = i2cAdressRightValue;
i2cAdressLeft = i2cAdressLeftValue;
}
// variables for speak / mouth sync
public int delaytime = 3;
public int delaytimestop = 5;
public int delaytimeletter = 1;
String lang;
public static void main(String[] args) {
LoggingFactory.init(Level.INFO);
try {
Runtime.start("sweety", "Sweety");
} catch (Exception e) {
Logging.logError(e);
}
}
public Sweety(String n) {
super(n);
}
/**
* Attach the servos to arduino and adafruitServoDriver pins
* @throws Exception e
*/
public void attach() throws Exception {
adaFruit16cLeft.attach("arduino",i2cBus,i2cAdressLeft);
adaFruit16cRight.attach("arduino",i2cBus,i2cAdressRight);
rightElbowServo.attach(adaFruit16cRight, rightElbow[pin]);
rightShoulderServo.attach(adaFruit16cRight, rightShoulder[pin]);
rightArmServo.attach(adaFruit16cRight, rightArm[pin]);
rightBicepsServo.attach(adaFruit16cRight, rightBiceps[pin]);
rightElbowServo.attach(adaFruit16cRight, rightElbow[pin]);
rightWristServo.attach(adaFruit16cRight, rightWrist[pin]);
leftShoulderServo.attach(adaFruit16cLeft, leftShoulder[pin]);
leftArmServo.attach(adaFruit16cLeft, leftArm[pin]);
leftBicepsServo.attach(adaFruit16cLeft, leftBiceps[pin]);
leftElbowServo.attach(adaFruit16cLeft, leftElbow[pin]);
leftWristServo.attach(adaFruit16cLeft, leftWrist[pin]);
rightThumbServo.attach(adaFruit16cRight, rightThumb[pin]);
rightIndexServo.attach(adaFruit16cRight, rightIndex[pin]);
rightMiddleServo.attach(adaFruit16cRight, rightMiddle[pin]);
rightRingServo.attach(adaFruit16cRight, rightRing[pin]);
rightPinkyServo.attach(adaFruit16cRight, rightPinky[pin]);
leftThumbServo.attach(adaFruit16cLeft, leftThumb[pin]);
leftIndexServo.attach(adaFruit16cLeft, leftIndex[pin]);
leftMiddleServo.attach(adaFruit16cLeft, leftMiddle[pin]);
leftRingServo.attach(adaFruit16cLeft, leftRing[pin]);
leftPinkyServo.attach(adaFruit16cLeft, leftPinky[pin]);
neckTiltServo.attach(arduino, neckTilt[pin]);
neckPanServo.attach(arduino, neckPan[pin]);
// Inverted servos
neckTiltServo.setInverted(true);
}
/**
* Connect the arduino to a COM port . Exemple : connect("COM8")
* @param port port
* @throws IOException e
*/
public void connect(String port) throws IOException {
arduino.connect(port);
sleep(2000);
arduino.pinMode(SHIFT, Arduino.OUTPUT);
arduino.pinMode(LATCH, Arduino.OUTPUT);
arduino.pinMode(DATA, Arduino.OUTPUT);
arduino.pinMode(pirSensorPin, Arduino.INPUT);
}
/**
* detach the servos from arduino pins
*/
public void detach() {
if (rightElbowServo != null)
rightElbowServo.detach();
if (rightShoulderServo != null)
rightShoulderServo.detach();
if (rightArmServo != null)
rightArmServo.detach();
if (rightBicepsServo != null)
rightBicepsServo.detach();
if (rightElbowServo != null)
rightElbowServo.detach();
if (rightWristServo != null)
rightWristServo.detach();
if (leftShoulderServo != null)
leftShoulderServo.detach();
if (leftShoulderServo != null)
leftShoulderServo.detach();
if (leftBicepsServo != null)
leftBicepsServo.detach();
if (leftElbowServo != null)
leftElbowServo.detach();
if (leftWristServo != null)
leftWristServo.detach();
if (rightThumbServo != null)
rightThumbServo.detach();
if (rightIndexServo != null)
rightIndexServo.detach();
if (rightMiddleServo != null)
rightMiddleServo.detach();
if (rightRingServo != null)
rightRingServo.detach();
if (rightPinkyServo != null)
rightPinkyServo.detach();
if (leftThumbServo != null)
leftThumbServo.detach();
if (leftIndexServo != null)
leftIndexServo.detach();
if (leftMiddleServo != null)
leftMiddleServo.detach();
if (leftRingServo != null)
leftRingServo.detach();
if (leftPinkyServo != null)
leftPinkyServo.detach();
if (neckTiltServo != null)
neckTiltServo.detach();
if (neckPanServo != null)
neckPanServo.detach();
}
/**
* Move the head . Use : head(neckTiltAngle, neckPanAngle -1 mean
* "no change"
* @param neckTiltAngle tilt
* @param neckPanAngle pan
*/
public void setHeadPosition(double neckTiltAngle, double neckPanAngle) {
if (neckTiltAngle == -1) {
neckTiltAngle = neckTiltServo.getPos();
}
if (neckPanAngle == -1) {
neckPanAngle = neckPanServo.getPos();
}
neckTiltServo.moveTo(neckTiltAngle);
neckPanServo.moveTo(neckPanAngle);
}
/**
* Move the right arm . Use : setRightArm(shoulder angle, arm angle, biceps angle,
* Elbow angle, wrist angle) -1 mean "no change"
* @param shoulderAngle s
* @param armAngle a
* @param bicepsAngle b
* @param ElbowAngle f
* @param wristAngle w
*/
public void setRightArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) {
// TODO protect against self collision
if (shoulderAngle == -1) {
shoulderAngle = rightShoulderServo.getPos();
}
if (armAngle == -1) {
armAngle = rightArmServo.getPos();
}
if (bicepsAngle == -1) {
armAngle = rightBicepsServo.getPos();
}
if (ElbowAngle == -1) {
ElbowAngle = rightElbowServo.getPos();
}
if (wristAngle == -1) {
wristAngle = rightWristServo.getPos();
}
rightShoulderServo.moveTo(shoulderAngle);
rightArmServo.moveTo(armAngle);
rightBicepsServo.moveTo(bicepsAngle);
rightElbowServo.moveTo(ElbowAngle);
rightWristServo.moveTo(wristAngle);
}
/*
* Move the left arm . Use : setLeftArm(shoulder angle, arm angle, biceps angle, Elbow angle,
* Elbow angle,wrist angle) -1 mean "no change"
* @param shoulderAngle s
* @param armAngle a
* @param bicepsAngle b
* @param ElbowAngle f
* @param wristAngle w
*/
public void setLeftArmPosition(double shoulderAngle, double armAngle, double bicepsAngle, double ElbowAngle, double wristAngle) {
// TODO protect against self collision with -> servoName.getPos()
if (shoulderAngle == -1) {
shoulderAngle = leftShoulderServo.getPos();
}
if (armAngle == -1) {
armAngle = leftArmServo.getPos();
}
if (bicepsAngle == -1) {
armAngle = leftBicepsServo.getPos();
}
if (ElbowAngle == -1) {
ElbowAngle = leftElbowServo.getPos();
}
if (wristAngle == -1) {
wristAngle = leftWristServo.getPos();
}
leftShoulderServo.moveTo(shoulderAngle);
leftArmServo.moveTo(armAngle);
leftBicepsServo.moveTo(bicepsAngle);
leftElbowServo.moveTo(ElbowAngle);
leftWristServo.moveTo(wristAngle);
}
/*
* Move the left hand . Use : setLeftHand(thumb angle, index angle, middle angle, ring angle,
* pinky angle) -1 mean "no change"
*/
public void setLeftHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) {
if (thumbAngle == -1) {
thumbAngle = leftThumbServo.getPos();
}
if (indexAngle == -1) {
indexAngle = leftIndexServo.getPos();
}
if (middleAngle == -1) {
middleAngle = leftMiddleServo.getPos();
}
if (ringAngle == -1) {
ringAngle = leftRingServo.getPos();
}
if (pinkyAngle == -1) {
pinkyAngle = leftPinkyServo.getPos();
}
leftThumbServo.moveTo(thumbAngle);
leftIndexServo.moveTo(indexAngle);
leftMiddleServo.moveTo(middleAngle);
leftRingServo.moveTo(ringAngle);
leftPinkyServo.moveTo(pinkyAngle);
}
/*
* Move the right hand . Use : setrightHand(thumb angle, index angle, middle angle, ring angle,
* pinky angle) -1 mean "no change"
*/
public void setRightHandPosition(double thumbAngle, double indexAngle, double middleAngle, double ringAngle, double pinkyAngle) {
if (thumbAngle == -1) {
thumbAngle = rightThumbServo.getPos();
}
if (indexAngle == -1) {
indexAngle = rightIndexServo.getPos();
}
if (middleAngle == -1) {
middleAngle = rightMiddleServo.getPos();
}
if (ringAngle == -1) {
ringAngle = rightRingServo.getPos();
}
if (pinkyAngle == -1) {
pinkyAngle = rightPinkyServo.getPos();
}
rightThumbServo.moveTo(thumbAngle);
rightIndexServo.moveTo(indexAngle);
rightMiddleServo.moveTo(middleAngle);
rightRingServo.moveTo(ringAngle);
rightPinkyServo.moveTo(pinkyAngle);
}
/*
* Set the mouth attitude . choose : smile, notHappy, speechLess, empty.
*/
public void mouthState(String value) {
if (value == "smile") {
myShiftOut("11011100");
} else if (value == "notHappy") {
myShiftOut("00111110");
} else if (value == "speechLess") {
myShiftOut("10111100");
} else if (value == "empty") {
myShiftOut("00000000");
}
}
/*
* drive the motors . Speed > 0 go forward . Speed < 0 go backward . Direction
* > 0 go right . Direction < 0 go left
*/
public void moveMotors(int speed, int direction) {
int speedMin = 50; // min PWM needed for the motors
boolean isMoving = false;
int rightCurrentSpeed = 0;
int leftCurrentSpeed = 0;
if (speed < 0) { // Go backward
arduino.analogWrite(rightMotorDirPin, 0);
arduino.analogWrite(leftMotorDirPin, 0);
speed = speed * -1;
} else {// Go forward
arduino.analogWrite(rightMotorDirPin, 255);
arduino.analogWrite(leftMotorDirPin, 255);
}
if (direction > speedMin && speed > speedMin) {// move and turn to the
// right
if (isMoving) {
arduino.analogWrite(rightMotorPwmPin, direction);
arduino.analogWrite(leftMotorPwmPin, speed);
} else {
rightCurrentSpeed = speedMin;
leftCurrentSpeed = speedMin;
while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) {
if (rightCurrentSpeed < direction) {
rightCurrentSpeed++;
}
if (leftCurrentSpeed < speed) {
leftCurrentSpeed++;
}
arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed);
arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed);
sleep(20);
}
isMoving = true;
}
} else if (direction < (speedMin * -1) && speed > speedMin) {// move and
// turn
// to
// the
// left
direction *= -1;
if (isMoving) {
arduino.analogWrite(leftMotorPwmPin, direction);
arduino.analogWrite(rightMotorPwmPin, speed);
} else {
rightCurrentSpeed = speedMin;
leftCurrentSpeed = speedMin;
while (rightCurrentSpeed < speed && leftCurrentSpeed < direction) {
if (rightCurrentSpeed < speed) {
rightCurrentSpeed++;
}
if (leftCurrentSpeed < direction) {
leftCurrentSpeed++;
}
arduino.analogWrite(rightMotorPwmPin, rightCurrentSpeed);
arduino.analogWrite(leftMotorPwmPin, leftCurrentSpeed);
sleep(20);
}
isMoving = true;
}
} else if (speed > speedMin) { // Go strait
if (isMoving) {
arduino.analogWrite(leftMotorPwmPin, speed);
arduino.analogWrite(rightMotorPwmPin, speed);
} else {
int CurrentSpeed = speedMin;
while (CurrentSpeed < speed) {
CurrentSpeed++;
arduino.analogWrite(rightMotorPwmPin, CurrentSpeed);
arduino.analogWrite(leftMotorPwmPin, CurrentSpeed);
sleep(20);
}
isMoving = true;
}
} else if (speed < speedMin && direction < speedMin * -1) {// turn left
arduino.analogWrite(rightMotorDirPin, 255);
arduino.analogWrite(leftMotorDirPin, 0);
arduino.analogWrite(leftMotorPwmPin, speedMin);
arduino.analogWrite(rightMotorPwmPin, speedMin);
}
else if (speed < speedMin && direction > speedMin) {// turn right
arduino.analogWrite(rightMotorDirPin, 0);
arduino.analogWrite(leftMotorDirPin, 255);
arduino.analogWrite(leftMotorPwmPin, speedMin);
arduino.analogWrite(rightMotorPwmPin, speedMin);
} else {// stop
arduino.analogWrite(leftMotorPwmPin, 0);
arduino.analogWrite(rightMotorPwmPin, 0);
isMoving = false;
}
}
/**
* Used to manage a shift register
*/
private void myShiftOut(String value) {
arduino.digitalWrite(LATCH, 0); // Stop the copy
for (int i = 0; i < 8; i++) { // Store the data
if (value.charAt(i) == '1') {
arduino.digitalWrite(DATA, 1);
} else {
arduino.digitalWrite(DATA, 0);
}
arduino.digitalWrite(SHIFT, 1);
arduino.digitalWrite(SHIFT, 0);
}
arduino.digitalWrite(LATCH, 1); // copy
}
/**
* Move the servos to show asked posture
* @param pos pos
*/
public void posture(String pos) {
if (pos == "rest") {
setLeftArmPosition(leftShoulder[rest], leftArm[rest], leftBiceps[rest], leftElbow[rest], leftWrist[rest]);
setRightArmPosition(rightShoulder[rest], rightArm[rest], rightBiceps[rest], rightElbow[rest], rightWrist[rest]);
setLeftHandPosition(leftThumb[rest], leftIndex[rest], leftMiddle[rest], leftRing[rest], leftPinky[rest]);
setRightHandPosition(rightThumb[rest], rightIndex[rest], rightMiddle[rest], rightRing[rest], rightPinky[rest]);
setHeadPosition(neckTilt[rest], neckPan[rest]);
}
/*
* Template else if (pos == ""){ setLeftArmPosition(, , , 85, 150);
* setRightArmPosition(, , , 116, 10); setHeadPosition(75, 127, 75); }
*/
// TODO correct angles for posture
else if (pos == "yes") {
setLeftArmPosition(0, 95, 136, 85, 150);
setRightArmPosition(155, 55, 5, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "concenter") {
setLeftArmPosition(37, 116, 85, 85, 150);
setRightArmPosition(109, 43, 54, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "showLeft") {
setLeftArmPosition(68, 63, 160, 85, 150);
setRightArmPosition(2, 76, 40, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "showRight") {
setLeftArmPosition(145, 79, 93, 85, 150);
setRightArmPosition(80, 110, 5, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "handsUp") {
setLeftArmPosition(0, 79, 93, 85, 150);
setRightArmPosition(155, 76, 40, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
} else if (pos == "carryBags") {
setLeftArmPosition(145, 79, 93, 85, 150);
setRightArmPosition(2, 76, 40, 116, 10);
setLeftHandPosition(-1, -1, -1, -1, -1);
setRightHandPosition(-1, -1, -1, -1, -1);
setHeadPosition(75, 85);
}
}
@Override
public Sweety publishState() {
super.publishState();
if (arduino != null)arduino.publishState();
if (rightShoulderServo != null)rightShoulderServo.publishState();
if (rightArmServo != null)rightArmServo.publishState();
if (rightBicepsServo != null) rightBicepsServo.publishState();
if (rightElbowServo != null) rightElbowServo.publishState();
if (rightWristServo != null)rightWristServo.publishState();
if (leftShoulderServo != null)leftShoulderServo.publishState();
if (leftArmServo != null)leftArmServo.publishState();
if (leftElbowServo != null)leftElbowServo.publishState();
if (leftBicepsServo != null)leftBicepsServo.publishState();
if (leftWristServo != null)leftWristServo.publishState();
if (rightThumbServo != null)rightThumbServo.publishState();
if (rightIndexServo != null)rightIndexServo.publishState();
if (rightMiddleServo != null)rightMiddleServo.publishState();
if (rightRingServo != null)rightRingServo.publishState();
if (rightPinkyServo != null)rightPinkyServo.publishState();
if (leftThumbServo != null)leftThumbServo.publishState();
if (leftIndexServo != null)leftIndexServo.publishState();
if (leftMiddleServo != null)leftMiddleServo.publishState();
if (leftRingServo != null)leftRingServo.publishState();
if (leftPinkyServo != null)leftPinkyServo.publishState();
if (neckTiltServo != null)neckTiltServo.publishState();
if (neckPanServo != null)neckPanServo.publishState();
return this;
}
/**
* Say text and move mouth leds
* @param text text being said
*/
public synchronized void saying(String text) { // Adapt mouth leds to words
log.info("Saying :" + text);
try {
mouth.speak(text);
} catch (Exception e) {
Logging.logError(e);
}
}
public synchronized void onStartSpeaking(String text) {
sleep(15);
boolean ison = false;
String testword;
String[] a = text.split(" ");
for (int w = 0; w < a.length; w++) {
testword = a[w];
char[] c = testword.toCharArray();
for (int x = 0; x < c.length; x++) {
char s = c[x];
if ((s == 'a' || s == 'e' || s == 'i' || s == 'o' || s == 'u' || s == 'y') && !ison) {
myShiftOut("00011100");
ison = true;
sleep(delaytime);
myShiftOut("00000100");
} else if (s == '.') {
ison = false;
myShiftOut("00000000");
sleep(delaytimestop);
} else {
ison = false;
sleep(delaytimeletter); //
}
}
}
}
public synchronized void onEndSpeaking(String utterance) {
myShiftOut("00000000");
}
public void setdelays(Integer d1, Integer d2, Integer d3) {
delaytime = d1;
delaytimestop = d2;
delaytimeletter = d3;
}
public void setLanguage(String lang){
this.lang = lang;
}
public void setVoice(String voice){
mouth.setVoice(voice);
}
@Override
public void startService() {
super.startService();
arduino = (Arduino) Runtime.start("arduino","Arduino");
adaFruit16cLeft = (Adafruit16CServoDriver) Runtime.start("I2cServoControlLeft","Adafruit16CServoDriver");
adaFruit16cRight = (Adafruit16CServoDriver) Runtime.start("I2cServoControlRight","Adafruit16CServoDriver");
chatBot = (ProgramAB) Runtime.start("chatBot","ProgramAB");
htmlFilter = (HtmlFilter) Runtime.start("htmlFilter","HtmlFilter");
mouth = (MarySpeech) Runtime.start("mouth","MarySpeech");
ear = (WebkitSpeechRecognition) Runtime.start("ear","WebkitSpeechRecognition");
webGui = (WebGui) Runtime.start("webGui","WebGui");
pir = (Pir) Runtime.start("pir","Pir");
// configure services
pir.attach(arduino,pirSensorPin );
// FIXME - there is likely an "attach" that does this...
subscribe(mouth.getName(), "publishStartSpeaking");
subscribe(mouth.getName(), "publishEndSpeaking");
}
public void startServos() {
rightShoulderServo = (Servo) Runtime.start("rightShoulderServo","Servo");
rightArmServo = (Servo) Runtime.start("rightArmServo","Servo");
rightBicepsServo = (Servo) Runtime.start("rightBicepsServo","Servo");
rightElbowServo = (Servo) Runtime.start("rightElbowServo","Servo");
rightWristServo = (Servo) Runtime.start("rightWristServo","Servo");
leftShoulderServo = (Servo) Runtime.start("leftShoulderServo","Servo");
leftArmServo = (Servo) Runtime.start("leftArmServo","Servo");
leftBicepsServo = (Servo) Runtime.start("leftBicepsServo","Servo");
leftElbowServo = (Servo) Runtime.start("leftElbowServo","Servo");
leftWristServo = (Servo) Runtime.start("leftWristServo","Servo");
rightThumbServo = (Servo) Runtime.start("rightThumbServo","Servo");
rightIndexServo = (Servo) Runtime.start("rightIndexServo","Servo");
rightMiddleServo = (Servo) Runtime.start("rightMiddleServo","Servo");
rightRingServo = (Servo) Runtime.start("rightRingServo","Servo");
rightPinkyServo = (Servo) Runtime.start("rightPinkyServo","Servo");
leftThumbServo = (Servo) Runtime.start("leftThumbServo","Servo");
leftIndexServo = (Servo) Runtime.start("leftIndexServo","Servo");
leftMiddleServo = (Servo) Runtime.start("leftMiddleServo","Servo");
leftRingServo = (Servo) Runtime.start("leftRingServo","Servo");
leftPinkyServo = (Servo) Runtime.start("leftPinkyServo","Servo");
neckTiltServo = (Servo) Runtime.start("neckTiltServo","Servo");
neckPanServo = (Servo) Runtime.start("neckPanServo","Servo");
// Set min and max angle for each servos
rightShoulderServo.setMinMax(rightShoulder[min], rightShoulder[max]);
rightArmServo.setMinMax(rightArm[min], rightArm[max]);
rightBicepsServo.setMinMax(rightBiceps[min], rightBiceps[max]);
rightElbowServo.setMinMax(rightElbow[min], rightElbow[max]);
rightWristServo.setMinMax(rightWrist[min], rightWrist[max]);
leftShoulderServo.setMinMax(leftShoulder[min], leftShoulder[max]);
leftArmServo.setMinMax(leftArm[min], leftArm[max]);
leftBicepsServo.setMinMax(leftBiceps[min], leftBiceps[max]);
leftElbowServo.setMinMax(leftElbow[min], leftElbow[max]);
leftWristServo.setMinMax(leftWrist[min], leftWrist[max]);
rightThumbServo.setMinMax(rightThumb[min], rightThumb[max]);
rightIndexServo.setMinMax(rightIndex[min], rightIndex[max]);
rightMiddleServo.setMinMax(rightMiddle[min], rightMiddle[max]);
rightRingServo.setMinMax(rightRing[min], rightRing[max]);
rightPinkyServo.setMinMax(rightPinky[min], rightPinky[max]);
leftThumbServo.setMinMax(leftThumb[min], leftThumb[max]);
leftIndexServo.setMinMax(leftIndex[min], leftIndex[max]);
leftMiddleServo.setMinMax(leftMiddle[min], leftMiddle[max]);
leftRingServo.setMinMax(leftRing[min], leftRing[max]);
leftPinkyServo.setMinMax(leftPinky[min], leftPinky[max]);
neckTiltServo.setMinMax(neckTilt[min], neckTilt[max]);
neckPanServo.setMinMax(neckPan[min], neckPan[max]);
// Set rest for each servos
rightShoulderServo.setRest(rightShoulder[rest]);
rightArmServo.setRest(rightArm[rest]);
rightBicepsServo.setRest(rightBiceps[rest]);
rightElbowServo.setRest(rightElbow[rest]);
rightWristServo.setRest(rightWrist[rest]);
leftShoulderServo.setRest(leftShoulder[rest]);
leftArmServo.setRest(leftArm[rest]);
leftBicepsServo.setRest(leftBiceps[rest]);
leftElbowServo.setRest(leftElbow[rest]);
leftWristServo.setRest(leftWrist[rest]);
rightThumbServo.setRest(rightThumb[rest]);
rightIndexServo.setRest(rightIndex[rest]);
rightMiddleServo.setRest(rightMiddle[rest]);
rightRingServo.setRest(rightRing[rest]);
rightPinkyServo.setRest(rightPinky[rest]);
leftThumbServo.setRest(leftThumb[rest]);
leftIndexServo.setRest(leftIndex[rest]);
leftMiddleServo.setRest(leftMiddle[rest]);
leftRingServo.setRest(leftRing[rest]);
leftPinkyServo.setRest(leftPinky[rest]);
neckTiltServo.setRest(neckTilt[rest]);
neckPanServo.setRest(neckPan[rest]);
}
/**
* Start the tracking services
*/
public void startTrack() throws Exception {
tracker = (Tracking) Runtime.start("tracker","Tracking");
sleep(1000);
tracker.connect(tracker.getOpenCV(),neckPanServo ,neckTiltServo);
//tracker.pid.invert("y");
//tracker.clearPreFilters();
}
/**
* Start the ultrasonic sensors services
* @param port port
* @throws Exception e
*/
public void startUltraSonic(String port) throws Exception {
USfront = (UltrasonicSensor) Runtime.start("USfront","UltrasonicSensor");
USfrontRight = (UltrasonicSensor) Runtime.start("USfrontRight","UltrasonicSensor");
USfrontLeft = (UltrasonicSensor) Runtime.start("USfrontLeft","UltrasonicSensor");
USback = (UltrasonicSensor) Runtime.start("USback","UltrasonicSensor");
USbackRight = (UltrasonicSensor) Runtime.start("USbackRight","UltrasonicSensor");
USbackLeft = (UltrasonicSensor) Runtime.start("USbackLeft","UltrasonicSensor");
USfront.attach(arduino, frontUltrasonicTrig, frontUltrasonicEcho);
USfrontRight.attach(arduino, front_rightUltrasonicTrig, front_rightUltrasonicEcho);
USfrontLeft.attach(arduino, front_leftUltrasonicTrig, front_leftUltrasonicEcho);
USback.attach(arduino, backUltrasonicTrig, backUltrasonicEcho);
USbackRight.attach(arduino, back_rightUltrasonicTrig, back_rightUltrasonicEcho);
USbackLeft.attach(arduino, back_leftUltrasonicTrig, back_leftUltrasonicEcho);
}
/**
* Stop the tracking services
* @throws Exception e
*/
public void stopTrack() throws Exception {
tracker.opencv.stopCapture();
tracker.releaseService();
}
public OpenNi startOpenNI() throws Exception {
// TODO modify this function to fit new sweety
/*
* Start the Kinect service
*/
if (openni == null) {
System.out.println("starting kinect");
openni = (OpenNi) Runtime.start("openni","OpenNi");
pid = (Pid) Runtime.start("pid","Pid");
pid.setMode("kinect", Pid.MODE_AUTOMATIC);
pid.setOutputRange("kinect", -1, 1);
pid.setPID("kinect", 10.0, 0.0, 1.0);
pid.setControllerDirection("kinect", 0);
// re-mapping of skeleton !
// openni.skeleton.leftElbow.mapXY(0, 180, 180, 0);
openni.skeleton.rightElbow.mapXY(0, 180, 180, 0);
// openni.skeleton.leftShoulder.mapYZ(0, 180, 180, 0);
openni.skeleton.rightShoulder.mapYZ(0, 180, 180, 0);
openni.skeleton.leftShoulder.mapXY(0, 180, 180, 0);
// openni.skeleton.rightShoulder.mapXY(0, 180, 180, 0);
openni.addListener("publishOpenNIData", this.getName(), "onOpenNIData");
// openni.addOpenNIData(this);
}
return openni;
}
public boolean copyGesture(boolean b) throws Exception {
log.info("copyGesture {}", b);
if (b) {
if (openni == null) {
openni = startOpenNI();
}
System.out.println("copying gestures");
openni.startUserTracking();
} else {
System.out.println("stop copying gestures");
if (openni != null) {
openni.stopCapture();
firstSkeleton = true;
}
}
copyGesture = b;
return b;
}
public String captureGesture() {
return captureGesture(null);
}
public String captureGesture(String gestureName) {
StringBuffer script = new StringBuffer();
String indentSpace = "";
if (gestureName != null) {
indentSpace = " ";
script.append(String.format("def %s():\n", gestureName));
}
script.append(indentSpace);
script.append(
String.format("Sweety.setRightArmPosition(%d,%d,%d,%d,%d)\n", rightShoulderServo.getPos(), rightArmServo.getPos(), rightBicepsServo.getPos(), rightElbowServo.getPos(), rightWristServo.getPos()));
script.append(indentSpace);
script
.append(String.format("Sweety.setLeftArmPosition(%d,%d,%d,%d,%d)\n", leftShoulderServo.getPos(), leftArmServo.getPos(), leftBicepsServo.getPos(), leftElbowServo.getPos(), leftWristServo.getPos()));
script.append(indentSpace);
script.append(String.format("Sweety.setHeadPosition(%d,%d)\n", neckTiltServo.getPos(), neckPanServo.getPos()));
send("python", "appendScript", script.toString());
return script.toString();
}
public void onOpenNIData(OpenNiData data) {
Skeleton skeleton = data.skeleton;
if (firstSkeleton) {
System.out.println("i see you");
firstSkeleton = false;
}
// TODO adapt for new design
int LElbow = Math.round(skeleton.leftElbow.getAngleXY()) - (180 - leftElbow[max]);
int Larm = Math.round(skeleton.leftShoulder.getAngleXY()) - (180 - leftArm[max]);
int Lshoulder = Math.round(skeleton.leftShoulder.getAngleYZ()) + leftShoulder[min];
int RElbow = Math.round(skeleton.rightElbow.getAngleXY()) + rightElbow[min];
int Rarm = Math.round(skeleton.rightShoulder.getAngleXY()) + rightArm[min];
int Rshoulder = Math.round(skeleton.rightShoulder.getAngleYZ()) - (180 - rightShoulder[max]);
// Move the left side
setLeftArmPosition(Lshoulder, Larm, LElbow, -1, -1);
// Move the right side
setRightArmPosition(Rshoulder, Rarm, RElbow, -1, -1);
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, and dependencies
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Sweety.class.getCanonicalName());
meta.addDescription("service for the Sweety robot");
meta.addCategory("robot");
return meta;
}
}
| Added setVelocity() | src/main/java/org/myrobotlab/service/Sweety.java | Added setVelocity() | <ide><path>rc/main/java/org/myrobotlab/service/Sweety.java
<ide> leftPinkyServo.setRest(leftPinky[rest]);
<ide> neckTiltServo.setRest(neckTilt[rest]);
<ide> neckPanServo.setRest(neckPan[rest]);
<add>
<add> setVelocity(75);
<add> }
<add>
<add> void setVelocity(int value) {
<add> rightShoulderServo.setVelocity(value);
<add> rightArmServo.setVelocity(value);
<add> rightBicepsServo.setVelocity(value);
<add> rightElbowServo.setVelocity(value);
<add> rightWristServo.setVelocity(value);
<add> leftShoulderServo.setVelocity(value);
<add> leftArmServo.setVelocity(value);
<add> leftBicepsServo.setVelocity(value);
<add> leftElbowServo.setVelocity(value);
<add> leftWristServo.setVelocity(value);
<add> rightThumbServo.setVelocity(value);
<add> rightIndexServo.setVelocity(value);
<add> rightMiddleServo.setVelocity(value);
<add> rightRingServo.setVelocity(value);
<add> rightPinkyServo.setVelocity(value);
<add> leftThumbServo.setVelocity(value);
<add> leftIndexServo.setVelocity(value);
<add> leftMiddleServo.setVelocity(value);
<add> leftRingServo.setVelocity(value);
<add> leftPinkyServo.setVelocity(value);
<add> neckTiltServo.setVelocity(value);
<add> neckPanServo.setVelocity(value);
<add>
<ide> }
<ide>
<ide> /** |
|
Java | mit | 2781b6688e7fcad428c14fe54d5b31a4a1f5f0a1 | 0 | sherxon/AlgoDS | package interviewquestions.easy;
/**
* Created by sherxon on 2016-12-27.
*/
public class RotateArray {
/**
* The idea is simple. First we will reverse all array elements. Then do another reversion of elements
* up to given kth-1 index and the of part of the array. Voila! rotated :)
* Time complexity is O(N) + O(N) = O(N);
* */
public void rotate(int[] a, int k) {
k %= a.length;
reverse(a, 0, a.length - 1);
reverse(a, 0, k - 1);
reverse(a, k, a.length - 1);
}
private void reverse(int[] a, int lo, int hi) {
while (lo < hi) {
int temp = a[lo];
a[lo] = a[hi];
a[hi] = temp;
lo++;
hi--;
}
}
}
| src/interviewquestions/easy/RotateArray.java | package interviewquestions.easy;
/**
* Created by sherxon on 2016-12-27.
*/
public class RotateArray {
/**
* The idea is simple. First we will reverse all array elements. Then do another reversion of elements
* up to given kth-1 index and the of part of the array. Voila! rotated :)
* Time complexity is O(N) + O(N) = O(N);
* */
public void rotate(int[] a, int k) {
k %= a.length;
reverse(a, 0, a.length);
reverse(a, 0, k - 1);
reverse(a, k, a.length);
}
private void reverse(int[] a, int lo, int hi) {
while (lo < hi) {
int temp = a[lo];
a[lo] = a[hi];
a[hi] = temp;
lo++;
hi--;
}
}
}
| perform reverse method cause an exception
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 | src/interviewquestions/easy/RotateArray.java | perform reverse method cause an exception | <ide><path>rc/interviewquestions/easy/RotateArray.java
<ide> * */
<ide> public void rotate(int[] a, int k) {
<ide> k %= a.length;
<del> reverse(a, 0, a.length);
<add> reverse(a, 0, a.length - 1);
<ide> reverse(a, 0, k - 1);
<del> reverse(a, k, a.length);
<add> reverse(a, k, a.length - 1);
<ide> }
<ide>
<ide> private void reverse(int[] a, int lo, int hi) { |
|
JavaScript | mit | 0cc9c127768ce406610958e1a241df25326f16c1 | 0 | natefaubion/matches.js,ermouth/matches.js | // patterns.js : Powerful pattern matching for Javascript
// Nathan Faubion <[email protected]>
var parser = require("./parser");
var compiler = require("./compiler");
var Matcher = require("./matcher").Matcher;
// Cache slice
var slice = Array.prototype.slice;
// Internal cache of all patterns
var patterns = {};
// Internal cache of all unique, normalized patterns
var normalized = {};
// Creates a pattern matching function given a string and a fn to execute.
function pattern () {
var args = slice.call(arguments);
// types
var targ0 = typeof args[0];
var targ1 = typeof args[1];
var targ2 = typeof args[2];
// Shared vars
var matcherFn, patternObj, patternFn, patternStr, successFn, chain, tree, last;
// pattern(matcherFn, chain)
if (targ0 == "function" && (targ1 == "undefined" || targ1 == "object")) {
matcherFn = args[0];
chain = args[1];
// Throw an error if the supplied function does not have a match chain.
if (!matcherFn.__matchChain) throw new Error("Not a matcher function");
// Splice the chains together.
if (chain) {
chain = chain.clone();
chain.last().next = matcherFn.__matchChain.clone();
} else {
chain = matcherFn.__matchChain.clone();
}
last = chain.pop();
return matcher(last.patternFn, last.successFn, chain);
}
// pattern(patternObj, chain)
else if (targ0 == "object" && (targ1 == "undefined" || targ1 == "object")) {
patternObj = args[0];
chain = args[1] ? args[1].clone() : null;
for (patternStr in patternObj) {
matcherFn = pattern(patternStr, patternObj[patternStr], chain);
chain = matcherFn.__matchChain;
}
return matcherFn;
}
// pattern(patternFn, successFn, chain)
else if (targ0 == "function" && targ1 == "function") {
chain = args[2] ? args[2].clone() : null;
return matcher(args[0], args[1], chain);
}
// pattern(patternStr, successFn, chain)
else {
patternStr = args[0];
successFn = args[1];
chain = args[2] ? args[2].clone() : null;
// Check if we've already compiled the same patternStr before.
if (patternStr in patterns) {
patternFn = patterns[patternStr];
}
else {
tree = parser.parse(patternStr);
// Check if we've already compiled a pattern function for the normalized
// pattern. If so, just use that and don't bother compiling.
if (tree.pattern in normalized) {
patternFn = (patterns[patternStr] = normalized[tree.pattern]);
}
// Compile the pattern function and cache it.
else {
patternFn = compiler.compile(tree);
patternFn.pattern = tree.pattern;
patterns[patternStr] = patternFn;
normalized[tree.pattern] = patternFn;
}
}
return matcher(patternFn, successFn, chain);
}
}
// Creates a function that tries a match and executes the given fn if
// successful. If not it tries subsequent patterns.
function matcher (patternFn, successFn, chain) {
var matcherObj = new Matcher(patternFn, successFn);
if (chain) {
chain.last().next = matcherObj;
} else {
chain = matcherObj;
}
var fn = function () {
var args = slice.call(arguments);
return chain.match(args, this);
};
fn.alt = function () {
var args = slice.call(arguments);
args.push(chain);
return pattern.apply(null, args);
}
fn.__matchChain = chain;
return fn;
}
// Export
exports.pattern = pattern;
exports.parser = parser;
exports.compiler = compiler;
| lib/index.js | // patterns.js : Powerful pattern matching for Javascript
// Nathan Faubion <[email protected]>
var parser = require("./parser");
var compiler = require("./compiler");
var Matcher = require("./matcher").Matcher;
// Cache slice
var slice = Array.prototype.slice;
// Internal cache of all patterns
var patterns = {};
// Internal cache of all unique, normalized patterns
var normalized = {};
// Creates a pattern matching function given a string and a fn to execute.
function pattern () {
var args = slice.call(arguments);
// types
var targ0 = typeof args[0];
var targ1 = typeof args[1];
var targ2 = typeof args[2];
// Shared vars
var matcherFn, patternObj, patternFn, patternStr, successFn, chain, tree, last;
// pattern(matcherFn, chain)
if (targ0 == "function" && (targ1 == "undefined" || targ1 == "object")) {
matcherFn = args[0];
chain = args[1];
// Throw an error if the supplied function does not have a match chain.
if (!matcherFn.__matchChain) throw new Error("Not a matcher function");
// Splice the chains together.
if (chain) {
chain = chain.clone();
chain.last().next = matcherFn.__matchChain.clone();
} else {
chain = matcherFn.__matchChain.clone();
}
last = chain.pop();
return matcher(last.patternFn, last.successFn, chain);
}
// pattern(patternObj, chain)
else if (targ0 == "object" && (targ1 == "undefined" || targ1 == "object")) {
patternObj = args[0];
chain = args[1] ? args[1].clone() : null;
for (patternStr in patternObj) {
matcherFn = pattern(patternStr, patternObj[patternStr], chain);
chain = matcherFn.__matchChain;
}
return matcherFn;
}
// pattern(patternFn, successFn, chain)
else if (targ0 == "function" && targ1 == "function") {
chain = args[2] ? args[2].clone() : null;
return matcher(args[0], args[1], chain);
}
// pattern(patternStr, successFn, chain)
else {
patternStr = args[0];
successFn = args[1];
chain = args[2] ? args[2].clone() : null;
tree = parser.parse(patternStr);
// Check if we've already compiled a pattern function for the normalized
// pattern. If so, just use that and don't bother compiling.
if (tree.pattern in normalized) {
patternFn = (patterns[patternStr] = normalized[tree.pattern]);
}
// Compile the pattern function and cache it.
else {
patternFn = compiler.compile(tree);
patternFn.pattern = tree.pattern;
patterns[patternStr] = patternFn;
normalized[tree.pattern] = patternFn;
}
return matcher(patternFn, successFn, chain);
}
}
// Creates a function that tries a match and executes the given fn if
// successful. If not it tries subsequent patterns.
function matcher (patternFn, successFn, chain) {
var matcherObj = new Matcher(patternFn, successFn);
if (chain) {
chain.last().next = matcherObj;
} else {
chain = matcherObj;
}
var fn = function () {
var args = slice.call(arguments);
return chain.match(args, this);
};
fn.alt = function () {
var args = slice.call(arguments);
args.push(chain);
return pattern.apply(null, args);
}
fn.__matchChain = chain;
return fn;
}
// Export
exports.pattern = pattern;
exports.parser = parser;
exports.compiler = compiler;
| Lookup pattern string in cache before attempting to parse
| lib/index.js | Lookup pattern string in cache before attempting to parse | <ide><path>ib/index.js
<ide> patternStr = args[0];
<ide> successFn = args[1];
<ide> chain = args[2] ? args[2].clone() : null;
<del> tree = parser.parse(patternStr);
<ide>
<del> // Check if we've already compiled a pattern function for the normalized
<del> // pattern. If so, just use that and don't bother compiling.
<del> if (tree.pattern in normalized) {
<del> patternFn = (patterns[patternStr] = normalized[tree.pattern]);
<add> // Check if we've already compiled the same patternStr before.
<add> if (patternStr in patterns) {
<add> patternFn = patterns[patternStr];
<ide> }
<ide>
<del> // Compile the pattern function and cache it.
<ide> else {
<del> patternFn = compiler.compile(tree);
<del> patternFn.pattern = tree.pattern;
<del> patterns[patternStr] = patternFn;
<del> normalized[tree.pattern] = patternFn;
<add> tree = parser.parse(patternStr);
<add>
<add> // Check if we've already compiled a pattern function for the normalized
<add> // pattern. If so, just use that and don't bother compiling.
<add> if (tree.pattern in normalized) {
<add> patternFn = (patterns[patternStr] = normalized[tree.pattern]);
<add> }
<add>
<add> // Compile the pattern function and cache it.
<add> else {
<add> patternFn = compiler.compile(tree);
<add> patternFn.pattern = tree.pattern;
<add> patterns[patternStr] = patternFn;
<add> normalized[tree.pattern] = patternFn;
<add> }
<ide> }
<ide>
<ide> return matcher(patternFn, successFn, chain); |
|
Java | mit | 8c854a8a89334ff2a331bff458eb68bb75d30320 | 0 | ShaneMcC/DMDirc-Client,greboid/DMDirc,DMDirc/DMDirc,csmith/DMDirc,DMDirc/DMDirc,csmith/DMDirc,DMDirc/DMDirc,DMDirc/DMDirc,greboid/DMDirc,greboid/DMDirc,ShaneMcC/DMDirc-Client,ShaneMcC/DMDirc-Client,greboid/DMDirc,ShaneMcC/DMDirc-Client,csmith/DMDirc,csmith/DMDirc | /*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.dmdirc.plugins;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import org.junit.Test;
import static org.junit.Assert.*;
public class PluginInfoTest {
private PluginInfo pi;
@Test
public void testCheckMinimum() throws PluginException {
try {
pi = new PluginInfo(new URL("file:///dev/null"), false);
assertTrue(pi.checkMinimumVersion("5", 6));
assertTrue(pi.checkMinimumVersion("5", 5));
assertTrue(pi.checkMinimumVersion("0", 17));
assertTrue(pi.checkMinimumVersion("100", 0));
assertTrue(pi.checkMinimumVersion("0", 0));
assertFalse(pi.checkMinimumVersion("abc", 6));
assertFalse(pi.checkMinimumVersion("7", 6));
} catch (MalformedURLException mue) { }
}
@Test
public void testCheckMaximim() throws PluginException {
try {
pi = new PluginInfo(new URL("file:///dev/null"), false);
assertTrue(pi.checkMaximumVersion("6", 6));
assertTrue(pi.checkMaximumVersion("7", 6));
assertTrue(pi.checkMaximumVersion("0", 6));
assertTrue(pi.checkMaximumVersion("6", 0));
assertTrue(pi.checkMaximumVersion("0", 0));
assertTrue(pi.checkMaximumVersion("", 17));
assertFalse(pi.checkMaximumVersion("abc", 6));
assertFalse(pi.checkMaximumVersion("7", 10));
} catch (MalformedURLException mue) { }
}
@Test
public void testOS() throws PluginException {
try {
pi = new PluginInfo(new URL("file:///dev/null"), false);
assertTrue(pi.checkOS("windows", "windows", "xp", "x86"));
assertFalse(pi.checkOS("windows", "linux", "2.6.2.11", "x86"));
assertTrue(pi.checkOS("windows:xp|98|3\\.1", "windows", "xp", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1", "windows", "vista", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1", "linux", "2.6.2.11", "x86"));
assertTrue(pi.checkOS("windows:xp|98|3\\.1:.86", "windows", "xp", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1:.86", "windows", "xp", "mips"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1:.86", "windows", "vista", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1:.86", "linux", "2.6.2.11", "x86"));
} catch (MalformedURLException mue) { }
}
@Test
public void testLoad() throws PluginException {
PluginInfo pi = new PluginInfo(getClass().getResource("testplugin.jar"));
assertEquals("Author <em@il>", pi.getAuthor());
assertEquals("Friendly", pi.getFriendlyVersion());
assertEquals("Description goes here", pi.getDescription());
assertEquals("randomname", pi.getName());
assertEquals("Friendly name", pi.getNiceName());
assertEquals("3", pi.getVersion().toString());
}
@Test
public void testUpdate() throws PluginException, IOException {
final File dir = new File(File.createTempFile("dmdirc-plugin-test", null).getParentFile(),
"dmdirc-plugin-test-folder");
final File pluginDir = new File(dir, "plugins");
dir.deleteOnExit();
pluginDir.mkdirs();
final File target = new File(pluginDir, "test.jar");
target.createNewFile();
new File(pluginDir, "test.jar.update").createNewFile();
new PluginInfo(target.toURI().toURL(), false);
assertTrue(new File(pluginDir, "test.jar").exists());
assertFalse(new File(pluginDir, "test.jar.update").exists());
}
} | test/com/dmdirc/plugins/PluginInfoTest.java | /*
* Copyright (c) 2006-2009 Chris Smith, Shane Mc Cormack, Gregory Holmes
*
* 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.dmdirc.plugins;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.MalformedURLException;
import org.junit.Test;
import static org.junit.Assert.*;
public class PluginInfoTest {
private PluginInfo pi;
@Test
public void testCheckMinimum() throws PluginException {
try {
pi = new PluginInfo(new URL("file:///dev/null"), false);
assertTrue(pi.checkMinimumVersion("5", 6));
assertTrue(pi.checkMinimumVersion("5", 5));
assertTrue(pi.checkMinimumVersion("0", 17));
assertTrue(pi.checkMinimumVersion("100", 0));
assertTrue(pi.checkMinimumVersion("0", 0));
assertFalse(pi.checkMinimumVersion("abc", 6));
assertFalse(pi.checkMinimumVersion("7", 6));
} catch (MalformedURLException mue) { }
}
@Test
public void testCheckMaximim() throws PluginException {
try {
pi = new PluginInfo(new URL("file:///dev/null"), false);
assertTrue(pi.checkMaximumVersion("6", 6));
assertTrue(pi.checkMaximumVersion("7", 6));
assertTrue(pi.checkMaximumVersion("0", 6));
assertTrue(pi.checkMaximumVersion("6", 0));
assertTrue(pi.checkMaximumVersion("0", 0));
assertTrue(pi.checkMaximumVersion("", 17));
assertFalse(pi.checkMaximumVersion("abc", 6));
assertFalse(pi.checkMaximumVersion("7", 10));
} catch (MalformedURLException mue) { }
}
@Test
public void testOS() throws PluginException {
try {
pi = new PluginInfo(new URL("file:///dev/null"), false);
assertTrue(pi.checkOS("windows", "windows", "xp", "x86"));
assertFalse(pi.checkOS("windows", "linux", "2.6.2.11", "x86"));
assertTrue(pi.checkOS("windows:xp|98|3\\.1", "windows", "xp", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1", "windows", "vista", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1", "linux", "2.6.2.11", "x86"));
assertTrue(pi.checkOS("windows:xp|98|3\\.1:.86", "windows", "xp", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1:.86", "windows", "xp", "mips"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1:.86", "windows", "vista", "x86"));
assertFalse(pi.checkOS("windows:xp|98|3\\.1:.86", "linux", "2.6.2.11", "x86"));
} catch (MalformedURLException mue) { }
}
@Test
public void testLoad() throws PluginException {
PluginInfo pi = new PluginInfo(getClass().getResource("testplugin.jar"));
assertEquals("Author <em@il>", pi.getAuthor());
assertEquals("Friendly", pi.getFriendlyVersion());
assertEquals("Description goes here", pi.getDescription());
assertEquals("randomname", pi.getName());
assertEquals("Friendly name", pi.getNiceName());
assertEquals(3, pi.getVersion());
}
@Test
public void testUpdate() throws PluginException, IOException {
final File dir = new File(File.createTempFile("dmdirc-plugin-test", null).getParentFile(),
"dmdirc-plugin-test-folder");
final File pluginDir = new File(dir, "plugins");
dir.deleteOnExit();
pluginDir.mkdirs();
final File target = new File(pluginDir, "test.jar");
target.createNewFile();
new File(pluginDir, "test.jar.update").createNewFile();
new PluginInfo(target.toURI().toURL(), false);
assertTrue(new File(pluginDir, "test.jar").exists());
assertFalse(new File(pluginDir, "test.jar.update").exists());
}
} | 3 now equals 3. (Fix broken unit test)
| test/com/dmdirc/plugins/PluginInfoTest.java | 3 now equals 3. (Fix broken unit test) | <ide><path>est/com/dmdirc/plugins/PluginInfoTest.java
<ide> assertEquals("Description goes here", pi.getDescription());
<ide> assertEquals("randomname", pi.getName());
<ide> assertEquals("Friendly name", pi.getNiceName());
<del> assertEquals(3, pi.getVersion());
<add> assertEquals("3", pi.getVersion().toString());
<ide> }
<ide>
<ide> @Test |
|
Java | mit | b63c4008cffdc5b919c0b7c43c8f1487541ccd51 | 0 | M4GiK/tosi-projects,M4GiK/tosi-projects | package com.m4gik.util;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
*
* This class contains JUnit tests for class {@link Util}.
*
* @author Michał Szczygieł <[email protected]>
*
*/
@RunWith(Parameterized.class)
public class UtilTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays
.asList(new Object[][] {
{ new String("713502673d67e5fa557629a71d331945")
.getBytes() },
{ new String("6eece560a2e8d6b919e81fe91b0e7156")
.getBytes() }, });
}
private final Object input;
public UtilTest(Object input) {
this.input = input;
}
@Test
public void testInputIsNotNull() {
assertThat(input, is(notNullValue()));
}
@Test(
expected = NumberFormatException.class)
public void testThrowIfGivenStingIsNotHexValue() {
Util.toString((byte[]) input);
}
}
| haval-algorithm/src/test/java/com/m4gik/util/UtilTest.java | package com.m4gik.util;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
/**
*
* This class contains JUnit tests for class {@link Util}.
*
* @author Michał Szczygieł <[email protected]>
*
*/
@RunWith(Parameterized.class)
public class UtilTest {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ new String("test").getBytes() },
{ new Integer(8).byteValue() } });
}
private final Object input;
public UtilTest(Object input) {
this.input = input;
}
@Test
public void testInputIsNotNull() {
assertThat(input, is(notNullValue()));
}
}
| Create TDD test for Util class.
| haval-algorithm/src/test/java/com/m4gik/util/UtilTest.java | Create TDD test for Util class. | <ide><path>aval-algorithm/src/test/java/com/m4gik/util/UtilTest.java
<ide>
<ide> @Parameterized.Parameters
<ide> public static Collection<Object[]> data() {
<del> return Arrays.asList(new Object[][] {
<del> { new String("test").getBytes() },
<del> { new Integer(8).byteValue() } });
<add> return Arrays
<add> .asList(new Object[][] {
<add> { new String("713502673d67e5fa557629a71d331945")
<add> .getBytes() },
<add> { new String("6eece560a2e8d6b919e81fe91b0e7156")
<add> .getBytes() }, });
<ide> }
<ide>
<ide> private final Object input;
<ide> assertThat(input, is(notNullValue()));
<ide> }
<ide>
<add> @Test(
<add> expected = NumberFormatException.class)
<add> public void testThrowIfGivenStingIsNotHexValue() {
<add> Util.toString((byte[]) input);
<add> }
<ide> } |
|
Java | mit | 3915470fc9ed2c3be456813bc7ad8a76f941cdf1 | 0 | quemb/QMBForm | package com.quemb.qmbform.descriptor;
import com.quemb.qmbform.R;
import com.quemb.qmbform.annotation.FormElement;
import com.quemb.qmbform.annotation.FormValidator;
import android.content.Context;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static com.quemb.qmbform.annotation.FormDescriptorAnnotationFactory.convertFormOptionsAnnotation;
/**
* Created by tonimoeckel on 14.07.14.
*/
public class RowDescriptor<T> extends FormItemDescriptor {
public static final String FormRowDescriptorTypeText = "text";
public static final String FormRowDescriptorTypeTextInline = "textInline";
public static final String FormRowDescriptorTypeHTMLText = "htmlText";
public static final String FormRowDescriptorTypeDetailInline = "detailInline";
public static final String FormRowDescriptorTypeDetail = "detail";
public static final String FormRowDescriptorTypeURL = "url";
public static final String FormRowDescriptorTypeEmail = "email";
public static final String FormRowDescriptorTypeEmailInline = "emailInline";
public static final String FormRowDescriptorTypePassword = "password";
public static final String FormRowDescriptorTypePasswordInline = "passwordInline";
public static final String FormRowDescriptorTypeNumber = "number";
public static final String FormRowDescriptorTypeNumberInline = "numberInline";
public static final String FormRowDescriptorTypeIntegerSlider = "integerSlider";
public static final String FormRowDescriptorTypeCurrency = "currency";
public static final String FormRowDescriptorTypePhone = "phone";
public static final String FormRowDescriptorTypeTwitter = "twitter";
public static final String FormRowDescriptorTypeAccount = "account";
public static final String FormRowDescriptorTypeInteger = "integer";
public static final String FormRowDescriptorTypeIntegerInline = "integerInline";
public static final String FormRowDescriptorTypeTextView = "textView";
public static final String FormRowDescriptorTypeTextViewInline = "textViewInline";
public static final String FormRowDescriptorTypeSelectorPush = "selectorPush";
public static final String FormRowDescriptorTypeSelectorActionSheet = "selectorActionSheet";
public static final String FormRowDescriptorTypeSelectorAlertView = "selectorAlertView";
public static final String FormRowDescriptorTypeSelectorPickerView = "selectorPickerView";
public static final String FormRowDescriptorTypeSelectorPickerViewInline = "selectorPickerViewInline";
public static final String FormRowDescriptorTypeSelectorSpinner = "selectorSpinner";
public static final String FormRowDescriptorTypeSelectorSpinnerInline = "selectorSpinnerInline";
public static final String FormRowDescriptorTypeTextPickerDialog = "textPickerDialog";
public static final String FormRowDescriptorTypeSelectorPickerDialog = "selectorPickerDialog";
public static final String FormRowDescriptorTypeSelectorPickerDialogVertical = "selectorPickerDialogVertical";
public static final String FormRowDescriptorTypeMultipleSelector = "multipleSelector";
public static final String FormRowDescriptorTypeSelectorLeftRight = "selectorLeftRight";
public static final String FormRowDescriptorTypeSelectorSegmentedControlInline = "selectorSegmentedControlInline";
public static final String FormRowDescriptorTypeSelectorSegmentedControl = "selectorSegmentedControl";
public static final String FormRowDescriptorTypeDateInline = "dateInline";
public static final String FormRowDescriptorTypeDateTimeInline = "datetimeInline";
public static final String FormRowDescriptorTypeTimeInline = "timeInline";
public static final String FormRowDescriptorTypeDate = "date";
public static final String FormRowDescriptorTypeDateTime = "datetime";
public static final String FormRowDescriptorTypeTime = "time";
public static final String FormRowDescriptorTypeDatePicker = "datePicker";
public static final String FormRowDescriptorTypePicker = "picker";
public static final String FormRowDescriptorTypeBooleanCheck = "booleanCheck";
public static final String FormRowDescriptorTypeBooleanSwitch = "booleanSwitch";
public static final String FormRowDescriptorTypeButton = "button";
public static final String FormRowDescriptorTypeButtonInline = "buttonInline";
public static final String FormRowDescriptorTypeImage = "image";
public static final String FormRowDescriptorTypeWeb = "web";
public static final String FormRowDescriptorTypeExternal = "external";
public static final String FormRowDescriptorTypeStepCounter = "stepCounter";
public static final String FormRowDescriptorTypeSectionSeperator = "sectionSeperator";
public static final String FormRowDescriptorTypeHtmlVertical = "htmlVertical";
private String mRowType;
private Value<T> mValue;
/**
* A list of valid values to pick from (e.g. used for spinners)
*/
private DataSource<T> mDataSource;
private Boolean mRequired = false;
private Boolean mDisabled = false;
private List<FormValidator> mValidators;
private List<FormOptionsObject> mSelectorOptions;
private SectionDescriptor mSectionDescriptor;
private int mHint = android.R.string.untitled;
private boolean mLastRowInSection = false;
public static RowDescriptor newInstance(String tag) {
return RowDescriptor.newInstance(tag, FormRowDescriptorTypeDetailInline);
}
public static RowDescriptor newInstance(String tag, String rowType) {
return RowDescriptor.newInstance(tag, rowType, null);
}
public static RowDescriptor newInstance(String tag, String rowType, String title) {
return RowDescriptor.newInstance(tag, rowType, title, null);
}
public static RowDescriptor newInstance(String tag, String rowType, String title, Value<?> value) {
RowDescriptor descriptor = new RowDescriptor();
descriptor.mTitle = title;
descriptor.mTag = tag;
descriptor.mRowType = rowType;
descriptor.setValue(value);
descriptor.mValidators = new ArrayList<FormValidator>();
return descriptor;
}
public static RowDescriptor newInstanceFromAnnotatedField(Field field, Value value, Context context) {
FormElement annotation = field.getAnnotation(FormElement.class);
RowDescriptor rowDescriptor = RowDescriptor.newInstance(
annotation.tag().length() > 0 ? annotation.tag() : field.getName(),
annotation.rowDescriptorType(),
context.getString(annotation.label()),
value);
rowDescriptor.setHint(annotation.hint());
rowDescriptor.setRequired(annotation.required());
rowDescriptor.setDisabled(annotation.disabled());
rowDescriptor.setSelectorOptions(convertFormOptionsAnnotation(
annotation.selectorOptions()));
return rowDescriptor;
}
public SectionDescriptor getSectionDescriptor() {
return mSectionDescriptor;
}
public void setSectionDescriptor(SectionDescriptor sectionDescriptor) {
mSectionDescriptor = sectionDescriptor;
}
public Value<T> getValue() {
return mValue;
}
public void setValue(Value<T> value) {
mValue = value;
}
public Object getValueData() {
return mValue.getValue();
}
public Boolean getRequired() {
return mRequired;
}
public void setRequired(Boolean required) {
mRequired = required;
}
public String getRowType() {
return mRowType;
}
public boolean hasDataSource() {
return mDataSource != null;
}
public DataSource<T> getDataSource() {
return mDataSource;
}
public void setDataSource(DataSource<T> dataSource) {
mDataSource = dataSource;
}
public Boolean getDisabled() {
return mDisabled;
}
public void setDisabled(Boolean disabled) {
mDisabled = disabled;
}
public void setHint(int hint) {
mHint = hint;
}
public int getHint() {
return mHint;
}
public String getHint(Context context) {
if (mHint == android.R.string.untitled) {
return null;
}
return context.getString(mHint);
}
public boolean isValid() {
boolean valid = true;
if (getRequired()) {
valid = getValue() != null && getValue().getValue() != null;
if (getSelectorOptions() != null && getSelectorOptions().size() > 0) {
valid = valid &&
FormOptionsObject.formOptionsObjectFromArrayWithValue(getValue().getValue(), getSelectorOptions()) != null;
}
}
if (getValidators() != null && valid) {
for (FormValidator validator : getValidators()) {
if (validator.validate(this) != null) {
valid = false;
break;
}
}
}
return valid;
}
public List<FormOptionsObject> getSelectorOptions() {
return mSelectorOptions;
}
public void setSelectorOptions(List<FormOptionsObject> selectorOptions) {
mSelectorOptions = selectorOptions;
}
public List<RowValidationError> getValidationErrors() {
List<RowValidationError> rowValidationErrors = new ArrayList<RowValidationError>();
if (getRequired()) {
if (!(getValue() != null && getValue().getValue() != null)) {
rowValidationErrors.add(new RowValidationError(this, R.string.validation_is_required));
} else if (getSelectorOptions() != null && getSelectorOptions().size() > 0) {
if (FormOptionsObject.formOptionsObjectFromArrayWithValue(getValue().getValue(), getSelectorOptions()) == null) {
rowValidationErrors.add(new RowValidationError(this, R.string.validation_is_required));
}
}
}
if (getValidators() != null) {
for (FormValidator validator : getValidators()) {
RowValidationError error = validator.validate(this);
if (error != null) {
rowValidationErrors.add(error);
}
}
}
return (rowValidationErrors.isEmpty()) ? null : rowValidationErrors;
}
public static RowDescriptor newInstance(RowDescriptor rowDescriptor) {
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
RowDescriptor newInstance = RowDescriptor.newInstance(rowDescriptor.getTag() + "_" + ts, rowDescriptor.getRowType());
newInstance.setDataSource(rowDescriptor.getDataSource());
return newInstance;
}
public List<FormValidator> getValidators() {
return mValidators;
}
public void addValidator(FormValidator validator) {
mValidators.add(validator);
}
public void setLastRowInSection(boolean lastRow) {
mLastRowInSection = lastRow;
}
public boolean isLastRowInSection() {
return mLastRowInSection;
}
}
| lib/QMBForm/src/main/java/com/quemb/qmbform/descriptor/RowDescriptor.java | package com.quemb.qmbform.descriptor;
import com.quemb.qmbform.R;
import com.quemb.qmbform.annotation.FormElement;
import com.quemb.qmbform.annotation.FormValidator;
import android.content.Context;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static com.quemb.qmbform.annotation.FormDescriptorAnnotationFactory.convertFormOptionsAnnotation;
/**
* Created by tonimoeckel on 14.07.14.
*/
public class RowDescriptor<T> extends FormItemDescriptor {
public static final String FormRowDescriptorTypeText = "text";
public static final String FormRowDescriptorTypeTextInline = "textInline";
public static final String FormRowDescriptorTypeHTMLText = "htmlText";
public static final String FormRowDescriptorTypeDetailInline = "detailInline";
public static final String FormRowDescriptorTypeDetail = "detail";
public static final String FormRowDescriptorTypeURL = "url";
public static final String FormRowDescriptorTypeEmail = "email";
public static final String FormRowDescriptorTypeEmailInline = "emailInline";
public static final String FormRowDescriptorTypePassword = "password";
public static final String FormRowDescriptorTypePasswordInline = "passwordInline";
public static final String FormRowDescriptorTypeNumber = "number";
public static final String FormRowDescriptorTypeNumberInline = "numberInline";
public static final String FormRowDescriptorTypeIntegerSlider = "integerSlider";
public static final String FormRowDescriptorTypeCurrency = "currency";
public static final String FormRowDescriptorTypePhone = "phone";
public static final String FormRowDescriptorTypeTwitter = "twitter";
public static final String FormRowDescriptorTypeAccount = "account";
public static final String FormRowDescriptorTypeInteger = "integer";
public static final String FormRowDescriptorTypeIntegerInline = "integerInline";
public static final String FormRowDescriptorTypeTextView = "textView";
public static final String FormRowDescriptorTypeTextViewInline = "textViewInline";
public static final String FormRowDescriptorTypeSelectorPush = "selectorPush";
public static final String FormRowDescriptorTypeSelectorActionSheet = "selectorActionSheet";
public static final String FormRowDescriptorTypeSelectorAlertView = "selectorAlertView";
public static final String FormRowDescriptorTypeSelectorPickerView = "selectorPickerView";
public static final String FormRowDescriptorTypeSelectorPickerViewInline = "selectorPickerViewInline";
public static final String FormRowDescriptorTypeSelectorSpinner = "selectorSpinner";
public static final String FormRowDescriptorTypeSelectorSpinnerInline = "selectorSpinnerInline";
public static final String FormRowDescriptorTypeTextPickerDialog = "textPickerDialog";
public static final String FormRowDescriptorTypeSelectorPickerDialog = "selectorPickerDialog";
public static final String FormRowDescriptorTypeSelectorPickerDialogVertical = "selectorPickerDialogVertical";
public static final String FormRowDescriptorTypeMultipleSelector = "multipleSelector";
public static final String FormRowDescriptorTypeSelectorLeftRight = "selectorLeftRight";
public static final String FormRowDescriptorTypeSelectorSegmentedControlInline = "selectorSegmentedControlInline";
public static final String FormRowDescriptorTypeSelectorSegmentedControl = "selectorSegmentedControl";
public static final String FormRowDescriptorTypeDateInline = "dateInline";
public static final String FormRowDescriptorTypeDateTimeInline = "datetimeInline";
public static final String FormRowDescriptorTypeTimeInline = "timeInline";
public static final String FormRowDescriptorTypeDate = "date";
public static final String FormRowDescriptorTypeDateTime = "datetime";
public static final String FormRowDescriptorTypeTime = "time";
public static final String FormRowDescriptorTypeDatePicker = "datePicker";
public static final String FormRowDescriptorTypePicker = "picker";
public static final String FormRowDescriptorTypeBooleanCheck = "booleanCheck";
public static final String FormRowDescriptorTypeBooleanSwitch = "booleanSwitch";
public static final String FormRowDescriptorTypeButton = "button";
public static final String FormRowDescriptorTypeButtonInline = "buttonInline";
public static final String FormRowDescriptorTypeImage = "image";
public static final String FormRowDescriptorTypeWeb = "web";
public static final String FormRowDescriptorTypeExternal = "external";
public static final String FormRowDescriptorTypeStepCounter = "stepCounter";
public static final String FormRowDescriptorTypeSectionSeperator = "sectionSeperator";
public static final String FormRowDescriptorTypeHtmlVertical = "htmlVertical";
private String mRowType;
private Value<T> mValue;
/**
* A list of valid values to pick from (e.g. used for spinners)
*/
private DataSource<T> mDataSource;
private Boolean mRequired = false;
private Boolean mDisabled = false;
private List<FormValidator> mValidators;
private List<FormOptionsObject> mSelectorOptions;
private SectionDescriptor mSectionDescriptor;
private int mHint = android.R.string.untitled;
public static RowDescriptor newInstance(String tag) {
return RowDescriptor.newInstance(tag, FormRowDescriptorTypeDetailInline);
}
public static RowDescriptor newInstance(String tag, String rowType) {
return RowDescriptor.newInstance(tag, rowType, null);
}
public static RowDescriptor newInstance(String tag, String rowType, String title) {
return RowDescriptor.newInstance(tag, rowType, title, null);
}
public static RowDescriptor newInstance(String tag, String rowType, String title, Value<?> value) {
RowDescriptor descriptor = new RowDescriptor();
descriptor.mTitle = title;
descriptor.mTag = tag;
descriptor.mRowType = rowType;
descriptor.setValue(value);
descriptor.mValidators = new ArrayList<FormValidator>();
return descriptor;
}
public static RowDescriptor newInstanceFromAnnotatedField(Field field, Value value, Context context) {
FormElement annotation = field.getAnnotation(FormElement.class);
RowDescriptor rowDescriptor = RowDescriptor.newInstance(
annotation.tag().length() > 0 ? annotation.tag() : field.getName(),
annotation.rowDescriptorType(),
context.getString(annotation.label()),
value);
rowDescriptor.setHint(annotation.hint());
rowDescriptor.setRequired(annotation.required());
rowDescriptor.setDisabled(annotation.disabled());
rowDescriptor.setSelectorOptions(convertFormOptionsAnnotation(
annotation.selectorOptions()));
return rowDescriptor;
}
public SectionDescriptor getSectionDescriptor() {
return mSectionDescriptor;
}
public void setSectionDescriptor(SectionDescriptor sectionDescriptor) {
mSectionDescriptor = sectionDescriptor;
}
public Value<T> getValue() {
return mValue;
}
public void setValue(Value<T> value) {
mValue = value;
}
public Object getValueData() {
return mValue.getValue();
}
public Boolean getRequired() {
return mRequired;
}
public void setRequired(Boolean required) {
mRequired = required;
}
public String getRowType() {
return mRowType;
}
public boolean hasDataSource() {
return mDataSource != null;
}
public DataSource<T> getDataSource() {
return mDataSource;
}
public void setDataSource(DataSource<T> dataSource) {
mDataSource = dataSource;
}
public Boolean getDisabled() {
return mDisabled;
}
public void setDisabled(Boolean disabled) {
mDisabled = disabled;
}
public void setHint(int hint) {
mHint = hint;
}
public int getHint() {
return mHint;
}
public String getHint(Context context) {
if (mHint == android.R.string.untitled) {
return null;
}
return context.getString(mHint);
}
public boolean isValid() {
boolean valid = true;
if (getRequired()) {
valid = getValue() != null && getValue().getValue() != null;
if (getSelectorOptions() != null && getSelectorOptions().size() > 0) {
valid = valid &&
FormOptionsObject.formOptionsObjectFromArrayWithValue(getValue().getValue(), getSelectorOptions()) != null;
}
}
if (getValidators() != null && valid) {
for (FormValidator validator : getValidators()) {
if (validator.validate(this) != null) {
valid = false;
break;
}
}
}
return valid;
}
public List<FormOptionsObject> getSelectorOptions() {
return mSelectorOptions;
}
public void setSelectorOptions(List<FormOptionsObject> selectorOptions) {
mSelectorOptions = selectorOptions;
}
public List<RowValidationError> getValidationErrors() {
List<RowValidationError> rowValidationErrors = new ArrayList<RowValidationError>();
if (getRequired()) {
if (!(getValue() != null && getValue().getValue() != null)) {
rowValidationErrors.add(new RowValidationError(this, R.string.validation_is_required));
} else if (getSelectorOptions() != null && getSelectorOptions().size() > 0) {
if (FormOptionsObject.formOptionsObjectFromArrayWithValue(getValue().getValue(), getSelectorOptions()) == null) {
rowValidationErrors.add(new RowValidationError(this, R.string.validation_is_required));
}
}
}
if (getValidators() != null) {
for (FormValidator validator : getValidators()) {
RowValidationError error = validator.validate(this);
if (error != null) {
rowValidationErrors.add(error);
}
}
}
return (rowValidationErrors.isEmpty()) ? null : rowValidationErrors;
}
public static RowDescriptor newInstance(RowDescriptor rowDescriptor) {
Long tsLong = System.currentTimeMillis() / 1000;
String ts = tsLong.toString();
RowDescriptor newInstance = RowDescriptor.newInstance(rowDescriptor.getTag() + "_" + ts, rowDescriptor.getRowType());
newInstance.setDataSource(rowDescriptor.getDataSource());
return newInstance;
}
public List<FormValidator> getValidators() {
return mValidators;
}
public void addValidator(FormValidator validator) {
mValidators.add(validator);
}
}
| Update RowDescriptor.java | lib/QMBForm/src/main/java/com/quemb/qmbform/descriptor/RowDescriptor.java | Update RowDescriptor.java | <ide><path>ib/QMBForm/src/main/java/com/quemb/qmbform/descriptor/RowDescriptor.java
<ide>
<ide> private int mHint = android.R.string.untitled;
<ide>
<add> private boolean mLastRowInSection = false;
<add>
<ide> public static RowDescriptor newInstance(String tag) {
<ide>
<ide> return RowDescriptor.newInstance(tag, FormRowDescriptorTypeDetailInline);
<ide> public void addValidator(FormValidator validator) {
<ide> mValidators.add(validator);
<ide> }
<add>
<add> public void setLastRowInSection(boolean lastRow) {
<add> mLastRowInSection = lastRow;
<add> }
<add>
<add> public boolean isLastRowInSection() {
<add> return mLastRowInSection;
<add> }
<ide> }
<ide> |
|
Java | apache-2.0 | 7cfa8599aac0a529d2cc20ddce8bcb134db098ba | 0 | kubatatami/JudoNetworking | package com.github.kubatatami.judonetworking.internals.executors;
import android.os.Build;
import android.os.Process;
import com.github.kubatatami.judonetworking.Endpoint;
import com.github.kubatatami.judonetworking.logs.JudoLogger;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by Kuba on 19/05/14.
*/
public class JudoExecutor extends ThreadPoolExecutor {
protected int threadPriority = Process.THREAD_PRIORITY_BACKGROUND;
protected Endpoint endpoint;
protected int count;
protected ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(final Runnable runnable) {
count++;
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Create thread " + count, JudoLogger.LogLevel.VERBOSE);
}
return new ConnectionThread(runnable, threadPriority, count, endpoint);
}
};
public JudoExecutor(Endpoint endpoint) {
super(48, Integer.MAX_VALUE, 30, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
this.endpoint = endpoint;
setThreadFactory(threadFactory);
prestartAllCoreThreads();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
allowCoreThreadTimeOut(true);
}
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
ConnectionThread connectionThread = (ConnectionThread) t;
connectionThread.resetCanceled();
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Before execute thread " + t.getName() + ":" + toString(), JudoLogger.LogLevel.VERBOSE);
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("After thread execute:" + toString(), JudoLogger.LogLevel.VERBOSE);
}
}
@Override
public void execute(Runnable command) {
super.execute(command);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Execute runnable" + toString(), JudoLogger.LogLevel.VERBOSE);
}
}
@Override
public void setCorePoolSize(int corePoolSize) {
super.setCorePoolSize(corePoolSize);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Core thread pool size:" + corePoolSize, JudoLogger.LogLevel.VERBOSE);
}
}
@Override
public void setMaximumPoolSize(int maximumPoolSize) {
super.setMaximumPoolSize(maximumPoolSize);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Maximum thread pool size:" + maximumPoolSize, JudoLogger.LogLevel.VERBOSE);
}
}
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
public int getThreadPriority() {
return threadPriority;
}
public static class ConnectionThread extends Thread {
Runnable runnable;
int threadPriority;
Canceller canceller;
boolean canceled;
Endpoint endpoint;
public ConnectionThread(Runnable runnable, int threadPriority, int count, Endpoint endpoint) {
super("JudoNetworking ConnectionPool " + count);
this.runnable = runnable;
this.endpoint = endpoint;
this.threadPriority = threadPriority;
}
@Override
public void run() {
Process.setThreadPriority(threadPriority);
runnable.run();
}
@Override
public void interrupt() {
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Interrupt task on: " + getName(), JudoLogger.LogLevel.VERBOSE);
}
canceled = true;
super.interrupt();
if (canceller != null) {
canceller.cancel();
canceller = null;
}
}
public void resetCanceled() {
this.canceled = false;
}
public void setCanceller(Canceller canceller) {
this.canceller = canceller;
}
public interface Canceller {
void cancel();
}
public boolean isCanceled() {
return canceled;
}
}
}
| base/src/main/java/com/github/kubatatami/judonetworking/internals/executors/JudoExecutor.java | package com.github.kubatatami.judonetworking.internals.executors;
import android.os.Build;
import android.os.Process;
import com.github.kubatatami.judonetworking.Endpoint;
import com.github.kubatatami.judonetworking.logs.JudoLogger;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by Kuba on 19/05/14.
*/
public class JudoExecutor extends ThreadPoolExecutor {
protected int threadPriority = Process.THREAD_PRIORITY_BACKGROUND;
protected Endpoint endpoint;
protected int count;
protected ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(final Runnable runnable) {
count++;
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Create thread " + count, JudoLogger.LogLevel.VERBOSE);
}
return new ConnectionThread(runnable, threadPriority, count, endpoint);
}
};
public JudoExecutor(Endpoint endpoint) {
super(2, Integer.MAX_VALUE, 30, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
this.endpoint = endpoint;
setThreadFactory(threadFactory);
prestartAllCoreThreads();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
allowCoreThreadTimeOut(true);
}
}
@Override
protected void beforeExecute(Thread t, Runnable r) {
super.beforeExecute(t, r);
ConnectionThread connectionThread = (ConnectionThread) t;
connectionThread.resetCanceled();
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Before execute thread " + t.getName() + ":" + toString(), JudoLogger.LogLevel.VERBOSE);
}
}
@Override
protected void afterExecute(Runnable r, Throwable t) {
super.afterExecute(r, t);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("After thread execute:" + toString(), JudoLogger.LogLevel.VERBOSE);
}
}
@Override
public void execute(Runnable command) {
super.execute(command);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Execute runnable" + toString(), JudoLogger.LogLevel.VERBOSE);
}
}
@Override
public void setCorePoolSize(int corePoolSize) {
super.setCorePoolSize(corePoolSize);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Core thread pool size:" + corePoolSize, JudoLogger.LogLevel.VERBOSE);
}
}
@Override
public void setMaximumPoolSize(int maximumPoolSize) {
super.setMaximumPoolSize(maximumPoolSize);
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Maximum thread pool size:" + maximumPoolSize, JudoLogger.LogLevel.VERBOSE);
}
}
public void setThreadPriority(int threadPriority) {
this.threadPriority = threadPriority;
}
public int getThreadPriority() {
return threadPriority;
}
public static class ConnectionThread extends Thread {
Runnable runnable;
int threadPriority;
Canceller canceller;
boolean canceled;
Endpoint endpoint;
public ConnectionThread(Runnable runnable, int threadPriority, int count, Endpoint endpoint) {
super("JudoNetworking ConnectionPool " + count);
this.runnable = runnable;
this.endpoint = endpoint;
this.threadPriority = threadPriority;
}
@Override
public void run() {
Process.setThreadPriority(threadPriority);
runnable.run();
}
@Override
public void interrupt() {
if ((endpoint.getDebugFlags() & Endpoint.THREAD_DEBUG) > 0) {
JudoLogger.log("Interrupt task on: " + getName(), JudoLogger.LogLevel.VERBOSE);
}
canceled = true;
super.interrupt();
if (canceller != null) {
canceller.cancel();
canceller = null;
}
}
public void resetCanceled() {
this.canceled = false;
}
public void setCanceller(Canceller canceller) {
this.canceller = canceller;
}
public interface Canceller {
void cancel();
}
public boolean isCanceled() {
return canceled;
}
}
}
| core size experiment
| base/src/main/java/com/github/kubatatami/judonetworking/internals/executors/JudoExecutor.java | core size experiment | <ide><path>ase/src/main/java/com/github/kubatatami/judonetworking/internals/executors/JudoExecutor.java
<ide> };
<ide>
<ide> public JudoExecutor(Endpoint endpoint) {
<del> super(2, Integer.MAX_VALUE, 30, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
<add> super(48, Integer.MAX_VALUE, 30, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
<ide> this.endpoint = endpoint;
<ide> setThreadFactory(threadFactory);
<ide> prestartAllCoreThreads(); |
|
Java | apache-2.0 | 32c4a6ebcff1b5b12eef19df3e94a6b52a2c0256 | 0 | jiyiren/LitePal,Ryan800/LitePal,luinnx/LitePal,EasonYi/LitePal,Lerist/LitePal,treejames/LitePal,axter/LitePal,weatherfish/LitePal,lifeqiuzhi520/LitePal,newyu/LitePal,LitePalFramework/LitePal,kuangxiao/LitePal,jxauchengchao/LitePal,zcwfeng/LitePal,canperragit/LitePal,hanziqi/LitePal,yooranchen/LitePal,siemensc62/LitePal,allencall1234/LitePal,Tinaltt/LitePal,Godchin1990/LitePal,stepway/LitePal,LitePalFramework/LitePal,tsdl2013/LitePal,hongyangAndroid/LitePal,HoyoShaw/LitePal | package org.litepal.crud;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.litepal.exceptions.DataSupportException;
/**
* This provides a send method to allow calling method in dynamic way. (Just
* like Ruby, but not clean or easy as Ruby to use).
*
* @author Tony Green
* @since 1.1
*/
class DynamicExecutor {
/**
* Disable to create an instance of DynamicExecutor.
*/
private DynamicExecutor() {
}
/**
* This method use java reflect API to execute method dynamically. Most
* importantly, it could access the methods with private modifier to break
* encapsulation.
*
* @param object
* The object to invoke method.
* @param methodName
* The method name to invoke.
* @param parameters
* The parameters.
* @param objectClass
* Use objectClass to find method to invoke.
* @param parameterTypes
* The parameter types.
* @return Returns the result of dynamically invoking method.
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
static Object send(Object object, String methodName, Object[] parameters, Class<?> objectClass,
Class<?>[] parameterTypes) throws SecurityException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
try {
if (parameters == null) {
parameters = new Object[] {};
}
if (parameterTypes == null) {
parameterTypes = new Class[] {};
}
Method method = objectClass.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method.invoke(object, parameters);
} catch (NoSuchMethodException e) {
throw new DataSupportException(DataSupportException.noSuchMethodException(
objectClass.getSimpleName(), methodName));
}
}
/**
* This method use java reflect API to set field value dynamically. Most
* importantly, it could access fields with private modifier to break
* encapsulation.
*
* @param object
* The object to access.
* @param fieldName
* The field name to access.
* @param value
* Assign this value to field.
* @param objectClass
* The class of object.
* @throws SecurityException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
static void setField(Object object, String fieldName, Object value, Class<?> objectClass)
throws SecurityException, IllegalArgumentException, IllegalAccessException {
try {
Field baseObjIdField = objectClass.getDeclaredField(fieldName);
baseObjIdField.setAccessible(true);
baseObjIdField.set(object, value);
} catch (NoSuchFieldException e) {
throw new DataSupportException(DataSupportException.noSuchFieldExceptioin(
objectClass.getSimpleName(), fieldName));
}
}
/**
* This method use java reflect API to get field value dynamically. Most
* importantly, it could access fields with private modifier to break
* encapsulation.
*
* @param object
* The object to access.
* @param fieldName
* The field name to access.
* @param objectClass
* The class of object.
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
static Object getField(Object object, String fieldName, Class<?> objectClass)
throws IllegalArgumentException, IllegalAccessException {
try {
Field baseObjIdField = objectClass.getDeclaredField(fieldName);
baseObjIdField.setAccessible(true);
return baseObjIdField.get(object);
} catch (NoSuchFieldException e) {
throw new DataSupportException(DataSupportException.noSuchFieldExceptioin(
objectClass.getSimpleName(), fieldName));
}
}
}
| src/org/litepal/crud/DynamicExecutor.java | package org.litepal.crud;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.litepal.exceptions.DataSupportException;
/**
* This provides a send method to allow calling method in dynamic way. (Just
* like Ruby, but not clean or easy as Ruby to use).
*
* @author Tony Green
* @since 1.1
*/
class DynamicExecutor {
/**
* Disable to create an instance of DynamicExecutor.
*/
private DynamicExecutor() {
}
/**
* This method use java reflect API to execute method dynamically. Most
* importantly, it could access the methods with private modifier to break
* encapsulation.
*
* @param object
* The object to invoke method.
* @param methodName
* The method name to invoke.
* @param parameters
* The parameters.
* @param objectClass
* Use objectClass to find method to invoke.
* @param parameterTypes
* The parameter types.
* @return Returns the result of dynamically invoking method.
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
static Object send(Object object, String methodName, Object[] parameters, Class<?> objectClass,
Class<?>[] parameterTypes) throws SecurityException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException {
try {
if (parameters == null) {
parameters = new Object[] {};
}
if (parameterTypes == null) {
parameterTypes = new Class[] {};
}
Method method = objectClass.getDeclaredMethod(methodName, parameterTypes);
method.setAccessible(true);
return method.invoke(object, parameters);
} catch (NoSuchMethodException e) {
throw new DataSupportException(DataSupportException.noSuchMethodException(
objectClass.getSimpleName(), methodName));
}
}
/**
* This method use java reflect API to set field value dynamically. Most
* importantly, it could access fields with private modifier to break
* encapsulation.
*
* @param object
* The object to access.
* @param fieldName
* The field name to access.
* @param value
* Assign this value to field.
* @param objectClass
* The class of object.
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
static void setField(Object object, String fieldName, Object value, Class<?> objectClass)
throws SecurityException, IllegalArgumentException, IllegalAccessException {
try {
Field baseObjIdField = objectClass.getDeclaredField(fieldName);
baseObjIdField.setAccessible(true);
baseObjIdField.set(object, value);
} catch (NoSuchFieldException e) {
throw new DataSupportException(DataSupportException.noSuchFieldExceptioin(
objectClass.getSimpleName(), fieldName));
}
}
/**
* This method use java reflect API to get field value dynamically. Most
* importantly, it could access fields with private modifier to break
* encapsulation.
*
* @param object
* The object to access.
* @param fieldName
* The field name to access.
* @param objectClass
* The class of object.
* @throws SecurityException
* @throws NoSuchFieldException
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
static Object getField(Object object, String fieldName, Class<?> objectClass)
throws IllegalArgumentException, IllegalAccessException {
try {
Field baseObjIdField = objectClass.getDeclaredField(fieldName);
baseObjIdField.setAccessible(true);
return baseObjIdField.get(object);
} catch (NoSuchFieldException e) {
throw new DataSupportException(DataSupportException.noSuchFieldExceptioin(
objectClass.getSimpleName(), fieldName));
}
}
}
| Remove unused throws
| src/org/litepal/crud/DynamicExecutor.java | Remove unused throws | <ide><path>rc/org/litepal/crud/DynamicExecutor.java
<ide> * The parameter types.
<ide> * @return Returns the result of dynamically invoking method.
<ide> * @throws SecurityException
<del> * @throws NoSuchMethodException
<ide> * @throws IllegalArgumentException
<ide> * @throws IllegalAccessException
<ide> * @throws InvocationTargetException
<ide> * @param objectClass
<ide> * The class of object.
<ide> * @throws SecurityException
<del> * @throws NoSuchFieldException
<ide> * @throws IllegalArgumentException
<ide> * @throws IllegalAccessException
<ide> */ |
|
JavaScript | apache-2.0 | d30056ccc91bdae311f3aa59ec12b2eaed9ae9ce | 0 | actionhero/actionhero,crrobinson14/actionhero,chimmelb/actionhero,chimmelb/actionhero,gcoonrod/actionhero,crrobinson14/actionhero,actionhero/actionhero,witem/actionhero,gcoonrod/actionhero,S3bb1/actionhero,crrobinson14/actionhero,gcoonrod/actionhero,witem/actionhero,S3bb1/actionhero,witem/actionhero,S3bb1/actionhero,actionhero/actionhero,gcoonrod/actionhero,witem/actionhero,chimmelb/actionhero,actionhero/actionhero | 'use strict';
var fs = require('fs');
var path = require('path');
module.exports = {
loadPriority: 0,
initialize: function(api, next){
if(!api.utils){ api.utils = {}; }
////////////////////////////////////////////////////////////////////////////
// merge two hashes recursively
api.utils.hashMerge = function(a, b, arg){
var c = {};
var i;
var response;
for(i in a){
if(api.utils.isPlainObject(a[i]) && Object.keys(a[i]).length > 0){
c[i] = api.utils.hashMerge(c[i], a[i], arg);
}else{
if(typeof a[i] === 'function'){
response = a[i](arg);
if(api.utils.isPlainObject(response)){
c[i] = api.utils.hashMerge(c[i], response, arg);
}else{
c[i] = response;
}
}else{
c[i] = a[i];
}
}
}
for(i in b){
if(api.utils.isPlainObject(b[i]) && Object.keys(b[i]).length > 0){
c[i] = api.utils.hashMerge(c[i], b[i], arg);
}else{
if(typeof b[i] === 'function'){
response = b[i](arg);
if(api.utils.isPlainObject(response)){
c[i] = api.utils.hashMerge(c[i], response, arg);
}else{
c[i] = response;
}
}else{
c[i] = b[i];
}
}
}
return c;
};
api.utils.isPlainObject = function(o){
var safeTypes = [Boolean, Number, String, Function, Array, Date, RegExp, Buffer];
var safeInstances = ['boolean', 'number', 'string', 'function'];
var expandPreventMatchKey = '_toExpand'; // set `_toExpand = false` within an object if you don't want to expand it
var i;
if(!o){ return false; }
if((o instanceof Object) === false){ return false; }
for(i in safeTypes){
if(o instanceof safeTypes[i]){ return false; }
}
for(i in safeInstances){
if(typeof o === safeInstances[i]){ return false; }
}
if(o[expandPreventMatchKey] === false){ return false; }
return (o.toString() === '[object Object]');
};
////////////////////////////////////////////////////////////////////////////
// string to hash
// http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference
api.utils.stringToHash = function(path, object){
if(!object){ object = api; }
function _index(obj, i){ return obj[i]; }
return path.split('.').reduce(_index, object);
};
////////////////////////////////////////////////////////////////////////////
// unique-ify an array
api.utils.arrayUniqueify = function(arr){
var a = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++){
if(arr[i] === arr[j]){ j = ++i; }
}
a.push(arr[i]);
}
return a;
};
////////////////////////////////////////////////////////////////////////////
// get all .js files in a directory
api.utils.recursiveDirectoryGlob = function(dir, extension, followLinkFiles){
var results = [];
if(!extension){ extension = '.js'; }
if(!followLinkFiles){ followLinkFiles = true; }
extension = extension.replace('.', '');
if(fs.existsSync(dir)){
fs.readdirSync(dir).forEach(function(file){
var fullFilePath = path.join(dir, file);
if(file[0] !== '.'){ // ignore 'system' files
var stats = fs.statSync(fullFilePath);
var child;
if(stats.isDirectory()){
child = api.utils.recursiveDirectoryGlob(fullFilePath, extension, followLinkFiles);
child.forEach(function(c){ results.push(c); });
}else if(stats.isSymbolicLink()){
var realPath = fs.readlinkSync(fullFilePath);
child = api.utils.recursiveDirectoryGlob(realPath, extension, followLinkFiles);
child.forEach(function(c){ results.push(c); });
}else if(stats.isFile()){
var fileParts = file.split('.');
var ext = fileParts[(fileParts.length - 1)];
// real file match
if(ext === extension){ results.push(fullFilePath); }
// linkfile traversal
if(ext === 'link' && followLinkFiles === true){
var linkedPath = api.utils.sourceRelativeLinkPath(fullFilePath, api.config.general.paths.plugin);
if(linkedPath){
child = api.utils.recursiveDirectoryGlob(linkedPath, extension, followLinkFiles);
child.forEach(function(c){ results.push(c); });
}else{
try{
api.log(['cannot find linked refrence to `%s`', file], 'warning');
}catch(e){
throw('cannot find linked refrence to' + file);
}
}
}
}
}
});
}
return results.sort();
};
api.utils.sourceRelativeLinkPath = function(linkfile, pluginPaths){
var type = fs.readFileSync(linkfile).toString();
var pathParts = linkfile.split(path.sep);
var name = pathParts[(pathParts.length - 1)].split('.')[0];
var pathsToTry = pluginPaths.slice(0);
var pluginRoot;
// TODO: always also try the local destination's `node_modules` to allow for nested plugins
// This might be a security risk without requiring explicit sourcing
pathsToTry.forEach(function(pluginPath){
var pluginPathAttempt = path.normalize(pluginPath + path.sep + name);
try{
var stats = fs.lstatSync(pluginPathAttempt);
if(!pluginRoot && stats.isDirectory()){ pluginRoot = pluginPathAttempt; }
}catch(e){ }
});
if(!pluginRoot){ return false; }
var pluginSection = path.normalize(pluginRoot + path.sep + type);
return pluginSection;
};
////////////////////////////////////////////////////////////////////////////
// object Clone
api.utils.objClone = function(obj){
return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyNames(obj).reduce(function(memo, name){
return (memo[name] = Object.getOwnPropertyDescriptor(obj, name)) && memo;
}, {}));
};
////////////////////////////////////////////////////////////////////////////
// attempt to collapse this object to an array; ie: {"0": "a", "1": "b"}
api.utils.collapseObjectToArray = function(obj){
try{
var keys = Object.keys(obj);
if(keys.length < 1){ return false; }
if(keys[0] !== '0'){ return false; }
if(keys[(keys.length - 1)] !== String(keys.length - 1)){ return false; }
var arr = [];
for(var i in keys){
var key = keys[i];
if(String(parseInt(key)) !== key){ return false; }
else{ arr.push(obj[key]); }
}
return arr;
}catch(e){
return false;
}
};
////////////////////////////////////////////////////////////////////////////
// get this servers external interface
api.utils.getExternalIPAddress = function(){
var os = require('os');
var ifaces = os.networkInterfaces();
var ip = false;
for(var dev in ifaces){
ifaces[dev].forEach(function(details){
if(details.family === 'IPv4' && details.address !== '127.0.0.1'){
ip = details.address;
}
});
}
return ip;
};
////////////////////////////////////////////////////////////////////////////
// cookie parse from headers of http(s) requests
api.utils.parseCookies = function(req){
var cookies = {};
if(req.headers.cookie){
req.headers.cookie.split(';').forEach(function(cookie){
var parts = cookie.split('=');
cookies[parts[0].trim()] = (parts[1] || '').trim();
});
}
return cookies;
};
////////////////////////////////////////////////////////////////////////////
// parse an IPv6 address
// https://github.com/evantahler/actionhero/issues/275 && https://github.com/nullivex
api.utils.parseIPv6URI = function(addr){
var host = '::1';
var port = '80';
var regexp = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
//if we have brackets parse them and find a port
if(addr.indexOf('[') > -1 && addr.indexOf(']') > -1){
var res = regexp.exec(addr);
if(res === null){
throw new Error('failed to parse address');
}
host = res[1];
port = res[2];
}else{
host = addr;
}
return {host: host, port: parseInt(port, 10)};
};
next();
}
};
| initializers/utils.js | 'use strict';
var fs = require('fs');
var path = require('path');
module.exports = {
loadPriority: 0,
initialize: function(api, next){
if(!api.utils){ api.utils = {}; }
////////////////////////////////////////////////////////////////////////////
// merge two hashes recursively
api.utils.hashMerge = function(a, b, arg){
var c = {};
var i;
var response;
for(i in a){
if(api.utils.isPlainObject(a[i]) && Object.keys(a[i]).length > 0){
c[i] = api.utils.hashMerge(c[i], a[i], arg);
}else{
if(typeof a[i] === 'function'){
response = a[i](arg);
if(api.utils.isPlainObject(response)){
c[i] = api.utils.hashMerge(c[i], response, arg);
}else{
c[i] = response;
}
}else{
c[i] = a[i];
}
}
}
for(i in b){
if(api.utils.isPlainObject(b[i]) && Object.keys(b[i]).length > 0){
c[i] = api.utils.hashMerge(c[i], b[i], arg);
}else{
if(typeof b[i] === 'function'){
response = b[i](arg);
if(api.utils.isPlainObject(response)){
c[i] = api.utils.hashMerge(c[i], response, arg);
}else{
c[i] = response;
}
}else{
c[i] = b[i];
}
}
}
return c;
};
api.utils.isPlainObject = function(o){
var safeTypes = [Boolean, Number, String, Function, Array, Date, RegExp, Buffer];
var safeInstances = ['boolean', 'number', 'string', 'function'];
var expandPreventMatchKey = '_toExpand'; // set `_toExpand = false` within an object if you don't want to expand it
var i;
if(!o){ return false; }
if((o instanceof Object) === false){ return false; }
for(i in safeTypes){
if(o instanceof safeTypes[i]){ return false; }
}
for(i in safeInstances){
if(typeof o === safeInstances[i]){ return false; }
}
if(o[expandPreventMatchKey] === false){ return false; }
return (o.toString() === '[object Object]');
};
////////////////////////////////////////////////////////////////////////////
// string to hash
// http://stackoverflow.com/questions/6393943/convert-javascript-string-in-dot-notation-into-an-object-reference
api.utils.stringToHash = function(path, object){
if(!object){ object = api; }
function _index(obj, i){ return obj[i]; }
return path.split('.').reduce(_index, object);
};
////////////////////////////////////////////////////////////////////////////
// unique-ify an array
api.utils.arrayUniqueify = function(arr){
var a = [];
for(var i = 0; i < arr.length; i++){
for(var j = i + 1; j < arr.length; j++){
if(arr[i] === arr[j]){ j = ++i; }
}
a.push(arr[i]);
}
return a;
};
////////////////////////////////////////////////////////////////////////////
// get all .js files in a directory
api.utils.recursiveDirectoryGlob = function(dir, extension, followLinkFiles){
var results = [];
if(!extension){ extension = '.js'; }
if(!followLinkFiles){ followLinkFiles = true; }
extension = extension.replace('.', '');
if(dir[dir.length - 1] !== path.sep){ dir += path.sep; }
if(fs.existsSync(dir)){
fs.readdirSync(dir).forEach(function(file){
var fullFilePath = path.normalize(dir + file);
if(file[0] !== '.'){ // ignore 'system' files
var stats = fs.statSync(fullFilePath);
var child;
if(stats.isDirectory()){
child = api.utils.recursiveDirectoryGlob(fullFilePath, extension, followLinkFiles);
child.forEach(function(c){ results.push(c); });
}else if(stats.isSymbolicLink()){
var realPath = fs.readlinkSync(fullFilePath);
child = api.utils.recursiveDirectoryGlob(realPath, extension, followLinkFiles);
child.forEach(function(c){ results.push(c); });
}else if(stats.isFile()){
var fileParts = file.split('.');
var ext = fileParts[(fileParts.length - 1)];
// real file match
if(ext === extension){ results.push(fullFilePath); }
// linkfile traversal
if(ext === 'link' && followLinkFiles === true){
var linkedPath = api.utils.sourceRelativeLinkPath(fullFilePath, api.config.general.paths.plugin);
if(linkedPath){
child = api.utils.recursiveDirectoryGlob(linkedPath, extension, followLinkFiles);
child.forEach(function(c){ results.push(c); });
}else{
try{
api.log(['cannot find linked refrence to `%s`', file], 'warning');
}catch(e){
throw('cannot find linked refrence to' + file);
}
}
}
}
}
});
}
return results.sort();
};
api.utils.sourceRelativeLinkPath = function(linkfile, pluginPaths){
var type = fs.readFileSync(linkfile).toString();
var pathParts = linkfile.split(path.sep);
var name = pathParts[(pathParts.length - 1)].split('.')[0];
var pathsToTry = pluginPaths.slice(0);
var pluginRoot;
// TODO: always also try the local destination's `node_modules` to allow for nested plugins
// This might be a security risk without requiring explicit sourcing
pathsToTry.forEach(function(pluginPath){
var pluginPathAttempt = path.normalize(pluginPath + path.sep + name);
try{
var stats = fs.lstatSync(pluginPathAttempt);
if(!pluginRoot && stats.isDirectory()){ pluginRoot = pluginPathAttempt; }
}catch(e){ }
});
if(!pluginRoot){ return false; }
var pluginSection = path.normalize(pluginRoot + path.sep + type);
return pluginSection;
};
////////////////////////////////////////////////////////////////////////////
// object Clone
api.utils.objClone = function(obj){
return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyNames(obj).reduce(function(memo, name){
return (memo[name] = Object.getOwnPropertyDescriptor(obj, name)) && memo;
}, {}));
};
////////////////////////////////////////////////////////////////////////////
// attempt to collapse this object to an array; ie: {"0": "a", "1": "b"}
api.utils.collapseObjectToArray = function(obj){
try{
var keys = Object.keys(obj);
if(keys.length < 1){ return false; }
if(keys[0] !== '0'){ return false; }
if(keys[(keys.length - 1)] !== String(keys.length - 1)){ return false; }
var arr = [];
for(var i in keys){
var key = keys[i];
if(String(parseInt(key)) !== key){ return false; }
else{ arr.push(obj[key]); }
}
return arr;
}catch(e){
return false;
}
};
////////////////////////////////////////////////////////////////////////////
// get this servers external interface
api.utils.getExternalIPAddress = function(){
var os = require('os');
var ifaces = os.networkInterfaces();
var ip = false;
for(var dev in ifaces){
ifaces[dev].forEach(function(details){
if(details.family === 'IPv4' && details.address !== '127.0.0.1'){
ip = details.address;
}
});
}
return ip;
};
////////////////////////////////////////////////////////////////////////////
// cookie parse from headers of http(s) requests
api.utils.parseCookies = function(req){
var cookies = {};
if(req.headers.cookie){
req.headers.cookie.split(';').forEach(function(cookie){
var parts = cookie.split('=');
cookies[parts[0].trim()] = (parts[1] || '').trim();
});
}
return cookies;
};
////////////////////////////////////////////////////////////////////////////
// parse an IPv6 address
// https://github.com/evantahler/actionhero/issues/275 && https://github.com/nullivex
api.utils.parseIPv6URI = function(addr){
var host = '::1';
var port = '80';
var regexp = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
//if we have brackets parse them and find a port
if(addr.indexOf('[') > -1 && addr.indexOf(']') > -1){
var res = regexp.exec(addr);
if(res === null){
throw new Error('failed to parse address');
}
host = res[1];
port = res[2];
}else{
host = addr;
}
return {host: host, port: parseInt(port, 10)};
};
next();
}
};
| Electron support, avoid bug electron/electron#5454
- remove trailing path separator from recursive directory glob
- use path.join(dir, file) instead of path.normalize(dir + file)
| initializers/utils.js | Electron support, avoid bug electron/electron#5454 - remove trailing path separator from recursive directory glob - use path.join(dir, file) instead of path.normalize(dir + file) | <ide><path>nitializers/utils.js
<ide> if(!followLinkFiles){ followLinkFiles = true; }
<ide>
<ide> extension = extension.replace('.', '');
<del> if(dir[dir.length - 1] !== path.sep){ dir += path.sep; }
<ide>
<ide> if(fs.existsSync(dir)){
<ide> fs.readdirSync(dir).forEach(function(file){
<del> var fullFilePath = path.normalize(dir + file);
<add> var fullFilePath = path.join(dir, file);
<ide> if(file[0] !== '.'){ // ignore 'system' files
<ide> var stats = fs.statSync(fullFilePath);
<ide> var child; |
|
Java | apache-2.0 | 7a8c02b92ba681046aeef4b8fdea9cf77f29652f | 0 | cn-cerc/summer-mis,cn-cerc/summer-mis | package cn.cerc.mis.core;
import cn.cerc.core.IHandle;
import cn.cerc.db.core.IAppConfig;
import cn.cerc.mis.config.ApplicationConfig;
import cn.cerc.ui.core.UrlRecord;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Deprecated // 请改使用 StartAppDefault
public class StartApp implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
StringBuffer builder = req.getRequestURL();
UrlRecord url = new UrlRecord();
url.setSite(builder.toString());
Map<String, String[]> items = req.getParameterMap();
for (String key : items.keySet()) {
String[] values = items.get(key);
for (String value : values) {
url.putParam(key, value);
}
}
log.info("url {}", url.getUrl());
String uri = req.getRequestURI();
Application.get(req);
// 处理默认首页问题
if ("/".equals(uri)) {
if (req.getParameter(ClientDevice.APP_CLIENT_ID) != null) {
req.getSession().setAttribute(ClientDevice.APP_CLIENT_ID, req.getParameter(ClientDevice.APP_CLIENT_ID));
}
if (req.getParameter(ClientDevice.APP_DEVICE_TYPE) != null) {
req.getSession().setAttribute(ClientDevice.APP_DEVICE_TYPE,
req.getParameter(ClientDevice.APP_DEVICE_TYPE));
}
IAppConfig conf = Application.getAppConfig();
resp.sendRedirect(String.format("%s%s", ApplicationConfig.App_Path, conf.getFormWelcome()));
return;
} else if ("/MobileConfig".equals(uri) || "/mobileConfig".equals(uri)) {
if (req.getParameter(ClientDevice.APP_CLIENT_ID) != null) {
req.getSession().setAttribute(ClientDevice.APP_CLIENT_ID, req.getParameter(ClientDevice.APP_CLIENT_ID));
}
if (req.getParameter(ClientDevice.APP_DEVICE_TYPE) != null) {
req.getSession().setAttribute(ClientDevice.APP_DEVICE_TYPE,
req.getParameter(ClientDevice.APP_DEVICE_TYPE));
}
try {
IForm form;
if (Application.get(req).containsBean("mobileConfig")) {
form = Application.getBean("mobileConfig", IForm.class);
} else {
form = Application.getBean("MobileConfig", IForm.class);
}
form.setRequest((HttpServletRequest) request);
form.setResponse((HttpServletResponse) response);
IHandle handle = Application.getHandle();
handle.setProperty(Application.sessionId, req.getSession().getId());
form.setHandle(handle);
IPage page = form.execute();
page.execute();
} catch (Exception e) {
resp.getWriter().print(e.getMessage());
}
return;
}
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
} | summer-mis/src/main/java/cn/cerc/mis/core/StartApp.java | package cn.cerc.mis.core;
import cn.cerc.core.IHandle;
import cn.cerc.db.core.IAppConfig;
import cn.cerc.mis.config.ApplicationConfig;
import cn.cerc.ui.core.UrlRecord;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
@Slf4j
@Deprecated // 请改使用 StartAppDefault
public class StartApp implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
StringBuffer builder = req.getRequestURL();
UrlRecord url = new UrlRecord();
url.setSite(builder.toString());
Map<String, String[]> items = req.getParameterMap();
for (String key : items.keySet()) {
String[] values = items.get(key);
for (String value : values) {
url.putParam(key, value);
}
}
String path = url.getUrl();
if (path.contains("?code=")) {
log.info("url {}", url.getUrl());
}
String uri = req.getRequestURI();
Application.get(req);
// 处理默认首页问题
if ("/".equals(uri)) {
if (req.getParameter(ClientDevice.APP_CLIENT_ID) != null) {
req.getSession().setAttribute(ClientDevice.APP_CLIENT_ID, req.getParameter(ClientDevice.APP_CLIENT_ID));
}
if (req.getParameter(ClientDevice.APP_DEVICE_TYPE) != null) {
req.getSession().setAttribute(ClientDevice.APP_DEVICE_TYPE,
req.getParameter(ClientDevice.APP_DEVICE_TYPE));
}
IAppConfig conf = Application.getAppConfig();
resp.sendRedirect(String.format("%s%s", ApplicationConfig.App_Path, conf.getFormWelcome()));
return;
} else if ("/MobileConfig".equals(uri) || "/mobileConfig".equals(uri)) {
if (req.getParameter(ClientDevice.APP_CLIENT_ID) != null) {
req.getSession().setAttribute(ClientDevice.APP_CLIENT_ID, req.getParameter(ClientDevice.APP_CLIENT_ID));
}
if (req.getParameter(ClientDevice.APP_DEVICE_TYPE) != null) {
req.getSession().setAttribute(ClientDevice.APP_DEVICE_TYPE,
req.getParameter(ClientDevice.APP_DEVICE_TYPE));
}
try {
IForm form;
if (Application.get(req).containsBean("mobileConfig")) {
form = Application.getBean("mobileConfig", IForm.class);
} else {
form = Application.getBean("MobileConfig", IForm.class);
}
form.setRequest((HttpServletRequest) request);
form.setResponse((HttpServletResponse) response);
IHandle handle = Application.getHandle();
handle.setProperty(Application.sessionId, req.getSession().getId());
form.setHandle(handle);
IPage page = form.execute();
page.execute();
} catch (Exception e) {
resp.getWriter().print(e.getMessage());
}
return;
}
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void destroy() {
}
} | Update StartApp.java
| summer-mis/src/main/java/cn/cerc/mis/core/StartApp.java | Update StartApp.java | <ide><path>ummer-mis/src/main/java/cn/cerc/mis/core/StartApp.java
<ide> url.putParam(key, value);
<ide> }
<ide> }
<del> String path = url.getUrl();
<del> if (path.contains("?code=")) {
<del> log.info("url {}", url.getUrl());
<del> }
<add> log.info("url {}", url.getUrl());
<ide>
<ide> String uri = req.getRequestURI();
<ide> Application.get(req); |
|
Java | apache-2.0 | 76d97e27959525895ff0f7a249f3be93fc5c92f3 | 0 | capitalone/Hydrograph,capitalone/Hydrograph,capitalone/Hydrograph | /*******************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.engine.core.component.generator;
import hydrograph.engine.core.component.entity.InputRDBMSEntity;
import hydrograph.engine.core.component.entity.utils.InputEntityUtils;
import hydrograph.engine.core.component.generator.base.InputComponentGeneratorBase;
import hydrograph.engine.core.constants.Constants;
import hydrograph.engine.jaxb.commontypes.TypeBaseComponent;
import hydrograph.engine.jaxb.inputtypes.Oracle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Class InputOracleEntityGenerator.
*
* @author Bitwise
*/
public class InputOracleEntityGenerator extends
InputComponentGeneratorBase {
private static Logger LOG = LoggerFactory
.getLogger(InputOracleEntityGenerator.class);
private Oracle inputOracleJaxb;
private InputRDBMSEntity inputRDBMSEntity;
public InputOracleEntityGenerator(TypeBaseComponent baseComponent) {
super(baseComponent);
}
@Override
public void castComponentFromBase(TypeBaseComponent baseComponent) {
inputOracleJaxb = (Oracle) baseComponent;
}
@Override
public void createEntity() {
inputRDBMSEntity = new InputRDBMSEntity();
}
@Override
public void initializeEntity() {
LOG.trace("Initializing input file Oracle component: " + inputOracleJaxb.getId());
inputRDBMSEntity.setComponentId(inputOracleJaxb.getId());
inputRDBMSEntity.setFieldsList(InputEntityUtils.extractInputFields(
inputOracleJaxb.getOutSocket().get(0).getSchema().getFieldOrRecordOrIncludeExternalSchema()));
inputRDBMSEntity.setOutSocketList(InputEntityUtils.extractOutSocket(inputOracleJaxb.getOutSocket()));
inputRDBMSEntity.setSid(inputOracleJaxb.getSid().getValue());
inputRDBMSEntity.setHostName(inputOracleJaxb.getHostName().getValue());
inputRDBMSEntity.setPort(inputOracleJaxb.getPort() == null ? Constants.ORACLE_PORT_NUMBER
: inputOracleJaxb.getPort().getValue().intValue());
inputRDBMSEntity.setRuntimeProperties(inputOracleJaxb.getRuntimeProperties() == null ? new Properties() : InputEntityUtils
.extractRuntimeProperties(inputOracleJaxb.getRuntimeProperties()));
inputRDBMSEntity.setBatch(inputOracleJaxb.getBatch());
if (inputOracleJaxb.getSelectQuery() != null) {
inputRDBMSEntity.setTableName("Dual");
inputRDBMSEntity.setSelectQuery(inputOracleJaxb.getSelectQuery().getValue());
} else {
inputRDBMSEntity.setSelectQuery(null);
inputRDBMSEntity.setTableName(inputOracleJaxb.getTableName().getValue());
}
inputRDBMSEntity.setCountQuery(inputOracleJaxb.getCountQuery() == null
? "select count(*) from (" + inputRDBMSEntity.getSelectQuery() + ")"
: inputOracleJaxb.getCountQuery().getValue());
inputRDBMSEntity.setUsername(inputOracleJaxb.getUserName().getValue());
inputRDBMSEntity.setPassword(inputOracleJaxb.getPassword().getValue());
inputRDBMSEntity.setDriverType(inputOracleJaxb.getDriverType().getValue());
if (inputOracleJaxb.getSchemaName() != null) {
inputRDBMSEntity.setSchemaName(inputOracleJaxb.getSchemaName().getValue());
if(inputOracleJaxb.getSelectQuery() == null) {
inputRDBMSEntity.setTableName(
inputOracleJaxb.getSchemaName().getValue() + "." + inputOracleJaxb.getTableName().getValue());
}
} else {
inputRDBMSEntity.setSchemaName(null);
}
/**new parameters that has been added after the open source release*/
inputRDBMSEntity.setNumPartitionsValue(inputOracleJaxb.getNumPartitions() == null ? Integer.MIN_VALUE : inputOracleJaxb.getNumPartitions().getValue().intValue());
if (inputOracleJaxb.getNumPartitions() != null && inputOracleJaxb.getNumPartitions().getValue().intValue() == 0) {
LOG.warn("The number of partitions has been entered as ZERO," +
"\nThe Execution shall still continue but will work on a single" +
"\npartition hence impacting performance");
}
/**
* @note : At first the check is made for the nullability of the partiton value; in case the partition
* value goes missing, the upper bound, lower bound and column name must not hold a value as the
* JDBCRDD has only two JDBC functions as the one which doesn't do any partitioning and does not accept
* the values from the below parameters listed and the second one which does partitoning accepts the
* aforementioned parameters. Absence of any one parameter may lead to undesirable outcomes
* */
if (inputOracleJaxb.getNumPartitions() == null) {
inputRDBMSEntity.setUpperBound(0);
inputRDBMSEntity.setLowerBound(0);
inputRDBMSEntity.setColumnName("");
} else {
if (inputOracleJaxb.getNumPartitions().getUpperBound() == null) {
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Upper bound cannot be NULL when numPartitions holds an integer value");
} else
inputRDBMSEntity.setUpperBound(inputOracleJaxb.getNumPartitions().getUpperBound().getValue().intValue());
if (inputOracleJaxb.getNumPartitions().getLowerBound() == null) {
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Lower bound cannot be NULL when numPartitions holds an integer value");
} else
inputRDBMSEntity.setLowerBound(inputOracleJaxb.getNumPartitions().getLowerBound().getValue().intValue());
if (inputOracleJaxb.getNumPartitions().getColumnName() == null) {
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Column Name cannot be NULL when numPartitions holds an integer value");
} else inputRDBMSEntity.setColumnName(inputOracleJaxb.getNumPartitions().getColumnName().getValue());
if (inputOracleJaxb.getNumPartitions().getLowerBound().getValue()
.intValue() == inputOracleJaxb.getNumPartitions().getUpperBound().getValue().intValue()) {
LOG.warn("'" + inputOracleJaxb.getId() + "'The upper bound and the lower bound values are same! In this case there will only be\n" +
"a single partition");
}
if (inputOracleJaxb.getNumPartitions().getLowerBound().getValue()
.intValue() > inputOracleJaxb.getNumPartitions().getUpperBound().getValue().intValue()) {
LOG.error("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Can\'t proceed with partitioning");
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' The lower bound is greater than upper bound");
}
}
//fetchsize
inputRDBMSEntity.setFetchSize(inputOracleJaxb.getFetchSize() == null ? null : inputOracleJaxb.getFetchSize().getValue());
//extra url parameters
if (inputOracleJaxb.getExtraUrlParams() != null) {
String rawParam = inputOracleJaxb.getExtraUrlParams().getValue();
Pattern regexForComma = Pattern.compile("([,]{0,1})");
Pattern regexForOthers = Pattern.compile("[$&:;?@#|'<>.^*()%+!]");
Pattern regexForRepitititons = Pattern.compile("([,]{2,})");
Matcher commaMatcher = regexForComma.matcher(rawParam);
Matcher otherCharMatcher = regexForOthers.matcher(rawParam);
Matcher doubleCharMatcher = regexForRepitititons.matcher(rawParam);
if(doubleCharMatcher.find()) {
throw new RuntimeException("Repeated comma found");
}
else if (otherCharMatcher.find()) {
throw new RuntimeException("Other delimiter found");
} else if (commaMatcher.find()) {
/*
* If the string happens to have a , then all the commas shall be replaced by &
* */
String correctedParams = rawParam.replaceAll(",", "&").replaceAll("(\\s+)","");
LOG.info("The extraUrlParams being used as"+ correctedParams );
inputRDBMSEntity.setExtraUrlParameters(correctedParams);
}
else {
String correctedParams = rawParam.replaceAll("(\\s+)","&");
LOG.info("The extraUrlParams being used as "+ correctedParams);
inputRDBMSEntity.setExtraUrlParameters(correctedParams);
}
} else {
LOG.info("extraUrlParameters initialized with null");
inputRDBMSEntity.setExtraUrlParameters(null);
}
/**END*/
}
@Override
public InputRDBMSEntity getEntity() {
return inputRDBMSEntity;
}
} | hydrograph.engine/hydrograph.engine.core/src/main/java/hydrograph/engine/core/component/generator/InputOracleEntityGenerator.java | /*******************************************************************************
* Copyright 2017 Capital One Services, LLC and Bitwise, 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 hydrograph.engine.core.component.generator;
import hydrograph.engine.core.component.entity.InputRDBMSEntity;
import hydrograph.engine.core.component.entity.utils.InputEntityUtils;
import hydrograph.engine.core.component.generator.base.InputComponentGeneratorBase;
import hydrograph.engine.core.constants.Constants;
import hydrograph.engine.jaxb.commontypes.TypeBaseComponent;
import hydrograph.engine.jaxb.inputtypes.Oracle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The Class InputOracleEntityGenerator.
*
* @author Bitwise
*/
public class InputOracleEntityGenerator extends
InputComponentGeneratorBase {
private static Logger LOG = LoggerFactory
.getLogger(InputOracleEntityGenerator.class);
private Oracle inputOracleJaxb;
private InputRDBMSEntity inputRDBMSEntity;
public InputOracleEntityGenerator(TypeBaseComponent baseComponent) {
super(baseComponent);
}
@Override
public void castComponentFromBase(TypeBaseComponent baseComponent) {
inputOracleJaxb = (Oracle) baseComponent;
}
@Override
public void createEntity() {
inputRDBMSEntity = new InputRDBMSEntity();
}
@Override
public void initializeEntity() {
LOG.trace("Initializing input file Oracle component: " + inputOracleJaxb.getId());
inputRDBMSEntity.setComponentId(inputOracleJaxb.getId());
inputRDBMSEntity.setFieldsList(InputEntityUtils.extractInputFields(
inputOracleJaxb.getOutSocket().get(0).getSchema().getFieldOrRecordOrIncludeExternalSchema()));
inputRDBMSEntity.setOutSocketList(InputEntityUtils.extractOutSocket(inputOracleJaxb.getOutSocket()));
inputRDBMSEntity.setSid(inputOracleJaxb.getSid().getValue());
inputRDBMSEntity.setHostName(inputOracleJaxb.getHostName().getValue());
inputRDBMSEntity.setPort(inputOracleJaxb.getPort() == null ? Constants.ORACLE_PORT_NUMBER
: inputOracleJaxb.getPort().getValue().intValue());
inputRDBMSEntity.setRuntimeProperties(inputOracleJaxb.getRuntimeProperties() == null ? new Properties() : InputEntityUtils
.extractRuntimeProperties(inputOracleJaxb.getRuntimeProperties()));
inputRDBMSEntity.setBatch(inputOracleJaxb.getBatch());
if (inputOracleJaxb.getSelectQuery() != null) {
inputRDBMSEntity.setTableName("Dual");
inputRDBMSEntity.setSelectQuery(inputOracleJaxb.getSelectQuery().getValue());
} else {
inputRDBMSEntity.setSelectQuery(null);
inputRDBMSEntity.setTableName(inputOracleJaxb.getTableName().getValue());
}
inputRDBMSEntity.setCountQuery(inputOracleJaxb.getCountQuery() == null
? "select count(*) from (" + inputRDBMSEntity.getSelectQuery() + ")"
: inputOracleJaxb.getCountQuery().getValue());
inputRDBMSEntity.setUsername(inputOracleJaxb.getUserName().getValue());
inputRDBMSEntity.setPassword(inputOracleJaxb.getPassword().getValue());
inputRDBMSEntity.setDriverType(inputOracleJaxb.getDriverType().getValue());
if (inputOracleJaxb.getSchemaName() != null) {
inputRDBMSEntity.setSchemaName(inputOracleJaxb.getSchemaName().getValue());
inputRDBMSEntity.setTableName(
inputOracleJaxb.getSchemaName().getValue() + "." + inputOracleJaxb.getTableName().getValue());
} else {
inputRDBMSEntity.setSchemaName(null);
}
/**new parameters that has been added after the open source release*/
inputRDBMSEntity.setNumPartitionsValue(inputOracleJaxb.getNumPartitions() == null ? Integer.MIN_VALUE : inputOracleJaxb.getNumPartitions().getValue().intValue());
if (inputOracleJaxb.getNumPartitions() != null && inputOracleJaxb.getNumPartitions().getValue().intValue() == 0) {
LOG.warn("The number of partitions has been entered as ZERO," +
"\nThe Execution shall still continue but will work on a single" +
"\npartition hence impacting performance");
}
/**
* @note : At first the check is made for the nullability of the partiton value; in case the partition
* value goes missing, the upper bound, lower bound and column name must not hold a value as the
* JDBCRDD has only two JDBC functions as the one which doesn't do any partitioning and does not accept
* the values from the below parameters listed and the second one which does partitoning accepts the
* aforementioned parameters. Absence of any one parameter may lead to undesirable outcomes
* */
if (inputOracleJaxb.getNumPartitions() == null) {
inputRDBMSEntity.setUpperBound(0);
inputRDBMSEntity.setLowerBound(0);
inputRDBMSEntity.setColumnName("");
} else {
if (inputOracleJaxb.getNumPartitions().getUpperBound() == null) {
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Upper bound cannot be NULL when numPartitions holds an integer value");
} else
inputRDBMSEntity.setUpperBound(inputOracleJaxb.getNumPartitions().getUpperBound().getValue().intValue());
if (inputOracleJaxb.getNumPartitions().getLowerBound() == null) {
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Lower bound cannot be NULL when numPartitions holds an integer value");
} else
inputRDBMSEntity.setLowerBound(inputOracleJaxb.getNumPartitions().getLowerBound().getValue().intValue());
if (inputOracleJaxb.getNumPartitions().getColumnName() == null) {
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Column Name cannot be NULL when numPartitions holds an integer value");
} else inputRDBMSEntity.setColumnName(inputOracleJaxb.getNumPartitions().getColumnName().getValue());
if (inputOracleJaxb.getNumPartitions().getLowerBound().getValue()
.intValue() == inputOracleJaxb.getNumPartitions().getUpperBound().getValue().intValue()) {
LOG.warn("'" + inputOracleJaxb.getId() + "'The upper bound and the lower bound values are same! In this case there will only be\n" +
"a single partition");
}
if (inputOracleJaxb.getNumPartitions().getLowerBound().getValue()
.intValue() > inputOracleJaxb.getNumPartitions().getUpperBound().getValue().intValue()) {
LOG.error("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' Can\'t proceed with partitioning");
throw new RuntimeException("Error in Input Oracle Component '" + inputOracleJaxb.getId() + "' The lower bound is greater than upper bound");
}
}
//fetchsize
inputRDBMSEntity.setFetchSize(inputOracleJaxb.getFetchSize() == null ? null : inputOracleJaxb.getFetchSize().getValue());
//extra url parameters
if (inputOracleJaxb.getExtraUrlParams() != null) {
String rawParam = inputOracleJaxb.getExtraUrlParams().getValue();
Pattern regexForComma = Pattern.compile("([,]{0,1})");
Pattern regexForOthers = Pattern.compile("[$&:;?@#|'<>.^*()%+!]");
Pattern regexForRepitititons = Pattern.compile("([,]{2,})");
Matcher commaMatcher = regexForComma.matcher(rawParam);
Matcher otherCharMatcher = regexForOthers.matcher(rawParam);
Matcher doubleCharMatcher = regexForRepitititons.matcher(rawParam);
if(doubleCharMatcher.find()) {
throw new RuntimeException("Repeated comma found");
}
else if (otherCharMatcher.find()) {
throw new RuntimeException("Other delimiter found");
} else if (commaMatcher.find()) {
/*
* If the string happens to have a , then all the commas shall be replaced by &
* */
String correctedParams = rawParam.replaceAll(",", "&").replaceAll("(\\s+)","");
LOG.info("The extraUrlParams being used as"+ correctedParams );
inputRDBMSEntity.setExtraUrlParameters(correctedParams);
}
else {
String correctedParams = rawParam.replaceAll("(\\s+)","&");
LOG.info("The extraUrlParams being used as "+ correctedParams);
inputRDBMSEntity.setExtraUrlParameters(correctedParams);
}
} else {
LOG.info("extraUrlParameters initialized with null");
inputRDBMSEntity.setExtraUrlParameters(null);
}
/**END*/
}
@Override
public InputRDBMSEntity getEntity() {
return inputRDBMSEntity;
}
} | Fixed a bug with the Oracle component failing when a select query was passed.
| hydrograph.engine/hydrograph.engine.core/src/main/java/hydrograph/engine/core/component/generator/InputOracleEntityGenerator.java | Fixed a bug with the Oracle component failing when a select query was passed. | <ide><path>ydrograph.engine/hydrograph.engine.core/src/main/java/hydrograph/engine/core/component/generator/InputOracleEntityGenerator.java
<ide> inputRDBMSEntity.setDriverType(inputOracleJaxb.getDriverType().getValue());
<ide> if (inputOracleJaxb.getSchemaName() != null) {
<ide> inputRDBMSEntity.setSchemaName(inputOracleJaxb.getSchemaName().getValue());
<del> inputRDBMSEntity.setTableName(
<del> inputOracleJaxb.getSchemaName().getValue() + "." + inputOracleJaxb.getTableName().getValue());
<add> if(inputOracleJaxb.getSelectQuery() == null) {
<add> inputRDBMSEntity.setTableName(
<add> inputOracleJaxb.getSchemaName().getValue() + "." + inputOracleJaxb.getTableName().getValue());
<add> }
<ide> } else {
<ide> inputRDBMSEntity.setSchemaName(null);
<ide> } |
|
Java | apache-2.0 | 060dec5b54bc96d2e239b1e01e9c86ebcd91ba02 | 0 | MichaelBel/Material | package org.app.material.widget;
import android.content.Context;
import android.support.annotation.ColorInt;
import android.support.annotation.NonNull;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import org.app.material.R;
import org.app.material.utils.AndroidUtilities;
import org.app.material.widget.ColorPicker.Channel;
import org.app.material.widget.ColorPicker.ChannelView;
import org.app.material.widget.ColorPicker.ColorMode;
import org.app.material.widget.ColorPicker.IndicatorMode;
import org.app.material.widget.ColorPicker.OnProgressChangedListener;
import java.util.ArrayList;
import java.util.List;
public class ColorView extends FrameLayout {
public static final int DEFAULT_COLOR = 0xFFFF5252;
public static final ColorMode DEFAULT_MODE = ColorMode.RGB;
public static final IndicatorMode DEFAULT_INDICATOR = IndicatorMode.DECIMAL;
private ColorMode colorMode;
private IndicatorMode indicatorMode;
private @ColorInt int initialColor;
private View colorView;
private List<ChannelView> channelViews;
public ColorView(Context context) {
this(context, DEFAULT_COLOR, DEFAULT_MODE, DEFAULT_INDICATOR);
}
public ColorView(@NonNull Context context, @ColorInt int initColor,
@NonNull final ColorMode colorMode, @NonNull IndicatorMode indicatorMode) {
super(context);
AndroidUtilities.bind(context);
this.setClipToPadding(false);
this.colorMode = colorMode;
this.indicatorMode = indicatorMode;
this.initialColor = initColor;
inflate(getContext(), R.layout.views, this);
colorView = findViewById(R.id.color_view);
colorView.setBackgroundColor(initialColor);
List<Channel> channels = colorMode.getColorMode().getChannels();
channelViews = new ArrayList<>();
for (Channel c : channels) {
channelViews.add(new ChannelView(c, initialColor, indicatorMode, context));
}
OnProgressChangedListener seekBarChangeListener = new OnProgressChangedListener() {
@Override
public void onProgressChanged() {
List<Channel> channels = new ArrayList<>();
for (ChannelView chan : channelViews) {
channels.add(chan.getChannel());
}
initialColor = colorMode.getColorMode().evaluateColor(channels);
colorView.setBackgroundColor(initialColor);
}
};
ViewGroup channelContainer = (ViewGroup) findViewById(R.id.channel_container);
for (ChannelView c : channelViews) {
channelContainer.addView(c);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) c.getLayoutParams();
params.topMargin = AndroidUtilities.dp(16);
params.bottomMargin = AndroidUtilities.dp(4);
c.registerListener(seekBarChangeListener);
}
}
@ColorInt
public int getInitialColor() {
return initialColor;
}
@NonNull
public ColorMode getColorMode() {
return colorMode;
}
@NonNull
public IndicatorMode getIndicatorMode() {
return indicatorMode;
}
} | material/src/main/java/org/app/material/widget/ColorView.java | package org.app.material.widget;
import android.content.Context;
import android.support.annotation.ColorInt;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import org.app.material.R;
import org.app.material.utils.AndroidUtilities;
import org.app.material.utils.Color;
import org.app.material.widget.ColorPicker.Channel;
import org.app.material.widget.ColorPicker.ChannelView;
import org.app.material.widget.ColorPicker.ColorMode;
import org.app.material.widget.ColorPicker.IndicatorMode;
import org.app.material.widget.ColorPicker.OnProgressChangedListener;
import java.util.ArrayList;
import java.util.List;
public class ColorView extends FrameLayout {
public static int DEFAULT_COLOR;
private final ColorMode colorMode;
private IndicatorMode indicatorMode;
private @ColorInt static int currentColor;
public final static ColorMode DEFAULT_MODE = ColorMode.RGB;
public final static IndicatorMode DEFAULT_INDICATOR = IndicatorMode.DECIMAL;
public ColorView(Context context) {
this(DEFAULT_COLOR, DEFAULT_MODE, DEFAULT_INDICATOR, context);
}
public ColorView(@ColorInt int initialColor, final ColorMode colorMode, IndicatorMode indicatorMode, Context context) {
super(context);
AndroidUtilities.bind(context);
DEFAULT_COLOR = Color.getThemeColor(context, R.attr.colorAccent);
this.indicatorMode = indicatorMode;
this.colorMode = colorMode;
currentColor = initialColor;
DEFAULT_COLOR = AndroidUtilities.getThemeColor(R.attr.colorAccent);
inflate(getContext(), R.layout.views, this);
setClipToPadding(false);
final View colorView = findViewById(R.id.color_view);
colorView.setBackgroundColor(currentColor);
List<Channel> channels = colorMode.getColorMode().getChannels();
final List<ChannelView> channelViews = new ArrayList<>();
for (Channel c : channels) {
channelViews.add(new ChannelView(c, currentColor, indicatorMode, getContext()));
}
OnProgressChangedListener seekBarChangeListener = new OnProgressChangedListener() {
@Override
public void onProgressChanged() {
List<Channel> channels = new ArrayList<>();
for (ChannelView chan : channelViews) {
channels.add(chan.getChannel());
}
currentColor = colorMode.getColorMode().evaluateColor(channels);
colorView.setBackgroundColor(currentColor);
}
};
ViewGroup channelContainer = (ViewGroup) findViewById(R.id.channel_container);
for (ChannelView c : channelViews) {
channelContainer.addView(c);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) c.getLayoutParams();
params.topMargin = AndroidUtilities.dp(16);
params.bottomMargin = AndroidUtilities.dp(4);
c.registerListener(seekBarChangeListener);
}
}
public ColorMode getColorMode() {
return colorMode;
}
public static int getCurrentColor() {
return currentColor;
}
public IndicatorMode getIndicatorMode() {
return indicatorMode;
}
} | Update widget
| material/src/main/java/org/app/material/widget/ColorView.java | Update widget | <ide><path>aterial/src/main/java/org/app/material/widget/ColorView.java
<ide>
<ide> import android.content.Context;
<ide> import android.support.annotation.ColorInt;
<add>import android.support.annotation.NonNull;
<ide> import android.view.View;
<ide> import android.view.ViewGroup;
<ide> import android.widget.FrameLayout;
<ide>
<ide> import org.app.material.R;
<ide> import org.app.material.utils.AndroidUtilities;
<del>import org.app.material.utils.Color;
<ide> import org.app.material.widget.ColorPicker.Channel;
<ide> import org.app.material.widget.ColorPicker.ChannelView;
<ide> import org.app.material.widget.ColorPicker.ColorMode;
<ide>
<ide> public class ColorView extends FrameLayout {
<ide>
<del> public static int DEFAULT_COLOR;
<add> public static final int DEFAULT_COLOR = 0xFFFF5252;
<add> public static final ColorMode DEFAULT_MODE = ColorMode.RGB;
<add> public static final IndicatorMode DEFAULT_INDICATOR = IndicatorMode.DECIMAL;
<ide>
<add> private ColorMode colorMode;
<add> private IndicatorMode indicatorMode;
<add> private @ColorInt int initialColor;
<ide>
<del> private final ColorMode colorMode;
<del> private IndicatorMode indicatorMode;
<del> private @ColorInt static int currentColor;
<del> public final static ColorMode DEFAULT_MODE = ColorMode.RGB;
<del> public final static IndicatorMode DEFAULT_INDICATOR = IndicatorMode.DECIMAL;
<add> private View colorView;
<add> private List<ChannelView> channelViews;
<ide>
<ide> public ColorView(Context context) {
<del> this(DEFAULT_COLOR, DEFAULT_MODE, DEFAULT_INDICATOR, context);
<add> this(context, DEFAULT_COLOR, DEFAULT_MODE, DEFAULT_INDICATOR);
<ide> }
<ide>
<del> public ColorView(@ColorInt int initialColor, final ColorMode colorMode, IndicatorMode indicatorMode, Context context) {
<add> public ColorView(@NonNull Context context, @ColorInt int initColor,
<add> @NonNull final ColorMode colorMode, @NonNull IndicatorMode indicatorMode) {
<ide> super(context);
<ide> AndroidUtilities.bind(context);
<ide>
<del> DEFAULT_COLOR = Color.getThemeColor(context, R.attr.colorAccent);
<add> this.setClipToPadding(false);
<ide>
<del>
<del>
<del>
<add> this.colorMode = colorMode;
<ide> this.indicatorMode = indicatorMode;
<del> this.colorMode = colorMode;
<del> currentColor = initialColor;
<del>
<del> DEFAULT_COLOR = AndroidUtilities.getThemeColor(R.attr.colorAccent);
<add> this.initialColor = initColor;
<ide>
<ide> inflate(getContext(), R.layout.views, this);
<del> setClipToPadding(false);
<ide>
<del> final View colorView = findViewById(R.id.color_view);
<del> colorView.setBackgroundColor(currentColor);
<add> colorView = findViewById(R.id.color_view);
<add> colorView.setBackgroundColor(initialColor);
<ide>
<ide> List<Channel> channels = colorMode.getColorMode().getChannels();
<ide>
<del> final List<ChannelView> channelViews = new ArrayList<>();
<del>
<add> channelViews = new ArrayList<>();
<ide> for (Channel c : channels) {
<del> channelViews.add(new ChannelView(c, currentColor, indicatorMode, getContext()));
<add> channelViews.add(new ChannelView(c, initialColor, indicatorMode, context));
<ide> }
<ide>
<ide> OnProgressChangedListener seekBarChangeListener = new OnProgressChangedListener() {
<ide> channels.add(chan.getChannel());
<ide> }
<ide>
<del> currentColor = colorMode.getColorMode().evaluateColor(channels);
<del> colorView.setBackgroundColor(currentColor);
<add> initialColor = colorMode.getColorMode().evaluateColor(channels);
<add> colorView.setBackgroundColor(initialColor);
<ide> }
<ide> };
<ide>
<ide>
<ide> for (ChannelView c : channelViews) {
<ide> channelContainer.addView(c);
<add>
<ide> LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) c.getLayoutParams();
<ide> params.topMargin = AndroidUtilities.dp(16);
<ide> params.bottomMargin = AndroidUtilities.dp(4);
<add>
<ide> c.registerListener(seekBarChangeListener);
<ide> }
<ide> }
<ide>
<add> @ColorInt
<add> public int getInitialColor() {
<add> return initialColor;
<add> }
<add>
<add> @NonNull
<ide> public ColorMode getColorMode() {
<ide> return colorMode;
<ide> }
<ide>
<del> public static int getCurrentColor() {
<del> return currentColor;
<del> }
<del>
<add> @NonNull
<ide> public IndicatorMode getIndicatorMode() {
<ide> return indicatorMode;
<ide> } |
|
Java | apache-2.0 | 9aef684f63e742c03708e0635d4653319ea85e98 | 0 | redisson/redisson,mrniko/redisson | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.codec;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
/**
*
* @author Nikita Koksharov
*
*/
public class KryoCodec extends BaseCodec {
public class RedissonKryoCodecException extends RuntimeException {
private static final long serialVersionUID = 9172336149805414947L;
public RedissonKryoCodecException(Throwable cause) {
super(cause.getMessage(), cause);
setStackTrace(cause.getStackTrace());
}
}
private final Queue<Kryo> objects = new ConcurrentLinkedQueue<>();
private final List<Class<?>> classes;
private final ClassLoader classLoader;
private final Decoder<Object> decoder = new Decoder<Object>() {
@Override
public Object decode(ByteBuf buf, State state) throws IOException {
Kryo kryo = null;
try {
kryo = get();
return kryo.readClassAndObject(new Input(new ByteBufInputStream(buf)));
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RedissonKryoCodecException(e);
} finally {
if (kryo != null) {
yield(kryo);
}
}
}
};
private final Encoder encoder = new Encoder() {
@Override
public ByteBuf encode(Object in) throws IOException {
Kryo kryo = null;
ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
try {
ByteBufOutputStream baos = new ByteBufOutputStream(out);
Output output = new Output(baos);
kryo = get();
kryo.writeClassAndObject(output, in);
output.close();
return baos.buffer();
} catch (Exception e) {
out.release();
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RedissonKryoCodecException(e);
} finally {
if (kryo != null) {
yield(kryo);
}
}
}
};
public KryoCodec() {
this(Collections.<Class<?>>emptyList());
}
public KryoCodec(ClassLoader classLoader) {
this(Collections.<Class<?>>emptyList(), classLoader);
}
public KryoCodec(ClassLoader classLoader, KryoCodec codec) {
this(codec.classes, classLoader);
}
public KryoCodec(List<Class<?>> classes) {
this(classes, null);
}
public KryoCodec(List<Class<?>> classes, ClassLoader classLoader) {
this.classes = classes;
this.classLoader = classLoader;
}
public Kryo get() {
Kryo kryo = objects.poll();
if (kryo == null) {
kryo = createInstance(classes, classLoader);
}
return kryo;
}
public void yield(Kryo kryo) {
objects.offer(kryo);
}
/**
* Sub classes can customize the Kryo instance by overriding this method
*
* @return create Kryo instance
*/
protected Kryo createInstance(List<Class<?>> classes, ClassLoader classLoader) {
Kryo kryo = new Kryo();
if (classLoader != null) {
kryo.setClassLoader(classLoader);
}
kryo.setReferences(false);
for (Class<?> clazz : classes) {
kryo.register(clazz);
}
return kryo;
}
@Override
public Decoder<Object> getValueDecoder() {
return decoder;
}
@Override
public Encoder getValueEncoder() {
return encoder;
}
@Override
public ClassLoader getClassLoader() {
if (classLoader != null) {
return classLoader;
}
return super.getClassLoader();
}
}
| redisson/src/main/java/org/redisson/codec/KryoCodec.java | /**
* Copyright (c) 2013-2020 Nikita Koksharov
*
* 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.redisson.codec;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.redisson.client.codec.BaseCodec;
import org.redisson.client.handler.State;
import org.redisson.client.protocol.Decoder;
import org.redisson.client.protocol.Encoder;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.buffer.ByteBufInputStream;
import io.netty.buffer.ByteBufOutputStream;
/**
*
* @author Nikita Koksharov
*
*/
public class KryoCodec extends BaseCodec {
public interface KryoPool {
Kryo get();
void yield(Kryo kryo);
ClassLoader getClassLoader();
List<Class<?>> getClasses();
}
public static class KryoPoolImpl implements KryoPool {
private final Queue<Kryo> objects = new ConcurrentLinkedQueue<Kryo>();
private final List<Class<?>> classes;
private final ClassLoader classLoader;
public KryoPoolImpl(List<Class<?>> classes, ClassLoader classLoader) {
this.classes = classes;
this.classLoader = classLoader;
}
public Kryo get() {
Kryo kryo = objects.poll();
if (kryo == null) {
kryo = createInstance();
}
return kryo;
}
public void yield(Kryo kryo) {
objects.offer(kryo);
}
/**
* Sub classes can customize the Kryo instance by overriding this method
*
* @return create Kryo instance
*/
protected Kryo createInstance() {
Kryo kryo = new Kryo();
if (classLoader != null) {
kryo.setClassLoader(classLoader);
}
kryo.setReferences(false);
for (Class<?> clazz : classes) {
kryo.register(clazz);
}
return kryo;
}
public List<Class<?>> getClasses() {
return classes;
}
@Override
public ClassLoader getClassLoader() {
return classLoader;
}
}
public class RedissonKryoCodecException extends RuntimeException {
private static final long serialVersionUID = 9172336149805414947L;
public RedissonKryoCodecException(Throwable cause) {
super(cause.getMessage(), cause);
setStackTrace(cause.getStackTrace());
}
}
private final KryoPool kryoPool;
private final Decoder<Object> decoder = new Decoder<Object>() {
@Override
public Object decode(ByteBuf buf, State state) throws IOException {
Kryo kryo = null;
try {
kryo = kryoPool.get();
return kryo.readClassAndObject(new Input(new ByteBufInputStream(buf)));
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RedissonKryoCodecException(e);
} finally {
if (kryo != null) {
kryoPool.yield(kryo);
}
}
}
};
private final Encoder encoder = new Encoder() {
@Override
public ByteBuf encode(Object in) throws IOException {
Kryo kryo = null;
ByteBuf out = ByteBufAllocator.DEFAULT.buffer();
try {
ByteBufOutputStream baos = new ByteBufOutputStream(out);
Output output = new Output(baos);
kryo = kryoPool.get();
kryo.writeClassAndObject(output, in);
output.close();
return baos.buffer();
} catch (Exception e) {
out.release();
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RedissonKryoCodecException(e);
} finally {
if (kryo != null) {
kryoPool.yield(kryo);
}
}
}
};
public KryoCodec() {
this(Collections.<Class<?>>emptyList());
}
public KryoCodec(ClassLoader classLoader) {
this(Collections.<Class<?>>emptyList(), classLoader);
}
public KryoCodec(ClassLoader classLoader, KryoCodec codec) {
this(codec.kryoPool.getClasses(), classLoader);
}
public KryoCodec(List<Class<?>> classes) {
this(classes, null);
}
public KryoCodec(List<Class<?>> classes, ClassLoader classLoader) {
this(new KryoPoolImpl(classes, classLoader));
}
public KryoCodec(KryoPool kryoPool) {
this.kryoPool = kryoPool;
}
@Override
public Decoder<Object> getValueDecoder() {
return decoder;
}
@Override
public Encoder getValueEncoder() {
return encoder;
}
@Override
public ClassLoader getClassLoader() {
if (kryoPool.getClassLoader() != null) {
return kryoPool.getClassLoader();
}
return super.getClassLoader();
}
}
| KryoCodec refactoring. #2402
| redisson/src/main/java/org/redisson/codec/KryoCodec.java | KryoCodec refactoring. #2402 | <ide><path>edisson/src/main/java/org/redisson/codec/KryoCodec.java
<ide> */
<ide> package org.redisson.codec;
<ide>
<add>import com.esotericsoftware.kryo.Kryo;
<add>import com.esotericsoftware.kryo.io.Input;
<add>import com.esotericsoftware.kryo.io.Output;
<add>import io.netty.buffer.ByteBuf;
<add>import io.netty.buffer.ByteBufAllocator;
<add>import io.netty.buffer.ByteBufInputStream;
<add>import io.netty.buffer.ByteBufOutputStream;
<add>import org.redisson.client.codec.BaseCodec;
<add>import org.redisson.client.handler.State;
<add>import org.redisson.client.protocol.Decoder;
<add>import org.redisson.client.protocol.Encoder;
<add>
<ide> import java.io.IOException;
<ide> import java.util.Collections;
<ide> import java.util.List;
<ide> import java.util.Queue;
<ide> import java.util.concurrent.ConcurrentLinkedQueue;
<del>
<del>import org.redisson.client.codec.BaseCodec;
<del>import org.redisson.client.handler.State;
<del>import org.redisson.client.protocol.Decoder;
<del>import org.redisson.client.protocol.Encoder;
<del>
<del>import com.esotericsoftware.kryo.Kryo;
<del>import com.esotericsoftware.kryo.io.Input;
<del>import com.esotericsoftware.kryo.io.Output;
<del>
<del>import io.netty.buffer.ByteBuf;
<del>import io.netty.buffer.ByteBufAllocator;
<del>import io.netty.buffer.ByteBufInputStream;
<del>import io.netty.buffer.ByteBufOutputStream;
<ide>
<ide> /**
<ide> *
<ide> *
<ide> */
<ide> public class KryoCodec extends BaseCodec {
<del>
<del> public interface KryoPool {
<del>
<del> Kryo get();
<del>
<del> void yield(Kryo kryo);
<del>
<del> ClassLoader getClassLoader();
<del>
<del> List<Class<?>> getClasses();
<del>
<del> }
<del>
<del> public static class KryoPoolImpl implements KryoPool {
<del>
<del> private final Queue<Kryo> objects = new ConcurrentLinkedQueue<Kryo>();
<del> private final List<Class<?>> classes;
<del> private final ClassLoader classLoader;
<del>
<del> public KryoPoolImpl(List<Class<?>> classes, ClassLoader classLoader) {
<del> this.classes = classes;
<del> this.classLoader = classLoader;
<del> }
<del>
<del> public Kryo get() {
<del> Kryo kryo = objects.poll();
<del> if (kryo == null) {
<del> kryo = createInstance();
<del> }
<del> return kryo;
<del> }
<del>
<del> public void yield(Kryo kryo) {
<del> objects.offer(kryo);
<del> }
<del>
<del> /**
<del> * Sub classes can customize the Kryo instance by overriding this method
<del> *
<del> * @return create Kryo instance
<del> */
<del> protected Kryo createInstance() {
<del> Kryo kryo = new Kryo();
<del> if (classLoader != null) {
<del> kryo.setClassLoader(classLoader);
<del> }
<del> kryo.setReferences(false);
<del> for (Class<?> clazz : classes) {
<del> kryo.register(clazz);
<del> }
<del> return kryo;
<del> }
<del>
<del> public List<Class<?>> getClasses() {
<del> return classes;
<del> }
<del>
<del> @Override
<del> public ClassLoader getClassLoader() {
<del> return classLoader;
<del> }
<del>
<del> }
<ide>
<ide> public class RedissonKryoCodecException extends RuntimeException {
<ide>
<ide> }
<ide> }
<ide>
<del> private final KryoPool kryoPool;
<add> private final Queue<Kryo> objects = new ConcurrentLinkedQueue<>();
<add> private final List<Class<?>> classes;
<add> private final ClassLoader classLoader;
<ide>
<ide> private final Decoder<Object> decoder = new Decoder<Object>() {
<ide> @Override
<ide> public Object decode(ByteBuf buf, State state) throws IOException {
<ide> Kryo kryo = null;
<ide> try {
<del> kryo = kryoPool.get();
<add> kryo = get();
<ide> return kryo.readClassAndObject(new Input(new ByteBufInputStream(buf)));
<ide> } catch (Exception e) {
<ide> if (e instanceof RuntimeException) {
<ide> throw new RedissonKryoCodecException(e);
<ide> } finally {
<ide> if (kryo != null) {
<del> kryoPool.yield(kryo);
<add> yield(kryo);
<ide> }
<ide> }
<ide> }
<ide> try {
<ide> ByteBufOutputStream baos = new ByteBufOutputStream(out);
<ide> Output output = new Output(baos);
<del> kryo = kryoPool.get();
<add> kryo = get();
<ide> kryo.writeClassAndObject(output, in);
<ide> output.close();
<ide> return baos.buffer();
<ide> throw new RedissonKryoCodecException(e);
<ide> } finally {
<ide> if (kryo != null) {
<del> kryoPool.yield(kryo);
<add> yield(kryo);
<ide> }
<ide> }
<ide> }
<ide> }
<ide>
<ide> public KryoCodec(ClassLoader classLoader, KryoCodec codec) {
<del> this(codec.kryoPool.getClasses(), classLoader);
<add> this(codec.classes, classLoader);
<ide> }
<ide>
<ide> public KryoCodec(List<Class<?>> classes) {
<ide> }
<ide>
<ide> public KryoCodec(List<Class<?>> classes, ClassLoader classLoader) {
<del> this(new KryoPoolImpl(classes, classLoader));
<add> this.classes = classes;
<add> this.classLoader = classLoader;
<ide> }
<ide>
<del> public KryoCodec(KryoPool kryoPool) {
<del> this.kryoPool = kryoPool;
<add> public Kryo get() {
<add> Kryo kryo = objects.poll();
<add> if (kryo == null) {
<add> kryo = createInstance(classes, classLoader);
<add> }
<add> return kryo;
<add> }
<add>
<add> public void yield(Kryo kryo) {
<add> objects.offer(kryo);
<add> }
<add>
<add> /**
<add> * Sub classes can customize the Kryo instance by overriding this method
<add> *
<add> * @return create Kryo instance
<add> */
<add> protected Kryo createInstance(List<Class<?>> classes, ClassLoader classLoader) {
<add> Kryo kryo = new Kryo();
<add> if (classLoader != null) {
<add> kryo.setClassLoader(classLoader);
<add> }
<add> kryo.setReferences(false);
<add> for (Class<?> clazz : classes) {
<add> kryo.register(clazz);
<add> }
<add> return kryo;
<ide> }
<ide>
<ide> @Override
<ide>
<ide> @Override
<ide> public ClassLoader getClassLoader() {
<del> if (kryoPool.getClassLoader() != null) {
<del> return kryoPool.getClassLoader();
<add> if (classLoader != null) {
<add> return classLoader;
<ide> }
<ide> return super.getClassLoader();
<ide> } |
|
Java | bsd-2-clause | bbb2d24c400bdcefb0dbba598e7f8b8e5547059a | 0 | martin-kuba/perun,zwejra/perun,martin-kuba/perun,martin-kuba/perun,stavamichal/perun,mvocu/perun,zoraseb/perun,mvocu/perun,zoraseb/perun,zwejra/perun,mvocu/perun,balcirakpeter/perun,martin-kuba/perun,CESNET/perun,CESNET/perun,mvocu/perun,martin-kuba/perun,zlamalp/perun,zwejra/perun,zwejra/perun,zoraseb/perun,stavamichal/perun,martin-kuba/perun,zlamalp/perun,zlamalp/perun,zoraseb/perun,stavamichal/perun,martin-kuba/perun,stavamichal/perun,stavamichal/perun,CESNET/perun,balcirakpeter/perun,CESNET/perun,CESNET/perun,zlamalp/perun,zlamalp/perun,zwejra/perun,stavamichal/perun,balcirakpeter/perun,zwejra/perun,balcirakpeter/perun,stavamichal/perun,CESNET/perun,CESNET/perun,mvocu/perun,balcirakpeter/perun,zlamalp/perun,zoraseb/perun,balcirakpeter/perun,zlamalp/perun,zoraseb/perun,mvocu/perun,balcirakpeter/perun,mvocu/perun | package cz.metacentrum.perun.rpc.methods;
import java.util.ArrayList;
import java.util.List;
import cz.metacentrum.perun.core.api.*;
import cz.metacentrum.perun.core.api.exceptions.AttributeAlreadyMarkedUniqueException;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.PerunException;
import cz.metacentrum.perun.core.api.exceptions.PrivilegeException;
import cz.metacentrum.perun.utils.graphs.GraphTextFormat;
import cz.metacentrum.perun.rpc.ApiCaller;
import cz.metacentrum.perun.rpc.ManagerMethod;
import cz.metacentrum.perun.core.api.exceptions.RpcException;
import cz.metacentrum.perun.rpc.deserializer.Deserializer;
import cz.metacentrum.perun.utils.graphs.GraphDTO;
public enum AttributesManagerMethod implements ManagerMethod {
/*#
* Returns all non-empty User-Facility attributes for selected User and Facility.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @return List<Attribute> All non-empty User-Facility attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
* @throw FacilityNotExistsException When Facility with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Facility attributes for selected Facility.
*
* @param facility int Facility <code>id</code>
* @return List<Attribute> All non-empty Facility attributes
* @throw FacilityNotExistsException When Facility with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Facility attributes for selected Facility
* If <code>attrNames</code> is empty, it returns empty list of attributes
*
* @param facility int Facility <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Facility attributes
* @throw FacilityNotExistsException When Facility with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Vo attributes for selected Vo.
*
* @param vo int Vo <code>id</code>
* @return List<Attribute> All non-empty Vo attributes
* @throw VoNotExistsException When Vo with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Vo attributes for selected Vo.
*
* @param vo int VO <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Vo attributes
* @throw VoNotExistsException When Vo with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:vo:attribute-def:def:contactEmail" , "urn:perun:vo:attribute-def:core:shortName" ]
*/
/*#
* Returns all non-empty UserExtSource attributes for selected UserExtSource.
*
* @param userExtSource int UserExtSource <code>id</code>
* @return List<Attribute> All non-empty UserExtSource attributes
* @throw UserExtSourceNotExistsException When Ues with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified UserExtSource attributes for selected UserExtSource.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified UserExtSource attributes
* @throw UserExtSourceNotExistsException When userExtSource with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:ues:attribute-def:opt:optionalAttribute" ]
*/
/*#
* Returns all non-empty Member-Resource attributes for selected Member and Resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> All non-empty Member-Resource attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns selected non-empty Member, User, Member-Resource and User-Facility attributes (by list of attribute names) for selected Member and Resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also user and user-facility attributes. <code>False</code> is default.
* @param attrNames List<String> List of attribute names
* @return List<Attribute> Selected non-empty User, Member, Member-Resource, User-Facility attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Member-Resource attributes for selected Member and Resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> All non-empty Member-Resource attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Get all attributes by the list of attrNames if they are in one of these namespaces:
* - member
* - group
* - member-group
* - resource
* - member-resource
* - group-resource
* - user (get from member object)
* - facility (get from resource object)
* - user-facility
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> All attributes from supported namespaces.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When Member is not from the same Vo as Resource.
* @throw GroupResourceMismatchException When Group is not from the same Vo as Resource.
*/
/*#
* Returns all non-empty Group-Resource attributes for selected Group and Resource.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> All non-empty Group-Resource attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Group-Resource attributes for selected Group and Resource.
* If <code>workWithGroupAttributes == true</code> then also all non-empty Group attributes are returned.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean If <code>true</code>, return also Group attributes. <code>False</code> is default.
* @return List<Attribute> All non-empty Group-Resource attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Group-Resource attributes for selected Group and Resource.
* If <code>attrNames</code> is empty, it returns all non-empty attributes.
* If <code>workWithGroupAttributes == true</code> then also Group attributes are returned. <code>False</code> is default.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attrNames List<String> Attribute names
* @param workWithGroupAttributes boolean If <code>true</code>, return also Group attributes. <code>False</code> is default.
* @return List<Attribute> Specified Group-Resource attributes and (if workWithGroupAttributes == true) also Group attributes.
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Resource attributes for selected Resource.
*
* @param resource int Resource <code>id</code>
* @return List<Attribute> All non-empty Resource attributes
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Resource attributes for selected Resource.
*
* @param resource int Resource <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Resource attributes.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Member-Group attributes for selected Member and Group.
* If <code>workWithUserAttribute == true</code> then also all non-empty User attributes are returned.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attrNames List<String> Attribute names
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> Specified Member-Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Member attributes for selected Member.
*
* @param member int Member <code>id</code>
* @return List<Attribute> All non-empty Member attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Member attributes for selected Member.
* If <code>workWithUserAttributes == true</code> then also all non-empty User attributes are returned.
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User attributes. <code>False</code> is default.
* @return List<Attribute> All non-empty Member attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Member-Group attributes for selected Member and Group
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Member-Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Member attributes for selected Member.
*
* @param member int Member <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Member attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:member:attribute-def:def:mail" , "urn:perun:member:attribute-def:def:membershipExpiration" ]
*/
/*#
* Returns all non-empty Member-Group attributes for selected Member and Group.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> All Member-Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty User attributes for selected User.
*
* @param user int User <code>id</code>
* @return List<Attribute> All non-empty User attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified User attributes for selected User.
*
* @param user int User <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified User attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:user:attribute-def:def:phone" , "urn:perun:user:attribute-def:def:preferredMail" ]
*/
/*#
* Returns all non-empty Group attributes for selected Group.
*
* @param group int Group <code>id</code>
* @return List<Attribute> All non-empty Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Group attributes for selected Group.
*
* @param group int Group <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:user:attribute-def:core:description" , "urn:perun:user:attribute-def:def:synchronizationEnabled" ]
*/
/*#
* Returns all non-empty Host attributes for selected Host.
*
* @param host int Host <code>id</code>
* @return List<Attribute> All non-empty Host attributes
* @throw HostNotExistsException When Group with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:host:attribute-def:core:hostname" , "urn:perun:host:attribute-def:def:frontend" ]
*/
/*#
* Returns all non-empty Entityless attributes with subject equaled <code>key</code>.
*
* @param key String String <code>key</code>
* @return List<Attribute> All non-empty Entityless attributes
*/
getAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("member") && parms.contains("resource")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
}
} else {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")));
}
}
} else if (parms.contains("vo")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")));
}
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
}
} else if (parms.contains("attrNames") && parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getResourceById(parms.readInt("resource"))
);
}
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithGroupAttributes"));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithGroupAttributes"));
}
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")));
}
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
if (parms.contains("attrNames")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithUserAttributes"));
}
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"));
}
} else if (parms.contains("attrNames")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attrNames", String.class));
}
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")));
}
} else if (parms.contains("user")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")));
}
} else if (parms.contains("group")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")));
}
} else if (parms.contains("host")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")));
} else if (parms.contains("key")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
parms.readString("key"));
} else if (parms.contains("userExtSource")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")));
}
}
else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, group, userExtSource or key");
}
}
},
/*#
* Returns all entityless attributes with <code>attrName</code> (for all namespaces of same attribute).
*
* @param attrName String Attribute name
* @return List<Attribute> All entityless attributes with same name
* @exampleParam attrName "urn:perun:entityless:attribute-def:def:namespace-minUID"
*/
getEntitylessAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getEntitylessAttributes(ac.getSession(), parms.readString("attrName"));
}
},
/*#
* Returns list of Keys which fits the attributeDefinition.
*
* @param attributeDefinition id of the attributeDefinition
* @return List<String> All keys for attributeDefinition
*/
getEntitylessKeys{
@Override
public List<String> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getEntitylessKeys(ac.getSession(), ac.getAttributeDefinitionById(parms.readInt("attributeDefinition")));
}
},
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param group in Group <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param vo int VO <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @param workWithUserAttributes boolean If <code>true</code>, store also User and Member attributes. <code>False</code> is default.
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
setAttributes {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("member") && parms.contains("resource")) {
if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithGroupAttributes"));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, group or userExtSource");
}
return null;
}
},
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param facility int Facility <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param vo int VO <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param resource int Resource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param member int Member <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param user int User <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param host int Host <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param facility int Facility <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param vo int VO <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param group int Group <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param resource int Resource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param member int Member <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param user int User <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param host int Host <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
getAttribute {
@Override
public Attribute call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("attributeId")) {
if (parms.contains("facility")) {
if (parms.contains("user")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readInt("attributeId"));
} else {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readInt("attributeId"));
}
} else if (parms.contains("vo")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readInt("attributeId"));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readInt("attributeId"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readInt("attributeId"));
} else {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readInt("attributeId"));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readInt("attributeId"));
} else {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readInt("attributeId"));
}
} else if (parms.contains("user")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readInt("attributeId"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readInt("attributeId"));
} else if (parms.contains("host")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readInt("attributeId"));
/* Not implemented yet
} else if (parms.contains("key")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
parms.readString("key"),
parms.readInt("attributeId"));
*/
} else if (parms.contains("userExtSource")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readInt("attributeId"));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, key, group or userExtSource");
}
} else {
if (parms.contains("facility")) {
if (parms.contains("user")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readString("attributeName"));
} else {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readString("attributeName"));
}
} else if (parms.contains("vo")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readString("attributeName"));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readString("attributeName"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readString("attributeName"));
} else {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readString("attributeName"));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readString("attributeName"));
} else {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readString("attributeName"));
}
} else if (parms.contains("user")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readString("attributeName"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readString("attributeName"));
} else if (parms.contains("host")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readString("attributeName"));
} else if (parms.contains("userExtSource")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readString("attributeName"));
} else if (parms.contains("key")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
parms.readString("key"),
parms.readString("attributeName"));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, key, group or userExtSource");
}
}
}
},
/*#
* Returns AttributeDefinition.
*
* @param attributeName String Attribute name
* @return AttributeDefinition Definition of an Attribute
*/
getAttributeDefinition {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributeDefinition(ac.getSession(),
parms.readString("attributeName"));
}
},
/*#
* Returns all AttributeDefinitions.
*
* @return List<AttributeDefinition> Definitions of Attributes
*/
getAttributesDefinition {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributesDefinition(ac.getSession());
}
},
/*#
* Returns AttributeDefinition.
*
* @param id int Attribute <code>id</code>
* @return AttributeDefinition Definition of an Attribute
*/
getAttributeDefinitionById {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributeDefinitionById(parms.readInt("id"));
}
},
/*#
* Returns all AttributeDefinitions in a namespace.
*
* @param namespace String Namespace
* @return List<AttributeDefinition> Definitions of Attributes in a namespace
*/
getAttributesDefinitionByNamespace {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributesDefinitionByNamespace(ac.getSession(),
parms.readString("namespace"));
}
},
/*#
* Returns all AttributeDefinitions for every entity and possible combination of entities with rights.
* Only attribute definition of attributes user can read (or write) you will get.
*
* Combination of entities is based on provided parameters, which are optional
* (at least one must be present).
*
* @param member int <code>id</code> of Member
* @param user int <code>id</code> of User
* @param vo int <code>id</code> of Virtual organization
* @param group int <code>id</code> of Group
* @param resource int <code>id</code> of Resource
* @param facility int <code>id</code> of Facility
* @param host int <code>id</code> of Host
* @param userExtSource int <code>id</code> of UserExtSource
*
* @return List<AttributeDefinition> Definitions of Attributes for entities
*/
getAttributesDefinitionWithRights {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
User user = null;
Member member = null;
Vo vo = null;
Group group = null;
Resource resource = null;
Facility facility = null;
Host host = null;
UserExtSource ues = null;
//Not supported entityless attirbutes now
//String entityless = null;
List<PerunBean> entities = new ArrayList<PerunBean>();
//If member exists in query
if (parms.contains("member")) {
member = ac.getMemberById(parms.readInt("member"));
entities.add(member);
}
//If user exists in query
if (parms.contains("user")) {
user = ac.getUserById(parms.readInt("user"));
entities.add(user);
}
//If vo exists in query
if (parms.contains("vo")) {
vo = ac.getVoById(parms.readInt("vo"));
entities.add(vo);
}
//If group exists in query
if (parms.contains("group")) {
group = ac.getGroupById(parms.readInt("group"));
entities.add(group);
}
//If resource exists in query
if (parms.contains("resource")) {
resource = ac.getResourceById(parms.readInt("resource"));
entities.add(resource);
}
//If facility exists in query
if (parms.contains("facility")) {
facility = ac.getFacilityById(parms.readInt("facility"));
entities.add(facility);
}
//If host exists in query
if (parms.contains("host")) {
host = ac.getHostById(parms.readInt("host"));
entities.add(host);
}
//If userExtSource exists in query
if (parms.contains("userExtSource")) {
ues = ac.getUserExtSourceById(parms.readInt("userExtSource"));
entities.add(ues);
}
//If entityless exists in query
/*if(parms.contains("entityless")) {
}*/
List<AttributeDefinition> attributesDefinition = ac.getAttributesManager().getAttributesDefinitionWithRights(ac.getSession(), entities);
return attributesDefinition;
}
},
/*#
* Sets an Attribute.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param facility int Facility <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param vo int VO <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param resource int Resource <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param member int Member <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param user int User <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param group int Group <code>id</code>
* @param attribute Attribute JSON object
*
*/
/*#
* Sets an Attribute.
*
* @param host int Host <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute Attribute JSON object
*/
setAttribute {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("key")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
parms.readString("key"),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, user, member, host, key, group or userExtSource");
}
return null;
}
},
/*#
* Creates AttributeDefinition
*
* AttributeDefinition object must contain: namespace, friendlyName, type. Description, displayName and unique are optional. Other Parameters are ignored.
* @param attribute AttributeDefinition object
* @return AttributeDefinition Created AttributeDefinition
* @exampleParam attribute { "friendlyName": "kerberosLogins", "namespace": "urn:perun:user:attribute-def:def", "type": "java.util.ArrayList" }
*/
/*#
* Creates AttributeDefinition
*
* @param friendlyName String friendlyName
* @param namespace String namespace in URN format
* @param description String description
* @param type String type which is one of the: "java.lang.String", "java.lang.Integer", "java.lang.Boolean", "java.util.ArrayList",
* "java.util.LinkedHashMap", "java.lang.LargeString" or "java.util.LargeArrayList"
* @param displayName String displayName
* @param unique Boolean unique
* @return AttributeDefinition Created AttributeDefinition
* @exampleParam friendlyName "kerberosLogins"
* @exampleParam namespace "urn:perun:user:attribute-def:def"
* @exampleParam type "java.util.ArrayList"
*/
createAttribute {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("attribute")) {
return ac.getAttributesManager().createAttribute(ac.getSession(),
parms.read("attribute", AttributeDefinition.class));
} else if (parms.contains("friendlyName") && parms.contains("namespace") && parms.contains("description") && parms.contains("type")
&& parms.contains("displayName") && parms.contains("unique")) {
AttributeDefinition attribute = new AttributeDefinition();
attribute.setFriendlyName(parms.readString("friendlyName"));
attribute.setNamespace(parms.readString("namespace"));
attribute.setDescription(parms.readString("description"));
attribute.setType(parms.readString("type"));
attribute.setDisplayName(parms.readString("displayName"));
attribute.setUnique(parms.readBoolean("unique"));
return ac.getAttributesManager().createAttribute(ac.getSession(), attribute);
} else {
throw new RpcException(RpcException.Type.WRONG_PARAMETER);
}
}
},
/*#
* Deletes attribute definition from Perun.
*
* Deletion fails if any entity in Perun has
* any value for this attribute set.
*
* @param attribute int AttributeDefinition <code>id</code>
*/
deleteAttribute {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
ac.getAttributesManager().deleteAttribute(ac.getSession(),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
return null;
}
},
/*#
* Returns member and member-resource attributes required by the specified service.
*
* @param member int Member <code>id</code>
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member and member-resource attributes required by the specified service.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns group-resource attributes required by specified service.
*
* @param group int Group <code>id</code>
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns resource attributes required by specified service.
*
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member, member-group and member-resource attributes required by specified service.
* If workWithUserAttributes == TRUE, then returns also user and user-facility attributes.
*
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and User-facility attributes. <code>False</code> is default.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member, member-group and member-resource attributes required by specified service.
*
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member-group attributes required by specified service.
* If workWithUserAttributes == TRUE, then returns also member and user attributes.
*
* @param service int Service <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member-group attributes required by specified service.
*
* @param service int Service <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns facility attributes required by specified service.
*
* @param facility int Facility <code>id</code>
* @param service int Service <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns facility attributes required by specified list of services.
*
* @param facility int Facility <code>id</code>
* @param services List<int> list of Service IDs
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required host attributes.
*
* @param host int Host <code>id</code>
* @param service int Service <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member and member-resource attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member and member-resource attributes.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required resource attributes.
*
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required user-facility attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required facility attributes.
*
* @param facility int Facility <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member attributes.
*
* @param member int Member <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member attributes.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member and member-group required attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member and member-group required attributes.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required user attributes.
*
* @param user int User <code>id</code>
* @return List<Attribute> Required Attributes
*/
getRequiredAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("service")) {
if (parms.contains("resource")) {
if (parms.contains("group")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
false);
}
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
}
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
}
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "group");
}
} else if (parms.contains("facility")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getFacilityById(parms.readInt("facility")));
} else if (parms.contains("host")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getHostById(parms.readInt("host")));
} else if (parms.contains("vo")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getVoById(parms.readInt("vo")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "host, resource or facility");
}
} else if (parms.contains("services")) {
// get list of services
List<Service> services = new ArrayList<Service>();
List<Integer> servIds = parms.readList("services", Integer.class);
for (Integer id : servIds) {
Service s = ac.getServiceById(id);
if (!services.contains(s)) {
services.add(s);
}
}
if (parms.contains("facility")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(), services,
ac.getFacilityById(parms.readInt("facility")));
} else if (parms.contains("resource")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(), services,
ac.getResourceById(parms.readInt("resource")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility or resource");
}
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
}
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")));
}
} else if (parms.contains("facility")) {
if (parms.contains("user")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
false);
}
} else {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), false);
}
}
} else if (parms.contains("user")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "service, resource, facility, member or user");
}
}
},
/*#
* Returns required attributes definition for a Service.
*
* @param service int Service <code>id</code>
* @return List<AttributeDefinition> Attributes definitions
*/
getRequiredAttributesDefinition {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getRequiredAttributesDefinition(ac.getSession(),
ac.getServiceById(parms.readInt("service")));
}
},
/*#
* Gets member, user, member-resource and user-facility attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Member, user, member-resource and user-facility attributes
*/
/*#
* Gets member-resource attributes and also user, user-facility and member attributes, if workWithUserAttributes == true.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Member-resource attributes (if workWithUserAttributes == true also user, user-facility and member attributes)
*/
/*#
* Gets member-resource attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Member-resource attributes
*/
/*#
* Gets member-group attributes and also user and member attributes, if workWithUserAttributes == true.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> Member-group attributes
*/
/*#
* Gets member-group attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Member-group attributes
*/
/*#
* Gets member attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param member int Member <code>id</code>
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @return List<Attribute> Member attributes
*/
/*#
* Gets user-facility attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @return List<Attribute> User-facility attributes
*/
/*#
* Gets user attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param user int User <code>id</code>
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @return List<Attribute> User's attributes
*/
/*#
* Gets group-resource and also group attributes, if workWithGroupAttributes == true.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
* @return List<Attribute> Group-resource and (if workWithGroupAttributes == true) group required attributes
*/
/*#
* Gets group-resource attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Group-resource attributes
*/
/*#
* Gets member-group and member-resource attributes.
* If workWithUserAttributes == TRUE then return also member, user, user-facility attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with member, user, user-facility attributes. False is default value.
* @return List<Attribute> Member-group and member-resource attributes, if workWithUserAttributes == TRUE, member, user and user-facility attributes are returned too.
*/
/*#
* Gets member-group and member-resource attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Member-group and member-resource attributes
*/
/*#
* Gets group attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Group's attributes
*/
/*#
* Gets host attributes.
* It returns attributes required by all services assigned to specified host. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param host int Host <code>id</code>
* @return List<Attribute> Group's attributes
*/
getResourceRequiredAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("resourceToGetServicesFrom")) {
if (parms.contains("member")) {
if (parms.contains("resource")) {
if (parms.contains("facility") && parms.contains("user")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")));
} else if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
false);
}
} else if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
}
} else if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
}
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")));
}
} else if (parms.contains("user")) {
if (parms.contains("facility")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getUserById(parms.readInt("user")));
}
} else if (parms.contains("group")) {
if (parms.contains("resource")) {
if (parms.contains("workWithGroupAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithGroupAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getGroupById(parms.readInt("group")));
}
} else if (parms.contains("host")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getHostById(parms.readInt("host")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "member, group, host or user");
}
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "resourceToGetServicesFrom");
}
}
},
/*#
* Tries to fill host attribute.
*
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill group-resource attribute.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill member-resource attribute.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill resource attribute.
*
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill user-facility attribute.
*
* @param user int User <code>id</code>
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill user attribute.
*
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill member-group attribute.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill member attribute.
*
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill group attribute.
*
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which may have filled value
*/
fillAttribute {
@Override
public Attribute call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("host")) {
Host host = ac.getHostById(parms.readInt("host"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
host,
ac.getAttributeById(host, parms.readInt("attribute")));
} else if (parms.contains("resource")) {
Resource resource = ac.getResourceById(parms.readInt("resource"));
if (parms.contains("group")) {
Group group = ac.getGroupById(parms.readInt("group"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
resource,
group,
ac.getAttributeById(resource, group, parms.readInt("attribute")));
} else if (parms.contains("member")) {
Member member = ac.getMemberById(parms.readInt("member"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
member, resource,
ac.getAttributeById(resource, member, parms.readInt("attribute")));
} else {
return ac.getAttributesManager().fillAttribute(ac.getSession(),
resource,
ac.getAttributeById(resource, parms.readInt("attribute")));
}
} else if (parms.contains("user")) {
User user = ac.getUserById(parms.readInt("user"));
if (parms.contains("facility")) {
Facility facility = ac.getFacilityById(parms.readInt("facility"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
facility,
user,
ac.getAttributeById(facility, user, parms.readInt("attribute")));
} else {
return ac.getAttributesManager().fillAttribute(ac.getSession(),
user,
ac.getAttributeById(user, parms.readInt("attribute")));
}
} else if (parms.contains("member")) {
Member member = ac.getMemberById(parms.readInt("member"));
if (parms.contains("group")) {
Group group = ac.getGroupById(parms.readInt("group"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
member,
group,
ac.getAttributeById(member, group, parms.readInt("attribute")));
} else {
return ac.getAttributesManager().fillAttribute(ac.getSession(),
member,
ac.getAttributeById(member, parms.readInt("attribute")));
}
} else if (parms.contains("group")) {
Group group = ac.getGroupById(parms.readInt("group"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
group,
ac.getAttributeById(group, parms.readInt("attribute")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "host, resource, user, member or group");
}
}
},
/*#
* Tries to fill host attributes.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill group-resource attributes.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill user, member, member-resource and user-facility attributes.
*
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-resource attributes and also user and user-facility attributes, if workWithUserAttributes == true.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-resource attributes.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill resource attributes.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-group attributes and also member and user attributes, if workWithUserAttributes == true.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-group attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member attributes.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill user-facility attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill user attributes.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill group attributes.
*
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
fillAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
List<Attribute> attributes = new ArrayList<Attribute>();
if (parms.contains("attributes")) {
attributes = parms.readList("attributes", Attribute.class);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "attributes");
}
if (parms.contains("host")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")),
attributes);
} else if (parms.contains("resource")) {
if (parms.contains("group")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
attributes);
} else if (parms.contains("user")) {
if (parms.contains("facility") && parms.contains("member")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
attributes);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, member");
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
attributes,
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
attributes);
}
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
attributes);
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes,
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes);
}
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
attributes);
}
} else if (parms.contains("user")) {
if (parms.contains("facility")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
attributes);
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
attributes);
}
} else if (parms.contains("group")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
attributes);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "host, resource, member, user or group");
}
}
},
/*#
* Checks if this user-facility attribute has valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw UserNotExistsException When the User with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this facility attribute has valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this vo attribute has valid semantics.
*
* @deprecated
* @param vo int Vo <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw VoNotExistsException When the vo with <code>id</code> doesn't exist.
* @throw WrongAttributeAssignmentException When the attribute isn't attribute of Vo with <code>id</code>.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-resource attribute has valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When the member with <code>id</code> and resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this group-resource attribute has valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't group-resource attribute.
* @throw GroupResourceMismatchException When the group with <code>id</code> and Resource with <code>id</code> aren't from the same Vo.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
*/
/*#
* Checks if this resource attribute has valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Resource with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-group attribute has valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-group attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member attribute has valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this group attribute has valid semantics.
*
* @deprecated
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Group with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
*/
/*#
* Checks if this host attribute has valid semantics.
*
* @deprecated
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Host with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw HostNotExistsException When the host with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
/*#
* Checks if this user attribute has valid semantics.
*
* @deprecated
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw UserNotExistsException When the user with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this userExtSource attribute has valid semantics.
*
* @deprecated
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of UserExtSource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw UserExtSourceNotExistsException When the specified user external source with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
checkAttributeValue {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, group, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if this user-facility attribute has valid syntax.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw UserNotExistsException When the User with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this facility attribute has valid syntax.
*
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't facility attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this vo attribute has valid syntax.
*
* @param vo int Vo <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw VoNotExistsException When the vo with <code>id</code> doesn't exist.
* @throw WrongAttributeAssignmentException When the attribute isn't attribute of Vo with <code>id</code>.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-resource attribute has valid syntax.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When the member with <code>id</code> and resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this group-resource attribute has valid syntax.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't group-resource attribute.
* @throw GroupResourceMismatchException When the group with <code>id</code> and Resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this resource attribute has valid syntax.
*
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Resource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-group attribute has valid syntax.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-group attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member attribute has valid syntax.
*
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this group attribute has valid syntax.
*
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Group with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
*/
/*#
* Checks if this host attribute has valid syntax.
*
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Host with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw HostNotExistsException When the host with <code>id</code> doesn't exist.
*/
/*#
* Checks if this user attribute has valid syntax.
*
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw UserNotExistsException When the user with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this userExtSource attribute has valid syntax.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of UserExtSource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw UserExtSourceNotExistsException When the specified user external source with <code>id</code> doesn't exist.
*/
checkAttributeSyntax {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, group, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if this user-facility attribute has valid semantics.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw UserNotExistsException When the User with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this facility attribute has valid semantics.
*
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this vo attribute has valid semantics.
*
* @param vo int Vo <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw VoNotExistsException When the vo with <code>id</code> doesn't exist.
* @throw WrongAttributeAssignmentException When the attribute isn't attribute of Vo with <code>id</code>.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-resource attribute has valid semantics.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When the member with <code>id</code> and resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this group-resource attribute has valid semantics.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't group-resource attribute.
* @throw GroupResourceMismatchException When the group with <code>id</code> and Resource with <code>id</code> aren't from the same Vo.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
*/
/*#
* Checks if this resource attribute has valid semantics.
*
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Resource with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-group attribute has valid semantics.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-group attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member attribute has valid semantics.
*
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this group attribute has valid semantics.
*
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Group with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
*/
/*#
* Checks if this host attribute has valid semantics.
*
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Host with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw HostNotExistsException When the host with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
/*#
* Checks if this user attribute has valid semantics.
*
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw UserNotExistsException When the user with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this userExtSource attribute has valid semantics.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of UserExtSource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw UserExtSourceNotExistsException When the specified user external source with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
checkAttributeSemantics {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, group, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if attributes have valid semantics. These attributes can be from namespace: member, user, member-resource and user-facility.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user-facility attributes have valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these facility attributes have valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these vo attributes have valid semantics.
*
* @deprecated
* @param vo int Vo <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these group-resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member attributes have valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these host attributes have valid semantics.
*
* @deprecated
* @param host int Host <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user attributes have valid semantics.
*
* @deprecated
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these userExtSource attributes have valid semantics.
*
* @deprecated
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
checkAttributesValue {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("resource") && parms.contains("member")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if attributes have valid semantics. These attributes can be from namespace: member, user, member-resource and user-facility.
*
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user-facility attributes have valid semantics.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these facility attributes have valid semantics.
*
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these vo attributes have valid semantics.
*
* @param vo int Vo <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these group-resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member attributes have valid semantics.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these host attributes have valid semantics.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user attributes have valid semantics.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these userExtSource attributes have valid semantics.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
checkAttributesSemantics {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("resource") && parms.contains("member")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if attributes have valid syntax. These attributes can be from namespace: member, user, member-resource and user-facility.
*
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user-facility attributes have valid syntax.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these facility attributes have valid syntax.
*
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these vo attributes have valid syntax.
*
* @param vo int Vo <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these group-resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-group attributes have valid syntax.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-group attributes have valid syntax.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member attributes have valid syntax.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these host attributes have valid syntax.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user attributes have valid syntax.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these userExtSource attributes have valid syntax.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
checkAttributesSyntax {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("resource") && parms.contains("member")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Remove attributes of namespace:
*
* user, user-facility, member, member-resource
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* user, user-facility, member, member-resource, member-group
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* user-facility
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* facility
*
* @param facility int Facility <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* vo
*
* @param vo int VO <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* resource
*
* @param resource int Resource <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* group-resource, group (optional)
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* group-resource
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member-resource
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member, user (optional)
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Set to true if you want to remove also user attributes. False is default value.
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member-group
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member
*
* @param member int Member <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* group
*
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* host
*
* @param host int Host <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* user
*
* @param user int User <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* userExtSource
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
removeAttributes {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
int[] ids = parms.readArrayOfInts("attributes");
List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(ids.length);
for(int i : ids) {
attributes.add(ac.getAttributeDefinitionById(i));
}
if (parms.contains("facility")) {
if (parms.contains("resource") && parms.contains("member") && parms.contains("user")) {
if (parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
attributes);
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
attributes);
}
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
attributes);
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
attributes);
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
attributes);
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
attributes);
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
attributes,
parms.readBoolean("workWithGroupAttributes"));
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
attributes);
}
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
attributes);
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes") && parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes,
parms.readBoolean("workWithUserAttributes"));
} else if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"), attributes);
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes);
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
attributes);
}
} else if (parms.contains("host")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")),
attributes);
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
attributes);
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
attributes);
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
attributes);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, group, host, resource, member, user or userExtSource");
}
return null;
}
},
/*#
* Remove attribute of namespace:
*
* user-facility
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* facility
*
* @param facility int Facility <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* vo
*
* @param vo int VO <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* resource
*
* @param resource int Resource <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* group-resource
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* member-resource
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* member-group
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* member
*
* @param member int Member <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* group
*
* @param group int Group <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* host
*
* @param host int Host <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* user
*
* @param user int User <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* userExtSource
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove entityless attribute
*
* key
*
* @param key String key for entityless attribute
* @param attribute int <code>id</code> of attribute to remove
*/
removeAttribute {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getUserById(parms.readInt("user")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("host")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getHostById(parms.readInt("host")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("key")){
ac.getAttributesManager().removeAttribute(ac.getSession(), parms.readString("key"),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, group, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Unset all attributes for the user on the facility.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
*/
/*#
* Unset all attributes for the facility and also user-facility attributes if workWithUserAttributes == true.
*
* @param facility int Facility <code>id</code>
* @param workWithUserAttributes boolean Remove also user facility attributes. False is default value.
*/
/*#
* Unset all attributes for the facility.
*
* @param facility int Facility <code>id</code>
*/
/*#
* Unset all attributes for the vo.
*
* @param vo int Vo <code>id</code>
*/
/*#
* Unset all attributes for the member on the resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
*/
/*#
* Unset all group-resource attributes and also group attributes if WorkWithGroupAttributes == true.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
*/
/*#
* Unset all group-resource attributes.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
*/
/*#
* Unset all resource attributes.
*
* @param resource int Resource <code>id</code>
*/
/*#
* Unset all member-group attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
*/
/*#
* Unset all member attributes.
*
* @param member int Member <code>id</code>
*/
/*#
* Unset all user attributes.
*
* @param user int User <code>id</code>
*/
/*#
* Unset all group attributes.
*
* @param group int Group <code>id</code>
*/
/*#
* Unset all host attributes.
*
* @param host int Host <code>id</code>
*/
/*#
* Unset all attributes for the userExtSource.
*
* @param userExtSource int UserExtSource <code>id</code>
*/
removeAllAttributes {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
} else if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithGroupAttributes"));
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")));
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")));
} else if (parms.contains("host")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, resource, vo, group, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Get all users logins as Attributes. Meaning it returns all non-empty User attributes with
* URN starting with: "urn:perun:user:attribute-def:def:login-namespace:".
*
* @param user int User <code>id</code>
* @return List<Attribute> List of users logins as Attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
*/
getLogins {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getLogins(ac.getSession(),
ac.getUserById(parms.readInt("user")));
}
},
/*#
* Updates AttributeDefinition in Perun based on provided object.
* Update is done on AttributeDefinition selected by its <code>id</code>.
*
* @param attributeDefinition AttributeDefinition AttributeDefinition with updated properties to store in DB
* @return AttributeDefinition updated AttributeDefinition
* @throw AttributeNotExistsException When AttributeDefinition with <code>id</code> in object doesn't exist.
*/
updateAttributeDefinition {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
return ac.getAttributesManager().updateAttributeDefinition(ac.getSession(),
parms.read("attributeDefinition", AttributeDefinition.class));
}
},
/*#
* Takes all Member related attributes (Member, User, Member-Resource, User-Facility) and tries to fill them and set them.
*
* @param member int Member <code>id</code>
* @throw WrongAttributeAssignmentException When we try to fill/set Attribute from unrelated namespace.
* @throw WrongAttributeValueException When value of some Attribute is not correct.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
doTheMagic {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.getAttributesManager().doTheMagic(ac.getSession(),
ac.getMemberById(parms.readInt("member")));
return null;
}
},
/*#
* Gets AttributeRights for specified Attribute. Rights specify which Role can do particular actions
* (read / write) with Attribute. Method always return rights for following roles:
* voadmin, groupadmin, facilityadmin, self.
*
* @param attributeId int Attribute <code>id</code>
* @return List<AttributeRights> all rights of the attribute
* @throw AttributeNotExistsException When Attribute with <code>id</code> doesn't exist.
*/
getAttributeRights {
@Override
public List<AttributeRights> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributeRights(ac.getSession(),
parms.readInt("attributeId"));
}
},
/*#
* Sets all AttributeRights in the list given as a parameter. Allowed Roles to set
* rights for are: voadmin, groupadmin, facilityadmin, self.
*
* @param rights List<AttributeRights> List of AttributeRights to set.
* @throw AttributeNotExistsException When Attribute with <code>id</code> doesn't exist.
*/
setAttributeRights {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
ac.getAttributesManager().setAttributeRights(ac.getSession(),
parms.readList("rights", AttributeRights.class));
return null;
}
},
/*#
* Converts attribute to unique - marks its definition as unique and ensures that all its values are unique.
* Entityless attributes cannot be converted to unique, only attributes attached to PerunBeans or pairs of PerunBeans.
*
* @param attrDefId int AttributeDefinition <code>id</code>
* @throw AttributeNotExistsException When Attribute with <code>id</code> doesn't exist.
* @throw AttributeAlreadymarkedUniqueException When Attribute is already marked as unique.
* @throw InternalErrorException when some attribute values are not unique
*/
convertAttributeToUnique {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws InternalErrorException, AttributeAlreadyMarkedUniqueException, PrivilegeException, AttributeNotExistsException {
ac.stateChangingCheck();
ac.getAttributesManager().convertAttributeToUnique(ac.getSession(), parms.readInt("attrDefId"));
return null;
}
},
/*#
* Generates text file describing dependencies between attribute modules.
* The format of text file can be specified by parameter.
* Modules that has no dependency relations are omitted.
*
* Warning: No matter which serializer you specify, this method always
* returns .txt file as an attachment.
*
* @param format String Currently supported formats are DOT and TGF.
* @throw InternalErrorException when some internal error happens.
* @exampleParam format [ "DOT" ]
*/
/*#
* Generates image file describing dependencies of given attribute.
* The format of text file can be specified by parameter.
* Modules that has no dependency relations are omitted.
*
* Warning: No matter which serializer you specify, this method always
* returns .txt file as an attachment.
*
* @param attrName attribute name which dependencies will be found.
* @param format String Currently supported formats are DOT and TGF.
* @throw InternalErrorException when some internal error happens.
* @throw AttributeNotExistsException when specified attribute doesn't exist.
* @exampleParam format [ "DOT" ]
* @exampleParam attrName [ "urn:perun:resource:attribute-def:virt:unixGID" ]
*/
getAttributeModulesDependenciesGraphText {
@Override
public GraphDTO call(ApiCaller ac, Deserializer parms) throws InternalErrorException, PrivilegeException, AttributeNotExistsException {
String formatString = parms.readString("format").toUpperCase();
GraphTextFormat format;
try {
format = GraphTextFormat.valueOf(formatString);
} catch (IllegalArgumentException e) {
throw new RpcException(RpcException.Type.WRONG_PARAMETER, "Wrong parameter in format, not supported graph format: " + formatString);
}
if (parms.contains("attrName")) {
return ac.getAttributesManager().getModulesDependenciesGraph(ac.getSession(), format, parms.readString("attrName"));
}
return ac.getAttributesManager().getModulesDependenciesGraph(ac.getSession(), format);
}
}
}
| perun-rpc/src/main/java/cz/metacentrum/perun/rpc/methods/AttributesManagerMethod.java | package cz.metacentrum.perun.rpc.methods;
import java.util.ArrayList;
import java.util.List;
import cz.metacentrum.perun.core.api.*;
import cz.metacentrum.perun.core.api.exceptions.AttributeAlreadyMarkedUniqueException;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.PerunException;
import cz.metacentrum.perun.core.api.exceptions.PrivilegeException;
import cz.metacentrum.perun.utils.graphs.GraphTextFormat;
import cz.metacentrum.perun.rpc.ApiCaller;
import cz.metacentrum.perun.rpc.ManagerMethod;
import cz.metacentrum.perun.core.api.exceptions.RpcException;
import cz.metacentrum.perun.rpc.deserializer.Deserializer;
import cz.metacentrum.perun.utils.graphs.GraphDTO;
public enum AttributesManagerMethod implements ManagerMethod {
/*#
* Returns all non-empty User-Facility attributes for selected User and Facility.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @return List<Attribute> All non-empty User-Facility attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
* @throw FacilityNotExistsException When Facility with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Facility attributes for selected Facility.
*
* @param facility int Facility <code>id</code>
* @return List<Attribute> All non-empty Facility attributes
* @throw FacilityNotExistsException When Facility with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Facility attributes for selected Facility
* If <code>attrNames</code> is empty, it returns empty list of attributes
*
* @param facility int Facility <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Facility attributes
* @throw FacilityNotExistsException When Facility with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Vo attributes for selected Vo.
*
* @param vo int Vo <code>id</code>
* @return List<Attribute> All non-empty Vo attributes
* @throw VoNotExistsException When Vo with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Vo attributes for selected Vo.
*
* @param vo int VO <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Vo attributes
* @throw VoNotExistsException When Vo with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:vo:attribute-def:def:contactEmail" , "urn:perun:vo:attribute-def:core:shortName" ]
*/
/*#
* Returns all non-empty UserExtSource attributes for selected UserExtSource.
*
* @param userExtSource int UserExtSource <code>id</code>
* @return List<Attribute> All non-empty UserExtSource attributes
* @throw UserExtSourceNotExistsException When Ues with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified UserExtSource attributes for selected UserExtSource.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified UserExtSource attributes
* @throw UserExtSourceNotExistsException When userExtSource with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:ues:attribute-def:opt:optionalAttribute" ]
*/
/*#
* Returns all non-empty Member-Resource attributes for selected Member and Resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> All non-empty Member-Resource attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns selected non-empty Member, User, Member-Resource and User-Facility attributes (by list of attribute names) for selected Member and Resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also user and user-facility attributes. <code>False</code> is default.
* @param attrNames List<String> List of attribute names
* @return List<Attribute> Selected non-empty User, Member, Member-Resource, User-Facility attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Member-Resource attributes for selected Member and Resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> All non-empty Member-Resource attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Get all attributes by the list of attrNames if they are in one of these namespaces:
* - member
* - group
* - member-group
* - resource
* - member-resource
* - group-resource
* - user (get from member object)
* - facility (get from resource object)
* - user-facility
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> All attributes from supported namespaces.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When Member is not from the same Vo as Resource.
* @throw GroupResourceMismatchException When Group is not from the same Vo as Resource.
*/
/*#
* Returns all non-empty Group-Resource attributes for selected Group and Resource.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> All non-empty Group-Resource attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Group-Resource attributes for selected Group and Resource.
* If <code>workWithGroupAttributes == true</code> then also all non-empty Group attributes are returned.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean If <code>true</code>, return also Group attributes. <code>False</code> is default.
* @return List<Attribute> All non-empty Group-Resource attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Group-Resource attributes for selected Group and Resource.
* If <code>attrNames</code> is empty, it returns all non-empty attributes.
* If <code>workWithGroupAttributes == true</code> then also Group attributes are returned. <code>False</code> is default.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attrNames List<String> Attribute names
* @param workWithGroupAttributes boolean If <code>true</code>, return also Group attributes. <code>False</code> is default.
* @return List<Attribute> Specified Group-Resource attributes and (if workWithGroupAttributes == true) also Group attributes.
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Resource attributes for selected Resource.
*
* @param resource int Resource <code>id</code>
* @return List<Attribute> All non-empty Resource attributes
* @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Member-Group attributes for selected Member and Group.
* If <code>workWithUserAttribute == true</code> then also all non-empty User attributes are returned.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attrNames List<String> Attribute names
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> Specified Member-Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Member attributes for selected Member.
*
* @param member int Member <code>id</code>
* @return List<Attribute> All non-empty Member attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty Member attributes for selected Member.
* If <code>workWithUserAttributes == true</code> then also all non-empty User attributes are returned.
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User attributes. <code>False</code> is default.
* @return List<Attribute> All non-empty Member attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Member-Group attributes for selected Member and Group
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Member-Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Member attributes for selected Member.
*
* @param member int Member <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Member attributes
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:member:attribute-def:def:mail" , "urn:perun:member:attribute-def:def:membershipExpiration" ]
*/
/*#
* Returns all non-empty Member-Group attributes for selected Member and Group.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> All Member-Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
/*#
* Returns all non-empty User attributes for selected User.
*
* @param user int User <code>id</code>
* @return List<Attribute> All non-empty User attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified User attributes for selected User.
*
* @param user int User <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified User attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:user:attribute-def:def:phone" , "urn:perun:user:attribute-def:def:preferredMail" ]
*/
/*#
* Returns all non-empty Group attributes for selected Group.
*
* @param group int Group <code>id</code>
* @return List<Attribute> All non-empty Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
*/
/*#
* Returns all specified Group attributes for selected Group.
*
* @param group int Group <code>id</code>
* @param attrNames List<String> Attribute names
* @return List<Attribute> Specified Group attributes
* @throw GroupNotExistsException When Group with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:user:attribute-def:core:description" , "urn:perun:user:attribute-def:def:synchronizationEnabled" ]
*/
/*#
* Returns all non-empty Host attributes for selected Host.
*
* @param host int Host <code>id</code>
* @return List<Attribute> All non-empty Host attributes
* @throw HostNotExistsException When Group with <code>id</code> doesn't exist.
* @exampleParam attrNames [ "urn:perun:host:attribute-def:core:hostname" , "urn:perun:host:attribute-def:def:frontend" ]
*/
/*#
* Returns all non-empty Entityless attributes with subject equaled <code>key</code>.
*
* @param key String String <code>key</code>
* @return List<Attribute> All non-empty Entityless attributes
*/
getAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("member") && parms.contains("resource")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
}
} else {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")));
}
}
} else if (parms.contains("vo")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")));
}
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
}
} else if (parms.contains("attrNames") && parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getResourceById(parms.readInt("resource"))
);
}
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithGroupAttributes"));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithGroupAttributes"));
}
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")));
}
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
if (parms.contains("attrNames")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attrNames", String.class),
parms.readBoolean("workWithUserAttributes"));
}
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"));
}
} else if (parms.contains("attrNames")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attrNames", String.class));
}
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")));
}
} else if (parms.contains("user")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")));
}
} else if (parms.contains("group")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")));
}
} else if (parms.contains("host")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")));
} else if (parms.contains("key")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
parms.readString("key"));
} else if (parms.contains("userExtSource")) {
if (parms.contains("attrNames")) {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attrNames", String.class));
} else {
return ac.getAttributesManager().getAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")));
}
}
else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, group, userExtSource or key");
}
}
},
/*#
* Returns all entityless attributes with <code>attrName</code> (for all namespaces of same attribute).
*
* @param attrName String Attribute name
* @return List<Attribute> All entityless attributes with same name
* @exampleParam attrName "urn:perun:entityless:attribute-def:def:namespace-minUID"
*/
getEntitylessAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getEntitylessAttributes(ac.getSession(), parms.readString("attrName"));
}
},
/*#
* Returns list of Keys which fits the attributeDefinition.
*
* @param attributeDefinition id of the attributeDefinition
* @return List<String> All keys for attributeDefinition
*/
getEntitylessKeys{
@Override
public List<String> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getEntitylessKeys(ac.getSession(), ac.getAttributeDefinitionById(parms.readInt("attributeDefinition")));
}
},
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param group in Group <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param vo int VO <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @param workWithUserAttributes boolean If <code>true</code>, store also User and Member attributes. <code>False</code> is default.
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
/*#
* Sets the attributes.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> List of attributes
*/
setAttributes {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("member") && parms.contains("resource")) {
if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithGroupAttributes"));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().setAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, group or userExtSource");
}
return null;
}
},
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param facility int Facility <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param vo int VO <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param resource int Resource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param member int Member <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param user int User <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param host int Host <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its <code>id</code>.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributeId int Attribute <code>id</code>
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param facility int Facility <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param vo int VO <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param group int Group <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param resource int Resource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param member int Member <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param user int User <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param host int Host <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
/*#
* Returns an Attribute by its name.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributeName String Attribute name
* @return Attribute Found Attribute
*/
getAttribute {
@Override
public Attribute call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("attributeId")) {
if (parms.contains("facility")) {
if (parms.contains("user")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readInt("attributeId"));
} else {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readInt("attributeId"));
}
} else if (parms.contains("vo")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readInt("attributeId"));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readInt("attributeId"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readInt("attributeId"));
} else {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readInt("attributeId"));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readInt("attributeId"));
} else {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readInt("attributeId"));
}
} else if (parms.contains("user")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readInt("attributeId"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readInt("attributeId"));
} else if (parms.contains("host")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readInt("attributeId"));
/* Not implemented yet
} else if (parms.contains("key")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
parms.readString("key"),
parms.readInt("attributeId"));
*/
} else if (parms.contains("userExtSource")) {
return ac.getAttributesManager().getAttributeById(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readInt("attributeId"));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, key, group or userExtSource");
}
} else {
if (parms.contains("facility")) {
if (parms.contains("user")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readString("attributeName"));
} else {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readString("attributeName"));
}
} else if (parms.contains("vo")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readString("attributeName"));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readString("attributeName"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readString("attributeName"));
} else {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readString("attributeName"));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readString("attributeName"));
} else {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readString("attributeName"));
}
} else if (parms.contains("user")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readString("attributeName"));
} else if (parms.contains("group")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.readString("attributeName"));
} else if (parms.contains("host")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readString("attributeName"));
} else if (parms.contains("userExtSource")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readString("attributeName"));
} else if (parms.contains("key")) {
return ac.getAttributesManager().getAttribute(ac.getSession(),
parms.readString("key"),
parms.readString("attributeName"));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, user, host, key, group or userExtSource");
}
}
}
},
/*#
* Returns AttributeDefinition.
*
* @param attributeName String Attribute name
* @return AttributeDefinition Definition of an Attribute
*/
getAttributeDefinition {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributeDefinition(ac.getSession(),
parms.readString("attributeName"));
}
},
/*#
* Returns all AttributeDefinitions.
*
* @return List<AttributeDefinition> Definitions of Attributes
*/
getAttributesDefinition {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributesDefinition(ac.getSession());
}
},
/*#
* Returns AttributeDefinition.
*
* @param id int Attribute <code>id</code>
* @return AttributeDefinition Definition of an Attribute
*/
getAttributeDefinitionById {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributeDefinitionById(parms.readInt("id"));
}
},
/*#
* Returns all AttributeDefinitions in a namespace.
*
* @param namespace String Namespace
* @return List<AttributeDefinition> Definitions of Attributes in a namespace
*/
getAttributesDefinitionByNamespace {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributesDefinitionByNamespace(ac.getSession(),
parms.readString("namespace"));
}
},
/*#
* Returns all AttributeDefinitions for every entity and possible combination of entities with rights.
* Only attribute definition of attributes user can read (or write) you will get.
*
* Combination of entities is based on provided parameters, which are optional
* (at least one must be present).
*
* @param member int <code>id</code> of Member
* @param user int <code>id</code> of User
* @param vo int <code>id</code> of Virtual organization
* @param group int <code>id</code> of Group
* @param resource int <code>id</code> of Resource
* @param facility int <code>id</code> of Facility
* @param host int <code>id</code> of Host
* @param userExtSource int <code>id</code> of UserExtSource
*
* @return List<AttributeDefinition> Definitions of Attributes for entities
*/
getAttributesDefinitionWithRights {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
User user = null;
Member member = null;
Vo vo = null;
Group group = null;
Resource resource = null;
Facility facility = null;
Host host = null;
UserExtSource ues = null;
//Not supported entityless attirbutes now
//String entityless = null;
List<PerunBean> entities = new ArrayList<PerunBean>();
//If member exists in query
if (parms.contains("member")) {
member = ac.getMemberById(parms.readInt("member"));
entities.add(member);
}
//If user exists in query
if (parms.contains("user")) {
user = ac.getUserById(parms.readInt("user"));
entities.add(user);
}
//If vo exists in query
if (parms.contains("vo")) {
vo = ac.getVoById(parms.readInt("vo"));
entities.add(vo);
}
//If group exists in query
if (parms.contains("group")) {
group = ac.getGroupById(parms.readInt("group"));
entities.add(group);
}
//If resource exists in query
if (parms.contains("resource")) {
resource = ac.getResourceById(parms.readInt("resource"));
entities.add(resource);
}
//If facility exists in query
if (parms.contains("facility")) {
facility = ac.getFacilityById(parms.readInt("facility"));
entities.add(facility);
}
//If host exists in query
if (parms.contains("host")) {
host = ac.getHostById(parms.readInt("host"));
entities.add(host);
}
//If userExtSource exists in query
if (parms.contains("userExtSource")) {
ues = ac.getUserExtSourceById(parms.readInt("userExtSource"));
entities.add(ues);
}
//If entityless exists in query
/*if(parms.contains("entityless")) {
}*/
List<AttributeDefinition> attributesDefinition = ac.getAttributesManager().getAttributesDefinitionWithRights(ac.getSession(), entities);
return attributesDefinition;
}
},
/*#
* Sets an Attribute.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param facility int Facility <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param vo int VO <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param resource int Resource <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param member int Member <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param user int User <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param group int Group <code>id</code>
* @param attribute Attribute JSON object
*
*/
/*#
* Sets an Attribute.
*
* @param host int Host <code>id</code>
* @param attribute Attribute JSON object
*/
/*#
* Sets an Attribute.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute Attribute JSON object
*/
setAttribute {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("key")) {
ac.getAttributesManager().setAttribute(ac.getSession(),
parms.readString("key"),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, user, member, host, key, group or userExtSource");
}
return null;
}
},
/*#
* Creates AttributeDefinition
*
* AttributeDefinition object must contain: namespace, friendlyName, type. Description, displayName and unique are optional. Other Parameters are ignored.
* @param attribute AttributeDefinition object
* @return AttributeDefinition Created AttributeDefinition
* @exampleParam attribute { "friendlyName": "kerberosLogins", "namespace": "urn:perun:user:attribute-def:def", "type": "java.util.ArrayList" }
*/
/*#
* Creates AttributeDefinition
*
* @param friendlyName String friendlyName
* @param namespace String namespace in URN format
* @param description String description
* @param type String type which is one of the: "java.lang.String", "java.lang.Integer", "java.lang.Boolean", "java.util.ArrayList",
* "java.util.LinkedHashMap", "java.lang.LargeString" or "java.util.LargeArrayList"
* @param displayName String displayName
* @param unique Boolean unique
* @return AttributeDefinition Created AttributeDefinition
* @exampleParam friendlyName "kerberosLogins"
* @exampleParam namespace "urn:perun:user:attribute-def:def"
* @exampleParam type "java.util.ArrayList"
*/
createAttribute {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("attribute")) {
return ac.getAttributesManager().createAttribute(ac.getSession(),
parms.read("attribute", AttributeDefinition.class));
} else if (parms.contains("friendlyName") && parms.contains("namespace") && parms.contains("description") && parms.contains("type")
&& parms.contains("displayName") && parms.contains("unique")) {
AttributeDefinition attribute = new AttributeDefinition();
attribute.setFriendlyName(parms.readString("friendlyName"));
attribute.setNamespace(parms.readString("namespace"));
attribute.setDescription(parms.readString("description"));
attribute.setType(parms.readString("type"));
attribute.setDisplayName(parms.readString("displayName"));
attribute.setUnique(parms.readBoolean("unique"));
return ac.getAttributesManager().createAttribute(ac.getSession(), attribute);
} else {
throw new RpcException(RpcException.Type.WRONG_PARAMETER);
}
}
},
/*#
* Deletes attribute definition from Perun.
*
* Deletion fails if any entity in Perun has
* any value for this attribute set.
*
* @param attribute int AttributeDefinition <code>id</code>
*/
deleteAttribute {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
ac.getAttributesManager().deleteAttribute(ac.getSession(),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
return null;
}
},
/*#
* Returns member and member-resource attributes required by the specified service.
*
* @param member int Member <code>id</code>
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member and member-resource attributes required by the specified service.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns group-resource attributes required by specified service.
*
* @param group int Group <code>id</code>
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns resource attributes required by specified service.
*
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member, member-group and member-resource attributes required by specified service.
* If workWithUserAttributes == TRUE, then returns also user and user-facility attributes.
*
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and User-facility attributes. <code>False</code> is default.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member, member-group and member-resource attributes required by specified service.
*
* @param service int Service <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member-group attributes required by specified service.
* If workWithUserAttributes == TRUE, then returns also member and user attributes.
*
* @param service int Service <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member-group attributes required by specified service.
*
* @param service int Service <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns facility attributes required by specified service.
*
* @param facility int Facility <code>id</code>
* @param service int Service <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns facility attributes required by specified list of services.
*
* @param facility int Facility <code>id</code>
* @param services List<int> list of Service IDs
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required host attributes.
*
* @param host int Host <code>id</code>
* @param service int Service <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member and member-resource attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member and member-resource attributes.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required resource attributes.
*
* @param resource int Resource <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required user-facility attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required facility attributes.
*
* @param facility int Facility <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member attributes.
*
* @param member int Member <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required member attributes.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member and member-group required attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Required Attributes
*/
/*#
* Returns member and member-group required attributes.
* If workWithUserAttributes == TRUE, then returns also user attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Required Attributes
*/
/*#
* Returns required user attributes.
*
* @param user int User <code>id</code>
* @return List<Attribute> Required Attributes
*/
getRequiredAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("service")) {
if (parms.contains("resource")) {
if (parms.contains("group")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
false);
}
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
}
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getResourceById(parms.readInt("resource")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
}
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "group");
}
} else if (parms.contains("facility")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getFacilityById(parms.readInt("facility")));
} else if (parms.contains("host")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getHostById(parms.readInt("host")));
} else if (parms.contains("vo")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getServiceById(parms.readInt("service")),
ac.getVoById(parms.readInt("vo")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "host, resource or facility");
}
} else if (parms.contains("services")) {
// get list of services
List<Service> services = new ArrayList<Service>();
List<Integer> servIds = parms.readList("services", Integer.class);
for (Integer id : servIds) {
Service s = ac.getServiceById(id);
if (!services.contains(s)) {
services.add(s);
}
}
if (parms.contains("facility")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(), services,
ac.getFacilityById(parms.readInt("facility")));
} else if (parms.contains("resource")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(), services,
ac.getResourceById(parms.readInt("resource")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility or resource");
}
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
}
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")));
}
} else if (parms.contains("facility")) {
if (parms.contains("user")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
false);
}
} else {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), false);
}
}
} else if (parms.contains("user")) {
return ac.getAttributesManager().getRequiredAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "service, resource, facility, member or user");
}
}
},
/*#
* Returns required attributes definition for a Service.
*
* @param service int Service <code>id</code>
* @return List<AttributeDefinition> Attributes definitions
*/
getRequiredAttributesDefinition {
@Override
public List<AttributeDefinition> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getRequiredAttributesDefinition(ac.getSession(),
ac.getServiceById(parms.readInt("service")));
}
},
/*#
* Gets member, user, member-resource and user-facility attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Member, user, member-resource and user-facility attributes
*/
/*#
* Gets member-resource attributes and also user, user-facility and member attributes, if workWithUserAttributes == true.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> Member-resource attributes (if workWithUserAttributes == true also user, user-facility and member attributes)
*/
/*#
* Gets member-resource attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Member-resource attributes
*/
/*#
* Gets member-group attributes and also user and member attributes, if workWithUserAttributes == true.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param workWithUserAttributes boolean If <code>true</code>, return also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> Member-group attributes
*/
/*#
* Gets member-group attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Member-group attributes
*/
/*#
* Gets member attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param member int Member <code>id</code>
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @return List<Attribute> Member attributes
*/
/*#
* Gets user-facility attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @return List<Attribute> User-facility attributes
*/
/*#
* Gets user attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param user int User <code>id</code>
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @return List<Attribute> User's attributes
*/
/*#
* Gets group-resource and also group attributes, if workWithGroupAttributes == true.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
* @return List<Attribute> Group-resource and (if workWithGroupAttributes == true) group required attributes
*/
/*#
* Gets group-resource attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Group-resource attributes
*/
/*#
* Gets member-group and member-resource attributes.
* If workWithUserAttributes == TRUE then return also member, user, user-facility attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Work with member, user, user-facility attributes. False is default value.
* @return List<Attribute> Member-group and member-resource attributes, if workWithUserAttributes == TRUE, member, user and user-facility attributes are returned too.
*/
/*#
* Gets member-group and member-resource attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param member int Member <code>id</code>
* @return List<Attribute> Member-group and member-resource attributes
*/
/*#
* Gets group attributes.
* It returns attributes required by all services assigned to specified resource. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param group int Group <code>id</code>
* @return List<Attribute> Group's attributes
*/
/*#
* Gets host attributes.
* It returns attributes required by all services assigned to specified host. Both empty and non-empty attributes are returned.
*
* @param resourceToGetServicesFrom int Resource to get services from <code>id</code>
* @param host int Host <code>id</code>
* @return List<Attribute> Group's attributes
*/
getResourceRequiredAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("resourceToGetServicesFrom")) {
if (parms.contains("member")) {
if (parms.contains("resource")) {
if (parms.contains("facility") && parms.contains("user")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")));
} else if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getMemberById(parms.readInt("member")),
false);
}
} else if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
}
} else if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
}
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getMemberById(parms.readInt("member")));
}
} else if (parms.contains("user")) {
if (parms.contains("facility")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getUserById(parms.readInt("user")));
}
} else if (parms.contains("group")) {
if (parms.contains("resource")) {
if (parms.contains("workWithGroupAttributes")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithGroupAttributes"));
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getGroupById(parms.readInt("group")));
}
} else if (parms.contains("host")) {
return ac.getAttributesManager().getResourceRequiredAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resourceToGetServicesFrom")),
ac.getHostById(parms.readInt("host")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "member, group, host or user");
}
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "resourceToGetServicesFrom");
}
}
},
/*#
* Tries to fill host attribute.
*
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill group-resource attribute.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill member-resource attribute.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill resource attribute.
*
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill user-facility attribute.
*
* @param user int User <code>id</code>
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill user attribute.
*
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill member-group attribute.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill member attribute.
*
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which MAY have filled value
*/
/*#
* Tries to fill group attribute.
*
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
* @return Attribute attribute which may have filled value
*/
fillAttribute {
@Override
public Attribute call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("host")) {
Host host = ac.getHostById(parms.readInt("host"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
host,
ac.getAttributeById(host, parms.readInt("attribute")));
} else if (parms.contains("resource")) {
Resource resource = ac.getResourceById(parms.readInt("resource"));
if (parms.contains("group")) {
Group group = ac.getGroupById(parms.readInt("group"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
resource,
group,
ac.getAttributeById(resource, group, parms.readInt("attribute")));
} else if (parms.contains("member")) {
Member member = ac.getMemberById(parms.readInt("member"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
member, resource,
ac.getAttributeById(resource, member, parms.readInt("attribute")));
} else {
return ac.getAttributesManager().fillAttribute(ac.getSession(),
resource,
ac.getAttributeById(resource, parms.readInt("attribute")));
}
} else if (parms.contains("user")) {
User user = ac.getUserById(parms.readInt("user"));
if (parms.contains("facility")) {
Facility facility = ac.getFacilityById(parms.readInt("facility"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
facility,
user,
ac.getAttributeById(facility, user, parms.readInt("attribute")));
} else {
return ac.getAttributesManager().fillAttribute(ac.getSession(),
user,
ac.getAttributeById(user, parms.readInt("attribute")));
}
} else if (parms.contains("member")) {
Member member = ac.getMemberById(parms.readInt("member"));
if (parms.contains("group")) {
Group group = ac.getGroupById(parms.readInt("group"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
member,
group,
ac.getAttributeById(member, group, parms.readInt("attribute")));
} else {
return ac.getAttributesManager().fillAttribute(ac.getSession(),
member,
ac.getAttributeById(member, parms.readInt("attribute")));
}
} else if (parms.contains("group")) {
Group group = ac.getGroupById(parms.readInt("group"));
return ac.getAttributesManager().fillAttribute(ac.getSession(),
group,
ac.getAttributeById(group, parms.readInt("attribute")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "host, resource, user, member or group");
}
}
},
/*#
* Tries to fill host attributes.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill group-resource attributes.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill user, member, member-resource and user-facility attributes.
*
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-resource attributes and also user and user-facility attributes, if workWithUserAttributes == true.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @param workWithUserAttributes boolean Work with user attributes. False is default value.
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-resource attributes.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill resource attributes.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-group attributes and also member and user attributes, if workWithUserAttributes == true.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>False</code> is default.
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member-group attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill member attributes.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill user-facility attributes.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill user attributes.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
/*#
* Tries to fill group attributes.
*
* @param group int Group <code>id</code>
* @param attributes List<Attribute> List of attributes
* @return List<Attribute> attributes which MAY have filled value
*/
fillAttributes {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
List<Attribute> attributes = new ArrayList<Attribute>();
if (parms.contains("attributes")) {
attributes = parms.readList("attributes", Attribute.class);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "attributes");
}
if (parms.contains("host")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")),
attributes);
} else if (parms.contains("resource")) {
if (parms.contains("group")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
attributes);
} else if (parms.contains("user")) {
if (parms.contains("facility") && parms.contains("member")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
attributes);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, member");
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
attributes,
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
attributes);
}
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
attributes);
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes,
parms.readBoolean("workWithUserAttributes"));
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes);
}
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
attributes);
}
} else if (parms.contains("user")) {
if (parms.contains("facility")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
attributes);
} else {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
attributes);
}
} else if (parms.contains("group")) {
return ac.getAttributesManager().fillAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
attributes);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "host, resource, member, user or group");
}
}
},
/*#
* Checks if this user-facility attribute has valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw UserNotExistsException When the User with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this facility attribute has valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this vo attribute has valid semantics.
*
* @deprecated
* @param vo int Vo <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw VoNotExistsException When the vo with <code>id</code> doesn't exist.
* @throw WrongAttributeAssignmentException When the attribute isn't attribute of Vo with <code>id</code>.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-resource attribute has valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When the member with <code>id</code> and resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this group-resource attribute has valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't group-resource attribute.
* @throw GroupResourceMismatchException When the group with <code>id</code> and Resource with <code>id</code> aren't from the same Vo.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
*/
/*#
* Checks if this resource attribute has valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Resource with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-group attribute has valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-group attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member attribute has valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this group attribute has valid semantics.
*
* @deprecated
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Group with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
*/
/*#
* Checks if this host attribute has valid semantics.
*
* @deprecated
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Host with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw HostNotExistsException When the host with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
/*#
* Checks if this user attribute has valid semantics.
*
* @deprecated
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw UserNotExistsException When the user with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this userExtSource attribute has valid semantics.
*
* @deprecated
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of UserExtSource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw UserExtSourceNotExistsException When the specified user external source with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
checkAttributeValue {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, group, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if this user-facility attribute has valid syntax.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw UserNotExistsException When the User with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this facility attribute has valid syntax.
*
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't facility attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this vo attribute has valid syntax.
*
* @param vo int Vo <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw VoNotExistsException When the vo with <code>id</code> doesn't exist.
* @throw WrongAttributeAssignmentException When the attribute isn't attribute of Vo with <code>id</code>.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-resource attribute has valid syntax.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When the member with <code>id</code> and resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this group-resource attribute has valid syntax.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't group-resource attribute.
* @throw GroupResourceMismatchException When the group with <code>id</code> and Resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this resource attribute has valid syntax.
*
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Resource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-group attribute has valid syntax.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-group attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member attribute has valid syntax.
*
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this group attribute has valid syntax.
*
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Group with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
*/
/*#
* Checks if this host attribute has valid syntax.
*
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Host with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw HostNotExistsException When the host with <code>id</code> doesn't exist.
*/
/*#
* Checks if this user attribute has valid syntax.
*
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw UserNotExistsException When the user with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this userExtSource attribute has valid syntax.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value has wrong/illegal syntax.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of UserExtSource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw UserExtSourceNotExistsException When the specified user external source with <code>id</code> doesn't exist.
*/
checkAttributeSyntax {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributeSyntax(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, group, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if this user-facility attribute has valid semantics.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw UserNotExistsException When the User with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this facility attribute has valid semantics.
*
* @param facility int Facility <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw FacilityNotExistsException When the facility with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't facility attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this vo attribute has valid semantics.
*
* @param vo int Vo <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw VoNotExistsException When the vo with <code>id</code> doesn't exist.
* @throw WrongAttributeAssignmentException When the attribute isn't attribute of Vo with <code>id</code>.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-resource attribute has valid semantics.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw MemberResourceMismatchException When the member with <code>id</code> and resource with <code>id</code> aren't from the same Vo.
*/
/*#
* Checks if this group-resource attribute has valid semantics.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't group-resource attribute.
* @throw GroupResourceMismatchException When the group with <code>id</code> and Resource with <code>id</code> aren't from the same Vo.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
*/
/*#
* Checks if this resource attribute has valid semantics.
*
* @param resource int Resource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw ResourceNotExistsException When the resource with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Resource with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member-group attribute has valid semantics.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-group attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this member attribute has valid semantics.
*
* @param member int Member <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw MemberNotExistsException When the member with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't member-resource attribute.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this group attribute has valid semantics.
*
* @param group int Group <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Group with <code>id</code>.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw GroupNotExistsException When the group with <code>id</code> doesn't exist.
*/
/*#
* Checks if this host attribute has valid semantics.
*
* @param host int Host <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of Host with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw HostNotExistsException When the host with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
/*#
* Checks if this user attribute has valid semantics.
*
* @param user int User <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw UserNotExistsException When the user with <code>id</code> doesn't exist.
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't user-facility attribute.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
*/
/*#
* Checks if this userExtSource attribute has valid semantics.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int Attribute <code>id</code>
*
* @throw WrongAttributeValueException When the attribute value is wrong/illegal.
* @throw WrongAttributeAssignmentException When the attribute with <code>id</code> isn't attribute of UserExtSource with <code>id</code>.
* @throw AttributeNotExistsException When the attribute with <code>id</code> doesn't exist.
* @throw UserExtSourceNotExistsException When the specified user external source with <code>id</code> doesn't exist.
* @throw WrongReferenceAttributeValueException When value of referenced attribute (if any) is not valid.
*/
checkAttributeSemantics {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.read("attribute", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.read("attribute", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributeSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.read("attribute", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, group, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if attributes have valid semantics. These attributes can be from namespace: member, user, member-resource and user-facility.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user-facility attributes have valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these facility attributes have valid semantics.
*
* @deprecated
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these vo attributes have valid semantics.
*
* @deprecated
* @param vo int Vo <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these group-resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these resource attributes have valid semantics.
*
* @deprecated
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member attributes have valid semantics.
*
* @deprecated
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these host attributes have valid semantics.
*
* @deprecated
* @param host int Host <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user attributes have valid semantics.
*
* @deprecated
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these userExtSource attributes have valid semantics.
*
* @deprecated
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
checkAttributesValue {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("resource") && parms.contains("member")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if attributes have valid semantics. These attributes can be from namespace: member, user, member-resource and user-facility.
*
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user-facility attributes have valid semantics.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these facility attributes have valid semantics.
*
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these vo attributes have valid semantics.
*
* @param vo int Vo <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these group-resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these resource attributes have valid semantics.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-group attributes have valid semantics.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member attributes have valid semantics.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these host attributes have valid semantics.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user attributes have valid semantics.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these userExtSource attributes have valid semantics.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
checkAttributesSemantics {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("resource") && parms.contains("member")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributesSemantics(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Checks if attributes have valid syntax. These attributes can be from namespace: member, user, member-resource and user-facility.
*
* @param facility int Facility <code>id</code>
* @param resource int Resource <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user-facility attributes have valid syntax.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these facility attributes have valid syntax.
*
* @param facility int Facility <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these vo attributes have valid syntax.
*
* @param vo int Vo <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these group-resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these resource attributes have valid syntax.
*
* @param resource int Resource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member-group attributes have valid syntax.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
* @param workWithUserAttributes boolean If <code>true</code>, process also User and Member attributes. <code>false</code> is default.
*/
/*#
* Checks if these member-group attributes have valid syntax.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these member attributes have valid syntax.
*
* @param member int Member <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these host attributes have valid syntax.
*
* @param host int Host <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these user attributes have valid syntax.
*
* @param user int User <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
/*#
* Checks if these userExtSource attributes have valid syntax.
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Attribute> Attributes List
*/
checkAttributesSyntax {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
if (parms.contains("facility")) {
if (parms.contains("user")) {
if (parms.contains("resource") && parms.contains("member")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("group")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
parms.readList("attributes", Attribute.class));
}
} else {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readList("attributes", Attribute.class));
}
} else if (parms.contains("host")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getHostById(parms.readInt("host")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("user")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getUserById(parms.readInt("user")),
parms.readList("attributes", Attribute.class));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().checkAttributesSyntax(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
parms.readList("attributes", Attribute.class));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Remove attributes of namespace:
*
* user, user-facility, member, member-resource
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* user, user-facility, member, member-resource, member-group
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* user-facility
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* facility
*
* @param facility int Facility <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* vo
*
* @param vo int VO <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* resource
*
* @param resource int Resource <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* group-resource, group (optional)
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* group-resource
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member-resource
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member, user (optional)
*
* @param member int Member <code>id</code>
* @param workWithUserAttributes boolean Set to true if you want to remove also user attributes. False is default value.
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member-group
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* member
*
* @param member int Member <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* group
*
* @param group int Group <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* host
*
* @param host int Host <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* user
*
* @param user int User <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
/*#
* Remove attributes of namespace:
*
* userExtSource
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attributes List<Integer> List of attributes IDs to remove
*/
removeAttributes {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
int[] ids = parms.readArrayOfInts("attributes");
List<AttributeDefinition> attributes = new ArrayList<AttributeDefinition>(ids.length);
for(int i : ids) {
attributes.add(ac.getAttributeDefinitionById(i));
}
if (parms.contains("facility")) {
if (parms.contains("resource") && parms.contains("member") && parms.contains("user")) {
if (parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
attributes);
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getResourceById(parms.readInt("resource")),
ac.getUserById(parms.readInt("user")),
ac.getMemberById(parms.readInt("member")),
attributes);
}
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
attributes);
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
attributes);
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
attributes);
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
attributes);
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
attributes,
parms.readBoolean("workWithGroupAttributes"));
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
attributes);
}
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
attributes);
}
} else if (parms.contains("member")) {
if (parms.contains("workWithUserAttributes") && parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes,
parms.readBoolean("workWithUserAttributes"));
} else if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
parms.readBoolean("workWithUserAttributes"), attributes);
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
attributes);
} else {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
attributes);
}
} else if (parms.contains("host")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")),
attributes);
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")),
attributes);
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
attributes);
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().removeAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
attributes);
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, group, host, resource, member, user or userExtSource");
}
return null;
}
},
/*#
* Remove attribute of namespace:
*
* user-facility
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* facility
*
* @param facility int Facility <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* vo
*
* @param vo int VO <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* resource
*
* @param resource int Resource <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* group-resource
*
* @param resource int Resource <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* member-resource
*
* @param resource int Resource <code>id</code>
* @param member int Member <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* member-group
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* member
*
* @param member int Member <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* group
*
* @param group int Group <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* host
*
* @param host int Host <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* user
*
* @param user int User <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove attribute of namespace:
*
* userExtSource
*
* @param userExtSource int UserExtSource <code>id</code>
* @param attribute int <code>id</code> of attribute to remove
*/
/*#
* Remove entityless attribute
*
* key
*
* @param key String key for entityless attribute
* @param attribute int <code>id</code> of attribute to remove
*/
removeAttribute {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getVoById(parms.readInt("vo")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getUserById(parms.readInt("user")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getGroupById(parms.readInt("group")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("host")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getHostById(parms.readInt("host")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().removeAttribute(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else if (parms.contains("key")){
ac.getAttributesManager().removeAttribute(ac.getSession(), parms.readString("key"),
ac.getAttributeDefinitionById(parms.readInt("attribute")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, vo, group, resource, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Unset all attributes for the user on the facility.
*
* @param facility int Facility <code>id</code>
* @param user int User <code>id</code>
*/
/*#
* Unset all attributes for the facility and also user-facility attributes if workWithUserAttributes == true.
*
* @param facility int Facility <code>id</code>
* @param workWithUserAttributes boolean Remove also user facility attributes. False is default value.
*/
/*#
* Unset all attributes for the facility.
*
* @param facility int Facility <code>id</code>
*/
/*#
* Unset all attributes for the vo.
*
* @param vo int Vo <code>id</code>
*/
/*#
* Unset all attributes for the member on the resource.
*
* @param member int Member <code>id</code>
* @param resource int Resource <code>id</code>
*/
/*#
* Unset all group-resource attributes and also group attributes if WorkWithGroupAttributes == true.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
* @param workWithGroupAttributes boolean Work with group attributes. False is default value.
*/
/*#
* Unset all group-resource attributes.
*
* @param group int Group <code>id</code>
* @param resource int Resource <code>id</code>
*/
/*#
* Unset all resource attributes.
*
* @param resource int Resource <code>id</code>
*/
/*#
* Unset all member-group attributes.
*
* @param member int Member <code>id</code>
* @param group int Group <code>id</code>
*/
/*#
* Unset all member attributes.
*
* @param member int Member <code>id</code>
*/
/*#
* Unset all user attributes.
*
* @param user int User <code>id</code>
*/
/*#
* Unset all group attributes.
*
* @param group int Group <code>id</code>
*/
/*#
* Unset all host attributes.
*
* @param host int Host <code>id</code>
*/
/*#
* Unset all attributes for the userExtSource.
*
* @param userExtSource int UserExtSource <code>id</code>
*/
removeAllAttributes {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
if (parms.contains("facility")) {
if (parms.contains("user")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
ac.getUserById(parms.readInt("user")));
} else if (parms.contains("workWithUserAttributes")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")),
parms.readBoolean("workWithUserAttributes"));
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getFacilityById(parms.readInt("facility")));
}
} else if (parms.contains("vo")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getVoById(parms.readInt("vo")));
} else if (parms.contains("resource")) {
if (parms.contains("member")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")), ac.getResourceById(parms.readInt("resource"))
);
} else if (parms.contains("group")) {
if (parms.contains("workWithGroupAttributes")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")),
parms.readBoolean("workWithGroupAttributes"));
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")),
ac.getGroupById(parms.readInt("group")));
}
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getResourceById(parms.readInt("resource")));
}
} else if (parms.contains("member")) {
if (parms.contains("group")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")),
ac.getGroupById(parms.readInt("group")));
} else {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getMemberById(parms.readInt("member")));
}
} else if (parms.contains("user")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getUserById(parms.readInt("user")));
} else if (parms.contains("group")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getGroupById(parms.readInt("group")));
} else if (parms.contains("host")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getHostById(parms.readInt("host")));
} else if (parms.contains("userExtSource")) {
ac.getAttributesManager().removeAllAttributes(ac.getSession(),
ac.getUserExtSourceById(parms.readInt("userExtSource")));
} else {
throw new RpcException(RpcException.Type.MISSING_VALUE, "facility, resource, vo, group, member, host, user or userExtSource");
}
return null;
}
},
/*#
* Get all users logins as Attributes. Meaning it returns all non-empty User attributes with
* URN starting with: "urn:perun:user:attribute-def:def:login-namespace:".
*
* @param user int User <code>id</code>
* @return List<Attribute> List of users logins as Attributes
* @throw UserNotExistsException When User with <code>id</code> doesn't exist.
*/
getLogins {
@Override
public List<Attribute> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getLogins(ac.getSession(),
ac.getUserById(parms.readInt("user")));
}
},
/*#
* Updates AttributeDefinition in Perun based on provided object.
* Update is done on AttributeDefinition selected by its <code>id</code>.
*
* @param attributeDefinition AttributeDefinition AttributeDefinition with updated properties to store in DB
* @return AttributeDefinition updated AttributeDefinition
* @throw AttributeNotExistsException When AttributeDefinition with <code>id</code> in object doesn't exist.
*/
updateAttributeDefinition {
@Override
public AttributeDefinition call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
return ac.getAttributesManager().updateAttributeDefinition(ac.getSession(),
parms.read("attributeDefinition", AttributeDefinition.class));
}
},
/*#
* Takes all Member related attributes (Member, User, Member-Resource, User-Facility) and tries to fill them and set them.
*
* @param member int Member <code>id</code>
* @throw WrongAttributeAssignmentException When we try to fill/set Attribute from unrelated namespace.
* @throw WrongAttributeValueException When value of some Attribute is not correct.
* @throw WrongReferenceAttributeValueException When value of some Attribute is not correct regarding to other Attribute value.
* @throw MemberNotExistsException When Member with <code>id</code> doesn't exist.
*/
doTheMagic {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.getAttributesManager().doTheMagic(ac.getSession(),
ac.getMemberById(parms.readInt("member")));
return null;
}
},
/*#
* Gets AttributeRights for specified Attribute. Rights specify which Role can do particular actions
* (read / write) with Attribute. Method always return rights for following roles:
* voadmin, groupadmin, facilityadmin, self.
*
* @param attributeId int Attribute <code>id</code>
* @return List<AttributeRights> all rights of the attribute
* @throw AttributeNotExistsException When Attribute with <code>id</code> doesn't exist.
*/
getAttributeRights {
@Override
public List<AttributeRights> call(ApiCaller ac, Deserializer parms) throws PerunException {
return ac.getAttributesManager().getAttributeRights(ac.getSession(),
parms.readInt("attributeId"));
}
},
/*#
* Sets all AttributeRights in the list given as a parameter. Allowed Roles to set
* rights for are: voadmin, groupadmin, facilityadmin, self.
*
* @param rights List<AttributeRights> List of AttributeRights to set.
* @throw AttributeNotExistsException When Attribute with <code>id</code> doesn't exist.
*/
setAttributeRights {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws PerunException {
ac.stateChangingCheck();
ac.getAttributesManager().setAttributeRights(ac.getSession(),
parms.readList("rights", AttributeRights.class));
return null;
}
},
/*#
* Converts attribute to unique - marks its definition as unique and ensures that all its values are unique.
* Entityless attributes cannot be converted to unique, only attributes attached to PerunBeans or pairs of PerunBeans.
*
* @param attrDefId int AttributeDefinition <code>id</code>
* @throw AttributeNotExistsException When Attribute with <code>id</code> doesn't exist.
* @throw AttributeAlreadymarkedUniqueException When Attribute is already marked as unique.
* @throw InternalErrorException when some attribute values are not unique
*/
convertAttributeToUnique {
@Override
public Void call(ApiCaller ac, Deserializer parms) throws InternalErrorException, AttributeAlreadyMarkedUniqueException, PrivilegeException, AttributeNotExistsException {
ac.stateChangingCheck();
ac.getAttributesManager().convertAttributeToUnique(ac.getSession(), parms.readInt("attrDefId"));
return null;
}
},
/*#
* Generates text file describing dependencies between attribute modules.
* The format of text file can be specified by parameter.
* Modules that has no dependency relations are omitted.
*
* Warning: No matter which serializer you specify, this method always
* returns .txt file as an attachment.
*
* @param format String Currently supported formats are DOT and TGF.
* @throw InternalErrorException when some internal error happens.
* @exampleParam format [ "DOT" ]
*/
/*#
* Generates image file describing dependencies of given attribute.
* The format of text file can be specified by parameter.
* Modules that has no dependency relations are omitted.
*
* Warning: No matter which serializer you specify, this method always
* returns .txt file as an attachment.
*
* @param attrName attribute name which dependencies will be found.
* @param format String Currently supported formats are DOT and TGF.
* @throw InternalErrorException when some internal error happens.
* @throw AttributeNotExistsException when specified attribute doesn't exist.
* @exampleParam format [ "DOT" ]
* @exampleParam attrName [ "urn:perun:resource:attribute-def:virt:unixGID" ]
*/
getAttributeModulesDependenciesGraphText {
@Override
public GraphDTO call(ApiCaller ac, Deserializer parms) throws InternalErrorException, PrivilegeException, AttributeNotExistsException {
String formatString = parms.readString("format").toUpperCase();
GraphTextFormat format;
try {
format = GraphTextFormat.valueOf(formatString);
} catch (IllegalArgumentException e) {
throw new RpcException(RpcException.Type.WRONG_PARAMETER, "Wrong parameter in format, not supported graph format: " + formatString);
}
if (parms.contains("attrName")) {
return ac.getAttributesManager().getModulesDependenciesGraph(ac.getSession(), format, parms.readString("attrName"));
}
return ac.getAttributesManager().getModulesDependenciesGraph(ac.getSession(), format);
}
}
}
| RPC: Added missing docs for getAttributes(resource,attrNames)
- Added API docs for getAttributes() version with resource and
specified list of attr names.
| perun-rpc/src/main/java/cz/metacentrum/perun/rpc/methods/AttributesManagerMethod.java | RPC: Added missing docs for getAttributes(resource,attrNames) | <ide><path>erun-rpc/src/main/java/cz/metacentrum/perun/rpc/methods/AttributesManagerMethod.java
<ide> *
<ide> * @param resource int Resource <code>id</code>
<ide> * @return List<Attribute> All non-empty Resource attributes
<add> * @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
<add> */
<add> /*#
<add> * Returns all specified Resource attributes for selected Resource.
<add> *
<add> * @param resource int Resource <code>id</code>
<add> * @param attrNames List<String> Attribute names
<add> * @return List<Attribute> Specified Resource attributes.
<ide> * @throw ResourceNotExistsException When Resource with <code>id</code> doesn't exist.
<ide> */
<ide> /*# |
|
Java | apache-2.0 | 07c782233ec5f3eb438b093dd3ba05661c716bba | 0 | AVnetWS/Hentoid,AVnetWS/Hentoid,AVnetWS/Hentoid | package me.devsaki.hentoid.util;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.Nonnull;
import me.devsaki.hentoid.BuildConfig;
import me.devsaki.hentoid.HentoidApp;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.database.ObjectBoxDB;
import me.devsaki.hentoid.database.domains.Content;
import timber.log.Timber;
import static android.os.Environment.MEDIA_MOUNTED;
import static android.os.Environment.getExternalStorageDirectory;
import static android.os.Environment.getExternalStorageState;
/**
* Created by avluis on 08/05/2016.
* File related utility class
*/
public class FileHelper {
// Note that many devices will report true (there are no guarantees of this being 'external')
public static final boolean isSDPresent = getExternalStorageState().equals(MEDIA_MOUNTED);
private static final String AUTHORIZED_CHARS = "[^a-zA-Z0-9.-]";
private static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".provider.FileProvider";
public static void saveUri(Uri uri) {
Timber.d("Saving Uri: %s", uri);
Preferences.setSdStorageUri(uri.toString());
}
public static void clearUri() {
Preferences.setSdStorageUri("");
}
public static boolean isSAF() {
return !Preferences.getSdStorageUri().isEmpty();
}
/**
* Determine if a file is on external sd card. (Kitkat+)
*
* @param file The file.
* @return true if on external sd card.
*/
public static boolean isOnExtSdCard(final File file) {
return getExtSdCardFolder(file) != null;
}
/**
* Determine the main folder of the external SD card containing the given file. (Kitkat+)
*
* @param file The file.
* @return The main folder of the external SD card containing this file,
* if the file is on an SD card. Otherwise, null is returned.
*/
public static String getExtSdCardFolder(final File file) {
String[] extSdPaths = getExtSdCardPaths();
try {
for (String extSdPath : extSdPaths) {
if (file.getCanonicalPath().startsWith(extSdPath)) {
return extSdPath;
}
}
} catch (IOException e) {
return null;
}
return null;
}
/**
* Get a list of external SD card paths. (Kitkat+)
*
* @return A list of external SD card paths.
*/
public static String[] getExtSdCardPaths() {
Context context = HentoidApp.getAppContext();
List<String> paths = new ArrayList<>();
for (File file : ContextCompat.getExternalFilesDirs(context, "external")) {
if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
int index = file.getAbsolutePath().lastIndexOf("/Android/data");
if (index < 0) {
Timber.w("Unexpected external file dir: %s", file.getAbsolutePath());
} else {
String path = file.getAbsolutePath().substring(0, index);
try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
// Keep non-canonical path.
}
paths.add(path);
}
}
}
return paths.toArray(new String[0]);
}
/**
* Check if a file or directory is writable.
* Detects write issues on external SD card.
*
* @param file The file or directory.
* @return true if the file or directory is writable.
*/
public static boolean isWritable(@NonNull final File file) {
if (file.isDirectory()) return isDirectoryWritable(file);
else return isFileWritable(file);
}
/**
* Check if a directory is writable.
* Detects write issues on external SD card.
*
* @param file The directory.
* @return true if the directory is writable.
*/
private static boolean isDirectoryWritable(@NonNull final File file) {
File testFile = new File(file, "test.txt");
boolean hasPermission = false;
try {
hasPermission = FileUtil.makeFile(testFile);
if (hasPermission)
try (OutputStream output = FileHelper.getOutputStream(testFile)) {
output.write("test".getBytes());
sync(output);
output.flush();
} catch (NullPointerException npe) {
Timber.e(npe, "Invalid Stream");
hasPermission = false;
} catch (IOException e) {
Timber.e(e, "IOException while checking permissions on %s", file.getAbsolutePath());
hasPermission = false;
}
} finally {
if (testFile.exists()) {
removeFile(testFile);
}
}
return hasPermission;
}
/**
* Check if a file is writable.
* Detects write issues on external SD card.
*
* @param file The file.
* @return true if the file is writable.
*/
private static boolean isFileWritable(@NonNull final File file) {
if (!file.canWrite()) return false;
// Ensure that it is indeed writable by opening an output stream
try {
FileOutputStream output = FileUtils.openOutputStream(file);
output.close();
} catch (IOException e) {
return false;
}
// Ensure that file is not created during this process.
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
return true;
}
/**
* Method ensures file creation from stream.
*
* @param stream - OutputStream
* @return true if all OK.
*/
static boolean sync(@NonNull final OutputStream stream) {
return (stream instanceof FileOutputStream) && FileUtil.sync((FileOutputStream) stream);
}
/**
* Get OutputStream from file.
*
* @param target The file.
* @return FileOutputStream.
*/
static OutputStream getOutputStream(@NonNull final File target) throws IOException {
return FileUtil.getOutputStream(target);
}
static InputStream getInputStream(@NonNull final File target) throws IOException {
return FileUtil.getInputStream(target);
}
/**
* Create a folder.
*
* @param file The folder to be created.
* @return true if creation was successful or the folder already exists
*/
public static boolean createDirectory(@NonNull File file) {
return FileUtil.makeDir(file);
}
/**
* Delete a file.
*
* @param target The file.
* @return true if deleted successfully.
*/
public static boolean removeFile(File target) {
return FileUtil.deleteFile(target);
}
/**
* Delete files in a target directory.
*
* @param target The folder.
* @return true if cleaned successfully.
*/
static boolean cleanDirectory(@NonNull File target) {
try {
return tryCleanDirectory(target);
} catch (Exception e) {
Timber.e(e, "Failed to clean directory");
return false;
}
}
/**
* Cleans a directory without deleting it.
* <p>
* Custom substitute for commons.io.FileUtils.cleanDirectory that supports devices without File.toPath
*
* @param directory directory to clean
* @return true if directory has been successfully cleaned
* @throws IOException in case cleaning is unsuccessful
* @throws IllegalArgumentException if {@code directory} does not exist or is not a directory
*/
private static boolean tryCleanDirectory(@NonNull File directory) throws IOException, SecurityException {
File[] files = directory.listFiles();
if (files == null) throw new IOException("Failed to list content of " + directory);
boolean isSuccess = true;
for (File file : files) {
if (file.isDirectory() && !tryCleanDirectory(file)) isSuccess = false;
if (!file.delete() && file.exists()) isSuccess = false;
}
return isSuccess;
}
public static boolean checkAndSetRootFolder(String folder) {
return checkAndSetRootFolder(folder, false);
}
public static boolean checkAndSetRootFolder(String folder, boolean notify) {
Context context = HentoidApp.getAppContext();
// Validate folder
File file = new File(folder);
if (!file.exists() && !file.isDirectory() && !FileUtil.makeDir(file)) {
if (notify) {
ToastUtil.toast(context, R.string.error_creating_folder);
}
return false;
}
File nomedia = new File(folder, ".nomedia");
boolean hasPermission;
// Clean up (if any) nomedia file
if (nomedia.exists()) {
boolean deleted = FileUtil.deleteFile(nomedia);
if (deleted) {
Timber.d(".nomedia file deleted");
}
}
// Re-create nomedia file to confirm write permissions
hasPermission = FileUtil.makeFile(nomedia);
if (!hasPermission) {
if (notify) {
ToastUtil.toast(context, R.string.error_write_permission);
}
return false;
}
boolean directorySaved = Preferences.setRootFolderName(folder);
if (!directorySaved) {
if (notify) {
ToastUtil.toast(context, R.string.error_creating_folder);
}
return false;
}
return true;
}
/**
* Create the ".nomedia" file in the app's root folder
*/
public static void createNoMedia() {
String settingDir = Preferences.getRootFolderName();
File noMedia = new File(settingDir, ".nomedia");
if (FileUtil.makeFile(noMedia)) {
ToastUtil.toast(R.string.nomedia_file_created);
} else {
Timber.d(".nomedia file already exists.");
}
}
@WorkerThread
public static void removeContent(Content content) {
// If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete
if (content.getStorageFolder().length() > 0) {
String settingDir = Preferences.getRootFolderName();
File dir = new File(settingDir, content.getStorageFolder());
if (deleteQuietly(dir) || FileUtil.deleteWithSAF(dir)) {
Timber.d("Directory %s removed.", dir);
} else {
Timber.d("Failed to delete directory: %s", dir);
}
}
}
/**
* Create the download directory of the given content
*
* @param context Context
* @param content Content for which the directory to create
* @return Created directory
*/
public static File createContentDownloadDir(Context context, Content content) {
String folderDir = formatDirPath(content);
String settingDir = Preferences.getRootFolderName();
if (settingDir.isEmpty()) {
settingDir = getDefaultDir(context, folderDir).getAbsolutePath();
}
Timber.d("New book directory %s in %s", folderDir, settingDir);
File file = new File(settingDir, folderDir);
if (!file.exists() && !FileUtil.makeDir(file)) {
file = new File(settingDir + folderDir);
if (!file.exists()) {
FileUtil.makeDir(file);
}
}
return file;
}
/**
* Format the download directory path of the given content according to current user preferences
*
* @param content Content to get the path from
* @return Canonical download directory path of the given content, according to current user preferences
*/
public static String formatDirPath(Content content) {
String siteFolder = content.getSite().getFolder();
String result = siteFolder;
int folderNamingPreference = Preferences.getFolderNameFormat();
if (folderNamingPreference == Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID) {
result = result + content.getAuthor().replaceAll(AUTHORIZED_CHARS, "_") + " - ";
}
if (folderNamingPreference == Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID || folderNamingPreference == Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_ID) {
result = result + content.getTitle().replaceAll(AUTHORIZED_CHARS, "_") + " - ";
}
result = result + "[" + content.getUniqueSiteId() + "]";
// Truncate folder dir to something manageable for Windows
// If we are to assume NTFS and Windows, then the fully qualified file, with it's drivename, path, filename, and extension, altogether is limited to 260 characters.
int truncLength = Preferences.getFolderTruncationNbChars();
if (truncLength > 0) {
if (result.length() - siteFolder.length() > truncLength)
result = result.substring(0, siteFolder.length() + truncLength - 1);
}
return result;
}
public static File getDefaultDir(Context context, String dir) {
File file;
try {
file = new File(getExternalStorageDirectory() + "/"
+ Consts.DEFAULT_LOCAL_DIRECTORY + "/" + dir);
} catch (Exception e) {
file = context.getDir("", Context.MODE_PRIVATE);
file = new File(file, "/" + Consts.DEFAULT_LOCAL_DIRECTORY);
}
if (!file.exists() && !FileUtil.makeDir(file)) {
file = context.getDir("", Context.MODE_PRIVATE);
file = new File(file, "/" + Consts.DEFAULT_LOCAL_DIRECTORY + "/" + dir);
if (!file.exists()) {
FileUtil.makeDir(file);
}
}
return file;
}
/**
* Recursively search for files of a given type from a base directory
*
* @param workingDir the base directory
* @return list containing all files with matching extension
*/
public static List<File> findFilesRecursively(File workingDir, String extension) {
List<File> files = new ArrayList<>();
File[] baseDirs = workingDir.listFiles();
for (File entry : baseDirs) {
if (entry.isDirectory()) {
files.addAll(findFilesRecursively(entry, extension));
} else {
if (getExtension(entry.getName()).equals(extension)) {
files.add(entry);
}
}
}
return files;
}
/**
* Method is used by onBindViewHolder(), speed is key
*/
public static String getThumb(Content content) {
String coverUrl = content.getCoverImageUrl();
// If trying to access a non-downloaded book cover (e.g. viewing the download queue)
if (content.getStorageFolder().equals("")) return coverUrl;
String extension = getExtension(coverUrl);
// Some URLs do not link the image itself (e.g Tsumino) => jpg by default
// NB : ideal would be to get the content-type of the resource behind coverUrl, but that's too time-consuming
if (extension.isEmpty() || extension.contains("/")) extension = "jpg";
File f = new File(Preferences.getRootFolderName(), content.getStorageFolder() + "/thumb." + extension);
return f.exists() ? f.getAbsolutePath() : coverUrl;
}
/**
* Open the given content using the viewer defined in user preferences
*
* @param context Context
* @param content Content to be opened
*/
public static void openContent(final Context context, Content content) {
Timber.d("Opening: %s from: %s", content.getTitle(), content.getStorageFolder());
String rootFolderName = Preferences.getRootFolderName();
File dir = new File(rootFolderName, content.getStorageFolder());
Timber.d("Opening: " + content.getTitle() + " from: " + dir);
if (isSAF() && getExtSdCardFolder(new File(rootFolderName)) == null) {
Timber.d("File not found!! Exiting method.");
ToastUtil.toast(R.string.sd_access_error);
return;
}
ToastUtil.toast("Opening: " + content.getTitle());
File imageFile = null;
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
Arrays.sort(files);
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".jpg") ||
filename.endsWith(".png") ||
filename.endsWith(".gif")) {
imageFile = file;
break;
}
}
}
if (imageFile == null) {
String message = context.getString(R.string.image_file_not_found)
.replace("@dir", dir.getAbsolutePath());
ToastUtil.toast(context, message);
} else {
int readContentPreference = Preferences.getContentReadAction();
if (readContentPreference == Preferences.Constant.PREF_READ_CONTENT_DEFAULT) {
openFile(context, imageFile);
} else if (readContentPreference == Preferences.Constant.PREF_READ_CONTENT_PERFECT_VIEWER) {
openPerfectViewer(context, imageFile);
}
}
ObjectBoxDB db = ObjectBoxDB.getInstance(context);
content.increaseReads().setLastReadDate(new Date().getTime());
db.updateContentReads(content);
try {
JsonHelper.saveJson(content.preJSONExport(), dir);
} catch (IOException e) {
Timber.e(e, "Error while writing to %s", dir.getAbsolutePath());
}
}
/**
* Open the given file using the device's app(s) of choice
*
* @param context Context
* @param aFile File to be opened
*/
public static void openFile(Context context, File aFile) {
Intent myIntent = new Intent(Intent.ACTION_VIEW);
File file = new File(aFile.getAbsolutePath());
String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
myIntent.setDataAndType(Uri.fromFile(file), mimeType);
try {
context.startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Timber.e(e, "Activity not found to open %s", aFile.getAbsolutePath());
ToastUtil.toast(context, R.string.error_open, Toast.LENGTH_LONG);
}
}
/**
* Open PerfectViewer telling it to display the given image
*
* @param context Context
* @param firstImage Image to be displayed
*/
private static void openPerfectViewer(Context context, File firstImage) {
try {
Intent intent = context
.getPackageManager()
.getLaunchIntentForPackage("com.rookiestudio.perfectviewer");
if (intent != null) {
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(firstImage), "image/*");
context.startActivity(intent);
}
} catch (Exception e) {
ToastUtil.toast(context, R.string.error_open_perfect_viewer);
}
}
/**
* Returns the extension of the given filename
*
* @param fileName Filename
* @return Extension of the given filename
*/
public static String getExtension(String fileName) {
return fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(Locale.getDefault()) : "";
}
public static void archiveContent(final Context context, Content content) {
Timber.d("Building file list for: %s", content.getTitle());
// Build list of files
String settingDir = Preferences.getRootFolderName();
File dir = new File(settingDir, content.getStorageFolder());
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
Arrays.sort(files);
ArrayList<File> fileList = new ArrayList<>();
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".json") || filename.contains("thumb")) {
break;
}
fileList.add(file);
}
// Create folder to share from
File sharedDir = new File(context.getExternalCacheDir() + "/shared");
if (FileUtil.makeDir(sharedDir)) {
Timber.d("Shared folder created.");
}
// Clean directory (in case of previous job)
if (cleanDirectory(sharedDir)) {
Timber.d("Shared folder cleaned up.");
}
// Build destination file
File dest = new File(context.getExternalCacheDir() + "/shared",
content.getTitle().replaceAll(AUTHORIZED_CHARS, "_") + ".zip");
Timber.d("Destination file: %s", dest);
// Convert ArrayList to Array
File[] fileArray = fileList.toArray(new File[0]);
// Compress files
new AsyncUnzip(context, dest).execute(fileArray, dest);
}
}
/**
* Save the given binary content in the given file
*
* @param file File to save content on
* @param binaryContent Content to save
* @throws IOException If any IOException occurs
*/
public static void saveBinaryInFile(File file, byte[] binaryContent) throws IOException {
byte buffer[] = new byte[1024];
int count;
try (InputStream input = new ByteArrayInputStream(binaryContent)) {
try (BufferedOutputStream output = new BufferedOutputStream(FileHelper.getOutputStream(file))) {
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
}
output.flush();
}
}
}
/**
* Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
* </ul>
* <p>
* Custom substitute for commons.io.FileUtils.deleteQuietly that works with devices that doesn't support File.toPath
*
* @param file file or directory to delete, can be {@code null}
* @return {@code true} if the file or directory was deleted, otherwise
* {@code false}
*/
private static boolean deleteQuietly(final File file) {
if (file == null) {
return false;
}
try {
if (file.isDirectory()) {
tryCleanDirectory(file);
}
} catch (final Exception ignored) {
}
try {
return file.delete();
} catch (final Exception ignored) {
return false;
}
}
public static boolean renameDirectory(File srcDir, File destDir) {
try {
FileUtils.moveDirectory(srcDir, destDir);
return true;
} catch (IOException e) {
return FileUtil.renameWithSAF(srcDir, destDir.getName());
} catch (Exception e) {
Timber.e(e);
}
return false;
}
private static class AsyncUnzip extends ZipUtil.ZipTask {
final Context context; // TODO - omg leak !
final File dest;
AsyncUnzip(Context context, File dest) {
this.context = context;
this.dest = dest;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
// Hentoid is FileProvider ready!!
sendIntent.putExtra(Intent.EXTRA_STREAM,
FileProvider.getUriForFile(context, AUTHORITY, dest));
sendIntent.setType(MimeTypes.getMimeType(dest));
context.startActivity(sendIntent);
}
}
// Please keep that, I need some way to trace actions when working with SD card features - Robb
public static void createFileWithMsg(@Nonnull String file, String msg) {
try {
FileHelper.saveBinaryInFile(new File(getDefaultDir(HentoidApp.getAppContext(), ""), file + ".txt"), (null == msg) ? "NULL".getBytes() : msg.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| app/src/main/java/me/devsaki/hentoid/util/FileHelper.java | package me.devsaki.hentoid.util;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import javax.annotation.Nonnull;
import me.devsaki.hentoid.BuildConfig;
import me.devsaki.hentoid.HentoidApp;
import me.devsaki.hentoid.R;
import me.devsaki.hentoid.database.ObjectBoxDB;
import me.devsaki.hentoid.database.domains.Content;
import timber.log.Timber;
import static android.os.Environment.MEDIA_MOUNTED;
import static android.os.Environment.getExternalStorageDirectory;
import static android.os.Environment.getExternalStorageState;
/**
* Created by avluis on 08/05/2016.
* File related utility class
*/
public class FileHelper {
// Note that many devices will report true (there are no guarantees of this being 'external')
public static final boolean isSDPresent = getExternalStorageState().equals(MEDIA_MOUNTED);
private static final String AUTHORIZED_CHARS = "[^a-zA-Z0-9.-]";
private static final String AUTHORITY = BuildConfig.APPLICATION_ID + ".provider.FileProvider";
public static void saveUri(Uri uri) {
Timber.d("Saving Uri: %s", uri);
Preferences.setSdStorageUri(uri.toString());
}
public static void clearUri() {
Preferences.setSdStorageUri("");
}
public static boolean isSAF() {
return !Preferences.getSdStorageUri().isEmpty();
}
/**
* Determine if a file is on external sd card. (Kitkat+)
*
* @param file The file.
* @return true if on external sd card.
*/
public static boolean isOnExtSdCard(final File file) {
return getExtSdCardFolder(file) != null;
}
/**
* Determine the main folder of the external SD card containing the given file. (Kitkat+)
*
* @param file The file.
* @return The main folder of the external SD card containing this file,
* if the file is on an SD card. Otherwise, null is returned.
*/
public static String getExtSdCardFolder(final File file) {
String[] extSdPaths = getExtSdCardPaths();
try {
for (String extSdPath : extSdPaths) {
if (file.getCanonicalPath().startsWith(extSdPath)) {
return extSdPath;
}
}
} catch (IOException e) {
return null;
}
return null;
}
/**
* Get a list of external SD card paths. (Kitkat+)
*
* @return A list of external SD card paths.
*/
public static String[] getExtSdCardPaths() {
Context context = HentoidApp.getAppContext();
List<String> paths = new ArrayList<>();
for (File file : ContextCompat.getExternalFilesDirs(context, "external")) {
if (file != null && !file.equals(context.getExternalFilesDir("external"))) {
int index = file.getAbsolutePath().lastIndexOf("/Android/data");
if (index < 0) {
Timber.w("Unexpected external file dir: %s", file.getAbsolutePath());
} else {
String path = file.getAbsolutePath().substring(0, index);
try {
path = new File(path).getCanonicalPath();
} catch (IOException e) {
// Keep non-canonical path.
}
paths.add(path);
}
}
}
return paths.toArray(new String[0]);
}
/**
* Check if a file or directory is writable.
* Detects write issues on external SD card.
*
* @param file The file or directory.
* @return true if the file or directory is writable.
*/
public static boolean isWritable(@NonNull final File file) {
if (file.isDirectory()) return isDirectoryWritable(file);
else return isFileWritable(file);
}
/**
* Check if a directory is writable.
* Detects write issues on external SD card.
*
* @param file The directory.
* @return true if the directory is writable.
*/
private static boolean isDirectoryWritable(@NonNull final File file) {
File testFile = new File(file, "test.txt");
boolean hasPermission = false;
try {
hasPermission = FileUtil.makeFile(testFile);
try (OutputStream output = FileHelper.getOutputStream(testFile)) {
output.write("test".getBytes());
sync(output);
output.flush();
} catch (NullPointerException npe) {
Timber.e(npe, "Invalid Stream");
hasPermission = false;
} catch (IOException e) {
Timber.e(e, "IOException while checking permissions on %s", file.getAbsolutePath());
hasPermission = false;
}
} finally {
if (testFile.exists()) {
removeFile(testFile);
}
}
return hasPermission;
}
/**
* Check if a file is writable.
* Detects write issues on external SD card.
*
* @param file The file.
* @return true if the file is writable.
*/
private static boolean isFileWritable(@NonNull final File file) {
if (!file.canWrite()) return false;
// Ensure that it is indeed writable by opening an output stream
try {
FileOutputStream output = FileUtils.openOutputStream(file);
output.close();
} catch (IOException e) {
return false;
}
// Ensure that file is not created during this process.
if (file.exists()) {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
return true;
}
/**
* Method ensures file creation from stream.
*
* @param stream - OutputStream
* @return true if all OK.
*/
static boolean sync(@NonNull final OutputStream stream) {
return (stream instanceof FileOutputStream) && FileUtil.sync((FileOutputStream) stream);
}
/**
* Get OutputStream from file.
*
* @param target The file.
* @return FileOutputStream.
*/
static OutputStream getOutputStream(@NonNull final File target) throws IOException {
return FileUtil.getOutputStream(target);
}
static InputStream getInputStream(@NonNull final File target) throws IOException {
return FileUtil.getInputStream(target);
}
/**
* Create a folder.
*
* @param file The folder to be created.
* @return true if creation was successful or the folder already exists
*/
public static boolean createDirectory(@NonNull File file) {
return FileUtil.makeDir(file);
}
/**
* Delete a file.
*
* @param target The file.
* @return true if deleted successfully.
*/
public static boolean removeFile(File target) {
return FileUtil.deleteFile(target);
}
/**
* Delete files in a target directory.
*
* @param target The folder.
* @return true if cleaned successfully.
*/
static boolean cleanDirectory(@NonNull File target) {
try {
return tryCleanDirectory(target);
} catch (Exception e) {
Timber.e(e, "Failed to clean directory");
return false;
}
}
/**
* Cleans a directory without deleting it.
* <p>
* Custom substitute for commons.io.FileUtils.cleanDirectory that supports devices without File.toPath
*
* @param directory directory to clean
* @return true if directory has been successfully cleaned
* @throws IOException in case cleaning is unsuccessful
* @throws IllegalArgumentException if {@code directory} does not exist or is not a directory
*/
private static boolean tryCleanDirectory(@NonNull File directory) throws IOException, SecurityException {
File[] files = directory.listFiles();
if (files == null) throw new IOException("Failed to list content of " + directory);
boolean isSuccess = true;
for (File file : files) {
if (file.isDirectory() && !tryCleanDirectory(file)) isSuccess = false;
if (!file.delete() && file.exists()) isSuccess = false;
}
return isSuccess;
}
public static boolean checkAndSetRootFolder(String folder) {
return checkAndSetRootFolder(folder, false);
}
public static boolean checkAndSetRootFolder(String folder, boolean notify) {
Context context = HentoidApp.getAppContext();
// Validate folder
File file = new File(folder);
if (!file.exists() && !file.isDirectory() && !FileUtil.makeDir(file)) {
if (notify) {
ToastUtil.toast(context, R.string.error_creating_folder);
}
return false;
}
File nomedia = new File(folder, ".nomedia");
boolean hasPermission;
// Clean up (if any) nomedia file
if (nomedia.exists()) {
boolean deleted = FileUtil.deleteFile(nomedia);
if (deleted) {
Timber.d(".nomedia file deleted");
}
}
// Re-create nomedia file to confirm write permissions
hasPermission = FileUtil.makeFile(nomedia);
if (!hasPermission) {
if (notify) {
ToastUtil.toast(context, R.string.error_write_permission);
}
return false;
}
boolean directorySaved = Preferences.setRootFolderName(folder);
if (!directorySaved) {
if (notify) {
ToastUtil.toast(context, R.string.error_creating_folder);
}
return false;
}
return true;
}
/**
* Create the ".nomedia" file in the app's root folder
*/
public static void createNoMedia() {
String settingDir = Preferences.getRootFolderName();
File noMedia = new File(settingDir, ".nomedia");
if (FileUtil.makeFile(noMedia)) {
ToastUtil.toast(R.string.nomedia_file_created);
} else {
Timber.d(".nomedia file already exists.");
}
}
@WorkerThread
public static void removeContent(Content content) {
// If the book has just starting being downloaded and there are no complete pictures on memory yet, it has no storage folder => nothing to delete
if (content.getStorageFolder().length() > 0) {
String settingDir = Preferences.getRootFolderName();
File dir = new File(settingDir, content.getStorageFolder());
if (deleteQuietly(dir) || FileUtil.deleteWithSAF(dir)) {
Timber.d("Directory %s removed.", dir);
} else {
Timber.d("Failed to delete directory: %s", dir);
}
}
}
/**
* Create the download directory of the given content
*
* @param context Context
* @param content Content for which the directory to create
* @return Created directory
*/
public static File createContentDownloadDir(Context context, Content content) {
String folderDir = formatDirPath(content);
String settingDir = Preferences.getRootFolderName();
if (settingDir.isEmpty()) {
settingDir = getDefaultDir(context, folderDir).getAbsolutePath();
}
Timber.d("New book directory %s in %s", folderDir, settingDir);
File file = new File(settingDir, folderDir);
if (!file.exists() && !FileUtil.makeDir(file)) {
file = new File(settingDir + folderDir);
if (!file.exists()) {
FileUtil.makeDir(file);
}
}
return file;
}
/**
* Format the download directory path of the given content according to current user preferences
*
* @param content Content to get the path from
* @return Canonical download directory path of the given content, according to current user preferences
*/
public static String formatDirPath(Content content) {
String siteFolder = content.getSite().getFolder();
String result = siteFolder;
int folderNamingPreference = Preferences.getFolderNameFormat();
if (folderNamingPreference == Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID) {
result = result + content.getAuthor().replaceAll(AUTHORIZED_CHARS, "_") + " - ";
}
if (folderNamingPreference == Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_AUTH_TITLE_ID || folderNamingPreference == Preferences.Constant.PREF_FOLDER_NAMING_CONTENT_TITLE_ID) {
result = result + content.getTitle().replaceAll(AUTHORIZED_CHARS, "_") + " - ";
}
result = result + "[" + content.getUniqueSiteId() + "]";
// Truncate folder dir to something manageable for Windows
// If we are to assume NTFS and Windows, then the fully qualified file, with it's drivename, path, filename, and extension, altogether is limited to 260 characters.
int truncLength = Preferences.getFolderTruncationNbChars();
if (truncLength > 0) {
if (result.length() - siteFolder.length() > truncLength)
result = result.substring(0, siteFolder.length() + truncLength - 1);
}
return result;
}
public static File getDefaultDir(Context context, String dir) {
File file;
try {
file = new File(getExternalStorageDirectory() + "/"
+ Consts.DEFAULT_LOCAL_DIRECTORY + "/" + dir);
} catch (Exception e) {
file = context.getDir("", Context.MODE_PRIVATE);
file = new File(file, "/" + Consts.DEFAULT_LOCAL_DIRECTORY);
}
if (!file.exists() && !FileUtil.makeDir(file)) {
file = context.getDir("", Context.MODE_PRIVATE);
file = new File(file, "/" + Consts.DEFAULT_LOCAL_DIRECTORY + "/" + dir);
if (!file.exists()) {
FileUtil.makeDir(file);
}
}
return file;
}
/**
* Recursively search for files of a given type from a base directory
*
* @param workingDir the base directory
* @return list containing all files with matching extension
*/
public static List<File> findFilesRecursively(File workingDir, String extension) {
List<File> files = new ArrayList<>();
File[] baseDirs = workingDir.listFiles();
for (File entry : baseDirs) {
if (entry.isDirectory()) {
files.addAll(findFilesRecursively(entry, extension));
} else {
if (getExtension(entry.getName()).equals(extension)) {
files.add(entry);
}
}
}
return files;
}
/**
* Method is used by onBindViewHolder(), speed is key
*/
public static String getThumb(Content content) {
String coverUrl = content.getCoverImageUrl();
// If trying to access a non-downloaded book cover (e.g. viewing the download queue)
if (content.getStorageFolder().equals("")) return coverUrl;
String extension = getExtension(coverUrl);
// Some URLs do not link the image itself (e.g Tsumino) => jpg by default
// NB : ideal would be to get the content-type of the resource behind coverUrl, but that's too time-consuming
if (extension.isEmpty() || extension.contains("/")) extension = "jpg";
File f = new File(Preferences.getRootFolderName(), content.getStorageFolder() + "/thumb." + extension);
return f.exists() ? f.getAbsolutePath() : coverUrl;
}
/**
* Open the given content using the viewer defined in user preferences
*
* @param context Context
* @param content Content to be opened
*/
public static void openContent(final Context context, Content content) {
Timber.d("Opening: %s from: %s", content.getTitle(), content.getStorageFolder());
String rootFolderName = Preferences.getRootFolderName();
File dir = new File(rootFolderName, content.getStorageFolder());
Timber.d("Opening: " + content.getTitle() + " from: " + dir);
if (isSAF() && getExtSdCardFolder(new File(rootFolderName)) == null) {
Timber.d("File not found!! Exiting method.");
ToastUtil.toast(R.string.sd_access_error);
return;
}
ToastUtil.toast("Opening: " + content.getTitle());
File imageFile = null;
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
Arrays.sort(files);
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".jpg") ||
filename.endsWith(".png") ||
filename.endsWith(".gif")) {
imageFile = file;
break;
}
}
}
if (imageFile == null) {
String message = context.getString(R.string.image_file_not_found)
.replace("@dir", dir.getAbsolutePath());
ToastUtil.toast(context, message);
} else {
int readContentPreference = Preferences.getContentReadAction();
if (readContentPreference == Preferences.Constant.PREF_READ_CONTENT_DEFAULT) {
openFile(context, imageFile);
} else if (readContentPreference == Preferences.Constant.PREF_READ_CONTENT_PERFECT_VIEWER) {
openPerfectViewer(context, imageFile);
}
}
ObjectBoxDB db = ObjectBoxDB.getInstance(context);
content.increaseReads().setLastReadDate(new Date().getTime());
db.updateContentReads(content);
try {
JsonHelper.saveJson(content.preJSONExport(), dir);
} catch (IOException e) {
Timber.e(e, "Error while writing to %s", dir.getAbsolutePath());
}
}
/**
* Open the given file using the device's app(s) of choice
*
* @param context Context
* @param aFile File to be opened
*/
public static void openFile(Context context, File aFile) {
Intent myIntent = new Intent(Intent.ACTION_VIEW);
File file = new File(aFile.getAbsolutePath());
String extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString());
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
myIntent.setDataAndType(Uri.fromFile(file), mimeType);
try {
context.startActivity(myIntent);
} catch (ActivityNotFoundException e) {
Timber.e(e, "Activity not found to open %s", aFile.getAbsolutePath());
ToastUtil.toast(context, R.string.error_open, Toast.LENGTH_LONG);
}
}
/**
* Open PerfectViewer telling it to display the given image
*
* @param context Context
* @param firstImage Image to be displayed
*/
private static void openPerfectViewer(Context context, File firstImage) {
try {
Intent intent = context
.getPackageManager()
.getLaunchIntentForPackage("com.rookiestudio.perfectviewer");
if (intent != null) {
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(firstImage), "image/*");
context.startActivity(intent);
}
} catch (Exception e) {
ToastUtil.toast(context, R.string.error_open_perfect_viewer);
}
}
/**
* Returns the extension of the given filename
*
* @param fileName Filename
* @return Extension of the given filename
*/
public static String getExtension(String fileName) {
return fileName.contains(".") ? fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase(Locale.getDefault()) : "";
}
public static void archiveContent(final Context context, Content content) {
Timber.d("Building file list for: %s", content.getTitle());
// Build list of files
String settingDir = Preferences.getRootFolderName();
File dir = new File(settingDir, content.getStorageFolder());
File[] files = dir.listFiles();
if (files != null && files.length > 0) {
Arrays.sort(files);
ArrayList<File> fileList = new ArrayList<>();
for (File file : files) {
String filename = file.getName();
if (filename.endsWith(".json") || filename.contains("thumb")) {
break;
}
fileList.add(file);
}
// Create folder to share from
File sharedDir = new File(context.getExternalCacheDir() + "/shared");
if (FileUtil.makeDir(sharedDir)) {
Timber.d("Shared folder created.");
}
// Clean directory (in case of previous job)
if (cleanDirectory(sharedDir)) {
Timber.d("Shared folder cleaned up.");
}
// Build destination file
File dest = new File(context.getExternalCacheDir() + "/shared",
content.getTitle().replaceAll(AUTHORIZED_CHARS, "_") + ".zip");
Timber.d("Destination file: %s", dest);
// Convert ArrayList to Array
File[] fileArray = fileList.toArray(new File[0]);
// Compress files
new AsyncUnzip(context, dest).execute(fileArray, dest);
}
}
/**
* Save the given binary content in the given file
*
* @param file File to save content on
* @param binaryContent Content to save
* @throws IOException If any IOException occurs
*/
public static void saveBinaryInFile(File file, byte[] binaryContent) throws IOException {
byte buffer[] = new byte[1024];
int count;
try (InputStream input = new ByteArrayInputStream(binaryContent)) {
try (BufferedOutputStream output = new BufferedOutputStream(FileHelper.getOutputStream(file))) {
while ((count = input.read(buffer)) != -1) {
output.write(buffer, 0, count);
}
output.flush();
}
}
}
/**
* Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
* <p>
* The difference between File.delete() and this method are:
* <ul>
* <li>A directory to be deleted does not have to be empty.</li>
* <li>No exceptions are thrown when a file or directory cannot be deleted.</li>
* </ul>
* <p>
* Custom substitute for commons.io.FileUtils.deleteQuietly that works with devices that doesn't support File.toPath
*
* @param file file or directory to delete, can be {@code null}
* @return {@code true} if the file or directory was deleted, otherwise
* {@code false}
*/
private static boolean deleteQuietly(final File file) {
if (file == null) {
return false;
}
try {
if (file.isDirectory()) {
tryCleanDirectory(file);
}
} catch (final Exception ignored) {
}
try {
return file.delete();
} catch (final Exception ignored) {
return false;
}
}
public static boolean renameDirectory(File srcDir, File destDir) {
try {
FileUtils.moveDirectory(srcDir, destDir);
return true;
} catch (IOException e) {
return FileUtil.renameWithSAF(srcDir, destDir.getName());
} catch (Exception e) {
Timber.e(e);
}
return false;
}
private static class AsyncUnzip extends ZipUtil.ZipTask {
final Context context; // TODO - omg leak !
final File dest;
AsyncUnzip(Context context, File dest) {
this.context = context;
this.dest = dest;
}
@Override
protected void onPostExecute(Boolean aBoolean) {
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
// Hentoid is FileProvider ready!!
sendIntent.putExtra(Intent.EXTRA_STREAM,
FileProvider.getUriForFile(context, AUTHORITY, dest));
sendIntent.setType(MimeTypes.getMimeType(dest));
context.startActivity(sendIntent);
}
}
// Please keep that, I need some way to trace actions when working with SD card features - Robb
public static void createFileWithMsg(@Nonnull String file, String msg) {
try {
FileHelper.saveBinaryInFile(new File(getDefaultDir(HentoidApp.getAppContext(), ""), file + ".txt"), (null == msg) ? "NULL".getBytes() : msg.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Avoid trying to open outputstream is makefile already failed
| app/src/main/java/me/devsaki/hentoid/util/FileHelper.java | Avoid trying to open outputstream is makefile already failed | <ide><path>pp/src/main/java/me/devsaki/hentoid/util/FileHelper.java
<ide>
<ide> try {
<ide> hasPermission = FileUtil.makeFile(testFile);
<del> try (OutputStream output = FileHelper.getOutputStream(testFile)) {
<del> output.write("test".getBytes());
<del> sync(output);
<del> output.flush();
<del> } catch (NullPointerException npe) {
<del> Timber.e(npe, "Invalid Stream");
<del> hasPermission = false;
<del> } catch (IOException e) {
<del> Timber.e(e, "IOException while checking permissions on %s", file.getAbsolutePath());
<del> hasPermission = false;
<del> }
<add> if (hasPermission)
<add> try (OutputStream output = FileHelper.getOutputStream(testFile)) {
<add> output.write("test".getBytes());
<add> sync(output);
<add> output.flush();
<add> } catch (NullPointerException npe) {
<add> Timber.e(npe, "Invalid Stream");
<add> hasPermission = false;
<add> } catch (IOException e) {
<add> Timber.e(e, "IOException while checking permissions on %s", file.getAbsolutePath());
<add> hasPermission = false;
<add> }
<ide> } finally {
<ide> if (testFile.exists()) {
<ide> removeFile(testFile); |
|
Java | bsd-3-clause | d255cf117ef4021bd8cb668de420fded9f7b45f8 | 0 | oschneid/mHIVE,oschneid/mHIVE,oschneid/mHIVE | package org.spin.mhive;
import org.spin.mhive.ADSRDialog.ADSRDialogSeekBarChangeListener;
import org.spin.mhive.WaveformDialog.OnWaveformDialogButtonListener;
import org.spin.mhive.replay.HapticNote;
import org.spin.mhive.replay.HapticNoteList;
import org.spin.mhive.replay.HapticNoteRecord;
import org.spin.mhive.replay.HapticNoteRecordPlay;
import org.spin.mhive.replay.HapticNoteRecordStop;
import com.example.mhive.R;
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class MainActivity extends Activity {
private int minFreq = 20;
private int maxFreq = 140;
private View mainInputView;
private SeekBar seekAttack, seekDecay, seekSustain, seekRelease;
private final int MAX_MS = 1000;
private HIVEAudioGenerator hiveAudioGenerator;
private HapticNoteList noteHistory;
private ArrayAdapter<HapticNote> noteHistoryAdapter;
WaveformDialog waveformDialog;
ADSRDialog adsrDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
mainInputView = findViewById(R.id.fullscreen_content);
//set up Audio Generator
hiveAudioGenerator = new HIVEAudioGenerator();
SetWaveform(HIVEAudioGenerator.OSCILLATOR_SINE);
//setup waveform button
RadioButton btnSineWave = (RadioButton)findViewById(R.id.btnWaveformSelectSine);
btnSineWave.setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_SINE));
((RadioButton)findViewById(R.id.btnWaveformSelectSquare)).setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_SQUARE));
((RadioButton)findViewById(R.id.btnWaveformSelectSawUp)).setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_SAWUP));
((RadioButton)findViewById(R.id.btnWaveformSelectTriangle)).setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_TRIANGLE));
btnSineWave.setChecked(true);
//setup ADSR toggle button
ToggleButton tglADSR = (ToggleButton)findViewById(R.id.tglADSR);
tglADSR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
hiveAudioGenerator.EnableADSR(isChecked);
}
});
tglADSR.setChecked(true);
//setup ADSR main button
seekAttack = (SeekBar)findViewById(R.id.seekAttack);
seekDecay = (SeekBar)findViewById(R.id.seekDecay);
seekSustain = (SeekBar)findViewById(R.id.seekSustain);
seekRelease = (SeekBar)findViewById(R.id.seekRelease);
seekAttack.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtAttackValue), MAX_MS));
seekDecay.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtDecayValue), MAX_MS));
seekSustain.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtSustainValue), 1));
seekRelease.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtReleaseValue), MAX_MS));
SetADSR(new ADSREnvelope(100, 100, 0.8f, 100));
//set up STUB recording
noteHistory = new HapticNoteList();
ToggleButton tglRecordButton = (ToggleButton)findViewById(R.id.tglRecordButton);
ListView lstHistory = (ListView)findViewById(R.id.lstHistory);
noteHistoryAdapter = new ArrayAdapter<HapticNote>(this, android.R.layout.simple_list_item_1, noteHistory);
lstHistory.setAdapter(noteHistoryAdapter);
tglRecordButton.setOnCheckedChangeListener(new RecordingButtonCheckedListener());
lstHistory.setOnItemClickListener(new HistoryItemSelectedListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE)
{
if (mainInputView.getX() <= event.getX()
&& mainInputView.getX()+mainInputView.getWidth() >= event.getX()
&& mainInputView.getY() <= event.getY()
&& mainInputView.getY()+mainInputView.getHeight() >= event.getY())
{
float xVal = (event.getX()-mainInputView.getX())/mainInputView.getWidth();
float yVal = (event.getY()-mainInputView.getY())/mainInputView.getHeight();
yVal = (float) (1.0 - Math.log(event.getY()) / Math.log(mainInputView.getHeight()));
yVal = Math.min(Math.max(yVal, 0.0f), 1.0f);
int freq = (int)(xVal * (maxFreq-minFreq)) + minFreq;
float atten = yVal; //attenuation
hiveAudioGenerator.Play(freq, atten);
} else {
hiveAudioGenerator.Stop();
}
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
hiveAudioGenerator.Stop();
}
return false;
}
public void SetWaveform(int waveform)
{
hiveAudioGenerator.setWaveform(waveform);
}
public int GetWaveform()
{
return hiveAudioGenerator.getCurrentWaveform();
}
class OnWaveformDialogButtonListener implements OnClickListener
{
private int value;
public OnWaveformDialogButtonListener(int value)
{
this.value = value;
}
@Override
public void onClick(View v)
{
SetWaveform(value);
}
}
public void SetADSR(ADSREnvelope envelope)
{
hiveAudioGenerator.SetADSR(envelope);
if(seekAttack != null)
{
seekAttack.setMax(MAX_MS);
seekAttack.setProgress(envelope.getAttack());
}
if(seekDecay != null)
{
seekDecay.setMax(MAX_MS);
seekDecay.setProgress(envelope.getDecay());
}
if(seekSustain != null)
{
seekSustain.setMax(100);
seekSustain.setProgress((int)(envelope.getSustain()*100));
}
if(seekRelease != null)
{
seekRelease.setMax(MAX_MS);
seekRelease.setProgress(envelope.getRelease());
}
}
public ADSREnvelope GetADSR()
{
return new ADSREnvelope((int)((float)seekAttack.getProgress()/(float)seekAttack.getMax()*(float)MAX_MS),
(int)((float)seekDecay.getProgress()/(float)seekDecay.getMax()*(float)MAX_MS),
(float)seekSustain.getProgress()/(float)seekSustain.getMax(),
(int)((float)seekRelease.getProgress()/(float)seekRelease.getMax()*(float)MAX_MS));
}
class ADSRDialogSeekBarChangeListener implements OnSeekBarChangeListener
{
TextView displayView;
int max;
public ADSRDialogSeekBarChangeListener(TextView displayView, int max)
{
this.displayView = displayView;
this.max = max;
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
{
float value = ((float)arg1/(float)arg0.getMax() * (float) max);
displayView.setText(""+value);
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {}
@Override
public void onStopTrackingTouch(SeekBar arg0)
{
SetADSR(GetADSR());
}
}
class RecordingButtonCheckedListener implements OnCheckedChangeListener
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
hiveAudioGenerator.StartRecording();
//TODO: Disable ADSR and Waveform
}
else
{
noteHistory.add(hiveAudioGenerator.StopRecording());
noteHistoryAdapter.notifyDataSetChanged();
}
}
}
class HistoryItemSelectedListener implements AdapterView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
hiveAudioGenerator.Replay(noteHistory.get(position));
}
}
}
| mHIVE/src/org/spin/mhive/MainActivity.java | package org.spin.mhive;
import org.spin.mhive.ADSRDialog.ADSRDialogSeekBarChangeListener;
import org.spin.mhive.WaveformDialog.OnWaveformDialogButtonListener;
import org.spin.mhive.replay.HapticNote;
import org.spin.mhive.replay.HapticNoteList;
import org.spin.mhive.replay.HapticNoteRecord;
import org.spin.mhive.replay.HapticNoteRecordPlay;
import org.spin.mhive.replay.HapticNoteRecordStop;
import com.example.mhive.R;
import android.app.Activity;
import android.graphics.Point;
import android.os.Bundle;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.SeekBar.OnSeekBarChangeListener;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* @see SystemUiHider
*/
public class MainActivity extends Activity {
private int minFreq = 20;
private int maxFreq = 140;
private View mainInputView;
private SeekBar seekAttack, seekDecay, seekSustain, seekRelease;
private final int MAX_MS = 1000;
private HIVEAudioGenerator hiveAudioGenerator;
private HapticNoteList noteHistory;
private ArrayAdapter<HapticNote> noteHistoryAdapter;
WaveformDialog waveformDialog;
ADSRDialog adsrDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
mainInputView = findViewById(R.id.fullscreen_content);
//set up Audio Generator
hiveAudioGenerator = new HIVEAudioGenerator();
SetWaveform(HIVEAudioGenerator.OSCILLATOR_SINE);
//setup waveform button
RadioButton btnSineWave = (RadioButton)findViewById(R.id.btnWaveformSelectSine);
btnSineWave.setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_SINE));
((RadioButton)findViewById(R.id.btnWaveformSelectSquare)).setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_SQUARE));
((RadioButton)findViewById(R.id.btnWaveformSelectSawUp)).setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_SAWUP));
((RadioButton)findViewById(R.id.btnWaveformSelectTriangle)).setOnClickListener(new OnWaveformDialogButtonListener(HIVEAudioGenerator.OSCILLATOR_TRIANGLE));
btnSineWave.setChecked(true);
//setup ADSR toggle button
ToggleButton tglADSR = (ToggleButton)findViewById(R.id.tglADSR);
tglADSR.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
hiveAudioGenerator.EnableADSR(isChecked);
}
});
tglADSR.setChecked(true);
//setup ADSR main button
seekAttack = (SeekBar)findViewById(R.id.seekAttack);
seekDecay = (SeekBar)findViewById(R.id.seekDecay);
seekSustain = (SeekBar)findViewById(R.id.seekSustain);
seekRelease = (SeekBar)findViewById(R.id.seekRelease);
seekAttack.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtAttackValue), MAX_MS));
seekDecay.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtDecayValue), MAX_MS));
seekSustain.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtSustainValue), 1));
seekRelease.setOnSeekBarChangeListener(new ADSRDialogSeekBarChangeListener((TextView)findViewById(R.id.txtReleaseValue), MAX_MS));
SetADSR(new ADSREnvelope(100, 100, 0.8f, 100));
//set up STUB recording
noteHistory = new HapticNoteList();
ToggleButton tglRecordButton = (ToggleButton)findViewById(R.id.tglRecordButton);
ListView lstHistory = (ListView)findViewById(R.id.lstHistory);
noteHistoryAdapter = new ArrayAdapter<HapticNote>(this, android.R.layout.simple_list_item_1, noteHistory);
lstHistory.setAdapter(noteHistoryAdapter);
tglRecordButton.setOnCheckedChangeListener(new RecordingButtonCheckedListener());
lstHistory.setOnItemClickListener(new HistoryItemSelectedListener());
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN
|| event.getAction() == MotionEvent.ACTION_MOVE)
{
if (mainInputView.getX() <= event.getX()
&& mainInputView.getX()+mainInputView.getWidth() >= event.getX()
&& mainInputView.getY() <= event.getY()
&& mainInputView.getY()+mainInputView.getHeight() >= event.getY())
{
float xVal = (event.getX()-mainInputView.getX())/mainInputView.getWidth();
float yVal = (event.getY()-mainInputView.getY())/mainInputView.getHeight();
yVal = (float) (1.0 - Math.log(event.getY()) / Math.log(mainInputView.getHeight()));
yVal = Math.min(Math.max(yVal, 0.0f), 1.0f);
int freq = (int)(xVal * (maxFreq-minFreq)) + minFreq;
float atten = yVal; //attenuation
hiveAudioGenerator.Play(freq, atten);
} else {
hiveAudioGenerator.Stop();
}
}
else if (event.getAction() == MotionEvent.ACTION_UP)
{
//TODO: put the recording stuff in HIVEAudioGenerator!
hiveAudioGenerator.Stop();
}
return false;
}
public void SetWaveform(int waveform)
{
hiveAudioGenerator.setWaveform(waveform);
}
public int GetWaveform()
{
return hiveAudioGenerator.getCurrentWaveform();
}
class OnWaveformDialogButtonListener implements OnClickListener
{
private int value;
public OnWaveformDialogButtonListener(int value)
{
this.value = value;
}
@Override
public void onClick(View v)
{
SetWaveform(value);
}
}
public void SetADSR(ADSREnvelope envelope)
{
hiveAudioGenerator.SetADSR(envelope);
if(seekAttack != null)
{
seekAttack.setMax(MAX_MS);
seekAttack.setProgress(envelope.getAttack());
}
if(seekDecay != null)
{
seekDecay.setMax(MAX_MS);
seekDecay.setProgress(envelope.getDecay());
}
if(seekSustain != null)
{
seekSustain.setMax(100);
seekSustain.setProgress((int)(envelope.getSustain()*100));
}
if(seekRelease != null)
{
seekRelease.setMax(MAX_MS);
seekRelease.setProgress(envelope.getRelease());
}
}
public ADSREnvelope GetADSR()
{
return new ADSREnvelope((int)((float)seekAttack.getProgress()/(float)seekAttack.getMax()*(float)MAX_MS),
(int)((float)seekDecay.getProgress()/(float)seekDecay.getMax()*(float)MAX_MS),
(float)seekSustain.getProgress()/(float)seekSustain.getMax(),
(int)((float)seekRelease.getProgress()/(float)seekRelease.getMax()*(float)MAX_MS));
}
class ADSRDialogSeekBarChangeListener implements OnSeekBarChangeListener
{
TextView displayView;
int max;
public ADSRDialogSeekBarChangeListener(TextView displayView, int max)
{
this.displayView = displayView;
this.max = max;
}
@Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2)
{
float value = ((float)arg1/(float)arg0.getMax() * (float) max);
displayView.setText(""+value);
}
@Override
public void onStartTrackingTouch(SeekBar arg0) {}
@Override
public void onStopTrackingTouch(SeekBar arg0)
{
SetADSR(GetADSR());
}
}
class RecordingButtonCheckedListener implements OnCheckedChangeListener
{
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
hiveAudioGenerator.StartRecording();
//TODO: Disable ADSR and Waveform
}
else
{
noteHistory.add(hiveAudioGenerator.StopRecording());
noteHistoryAdapter.notifyDataSetChanged();
}
}
}
class HistoryItemSelectedListener implements AdapterView.OnItemClickListener
{
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
hiveAudioGenerator.Replay(noteHistory.get(position));
}
}
}
| Minor cleanup
| mHIVE/src/org/spin/mhive/MainActivity.java | Minor cleanup | <ide><path>HIVE/src/org/spin/mhive/MainActivity.java
<ide> }
<ide> else if (event.getAction() == MotionEvent.ACTION_UP)
<ide> {
<del> //TODO: put the recording stuff in HIVEAudioGenerator!
<ide> hiveAudioGenerator.Stop();
<del>
<ide> }
<ide>
<ide> return false; |
|
JavaScript | apache-2.0 | 4ec463b8861ccd0f3fa70f618906f0230fbdc7b2 | 0 | jlhughes/foam,foam-framework/foam,jlhughes/foam,foam-framework/foam,foam-framework/foam,foam-framework/foam,jlhughes/foam,jlhughes/foam,foam-framework/foam | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
package: 'foam.demos',
name: 'U2Demo',
extends: 'foam.u2.Element',
requires: [
'foam.util.Timer',
'foam.u2.tag.Checkbox',
'foam.u2.MultiLineTextField',
'foam.u2.FunctionView',
'foam.u2.md.DetailView as MDDetailView',
'foam.u2.DateView'
],
methods: [
function init() {
this.SUPER();
var d1 = this.DateView.create();
var d2 = this.DateView.create();
d1.data$ = d2.data$;
d1.write();
d2.write();
d1.data$.addListener(function() { console.log("8** ", d1.data); });
d1.date = new Date();
var timer = GLOBAL.timer = this.Timer.create();
timer.start();
var E = X.E.bind(X.sub());
var dynamic = GLOBAL.dynamic = X.dynamic;
E('b').add(
'bold',
E('br'),
'<span style="color:red">HTML Injection Attempt</span>',
E('br')).write();
E('b').add(
'color: ',
E('font').attrs({color: 'red'}).add('red', E('br'))).write();
var e = E('font').add('text', E('br'));
console.log('id: ', e.id);
e.write();
e.attrs({color: 'orange'});
e.style({
fontWeight: 'bold',
fontSize: '24pt'
});
e.on('click', function() { console.log('clicked'); });
var e13 = E('div').add(
'dynamic function PLAN B * ',
function() { return timer.second % 2 ? ['PING', ' ', 'PING'] : E('span').add('PONG').style({color: 'orange'}); },
' * dynamic value: ',
timer.i$,
' ',
dynamic(function(i) { return i%10; }, timer.i$));
e13.write();
E('div').add(
function() {
return timer.second % 5 ?
'TICK' :
E('span').add('TOCK').style({
'font-size': dynamic(function(i) { return i%2 ? '12px' : '24px'; }, timer.second$)
});
}
).write();
E('span').add('TOCK').style({
'font-size': dynamic(function(i) { return i%2 ? '12px' : '24px'; }, timer.second$)
}).write();
var e2 = E('font').add('on click, before', E('br')).on('click', function() { console.log('clicked, before'); });
e2.write();
var e2b = E('font').add('on click, after');
e2b.write();
e2b.on('click', function() { console.log('clicked, after'); });
var e3 = E('div').add('first line, added before');
e3.write();
e3.add(E('br'),'second line, added after');
var e4 = E('div').add('add style before').style({color: 'blue'});
e4.write();
var e5 = E('div').add('add style after');
e5.write();
e5.style({color: 'blue'});
var e6 = E('div').add('add class before').cls('important');
e6.write();
var e7 = E('div').add('add class after');
e7.write();
e7.cls('important');
E('div').add('dynamic class with value').cls(dynamic(function(i) { return i%2 ? 'important' : null; }, timer.second$)).write();
E('div').add('dynamic class with fn').cls(function() { return timer.second%2 ? 'important' : null; }).write();
E('div').add('dynamic class with fn (hidden)').style({display:'block'}).cls(function(i) { return timer.second%3 && 'hidden'; }).write();
var e8 = E('input');
e8.write();
var v8 = e8.attrValue();
v8.set('foobar');
// Will update on submit
v8.addListener(function() { console.log('**change: ', arguments); });
// Will update on the keystroke
e8.attrValue(null, 'input').addListener(function() { console.log('**input: ', arguments); });
var e9 = E('input');
e9.write();
timer.i$ = e9.attrValue();
var e10 = E('font').add(E('br'), 'set attr before').attrs({color: 'red'});
e10.write();
var e11 = E('font').add(E('br'), 'set attr after',E('br'));
e11.write();
e11.attrs({color: 'red'});
var e12 = E('div').add('dynamic style');
e12.write();
e12.style({
background: '#ccc',
width: 200,
visibility: function() { return Math.floor(timer.i/30) % 2 ? 'hidden' : 'visible'; },
color: function() { return Math.floor(timer.i/20) % 2 ? 'black' : 'yellow'; }
});
var e14 = E('font').style({height: '80px', display: 'block'}).add('dynamic attribute');
var v = SimpleValue.create();
v.set('pink');
e14.write();
e14.attrs({
size: function() { return Math.floor(timer.i/20) % 9; },
color: v
});
setTimeout(function() { v.set('black'); }, 2000);
E('div').style({height: '30px'}).write();
MODEL({name: 'Person', properties: ['firstName', 'lastName', 'age']});
var dd = Person.create({firstName: 'Donald', lastName: 'Duck', age: 83});
foam.u2.DetailView.create({data:dd}).write();
var dv = foam.u2.DetailView.create().write();
this.MDDetailView.create({data:dd}).write();
setTimeout(function() { dv.data = dd; }, 2000);
// setTimeout(function() { dv.properties = [dv.model_.PROPERTIES, dv.model_.MODEL, dv.model_.DATA]; }, 5000);
setTimeout(function() { dv.title = 'New Title'; }, 7000);
var e15 = foam.u2.tag.Input.create().write();
e15.data$ = timer.i$;
var e15b = E('input').write();
e15b.data$ = timer.i$;
E('div').style({height: '30px'}).write();
foam.u2.tag.Input.create().write().data$ = foam.u2.tag.Input.create().write().data$;
foam.u2.tag.Input.create({ onKey: true }).write().data$ = foam.u2.tag.Input.create({ onKey: true }).write().data$;
E('div').style({height: '30px'}).write();
foam.u2.tag.TextArea.create().write().data$ = foam.u2.tag.TextArea.create().write().data$;
foam.u2.tag.TextArea.create({ onKey: true }).write().data$ = foam.u2.tag.TextArea.create({ onKey: true }).write().data$;
E('div').style({height: '30px'}).write();
var e16 = foam.u2.tag.Select.create({placeholder: 'Pick a Colour:', choices: [['r', 'Red'],['g', 'Green'], ['b', 'Blue'], 'Pink']}).write();
var e17 = foam.u2.tag.Select.create({choices: [['r', 'Red'],['g', 'Green'], ['b', 'Blue'], 'Pink']}).write();
e16.data$ = e17.data$;
setTimeout(function() {
e17.choices = [['b', 'Bert'], ['e', 'Ernie']];
}, 5000);
//timer.stop();
MODEL({
name: 'AllViews',
properties: [
{
name: 'default'
},
{
type: 'String',
name: 'string'
},
{
type: 'String',
name: 'displayWidth',
displayWidth: 60
},
{
type: 'String',
name: 'displayHeight',
displayHeight: 3
},
{
type: 'Boolean',
name: 'boolean'
},
{
type: 'Boolean',
name: 'defaultValueTrue',
defaultValue: true
},
{
type: 'Date',
name: 'date'
},
{
type: 'DateTime',
name: 'dateTime'
},
{
type: 'Int',
name: 'int'
},
{
model_: 'LongProperty',
name: 'long'
},
{
type: 'Float',
name: 'float'
},
{
type: 'Int',
name: 'withUnits',
units: 'ms'
},
{
type: 'Function',
name: 'function'
},
{
model_: 'TemplateProperty',
name: 'template'
},
{
type: 'Array',
name: 'array'
},
// ReferenceProperty
{
type: 'StringArray',
name: 'stringArray'
},
{
type: 'EMail',
name: 'email'
},
{
type: 'Image',
name: 'image'
},
{
type: 'URL',
name: 'url'
},
{
type: 'Color',
name: 'color'
},
{
type: 'Password',
name: 'password'
},
{
type: 'PhoneNumber',
name: 'phoneNumber'
}
]
});
E('div').style({height: '30px'}).write();
var e = E('div').add(
E('span').add("hello "),
E('span').add("!")).write();
e.insertBefore(E('span').add('world'), e.children[1]);
var e = E('div').add(
E('span').add("hello "),
E('span').add("!"));
e.insertBefore(E('span').add('world'), e.children[1]);
e.write();
var e = E('div').add(
E('span').add("hello "),
E('span').add("!")).write();
e.insertAfter(E('span').add('world'), e.children[0]);
var e = E('div').add(
E('span').add("hello "),
E('span').add("!"));
e.insertAfter(E('span').add('world'), e.children[0]);
e.write();
var e = E('div').add(
E('span').add("hello "),
E('span').add("!"));
e.addBefore(e.children[1], E('span').add('there '), E('span').add('world'));
e.write();
var oldChild = E().add('First Child').style({color: 'red'});
var newChild = E().add('Second Child').style({color: 'green'});
var e = E('div').tag('br').add(oldChild).tag('br').write();
e.replaceChild(newChild, oldChild);
var dv2 = foam.u2.DetailView.create({data: AllViews.create()}).write();
var dv3 = foam.u2.DetailView.create({data: dv2.data}).write();
CLASS({
name: 'TestObject',
properties: [
'id',
'a',
'b'
]
});
var dao = [];
var text = [
'hello',
'world',
'this',
'is',
'some',
'random',
'text',
'options'
];
for ( var i = 0 ; i < 50; i++ ) {
dao.push({
id: i,
a: text[Math.floor(Math.random() * text.length)],
b: text[Math.floor(Math.random() * text.length)]
});
}
dao = JSONUtil.arrayToObjArray(X, dao, TestObject);
var count = COUNT();
dao.pipe(count);
var scroll = E('input').attrs({
type: 'range',
min: 0,
max: count.count$,
step: 1
});
E('div').add("Scroll amount").add(scroll).write();
/*
foam.u2.DAOListView.create({
data: foam.dao.ScrollDAO.create({
src: dao,
scrollValue$: scroll.attrValue(),
scrollSize: 5,
model: TestObject
})
}).write();
*/
setInterval((function() {
var i = 0;
var j = 50;
return function() {
dao.remove(i++);
dao.put(TestObject.create({
id: j++,
a: text[Math.floor(Math.random() * text.length)],
b: text[Math.floor(Math.random() * text.length)]
}));
};
})(), 5000);
E().add(
' rw: ', foam.u2.tag.Input.create({mode: 'rw', data: 'value'}),
' disabled: ', foam.u2.tag.Input.create({mode: 'disabled', data: 'value'}),
' ro: ', foam.u2.tag.Input.create({mode: 'ro', data: 'value'}),
' hidden: ', foam.u2.tag.Input.create({mode: 'hidden', data: 'value'})).write();
E().add(
' rw: ', foam.u2.tag.Checkbox.create({mode: 'rw', data: true}),
' disabled: ', foam.u2.tag.Checkbox.create({mode: 'disabled', data: true}),
' ro: ', foam.u2.tag.Checkbox.create({mode: 'ro', data: true}),
' hidden: ', foam.u2.tag.Checkbox.create({mode: 'hidden', data: true})).write();
MODEL({
name: 'VisibilityTest',
properties: [
{
name: 'final',
visibility: 'final'
},
{
name: 'rw',
visibility: 'rw'
},
{
name: 'ro',
visibility: 'ro'
},
{
name: 'hidden',
visibility: 'hidden'
}
]
});
var vt = VisibilityTest.create({final: 'final', rw: 'rw', ro: 'ro'});
E().add(
E('br'),
E('br'),
foam.u2.DetailView.create({title: 'default', data: vt}),
foam.u2.DetailView.create({title: 'Create', data: vt, controllerMode: 'create'}),
foam.u2.DetailView.create({title: 'Modify', data: vt, controllerMode: 'modify'}),
foam.u2.DetailView.create({title: 'View', data: vt, controllerMode: 'view'})
).write();
E().x({data: timer}).add(
E('br'),
E('br'),
foam.u2.DetailView.create({data: timer, showActions: true}),
E('br'),
timer.STEP,
' : ',
timer.model_.actions
).write();
E('br').write();
foam.u2.ElementParser.create();
var p = foam.u2.ElementParser.parser__.create();
// console.log(p.parseString('hello'));
console.log(p.parseString('<input readonly>'));
console.log(p.parseString('<input disabled="disabled">'));
console.log(p.parseString('<div id="foo" onclick="foo"><input readonly type="color"><i>italic</i>(( if ( true ) { ))<b>bold </b>(( } ))<span>span</span></div>'));
console.log(p.parseString('<div><b if={{true}}></b></div>'));
console.log(p.parseString(multiline(function(){/*
<div id="foo" onclick="foo" class="fooClass barClass" style="color:red;padding:5px;">
<b if={{true}}>bold*************************</b>
<!-- A Comment -->
<input readonly type="color">
<i>italic</i>
{{this.fname}}
{{this.fname$}}
(( if ( true ) { ))
<b>bold</b>
(( } ))
<b if={{true}}>bold</b>
<b if="true">bold2 </b>
<!--
<b repeat="i in 1 to 10">i: {{i}}</b>
<i repeat="j in this.dao">j: {{j}}</i>
-->
<span>span</span>
</div>
*/})));
MODEL({
name: 'RedElement',
extends: 'foam.u2.Element',
methods: [ function init() { this.SUPER(); this.style({color: 'red'}); } ]
});
MODEL({
name: 'PersonWithTemplate',
properties: [
{
name: 'firstName',
toPropertyE: function(X) {
return X.lookup('foam.u2.md.TextField').create(null, X);
}
},
'lastName', 'age', 'brother'
],
actions: [
{
name: 'go',
code: function() { console.log('Go!' + this.firstName); }
}
],
listeners: [
{ name: 'click', code: function() { console.log('click'); } }
],
methods: [
function toEMethod() { return E('b').add(E('br'),'from method'); }
],
templates: [
function toE() {/*#U2
<div as="top" id="special" class="c1 c2" x:brother={{this.brother}} x:data={{this}} x:timer={{timer}} foo="bar" bar={{'foo'}} onClick="click"
style="
background: #f9f9f9;
color: gray;
margin: 6px;
padding: 12px;
">
(( if ( true ) { ))
<h1>Person With Template</h1>
<br>
(( } ))
<div><b>First Name: </b>{{this.firstName}}</div>
<div><b>First Name: </b>{{this.firstName$}}</div>
<br/>
<brother:firstName label="BROTHER"/> <brother:go/>
<:firstName label="FIRST NAME"/> <!-- A Property -->
<:go/> <!-- An Action -->
<:toEMethod/> <!-- A Method -->
<:toE2/> <!-- Another Template -->
{{this.FIRST_NAME}} <!-- Same result as above -->
{{this.GO}} <!-- Same result as above -->
{{this.toEMethod()}} <!-- Same result as above -->
{{this.toE2()}} <!-- Same result as above -->
<br>
<b>timer: </b> <timer:SECOND/> <timer:STOP/> <timer:START/> <br/>
<br>
{{ E('i').add('italic') }}
<br/>
<h2>Custom Elements</h2>
<red>not red</red>
<p as="p">
(( p.Y.registerE('red', RedElement); ))
<red>red</red>
</p>
<red>not red again</red>
<br>
(( if ( true ) { ))
<b>condition: style 1 true</b>
(( } ))
(( if ( false ) { ))
<b>condition: style 1 false</b>
(( } ))
<br>
<b if={{true}}>condition: style 2 true</b>
<b if={{false}}>condition: style 2 false</b>
<br>
<b if="true">condition: style 3 true</b>
<b if="false">condition: style 3 false</b>
<br>
<b class="important">static class</b>
<br>
<b class={{dynamic(function(i) { return i%2 && 'important'; }, timer.second$)}}>dynamic class</b>
<div repeat="i in 1..10">Loop 1: {{i}}</div>
<div repeat="i in ['a','b','c']">Loop 2: {{i}}</div>
</div>
*/},
function toE2() {/*#U2
<blockquote style="color:red">
sub template
</blockquote>
*/}
]
});
var p = PersonWithTemplate.create({firstName: 'Sebastian', lastName: 'Greer', age: 11});
var p2 = PersonWithTemplate.create({firstName: 'Alexey', lastName: 'Greer', age: 19});
p.brother = p2;
var e = p.toE();
console.log(p.toE.toString());
e.write();
console.log(p.model_.templates[0].template.toString().length, p.toE.toString().length);
// 1238 861 -> 811 (tag) -> 790 (div br defaults) -> 742 (remove empty strings "")
}
]
}); | js/foam/demos/U2Demo.js | /**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
CLASS({
package: 'foam.demos',
name: 'U2Demo',
extends: 'foam.u2.Element',
requires: [
'foam.util.Timer',
'foam.u2.tag.Checkbox',
'foam.u2.MultiLineTextField',
'foam.u2.FunctionView',
'foam.u2.md.DetailView as MDDetailView',
'foam.u2.DateView'
],
methods: [
function init() {
this.SUPER();
var d1 = this.DateView.create();
var d2 = this.DateView.create();
d1.data$ = d2.data$;
d1.write();
d2.write();
d1.data$.addListener(function() { console.log("8** ", d1.data); });
d1.date = new Date();
var timer = GLOBAL.timer = this.Timer.create();
timer.start();
var E = X.E.bind(X.sub());
var dynamic = GLOBAL.dynamic = X.dynamic;
E('b').add('bold', E('br')).write();
E('b').add(
'color: ',
E('font').attrs({color: 'red'}).add('red', E('br'))).write();
var e = E('font').add('text', E('br'));
console.log('id: ', e.id);
e.write();
e.attrs({color: 'orange'});
e.style({
fontWeight: 'bold',
fontSize: '24pt'
});
e.on('click', function() { console.log('clicked'); });
var e13 = E('div').add(
'dynamic function PLAN B * ',
function() { return timer.second % 2 ? ['PING', ' ', 'PING'] : E('span').add('PONG').style({color: 'orange'}); },
' * dynamic value: ',
timer.i$,
' ',
dynamic(function(i) { return i%10; }, timer.i$));
e13.write();
E('div').add(
function() {
return timer.second % 5 ?
'TICK' :
E('span').add('TOCK').style({
'font-size': dynamic(function(i) { return i%2 ? '12px' : '24px'; }, timer.second$)
});
}
).write();
E('span').add('TOCK').style({
'font-size': dynamic(function(i) { return i%2 ? '12px' : '24px'; }, timer.second$)
}).write();
var e2 = E('font').add('on click, before', E('br')).on('click', function() { console.log('clicked, before'); });
e2.write();
var e2b = E('font').add('on click, after');
e2b.write();
e2b.on('click', function() { console.log('clicked, after'); });
var e3 = E('div').add('first line, added before');
e3.write();
e3.add(E('br'),'second line, added after');
var e4 = E('div').add('add style before').style({color: 'blue'});
e4.write();
var e5 = E('div').add('add style after');
e5.write();
e5.style({color: 'blue'});
var e6 = E('div').add('add class before').cls('important');
e6.write();
var e7 = E('div').add('add class after');
e7.write();
e7.cls('important');
E('div').add('dynamic class with value').cls(dynamic(function(i) { return i%2 ? 'important' : null; }, timer.second$)).write();
E('div').add('dynamic class with fn').cls(function() { return timer.second%2 ? 'important' : null; }).write();
E('div').add('dynamic class with fn (hidden)').style({display:'block'}).cls(function(i) { return timer.second%3 && 'hidden'; }).write();
var e8 = E('input');
e8.write();
var v8 = e8.attrValue();
v8.set('foobar');
// Will update on submit
v8.addListener(function() { console.log('**change: ', arguments); });
// Will update on the keystroke
e8.attrValue(null, 'input').addListener(function() { console.log('**input: ', arguments); });
var e9 = E('input');
e9.write();
timer.i$ = e9.attrValue();
var e10 = E('font').add(E('br'), 'set attr before').attrs({color: 'red'});
e10.write();
var e11 = E('font').add(E('br'), 'set attr after',E('br'));
e11.write();
e11.attrs({color: 'red'});
var e12 = E('div').add('dynamic style');
e12.write();
e12.style({
background: '#ccc',
width: 200,
visibility: function() { return Math.floor(timer.i/30) % 2 ? 'hidden' : 'visible'; },
color: function() { return Math.floor(timer.i/20) % 2 ? 'black' : 'yellow'; }
});
var e14 = E('font').style({height: '80px', display: 'block'}).add('dynamic attribute');
var v = SimpleValue.create();
v.set('pink');
e14.write();
e14.attrs({
size: function() { return Math.floor(timer.i/20) % 9; },
color: v
});
setTimeout(function() { v.set('black'); }, 2000);
E('div').style({height: '30px'}).write();
MODEL({name: 'Person', properties: ['firstName', 'lastName', 'age']});
var dd = Person.create({firstName: 'Donald', lastName: 'Duck', age: 83});
foam.u2.DetailView.create({data:dd}).write();
var dv = foam.u2.DetailView.create().write();
this.MDDetailView.create({data:dd}).write();
setTimeout(function() { dv.data = dd; }, 2000);
// setTimeout(function() { dv.properties = [dv.model_.PROPERTIES, dv.model_.MODEL, dv.model_.DATA]; }, 5000);
setTimeout(function() { dv.title = 'New Title'; }, 7000);
var e15 = foam.u2.tag.Input.create().write();
e15.data$ = timer.i$;
var e15b = E('input').write();
e15b.data$ = timer.i$;
E('div').style({height: '30px'}).write();
foam.u2.tag.Input.create().write().data$ = foam.u2.tag.Input.create().write().data$;
foam.u2.tag.Input.create({ onKey: true }).write().data$ = foam.u2.tag.Input.create({ onKey: true }).write().data$;
E('div').style({height: '30px'}).write();
foam.u2.tag.TextArea.create().write().data$ = foam.u2.tag.TextArea.create().write().data$;
foam.u2.tag.TextArea.create({ onKey: true }).write().data$ = foam.u2.tag.TextArea.create({ onKey: true }).write().data$;
E('div').style({height: '30px'}).write();
var e16 = foam.u2.tag.Select.create({placeholder: 'Pick a Colour:', choices: [['r', 'Red'],['g', 'Green'], ['b', 'Blue'], 'Pink']}).write();
var e17 = foam.u2.tag.Select.create({choices: [['r', 'Red'],['g', 'Green'], ['b', 'Blue'], 'Pink']}).write();
e16.data$ = e17.data$;
setTimeout(function() {
e17.choices = [['b', 'Bert'], ['e', 'Ernie']];
}, 5000);
//timer.stop();
MODEL({
name: 'AllViews',
properties: [
{
name: 'default'
},
{
type: 'String',
name: 'string'
},
{
type: 'String',
name: 'displayWidth',
displayWidth: 60
},
{
type: 'String',
name: 'displayHeight',
displayHeight: 3
},
{
type: 'Boolean',
name: 'boolean'
},
{
type: 'Boolean',
name: 'defaultValueTrue',
defaultValue: true
},
{
type: 'Date',
name: 'date'
},
{
type: 'DateTime',
name: 'dateTime'
},
{
type: 'Int',
name: 'int'
},
{
model_: 'LongProperty',
name: 'long'
},
{
type: 'Float',
name: 'float'
},
{
type: 'Int',
name: 'withUnits',
units: 'ms'
},
{
type: 'Function',
name: 'function'
},
{
model_: 'TemplateProperty',
name: 'template'
},
{
type: 'Array',
name: 'array'
},
// ReferenceProperty
{
type: 'StringArray',
name: 'stringArray'
},
{
type: 'EMail',
name: 'email'
},
{
type: 'Image',
name: 'image'
},
{
type: 'URL',
name: 'url'
},
{
type: 'Color',
name: 'color'
},
{
type: 'Password',
name: 'password'
},
{
type: 'PhoneNumber',
name: 'phoneNumber'
}
]
});
E('div').style({height: '30px'}).write();
var e = E('div').add(
E('span').add("hello "),
E('span').add("!")).write();
e.insertBefore(E('span').add('world'), e.children[1]);
var e = E('div').add(
E('span').add("hello "),
E('span').add("!"));
e.insertBefore(E('span').add('world'), e.children[1]);
e.write();
var e = E('div').add(
E('span').add("hello "),
E('span').add("!")).write();
e.insertAfter(E('span').add('world'), e.children[0]);
var e = E('div').add(
E('span').add("hello "),
E('span').add("!"));
e.insertAfter(E('span').add('world'), e.children[0]);
e.write();
var e = E('div').add(
E('span').add("hello "),
E('span').add("!"));
e.addBefore(e.children[1], E('span').add('there '), E('span').add('world'));
e.write();
var oldChild = E().add('First Child').style({color: 'red'});
var newChild = E().add('Second Child').style({color: 'green'});
var e = E('div').tag('br').add(oldChild).tag('br').write();
e.replaceChild(newChild, oldChild);
var dv2 = foam.u2.DetailView.create({data: AllViews.create()}).write();
var dv3 = foam.u2.DetailView.create({data: dv2.data}).write();
CLASS({
name: 'TestObject',
properties: [
'id',
'a',
'b'
]
});
var dao = [];
var text = [
'hello',
'world',
'this',
'is',
'some',
'random',
'text',
'options'
];
for ( var i = 0 ; i < 50; i++ ) {
dao.push({
id: i,
a: text[Math.floor(Math.random() * text.length)],
b: text[Math.floor(Math.random() * text.length)]
});
}
dao = JSONUtil.arrayToObjArray(X, dao, TestObject);
var count = COUNT();
dao.pipe(count);
var scroll = E('input').attrs({
type: 'range',
min: 0,
max: count.count$,
step: 1
});
E('div').add("Scroll amount").add(scroll).write();
/*
foam.u2.DAOListView.create({
data: foam.dao.ScrollDAO.create({
src: dao,
scrollValue$: scroll.attrValue(),
scrollSize: 5,
model: TestObject
})
}).write();
*/
setInterval((function() {
var i = 0;
var j = 50;
return function() {
dao.remove(i++);
dao.put(TestObject.create({
id: j++,
a: text[Math.floor(Math.random() * text.length)],
b: text[Math.floor(Math.random() * text.length)]
}));
};
})(), 5000);
E().add(
' rw: ', foam.u2.tag.Input.create({mode: 'rw', data: 'value'}),
' disabled: ', foam.u2.tag.Input.create({mode: 'disabled', data: 'value'}),
' ro: ', foam.u2.tag.Input.create({mode: 'ro', data: 'value'}),
' hidden: ', foam.u2.tag.Input.create({mode: 'hidden', data: 'value'})).write();
E().add(
' rw: ', foam.u2.tag.Checkbox.create({mode: 'rw', data: true}),
' disabled: ', foam.u2.tag.Checkbox.create({mode: 'disabled', data: true}),
' ro: ', foam.u2.tag.Checkbox.create({mode: 'ro', data: true}),
' hidden: ', foam.u2.tag.Checkbox.create({mode: 'hidden', data: true})).write();
MODEL({
name: 'VisibilityTest',
properties: [
{
name: 'final',
visibility: 'final'
},
{
name: 'rw',
visibility: 'rw'
},
{
name: 'ro',
visibility: 'ro'
},
{
name: 'hidden',
visibility: 'hidden'
}
]
});
var vt = VisibilityTest.create({final: 'final', rw: 'rw', ro: 'ro'});
E().add(
E('br'),
E('br'),
foam.u2.DetailView.create({title: 'default', data: vt}),
foam.u2.DetailView.create({title: 'Create', data: vt, controllerMode: 'create'}),
foam.u2.DetailView.create({title: 'Modify', data: vt, controllerMode: 'modify'}),
foam.u2.DetailView.create({title: 'View', data: vt, controllerMode: 'view'})
).write();
E().x({data: timer}).add(
E('br'),
E('br'),
foam.u2.DetailView.create({data: timer, showActions: true}),
E('br'),
timer.STEP,
' : ',
timer.model_.actions
).write();
E('br').write();
foam.u2.ElementParser.create();
var p = foam.u2.ElementParser.parser__.create();
// console.log(p.parseString('hello'));
console.log(p.parseString('<input readonly>'));
console.log(p.parseString('<input disabled="disabled">'));
console.log(p.parseString('<div id="foo" onclick="foo"><input readonly type="color"><i>italic</i>(( if ( true ) { ))<b>bold </b>(( } ))<span>span</span></div>'));
console.log(p.parseString('<div><b if={{true}}></b></div>'));
console.log(p.parseString(multiline(function(){/*
<div id="foo" onclick="foo" class="fooClass barClass" style="color:red;padding:5px;">
<b if={{true}}>bold*************************</b>
<!-- A Comment -->
<input readonly type="color">
<i>italic</i>
{{this.fname}}
{{this.fname$}}
(( if ( true ) { ))
<b>bold</b>
(( } ))
<b if={{true}}>bold</b>
<b if="true">bold2 </b>
<!--
<b repeat="i in 1 to 10">i: {{i}}</b>
<i repeat="j in this.dao">j: {{j}}</i>
-->
<span>span</span>
</div>
*/})));
MODEL({
name: 'RedElement',
extends: 'foam.u2.Element',
methods: [ function init() { this.SUPER(); this.style({color: 'red'}); } ]
});
MODEL({
name: 'PersonWithTemplate',
properties: [
{
name: 'firstName',
toPropertyE: function(X) {
return X.lookup('foam.u2.md.TextField').create(null, X);
}
},
'lastName', 'age', 'brother'
],
actions: [
{
name: 'go',
code: function() { console.log('Go!' + this.firstName); }
}
],
listeners: [
{ name: 'click', code: function() { console.log('click'); } }
],
methods: [
function toEMethod() { return E('b').add(E('br'),'from method'); }
],
templates: [
function toE() {/*#U2
<div as="top" id="special" class="c1 c2" x:brother={{this.brother}} x:data={{this}} x:timer={{timer}} foo="bar" bar={{'foo'}} onClick="click"
style="
background: #f9f9f9;
color: gray;
margin: 6px;
padding: 12px;
">
(( if ( true ) { ))
<h1>Person With Template</h1>
<br>
(( } ))
<div><b>First Name: </b>{{this.firstName}}</div>
<div><b>First Name: </b>{{this.firstName$}}</div>
<br/>
<brother:firstName label="BROTHER"/> <brother:go/>
<:firstName label="FIRST NAME"/> <!-- A Property -->
<:go/> <!-- An Action -->
<:toEMethod/> <!-- A Method -->
<:toE2/> <!-- Another Template -->
{{this.FIRST_NAME}} <!-- Same result as above -->
{{this.GO}} <!-- Same result as above -->
{{this.toEMethod()}} <!-- Same result as above -->
{{this.toE2()}} <!-- Same result as above -->
<br>
<b>timer: </b> <timer:SECOND/> <timer:STOP/> <timer:START/> <br/>
<br>
{{ E('i').add('italic') }}
<br/>
<h2>Custom Elements</h2>
<red>not red</red>
<p as="p">
(( p.Y.registerE('red', RedElement); ))
<red>red</red>
</p>
<red>not red again</red>
<br>
(( if ( true ) { ))
<b>condition: style 1 true</b>
(( } ))
(( if ( false ) { ))
<b>condition: style 1 false</b>
(( } ))
<br>
<b if={{true}}>condition: style 2 true</b>
<b if={{false}}>condition: style 2 false</b>
<br>
<b if="true">condition: style 3 true</b>
<b if="false">condition: style 3 false</b>
<br>
<b class="important">static class</b>
<br>
<b class={{dynamic(function(i) { return i%2 && 'important'; }, timer.second$)}}>dynamic class</b>
<div repeat="i in 1..10">Loop 1: {{i}}</div>
<div repeat="i in ['a','b','c']">Loop 2: {{i}}</div>
</div>
*/},
function toE2() {/*#U2
<blockquote style="color:red">
sub template
</blockquote>
*/}
]
});
var p = PersonWithTemplate.create({firstName: 'Sebastian', lastName: 'Greer', age: 11});
var p2 = PersonWithTemplate.create({firstName: 'Alexey', lastName: 'Greer', age: 19});
p.brother = p2;
var e = p.toE();
console.log(p.toE.toString());
e.write();
console.log(p.model_.templates[0].template.toString().length, p.toE.toString().length);
// 1238 861 -> 811 (tag) -> 790 (div br defaults) -> 742 (remove empty strings "")
}
]
}); | U2: Added HTML Injection test to U2Demo.
| js/foam/demos/U2Demo.js | U2: Added HTML Injection test to U2Demo. | <ide><path>s/foam/demos/U2Demo.js
<ide> var E = X.E.bind(X.sub());
<ide> var dynamic = GLOBAL.dynamic = X.dynamic;
<ide>
<del>E('b').add('bold', E('br')).write();
<add>E('b').add(
<add> 'bold',
<add> E('br'),
<add> '<span style="color:red">HTML Injection Attempt</span>',
<add> E('br')).write();
<ide>
<ide> E('b').add(
<ide> 'color: ', |
|
Java | apache-2.0 | bc90d0663caadd3df5c5943dc2af5101a4275fc2 | 0 | vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
addDefaultSearchAccessLog();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
| config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java | // Copyright 2019 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.model.admin;
import com.yahoo.config.model.deploy.DeployState;
import com.yahoo.config.model.producer.AbstractConfigProducer;
import com.yahoo.vespa.model.container.ContainerCluster;
import com.yahoo.vespa.model.container.component.Handler;
/**
* @author gjoranv
*/
public class LogserverContainerCluster extends ContainerCluster<LogserverContainer> {
public LogserverContainerCluster(AbstractConfigProducer<?> parent, String name, DeployState deployState) {
super(parent, name, name, deployState);
addDefaultHandlersWithVip();
addLogHandler();
}
@Override
protected void doPrepare(DeployState deployState) { }
private void addLogHandler() {
Handler<?> logHandler = Handler.fromClassName(ContainerCluster.LOG_HANDLER_CLASS);
logHandler.addServerBindings("*://*/logs");
addComponent(logHandler);
}
}
| Add access log for logserver container
| config-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java | Add access log for logserver container | <ide><path>onfig-model/src/main/java/com/yahoo/vespa/model/admin/LogserverContainerCluster.java
<ide>
<ide> addDefaultHandlersWithVip();
<ide> addLogHandler();
<add> addDefaultSearchAccessLog();
<ide> }
<ide>
<ide> @Override |
|
JavaScript | mit | 0e93f4646955c4e22dc46b0655642b1a069273ae | 0 | a-rmz/sbotify | /* @flow */
const router = require('express').Router();
const SpotifyController = require('./SpotifyController');
const controller = new SpotifyController();
const validParams = ['song', 'artist', 'album'];
/**
* Ensure the token is valid
* @type {void}
*/
router.post('/', (req, res, next) => {
if (req.body.token == process.env.SLACK_VERIFY_TOKEN) {
next();
}
});
/**
* Middleware layer that verifies that both parameter and keyword
* are present in the command
* @type {void}
*/
router.post('/', (req, res, next) => {
const { body } = req;
const { text } = body;
const tokens: [string] = text.split(' ');
const param: string = tokens[0];
const keyword: string = tokens.slice(1).join(' ');
console.log(param);
console.log(keyword);
if (validParams.indexOf(param) === -1 || keyword.length <= 0) {
res.status(200).send('Please enter a valid command!');
return;
}
req.param = param;
req.keyword = keyword;
next();
});
/**
* Main router endpoint.
* Makes the call to the controller and returns the message
* @type {void}
*/
router.post('/', (req, res) => {
const param: string = req.param;
const keyword: string = req.keyword;
controller.search(param, keyword)
.then(response => {
res.status(200).send(response);
});
});
module.exports = router;
| src/lib/spotifyRouter.js | /* @flow */
const router = require('express').Router();
const SpotifyController = require('./SpotifyController');
const controller = new SpotifyController();
const validParams = ['song', 'artist', 'album'];
/**
* Middleware layer that verifies that both parameter and keyword
* are present in the command
*/
router.post('/', (req, res, next) => {
const { body } = req;
const { text } = body;
const tokens: [string] = text.split(' ');
const param: string = tokens[0];
const keyword: string = tokens.slice(1).join(' ');
console.log(param);
console.log(keyword);
if (validParams.indexOf(param) === -1 || keyword.length <= 0) {
res.status(200).send('Please enter a valid command!');
return;
}
req.param = param;
req.keyword = keyword;
next();
});
/**
* Main router endpoint.
* Makes the call to the controller and returns the message
*/
router.post('/', (req, res) => {
const param: string = req.param;
const keyword: string = req.keyword;
controller.search(param, keyword)
.then(response => {
res.status(200).send(response);
});
});
module.exports = router;
| Validation for slack token
| src/lib/spotifyRouter.js | Validation for slack token | <ide><path>rc/lib/spotifyRouter.js
<ide> const validParams = ['song', 'artist', 'album'];
<ide>
<ide> /**
<add> * Ensure the token is valid
<add> * @type {void}
<add> */
<add>router.post('/', (req, res, next) => {
<add> if (req.body.token == process.env.SLACK_VERIFY_TOKEN) {
<add> next();
<add> }
<add>});
<add>
<add>/**
<ide> * Middleware layer that verifies that both parameter and keyword
<ide> * are present in the command
<add> * @type {void}
<ide> */
<ide> router.post('/', (req, res, next) => {
<ide> const { body } = req;
<ide> /**
<ide> * Main router endpoint.
<ide> * Makes the call to the controller and returns the message
<add> * @type {void}
<ide> */
<ide> router.post('/', (req, res) => {
<ide> const param: string = req.param; |
|
Java | mpl-2.0 | fb3995e8a531539c423cbbccb3ba68f6afc3d2cf | 0 | pragma-/networklog,RyanTech/networklog,pragma-/networklog,snehesht/networklog,snehesht/networklog,vaginessa/networklog,pragma-/networklog,pragma-/networklog,pragma-/networklog,vaginessa/networklog,vaginessa/networklog,snehesht/networklog,snehesht/networklog,RyanTech/networklog,vaginessa/networklog,RyanTech/networklog,vaginessa/networklog,pragma-/networklog,snehesht/networklog,snehesht/networklog,RyanTech/networklog,snehesht/networklog,vaginessa/networklog,pragma-/networklog,rosenpin/networklog,vaginessa/networklog,RyanTech/networklog,rosenpin/networklog,RyanTech/networklog | /* (C) 2012 Pragmatic Software
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
package com.googlecode.networklog;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.Context;
import android.util.Log;
import java.io.File;
public class Settings implements OnSharedPreferenceChangeListener {
private SharedPreferences prefs;
private Context context;
// Force use of context constructor
private Settings() {}
public Settings(Context context) {
PreferenceManager.setDefaultValues(context, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(this);
MyLog.enabled = getLogcatDebug();
this.context = context;
}
public String getHistorySize() {
return prefs.getString("history_size", "14400000");
}
public String getClearLogTimerange() {
return prefs.getString("clearlog_timerange", "0");
}
public String getLogFile() {
String logfile = prefs.getString("logfile", null);
if(logfile == null) {
logfile = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "networklog.txt";
Log.d("NetworkLog", "Set default logfile path: " + logfile);
}
return logfile;
}
public boolean getInvertUploadDownload() {
return prefs.getBoolean("invert_upload_download", false);
}
public boolean getWatchRules() {
return prefs.getBoolean("watch_rules", false);
}
public int getWatchRulesTimeout() {
return Integer.parseInt(prefs.getString("watch_rules_timeout", "120000"));
}
public boolean getBehindFirewall() {
return prefs.getBoolean("behind_firewall", false);
}
public boolean getThroughputBps() {
return prefs.getBoolean("throughput_bps", true);
}
public boolean getRoundValues() {
return prefs.getBoolean("round_values", true);
}
public boolean getStartForeground() {
return prefs.getBoolean("start_foreground", true);
}
public boolean getStartServiceAtBoot() {
return prefs.getBoolean("startServiceAtBoot", false);
}
public boolean getStartServiceAtStart() {
return prefs.getBoolean("startServiceAtStart", false);
}
public boolean getStopServiceAtExit() {
return prefs.getBoolean("stopServiceAtExit", false);
}
public boolean getResolveHosts() {
return prefs.getBoolean("resolve_hosts", false);
}
public boolean getResolvePorts() {
return prefs.getBoolean("resolve_ports", true);
}
public boolean getResolveCopies() {
return !prefs.getBoolean("copy_original_addrs", false);
}
public boolean getConfirmExit() {
return prefs.getBoolean("confirm_exit", true);
}
public String getFilterTextInclude() {
return prefs.getString("filter_text_include", "");
}
public boolean getFilterUidInclude() {
return prefs.getBoolean("filter_by_uid_include", false);
}
public boolean getFilterNameInclude() {
return prefs.getBoolean("filter_by_name_include", false);
}
public boolean getFilterAddressInclude() {
return prefs.getBoolean("filter_by_address_include", false);
}
public boolean getFilterPortInclude() {
return prefs.getBoolean("filter_by_port_include", false);
}
public boolean getFilterInterfaceInclude() {
return prefs.getBoolean("filter_by_interface_include", false);
}
public boolean getFilterProtocolInclude() {
return prefs.getBoolean("filter_by_protocol_include", false);
}
public String getFilterTextExclude() {
return prefs.getString("filter_text_exclude", "");
}
public boolean getFilterUidExclude() {
return prefs.getBoolean("filter_by_uid_exclude", false);
}
public boolean getFilterNameExclude() {
return prefs.getBoolean("filter_by_name_exclude", false);
}
public boolean getFilterAddressExclude() {
return prefs.getBoolean("filter_by_address_exclude", false);
}
public boolean getFilterPortExclude() {
return prefs.getBoolean("filter_by_port_exclude", false);
}
public boolean getFilterInterfaceExclude() {
return prefs.getBoolean("filter_by_interface_exclude", false);
}
public boolean getFilterProtocolExclude() {
return prefs.getBoolean("filter_by_protocol_exclude", false);
}
public int getUpdateMaxLogEntries() {
return prefs.getInt("update_max_log_entries", 0);
}
public long getMaxLogEntries() {
int updateMaxLogEntries = getUpdateMaxLogEntries();
if(updateMaxLogEntries == 0) {
setUpdateMaxLogEntries(1);
if(getMaxLogEntries() > 75000) {
setMaxLogEntries(75000);
}
}
return Long.parseLong(prefs.getString("max_log_entries", "75000"));
}
public Sort getPreSortBy() {
return Sort.forValue(prefs.getString("presort_by", "NAME"));
}
public Sort getSortBy() {
return Sort.forValue(prefs.getString("sort_by", "BYTES"));
}
public boolean getLogcatDebug() {
return prefs.getBoolean("logcat_debug", false);
}
public boolean getStatusbarNotifications() {
return prefs.getBoolean("notifications_statusbar", false);
}
public boolean getToastNotifications() {
return prefs.getBoolean("notifications_toast", false);
}
public int getToastNotificationsDuration() {
return Integer.parseInt(prefs.getString("notifications_toast_duration", "3500"));
}
public int getToastNotificationsPosition() {
return Integer.parseInt(prefs.getString("notifications_toast_position", "-1"));
}
public int getToastNotificationsYOffset() {
return prefs.getInt("notifications_toast_yoffset", 0);
}
public int getToastNotificationsOpacity() {
return prefs.getInt("notifications_toast_opacity", 119);
}
public boolean getToastNotificationsShowAddress() {
return prefs.getBoolean("notifications_toast_show_address", true);
}
public long getGraphInterval() {
return prefs.getLong("interval", 300000);
}
public long getGraphViewsize() {
return prefs.getLong("viewsize", 1000 * 60 * 60 * 4);
}
public int getLogMethod() {
return Integer.parseInt(prefs.getString("log_method", "0"));
}
public void setResolveHosts(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("resolve_hosts", value);
editor.commit();
}
public void setResolvePorts(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("resolve_ports", value);
editor.commit();
}
public void setResolveCopies(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("copy_original_addrs", value);
editor.commit();
}
public void setConfirmExit(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("confirm_exit", value);
editor.commit();
}
public void setFilterTextInclude(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("filter_text_include", value);
editor.commit();
}
public void setFilterUidInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_uid_include", value);
editor.commit();
}
public void setFilterNameInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_name_include", value);
editor.commit();
}
public void setFilterAddressInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_address_include", value);
editor.commit();
}
public void setFilterPortInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_port_include", value);
editor.commit();
}
public void setFilterInterfaceInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_interface_include", value);
editor.commit();
}
public void setFilterProtocolInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_protocol_include", value);
editor.commit();
}
public void setFilterTextExclude(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("filter_text_exclude", value);
editor.commit();
}
public void setFilterUidExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_uid_exclude", value);
editor.commit();
}
public void setFilterNameExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_name_exclude", value);
editor.commit();
}
public void setFilterAddressExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_address_exclude", value);
editor.commit();
}
public void setFilterPortExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_port_exclude", value);
editor.commit();
}
public void setFilterInterfaceExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_interface_exclude", value);
editor.commit();
}
public void setFilterProtocolExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_protocol_exclude", value);
editor.commit();
}
public void setUpdateMaxLogEntries(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("update_max_log_entries", value);
editor.commit();
}
public void setMaxLogEntries(long value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("max_log_entries", String.valueOf(value));
editor.commit();
}
public void setPreSortBy(Sort value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("presort_by", value.toString());
editor.commit();
}
public void setSortBy(Sort value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("sort_by", value.toString());
editor.commit();
}
public void setLogcatDebug(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("logcat_debug", value);
editor.commit();
}
public void setStatusbarNotifications(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notifications_statusbar", value);
editor.commit();
}
public void setToastNotifications(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notifications_toast", value);
editor.commit();
}
public void setToastNotificationsDuration(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("notifications_toast_duration", String.valueOf(value));
editor.commit();
}
public void setToastNotificationsPosition(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("notifications_toast_position", String.valueOf(value));
editor.commit();
}
public void setToastNotificationsYOffset(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notifications_toast_yoffset", value);
editor.commit();
}
public void setToastNotificationsOpacity(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notifications_toast_opacity", value);
editor.commit();
}
public void setToastNotificationsShowAddress(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notifications_toast_show_address", value);
editor.commit();
}
public void setGraphInterval(long value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("interval", value);
editor.commit();
}
public void setGraphViewsize(long value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("viewsize", value);
editor.commit();
}
public void setInvertUploadDownload(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("invert_upload_download", value);
editor.commit();
}
public void setWatchRules(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("watch_rules", value);
editor.commit();
}
public void setWatchRulesTimeout(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("watch_rules_timeout", String.valueOf(value));
editor.commit();
}
public void setBehindFirewall(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("behind_firewall", value);
editor.commit();
}
public void setThroughputBps(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("throughput_bps", value);
editor.commit();
}
public void setRoundValues(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("round_values", value);
editor.commit();
}
public void setStartForeground(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("start_foreground", value);
editor.commit();
}
public void setStartServiceAtBoot(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("startServiceAtBoot", value);
editor.commit();
}
public void setStartServiceAtStart(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("startServiceAtStart", value);
editor.commit();
}
public void setStopServiceAtExit(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("stopServiceAtExit", value);
editor.commit();
}
public void setHistorySize(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("history_size", value);
editor.commit();
}
public void setClearLogTimerange(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("clearlog_timerange", value);
editor.commit();
}
public void setLogMethod(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("log_method", String.valueOf(value));
editor.commit();
}
public void setLogFile(String value) {
String oldValue = prefs.getString("logfile", null);
if(oldValue != null && !oldValue.equals(value)) {
// update only if values have changed (mainly to ensure service
// doesn't restart for same values)
SharedPreferences.Editor editor = prefs.edit();
editor.putString("logfile", value);
editor.commit();
if(NetworkLogService.instance != null) {
// if service is running, restart service so that logfile is opened
// with new path
NetworkLog.instance.stopService();
NetworkLog.instance.startService();
}
}
}
public void showSampleToast() {
if(NetworkLog.context != null && NetworkLog.handler != null) {
String msg = String.format(NetworkLog.context.getResources().getString(R.string.sample_toast_message),
NetworkLogService.toastYOffset, NetworkLogService.toastOpacity);
NetworkLogService.showToast(NetworkLog.context, NetworkLog.handler, msg, true);
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
MyLog.d("Shared prefs changed: [" + key + "]");
if(key.equals("log_method")) {
int value = Integer.parseInt(prefs.getString(key, "0"));
MyLog.d("New " + key + " value [" + value + "]");
if(NetworkLogService.instance != null) {
NetworkLog.instance.stopService();
NetworkLog.instance.startService();
}
}
if(key.equals("logfile")) {
String value = prefs.getString(key, null);
MyLog.d("New " + key + " value [" + value + "]");
// update service
return;
}
if(key.equals("startServiceAtBoot")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
}
if(key.equals("startServiceAtStart")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.startServiceAtStart = value;
return;
}
if(key.equals("stopServiceAtExit")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.stopServiceAtExit = value;
return;
}
if(key.equals("resolve_hosts")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.resolveHosts = value;
NetworkLog.logFragment.refreshAdapter();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("resolve_ports")) {
boolean value = prefs.getBoolean(key, true);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.resolvePorts = value;
NetworkLog.logFragment.refreshAdapter();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("copy_original_addrs")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.resolveCopies = !value;
return;
}
if(key.equals("max_log_entries")) {
String value = prefs.getString(key, "75000");
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.logFragment.maxLogEntries = Long.parseLong(value);
NetworkLog.logFragment.pruneLogEntries();
return;
}
if(key.equals("logcat_debug")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
MyLog.enabled = value;
return;
}
if(key.equals("presort_by")) {
String value = prefs.getString(key, "BYTES");
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.appFragment.preSortBy = Sort.forValue(value);
NetworkLog.appFragment.setPreSortMethod();
NetworkLog.appFragment.preSortData();
NetworkLog.appFragment.sortData();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("sort_by")) {
String value = prefs.getString(key, "BYTES");
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.appFragment.sortBy = Sort.forValue(value);
NetworkLog.appFragment.setSortMethod();
NetworkLog.appFragment.preSortData();
NetworkLog.appFragment.sortData();
NetworkLog.appFragment.sortChildren();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("notifications_toast")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastEnabled = value;
return;
}
if(key.equals("notifications_toast_duration")) {
int value = Integer.parseInt(prefs.getString(key, "3500"));
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastDuration = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_position")) {
int value = Integer.parseInt(prefs.getString(key, "-1"));
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastPosition = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_yoffset")) {
int value = prefs.getInt(key, 0);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastYOffset = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_opacity")) {
int value = prefs.getInt(key, 119);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastOpacity = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_show_address")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastShowAddress = value;
return;
}
if(key.equals("round_values")) {
boolean value = prefs.getBoolean(key, true);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.appFragment.roundValues = value;
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("invert_upload_download")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.invertUploadDownload = value;
return;
}
if(key.equals("watch_rules")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.watchRules = value;
if(NetworkLogService.instance != null) {
NetworkLogService.instance.startWatchingRules();
}
return;
}
if(key.equals("watch_rules_timeout")) {
int value = Integer.parseInt(prefs.getString(key, "120000"));
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.watchRulesTimeout = value;
if(NetworkLogService.rulesWatcher != null) {
NetworkLogService.rulesWatcher.interrupt();
}
return;
}
if(key.equals("behind_firewall")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.behindFirewall = value;
if(NetworkLogService.instance != null) {
Iptables.removeRules(context);
Iptables.addRules(context);
}
return;
}
if(key.equals("throughput_bps")) {
boolean value = prefs.getBoolean(key, true);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.throughputBps = value;
ThroughputTracker.updateThroughputBps();
return;
}
}
}
| src/com/googlecode/networklog/Settings.java | /* (C) 2012 Pragmatic Software
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/
*/
package com.googlecode.networklog;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.Context;
import android.util.Log;
import java.io.File;
public class Settings implements OnSharedPreferenceChangeListener {
private SharedPreferences prefs;
private Context context;
// Force use of context constructor
private Settings() {}
public Settings(Context context) {
PreferenceManager.setDefaultValues(context, R.xml.preferences, false);
prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(this);
MyLog.enabled = getLogcatDebug();
this.context = context;
}
public String getHistorySize() {
return prefs.getString("history_size", "14400000");
}
public String getClearLogTimerange() {
return prefs.getString("clearlog_timerange", "0");
}
public String getLogFile() {
String logfile = prefs.getString("logfile", null);
if(logfile == null) {
logfile = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "networklog.txt";
Log.d("NetworkLog", "Set default logfile path: " + logfile);
}
return logfile;
}
public boolean getInvertUploadDownload() {
return prefs.getBoolean("invert_upload_download", false);
}
public boolean getWatchRules() {
return prefs.getBoolean("watch_rules", false);
}
public int getWatchRulesTimeout() {
return Integer.parseInt(prefs.getString("watch_rules_timeout", "120000"));
}
public boolean getBehindFirewall() {
return prefs.getBoolean("behind_firewall", false);
}
public boolean getThroughputBps() {
return prefs.getBoolean("throughput_bps", true);
}
public boolean getRoundValues() {
return prefs.getBoolean("round_values", true);
}
public boolean getStartForeground() {
return prefs.getBoolean("start_foreground", true);
}
public boolean getStartServiceAtBoot() {
return prefs.getBoolean("startServiceAtBoot", false);
}
public boolean getStartServiceAtStart() {
return prefs.getBoolean("startServiceAtStart", false);
}
public boolean getStopServiceAtExit() {
return prefs.getBoolean("stopServiceAtExit", false);
}
public boolean getResolveHosts() {
return prefs.getBoolean("resolve_hosts", false);
}
public boolean getResolvePorts() {
return prefs.getBoolean("resolve_ports", true);
}
public boolean getResolveCopies() {
return !prefs.getBoolean("copy_original_addrs", false);
}
public boolean getConfirmExit() {
return prefs.getBoolean("confirm_exit", true);
}
public String getFilterTextInclude() {
return prefs.getString("filter_text_include", "");
}
public boolean getFilterUidInclude() {
return prefs.getBoolean("filter_by_uid_include", false);
}
public boolean getFilterNameInclude() {
return prefs.getBoolean("filter_by_name_include", false);
}
public boolean getFilterAddressInclude() {
return prefs.getBoolean("filter_by_address_include", false);
}
public boolean getFilterPortInclude() {
return prefs.getBoolean("filter_by_port_include", false);
}
public boolean getFilterInterfaceInclude() {
return prefs.getBoolean("filter_by_interface_include", false);
}
public boolean getFilterProtocolInclude() {
return prefs.getBoolean("filter_by_protocol_include", false);
}
public String getFilterTextExclude() {
return prefs.getString("filter_text_exclude", "");
}
public boolean getFilterUidExclude() {
return prefs.getBoolean("filter_by_uid_exclude", false);
}
public boolean getFilterNameExclude() {
return prefs.getBoolean("filter_by_name_exclude", false);
}
public boolean getFilterAddressExclude() {
return prefs.getBoolean("filter_by_address_exclude", false);
}
public boolean getFilterPortExclude() {
return prefs.getBoolean("filter_by_port_exclude", false);
}
public boolean getFilterInterfaceExclude() {
return prefs.getBoolean("filter_by_interface_exclude", false);
}
public boolean getFilterProtocolExclude() {
return prefs.getBoolean("filter_by_protocol_exclude", false);
}
public int getUpdateMaxLogEntries() {
return prefs.getInt("update_max_log_entries", 0);
}
public long getMaxLogEntries() {
int updateMaxLogEntries = getUpdateMaxLogEntries();
if(updateMaxLogEntries == 0) {
setUpdateMaxLogEntries(1);
if(getMaxLogEntries() > 75000) {
setMaxLogEntries(75000);
}
}
return Long.parseLong(prefs.getString("max_log_entries", "75000"));
}
public Sort getPreSortBy() {
return Sort.forValue(prefs.getString("presort_by", "NAME"));
}
public Sort getSortBy() {
return Sort.forValue(prefs.getString("sort_by", "BYTES"));
}
public boolean getLogcatDebug() {
return prefs.getBoolean("logcat_debug", false);
}
public boolean getStatusbarNotifications() {
return prefs.getBoolean("notifications_statusbar", false);
}
public boolean getToastNotifications() {
return prefs.getBoolean("notifications_toast", false);
}
public int getToastNotificationsDuration() {
return Integer.parseInt(prefs.getString("notifications_toast_duration", "3500"));
}
public int getToastNotificationsPosition() {
return Integer.parseInt(prefs.getString("notifications_toast_position", "-1"));
}
public int getToastNotificationsYOffset() {
return prefs.getInt("notifications_toast_yoffset", 0);
}
public int getToastNotificationsOpacity() {
return prefs.getInt("notifications_toast_opacity", 119);
}
public boolean getToastNotificationsShowAddress() {
return prefs.getBoolean("notifications_toast_show_address", true);
}
public long getGraphInterval() {
return prefs.getLong("interval", 300000);
}
public long getGraphViewsize() {
return prefs.getLong("viewsize", 1000 * 60 * 60 * 4);
}
public int getLogMethod() {
return Integer.parseInt(prefs.getString("log_method", "0"));
}
public void setResolveHosts(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("resolve_hosts", value);
editor.commit();
}
public void setResolvePorts(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("resolve_ports", value);
editor.commit();
}
public void setResolveCopies(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("copy_original_addrs", value);
editor.commit();
}
public void setConfirmExit(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("confirm_exit", value);
editor.commit();
}
public void setFilterTextInclude(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("filter_text_include", value);
editor.commit();
}
public void setFilterUidInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_uid_include", value);
editor.commit();
}
public void setFilterNameInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_name_include", value);
editor.commit();
}
public void setFilterAddressInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_address_include", value);
editor.commit();
}
public void setFilterPortInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_port_include", value);
editor.commit();
}
public void setFilterInterfaceInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_interface_include", value);
editor.commit();
}
public void setFilterProtocolInclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_protocol_include", value);
editor.commit();
}
public void setFilterTextExclude(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("filter_text_exclude", value);
editor.commit();
}
public void setFilterUidExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_uid_exclude", value);
editor.commit();
}
public void setFilterNameExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_name_exclude", value);
editor.commit();
}
public void setFilterAddressExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_address_exclude", value);
editor.commit();
}
public void setFilterPortExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_port_exclude", value);
editor.commit();
}
public void setFilterInterfaceExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_interface_exclude", value);
editor.commit();
}
public void setFilterProtocolExclude(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("filter_by_protocol_exclude", value);
editor.commit();
}
public void setUpdateMaxLogEntries(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("update_max_log_entries", value);
editor.commit();
}
public void setMaxLogEntries(long value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("max_log_entries", String.valueOf(value));
editor.commit();
}
public void setPreSortBy(Sort value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("presort_by", value.toString());
editor.commit();
}
public void setSortBy(Sort value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("sort_by", value.toString());
editor.commit();
}
public void setLogcatDebug(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("logcat_debug", value);
editor.commit();
}
public void setStatusbarNotifications(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notifications_statusbar", value);
editor.commit();
}
public void setToastNotifications(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notifications_toast", value);
editor.commit();
}
public void setToastNotificationsDuration(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("notifications_toast_duration", String.valueOf(value));
editor.commit();
}
public void setToastNotificationsPosition(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("notifications_toast_position", String.valueOf(value));
editor.commit();
}
public void setToastNotificationsYOffset(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notifications_toast_yoffset", value);
editor.commit();
}
public void setToastNotificationsOpacity(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("notifications_toast_opacity", value);
editor.commit();
}
public void setToastNotificationsShowAddress(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("notifications_toast_show_address", value);
editor.commit();
}
public void setGraphInterval(long value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("interval", value);
editor.commit();
}
public void setGraphViewsize(long value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("viewsize", value);
editor.commit();
}
public void setInvertUploadDownload(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("invert_upload_download", value);
editor.commit();
}
public void setWatchRules(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("watch_rules", value);
editor.commit();
}
public void setWatchRulesTimeout(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("watch_rules_timeout", String.valueOf(value));
editor.commit();
}
public void setBehindFirewall(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("behind_firewall", value);
editor.commit();
}
public void setThroughputBps(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("throughput_bps", value);
editor.commit();
}
public void setRoundValues(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("round_values", value);
editor.commit();
}
public void setStartForeground(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("start_foreground", value);
editor.commit();
}
public void setStartServiceAtBoot(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("startServiceAtBoot", value);
editor.commit();
}
public void setStartServiceAtStart(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("startServiceAtStart", value);
editor.commit();
}
public void setStopServiceAtExit(boolean value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("stopServiceAtExit", value);
editor.commit();
}
public void setHistorySize(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("history_size", value);
editor.commit();
}
public void setClearLogTimerange(String value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("clearlog_timerange", value);
editor.commit();
}
public void setLogMethod(int value) {
SharedPreferences.Editor editor = prefs.edit();
editor.putString("log_method", String.valueOf(value));
editor.commit();
}
public void setLogFile(String value) {
String oldValue = prefs.getString("logfile", null);
if(oldValue != null && !oldValue.equals(value)) {
// update only if values have changed (mainly to ensure service
// doesn't restart for same values)
SharedPreferences.Editor editor = prefs.edit();
editor.putString("logfile", value);
editor.commit();
if(NetworkLogService.instance != null) {
// if service is running, restart service so that logfile is opened
// with new path
NetworkLog.instance.stopService();
NetworkLog.instance.startService();
}
}
}
public void showSampleToast() {
if(NetworkLog.context != null && NetworkLog.handler != null) {
String msg = String.format(NetworkLog.context.getResources().getString(R.string.sample_toast_message),
NetworkLogService.toastYOffset, NetworkLogService.toastOpacity);
NetworkLogService.showToast(NetworkLog.context, NetworkLog.handler, msg, true);
}
}
@Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
MyLog.d("Shared prefs changed: [" + key + "]");
if(key.equals("log_method")) {
int value = Integer.parseInt(prefs.getString(key, "0"));
MyLog.d("New " + key + " value [" + value + "]");
if(NetworkLogService.instance != null) {
NetworkLog.instance.stopService();
NetworkLog.instance.startService();
}
}
if(key.equals("logfile")) {
String value = prefs.getString(key, null);
MyLog.d("New " + key + " value [" + value + "]");
// update service
return;
}
if(key.equals("startServiceAtBoot")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
}
if(key.equals("startServiceAtStart")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.startServiceAtStart = value;
return;
}
if(key.equals("stopServiceAtExit")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.stopServiceAtExit = value;
return;
}
if(key.equals("resolve_hosts")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.resolveHosts = value;
NetworkLog.logFragment.refreshAdapter();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("resolve_ports")) {
boolean value = prefs.getBoolean(key, true);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.resolvePorts = value;
NetworkLog.logFragment.refreshAdapter();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("copy_original_addrs")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.resolveCopies = !value;
return;
}
if(key.equals("max_log_entries")) {
String value = prefs.getString(key, "75000");
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.logFragment.maxLogEntries = Long.parseLong(value);
NetworkLog.logFragment.pruneLogEntries();
return;
}
if(key.equals("logcat_debug")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
MyLog.enabled = value;
return;
}
if(key.equals("presort_by")) {
String value = prefs.getString(key, "BYTES");
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.appFragment.preSortBy = Sort.forValue(value);
NetworkLog.appFragment.setPreSortMethod();
NetworkLog.appFragment.preSortData();
NetworkLog.appFragment.sortData();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("sort_by")) {
String value = prefs.getString(key, "BYTES");
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.appFragment.sortBy = Sort.forValue(value);
NetworkLog.appFragment.setSortMethod();
NetworkLog.appFragment.preSortData();
NetworkLog.appFragment.sortData();
NetworkLog.appFragment.sortChildren();
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("notifications_toast")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastEnabled = value;
return;
}
if(key.equals("notifications_toast_duration")) {
int value = Integer.parseInt(prefs.getString(key, "3500"));
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastDuration = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_position")) {
int value = Integer.parseInt(prefs.getString(key, "-1"));
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastPosition = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_yoffset")) {
int value = prefs.getInt(key, 0);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastYOffset = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_opacity")) {
int value = prefs.getInt(key, 119);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastOpacity = value;
showSampleToast();
return;
}
if(key.equals("notifications_toast_show_address")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.toastShowAddress = value;
return;
}
if(key.equals("round_values")) {
boolean value = prefs.getBoolean(key, true);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLog.appFragment.roundValues = value;
NetworkLog.appFragment.refreshAdapter();
return;
}
if(key.equals("invert_upload_download")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.invertUploadDownload = value;
return;
}
if(key.equals("watch_rules")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.watchRules = value;
if(NetworkLogService.instance != null) {
NetworkLogService.instance.startWatchingRules();
}
return;
}
if(key.equals("watch_rules_timeout")) {
int value = Integer.parseInt(prefs.getString(key, "120000"));
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.watchRulesTimeout = value;
if(NetworkLogService.rulesWatcher != null) {
NetworkLogService.rulesWatcher.interrupt();
}
return;
}
if(key.equals("behind_firewall")) {
boolean value = prefs.getBoolean(key, false);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.behindFirewall = value;
if(NetworkLogService.instance != null) {
Iptables.removeRules(context);
Iptables.addRules(context);
}
return;
}
if(key.equals("throughput_bps")) {
boolean value = prefs.getBoolean(key, true);
MyLog.d("New " + key + " value [" + value + "]");
NetworkLogService.throughputBps = value;
ThroughputTracker.updateThroughputBps();
return;
}
}
}
| Minor correction of indentation
| src/com/googlecode/networklog/Settings.java | Minor correction of indentation | <ide><path>rc/com/googlecode/networklog/Settings.java
<ide> editor.commit();
<ide> }
<ide>
<del> public void setStartForeground(boolean value) {
<add> public void setStartForeground(boolean value) {
<ide> SharedPreferences.Editor editor = prefs.edit();
<ide> editor.putBoolean("start_foreground", value);
<ide> editor.commit(); |
|
Java | apache-2.0 | ca2000898916b65c4e1d0748966ad966d97d7fb4 | 0 | mathieufortin01/pdfbox,ChunghwaTelecom/pdfbox,benmccann/pdfbox,veraPDF/veraPDF-pdfbox,torakiki/sambox,BezrukovM/veraPDF-pdfbox,BezrukovM/veraPDF-pdfbox,ZhenyaM/veraPDF-pdfbox,mdamt/pdfbox,ZhenyaM/veraPDF-pdfbox,veraPDF/veraPDF-pdfbox,joansmith/pdfbox,mdamt/pdfbox,joansmith/pdfbox,gavanx/pdflearn,torakiki/sambox,mathieufortin01/pdfbox,ChunghwaTelecom/pdfbox,gavanx/pdflearn,benmccann/pdfbox | /*
* 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.pdfbox.filter;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
/**
* Decompresses data encoded using the JBIG2 standard, reproducing the original
* monochrome (1 bit per pixel) image data (or an approximation of that data).
*
* Requires a JBIG2 plugin for Java Image I/O to be installed. A known working
* plug-in is <a href="http://code.google.com/p/jbig2-imageio/">jbig2-imageio</a>
* which is available under the GPL v3 license.
*
* @author Timo Boehme
*/
final class JBIG2Filter extends Filter
{
private static final Log LOG = LogFactory.getLog(JBIG2Filter.class);
@Override
public final DecodeResult decode(InputStream encoded, OutputStream decoded,
COSDictionary parameters, int index) throws IOException
{
ImageReader reader = findImageReader("JBIG2", "jbig2-imageio is not installed");
DecodeResult result = new DecodeResult(new COSDictionary());
result.getParameters().addAll(parameters);
COSInteger bits = (COSInteger) parameters.getDictionaryObject(COSName.BITS_PER_COMPONENT);
COSDictionary params = (COSDictionary) parameters.getDictionaryObject(COSName.DECODE_PARMS);
COSStream globals = null;
if (params != null)
{
globals = (COSStream) params.getDictionaryObject(COSName.JBIG2_GLOBALS);
}
ImageInputStream iis = null;
try
{
if (globals != null)
{
iis = ImageIO.createImageInputStream(
new SequenceInputStream(globals.getUnfilteredStream(), encoded));
reader.setInput(iis);
}
else
{
iis = ImageIO.createImageInputStream(encoded);
reader.setInput(iis);
}
BufferedImage image;
try
{
image = reader.read(0, reader.getDefaultReadParam());
}
catch (Exception e)
{
// wrap and rethrow any exceptions
throw new IOException("Could not read JBIG2 image", e);
}
// I am assuming since JBIG2 is always black and white
// depending on your renderer this might or might be needed
if (image.getColorModel().getPixelSize() != bits.intValue())
{
if (bits.intValue() != 1)
{
LOG.warn("Attempting to handle a JBIG2 with more than 1-bit depth");
}
BufferedImage packedImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_BYTE_BINARY);
Graphics graphics = packedImage.getGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
image = packedImage;
}
DataBuffer dBuf = image.getData().getDataBuffer();
if (dBuf.getDataType() == DataBuffer.TYPE_BYTE)
{
decoded.write(((DataBufferByte) dBuf).getData());
}
else
{
throw new IOException("Unexpected image buffer type");
}
}
finally
{
if (iis != null)
{
iis.close();
}
reader.dispose();
}
// repair missing color space
if (!parameters.containsKey(COSName.COLORSPACE))
{
result.getParameters().setName(COSName.COLORSPACE, COSName.DEVICEGRAY.getName());
}
return new DecodeResult(parameters);
}
@Override
protected final void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
throws IOException
{
throw new UnsupportedOperationException("JBIG2 encoding not implemented");
}
}
| pdfbox/src/main/java/org/apache/pdfbox/filter/JBIG2Filter.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.pdfbox.filter;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferByte;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSInteger;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.cos.COSStream;
/**
* Decompresses data encoded using the JBIG2 standard, reproducing the original
* monochrome (1 bit per pixel) image data (or an approximation of that data).
*
* Requires a JBIG2 plugin for Java Image I/O to be installed. A known working
* plug-in is <a href="http://code.google.com/p/jbig2-imageio/">jbig2-imageio</a>
* which is available under the GPL v3 license.
*
* @author Timo Boehme
*/
final class JBIG2Filter extends Filter
{
private static final Log LOG = LogFactory.getLog(JBIG2Filter.class);
@Override
public final DecodeResult decode(InputStream encoded, OutputStream decoded,
COSDictionary parameters, int index) throws IOException
{
ImageReader reader = findImageReader("JBIG2", "jbig2-imageio is not installed");
DecodeResult result = new DecodeResult(new COSDictionary());
result.getParameters().addAll(parameters);
COSInteger bits = (COSInteger) parameters.getDictionaryObject(COSName.BITS_PER_COMPONENT);
COSDictionary params = (COSDictionary) parameters.getDictionaryObject(COSName.DECODE_PARMS);
COSStream globals = null;
if (params != null)
{
globals = (COSStream) params.getDictionaryObject(COSName.JBIG2_GLOBALS);
}
ImageInputStream iis = null;
try
{
if (globals != null)
{
iis = ImageIO.createImageInputStream(
new SequenceInputStream(globals.getUnfilteredStream(), encoded));
reader.setInput(iis);
}
else
{
iis = ImageIO.createImageInputStream(encoded);
reader.setInput(iis);
}
BufferedImage image;
try
{
image = reader.read(0);
}
catch (Exception e)
{
// wrap and rethrow any exceptions
throw new IOException("Could not read JBIG2 image", e);
}
// I am assuming since JBIG2 is always black and white
// depending on your renderer this might or might be needed
if (image.getColorModel().getPixelSize() != bits.intValue())
{
if (bits.intValue() != 1)
{
LOG.warn("Attempting to handle a JBIG2 with more than 1-bit depth");
}
BufferedImage packedImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_BYTE_BINARY);
Graphics graphics = packedImage.getGraphics();
graphics.drawImage(image, 0, 0, null);
graphics.dispose();
image = packedImage;
}
DataBuffer dBuf = image.getData().getDataBuffer();
if (dBuf.getDataType() == DataBuffer.TYPE_BYTE)
{
decoded.write(((DataBufferByte) dBuf).getData());
}
else
{
throw new IOException("Unexpected image buffer type");
}
}
finally
{
if (iis != null)
{
iis.close();
}
reader.dispose();
}
// repair missing color space
if (!parameters.containsKey(COSName.COLORSPACE))
{
result.getParameters().setName(COSName.COLORSPACE, COSName.DEVICEGRAY.getName());
}
return new DecodeResult(parameters);
}
@Override
protected final void encode(InputStream input, OutputStream encoded, COSDictionary parameters)
throws IOException
{
throw new UnsupportedOperationException("JBIG2 encoding not implemented");
}
}
| PDFBOX-2594: Set default params in JBIG2Filter, as suggested by Daniel Bonniot de Ruisselet
git-svn-id: c3ad59981690829a43dc34c293c4e2cd04bcd994@1650378 13f79535-47bb-0310-9956-ffa450edef68
| pdfbox/src/main/java/org/apache/pdfbox/filter/JBIG2Filter.java | PDFBOX-2594: Set default params in JBIG2Filter, as suggested by Daniel Bonniot de Ruisselet | <ide><path>dfbox/src/main/java/org/apache/pdfbox/filter/JBIG2Filter.java
<ide> BufferedImage image;
<ide> try
<ide> {
<del> image = reader.read(0);
<add> image = reader.read(0, reader.getDefaultReadParam());
<ide> }
<ide> catch (Exception e)
<ide> { |
|
Java | apache-2.0 | 62d24d8ee550218978669815d3422aa0e7615f74 | 0 | pedroSG94/rtmp-rtsp-stream-client-java,pedroSG94/rtmp-streamer-java,pedroSG94/rtmp-rtsp-stream-client-java | package com.github.faucamp.simplertmp.io;
import android.util.Log;
import com.github.faucamp.simplertmp.RtmpPublisher;
import com.github.faucamp.simplertmp.Util;
import com.github.faucamp.simplertmp.amf.AmfMap;
import com.github.faucamp.simplertmp.amf.AmfNull;
import com.github.faucamp.simplertmp.amf.AmfNumber;
import com.github.faucamp.simplertmp.amf.AmfObject;
import com.github.faucamp.simplertmp.amf.AmfString;
import com.github.faucamp.simplertmp.packets.Abort;
import com.github.faucamp.simplertmp.packets.Audio;
import com.github.faucamp.simplertmp.packets.Command;
import com.github.faucamp.simplertmp.packets.Data;
import com.github.faucamp.simplertmp.packets.Handshake;
import com.github.faucamp.simplertmp.packets.RtmpPacket;
import com.github.faucamp.simplertmp.packets.UserControl;
import com.github.faucamp.simplertmp.packets.Video;
import com.github.faucamp.simplertmp.packets.WindowAckSize;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.ossrs.rtmp.BitrateManager;
import net.ossrs.rtmp.ConnectCheckerRtmp;
import net.ossrs.rtmp.CreateSSLSocket;
/**
* Main RTMP connection implementation class
*
* @author francois, leoma, pedro
*/
public class RtmpConnection implements RtmpPublisher {
private static final String TAG = "RtmpConnection";
private static final Pattern rtmpUrlPattern =
Pattern.compile("^rtmps?://([^/:]+)(?::(\\d+))*/([^/]+)/?([^*]*)$");
private int port;
private String host;
private String appName;
private String streamName;
private String publishType;
private String tcUrl;
private Socket socket;
private final RtmpSessionInfo rtmpSessionInfo = new RtmpSessionInfo();
private final RtmpDecoder rtmpDecoder = new RtmpDecoder(rtmpSessionInfo);
private BufferedInputStream inputStream;
private BufferedOutputStream outputStream;
private Thread rxPacketHandler;
private volatile boolean connected = false;
private volatile boolean publishPermitted = false;
private final Object connectingLock = new Object();
private final Object publishLock = new Object();
private int currentStreamId = 0;
private int transactionIdCounter = 0;
private int videoWidth;
private int videoHeight;
private final ConnectCheckerRtmp connectCheckerRtmp;
//for secure transport
private boolean tlsEnabled;
//for auth
private String user = null;
private String password = null;
private boolean onAuth = false;
private String netConnectionDescription;
private final BitrateManager bitrateManager;
private boolean isEnableLogs = true;
public RtmpConnection(ConnectCheckerRtmp connectCheckerRtmp) {
this.connectCheckerRtmp = connectCheckerRtmp;
bitrateManager = new BitrateManager(connectCheckerRtmp);
}
private void handshake(InputStream in, OutputStream out) throws IOException {
Handshake handshake = new Handshake();
handshake.writeC0(out);
handshake.writeC1(out); // Write C1 without waiting for S0
out.flush();
handshake.readS0(in);
handshake.readS1(in);
handshake.writeC2(out);
out.flush();
handshake.readS2(in);
}
private String getAppName(String app, String name) {
if (!name.contains("/")) {
return app;
} else {
return app + "/" + name.substring(0, name.indexOf("/"));
}
}
private String getStreamName(String name) {
if (!name.contains("/")) {
return name;
} else {
return name.substring(name.indexOf("/") + 1);
}
}
private String getTcUrl(String url) {
if (url.endsWith("/")) {
return url.substring(0, url.length() - 1);
} else {
return url;
}
}
@Override
public boolean connect(String url) {
if (url == null) {
connectCheckerRtmp.onConnectionFailedRtmp(
"Endpoint malformed, should be: rtmp://ip:port/appname/streamname");
return false;
}
Matcher rtmpMatcher = rtmpUrlPattern.matcher(url);
if (rtmpMatcher.matches()) {
tlsEnabled = rtmpMatcher.group(0).startsWith("rtmps");
} else {
connectCheckerRtmp.onConnectionFailedRtmp(
"Endpoint malformed, should be: rtmp://ip:port/appname/streamname");
return false;
}
host = rtmpMatcher.group(1);
String portStr = rtmpMatcher.group(2);
port = portStr != null ? Integer.parseInt(portStr) : 1935;
appName = getAppName(rtmpMatcher.group(3), rtmpMatcher.group(4));
String streamName = getStreamName(rtmpMatcher.group(4));
tcUrl = getTcUrl(rtmpMatcher.group(0).substring(0, rtmpMatcher.group(0).length() - streamName.length()));
this.streamName = streamName;
// socket connection
Log.d(TAG, "connect() called. Host: "
+ host
+ ", port: "
+ port
+ ", appName: "
+ appName
+ ", publishPath: "
+ streamName);
rtmpSessionInfo.reset();
if (!establishConnection()) return false;
// Start the "main" handling thread
rxPacketHandler = new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "starting main rx handler loop");
handleRxPacketLoop();
}
});
rxPacketHandler.start();
return rtmpConnect();
}
private boolean establishConnection() {
try {
if (!tlsEnabled) {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(host, port);
socket.connect(socketAddress, 5000);
} else {
socket = CreateSSLSocket.createSSlSocket(host, port);
if (socket == null) throw new IOException("Socket creation failed");
}
inputStream = new BufferedInputStream(socket.getInputStream());
outputStream = new BufferedOutputStream(socket.getOutputStream());
Log.d(TAG, "connect(): socket connection established, doing handhake...");
handshake(inputStream, outputStream);
Log.d(TAG, "connect(): handshake done");
return true;
} catch (Exception e) {
Log.e(TAG, "Error", e);
connectCheckerRtmp.onConnectionFailedRtmp("Connect error, " + e.getMessage());
return false;
}
}
private boolean rtmpConnect() {
if (connected) {
connectCheckerRtmp.onConnectionFailedRtmp("Already connected");
return false;
}
sendConnect("");
synchronized (connectingLock) {
try {
connectingLock.wait(getConnectionTimeoutMs());
} catch (InterruptedException ex) {
// do nothing
}
}
if (!connected) {
shutdown(true);
connectCheckerRtmp.onConnectionFailedRtmp("Fail to connect, time out");
}
return connected;
}
private void sendConnect(String user) {
ChunkStreamInfo.markSessionTimestampTx();
Log.d(TAG, "rtmpConnect(): Building 'connect' invoke packet");
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
Command invoke = new Command("connect", ++transactionIdCounter, chunkStreamInfo);
invoke.getHeader().setMessageStreamId(0);
AmfObject args = new AmfObject();
args.setProperty("app", appName + user);
args.setProperty("flashVer", "FMLE/3.0 (compatible; Lavf57.56.101)");
args.setProperty("swfUrl", "");
args.setProperty("tcUrl", tcUrl + user);
args.setProperty("fpad", false);
args.setProperty("capabilities", 239);
args.setProperty("audioCodecs", 3191);
args.setProperty("videoCodecs", 252);
args.setProperty("videoFunction", 1);
args.setProperty("pageUrl", "");
args.setProperty("objectEncoding", 0);
invoke.addData(args);
sendRtmpPacket(invoke);
}
private String getAdobeAuthUserResult(String user, String password, String salt, String challenge,
String opaque) {
String challenge2 = String.format("%08x", new Random().nextInt());
String response = Util.stringToMD5BASE64(user + salt + password);
if (!opaque.isEmpty()) {
response += opaque;
} else if (!challenge.isEmpty()) {
response += challenge;
}
response = Util.stringToMD5BASE64(response + challenge2);
String result = "?authmod=adobe&user=" + user + "&challenge=" + challenge2 + "&response=" + response;
if (!opaque.isEmpty()) {
result += "&opaque=" + opaque;
}
return result;
}
/**
* Limelight auth. This auth is closely to Digest auth
* http://tools.ietf.org/html/rfc2617
* http://en.wikipedia.org/wiki/Digest_access_authentication
*
* https://github.com/ossrs/librtmp/blob/feature/srs/librtmp/rtmp.c
*/
private String getLlnwAuthUserResult(String user, String password, String nonce, String app) {
String authMod = "llnw";
String realm = "live";
String method = "publish";
String qop = "auth";
String ncHex = String.format("%08x", 1);
String cNonce = String.format("%08x", new Random().nextInt());
String path = app;
//extract query parameters
int queryPos = path.indexOf("?");
if (queryPos >= 0) path = path.substring(0, queryPos);
if (!path.contains("/")) path += "/_definst_";
String hash1 = Util.getMd5Hash(user + ":" + realm + ":" + password);
String hash2 = Util.getMd5Hash(method + ":/" + path);
String hash3 = Util.getMd5Hash(hash1 + ":" + nonce + ":" + ncHex + ":" + cNonce + ":" + qop + ":" + hash2);
return "?authmod=" + authMod + "&user=" + user + "&nonce=" + nonce + "&cnonce=" + cNonce + "&nc=" + ncHex + "&response=" + hash3;
}
@Override
public boolean publish(String type) {
if (type == null) {
connectCheckerRtmp.onConnectionFailedRtmp("Null publish type");
return false;
}
publishType = type;
return createStream();
}
private boolean createStream() {
if (!connected || currentStreamId != 0) {
connectCheckerRtmp.onConnectionFailedRtmp(
"Create stream failed, connected= " + connected + ", StreamId= " + currentStreamId);
return false;
}
netConnectionDescription = null;
Log.d(TAG, "createStream(): Sending releaseStream command...");
// transactionId == 2
Command releaseStream = new Command("releaseStream", ++transactionIdCounter);
releaseStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
releaseStream.addData(new AmfNull()); // command object: null for "createStream"
releaseStream.addData(streamName); // command object: null for "releaseStream"
sendRtmpPacket(releaseStream);
Log.d(TAG, "createStream(): Sending FCPublish command...");
// transactionId == 3
Command FCPublish = new Command("FCPublish", ++transactionIdCounter);
FCPublish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
FCPublish.addData(new AmfNull()); // command object: null for "FCPublish"
FCPublish.addData(streamName);
sendRtmpPacket(FCPublish);
Log.d(TAG, "createStream(): Sending createStream command...");
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_OVER_CONNECTION);
// transactionId == 4
Command createStream = new Command("createStream", ++transactionIdCounter, chunkStreamInfo);
createStream.addData(new AmfNull()); // command object: null for "createStream"
sendRtmpPacket(createStream);
// Waiting for "NetStream.Publish.Start" response.
synchronized (publishLock) {
try {
publishLock.wait(5000);
} catch (InterruptedException ex) {
// do nothing
}
}
if (!publishPermitted) {
shutdown(true);
if (netConnectionDescription != null && !netConnectionDescription.isEmpty()) {
connectCheckerRtmp.onConnectionFailedRtmp(netConnectionDescription);
} else {
connectCheckerRtmp.onConnectionFailedRtmp(
"Error configure stream, publish permitted failed");
}
}
return publishPermitted;
}
private void fmlePublish() {
if (!connected || currentStreamId == 0) {
Log.e(TAG, "fmlePublish failed");
return;
}
Log.d(TAG, "fmlePublish(): Sending publish command...");
Command publish = new Command("publish", ++transactionIdCounter);
publish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
publish.getHeader().setMessageStreamId(currentStreamId);
publish.addData(new AmfNull()); // command object: null for "publish"
publish.addData(streamName);
publish.addData(publishType);
sendRtmpPacket(publish);
}
private void onMetaData() {
if (!connected || currentStreamId == 0) {
Log.e(TAG, "onMetaData failed");
return;
}
Log.d(TAG, "onMetaData(): Sending empty onMetaData...");
Data metadata = new Data("@setDataFrame");
metadata.getHeader().setMessageStreamId(currentStreamId);
metadata.addData("onMetaData");
AmfMap ecmaArray = new AmfMap();
ecmaArray.setProperty("duration", 0);
ecmaArray.setProperty("width", videoWidth);
ecmaArray.setProperty("height", videoHeight);
ecmaArray.setProperty("videocodecid", 7);
ecmaArray.setProperty("framerate", 30);
ecmaArray.setProperty("videodatarate", 0);
// @see FLV video_file_format_spec_v10_1.pdf
// According to E.4.2.1 AUDIODATA
// "If the SoundFormat indicates AAC, the SoundType should be 1 (stereo) and the SoundRate should be 3 (44 kHz).
// However, this does not mean that AAC audio in FLV is always stereo, 44 kHz data. Instead, the Flash Player ignores
// these values and extracts the channel and sample rate data is encoded in the AAC bit stream."
ecmaArray.setProperty("audiocodecid", 10);
ecmaArray.setProperty("audiosamplerate", 44100);
ecmaArray.setProperty("audiosamplesize", 16);
ecmaArray.setProperty("audiodatarate", 0);
ecmaArray.setProperty("stereo", true);
ecmaArray.setProperty("filesize", 0);
metadata.addData(ecmaArray);
sendRtmpPacket(metadata);
}
@Override
public void close() {
if (socket != null) {
closeStream();
}
shutdown(true);
}
private void closeStream() {
if (!connected || currentStreamId == 0 || !publishPermitted) {
Log.e(TAG, "closeStream failed");
return;
}
Log.d(TAG, "closeStream(): setting current stream ID to 0");
Command closeStream = new Command("closeStream", ++transactionIdCounter);
closeStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
closeStream.getHeader().setMessageStreamId(currentStreamId);
closeStream.addData(new AmfNull());
sendRtmpPacket(closeStream);
}
private synchronized void shutdown(boolean r) {
if (socket != null) {
try {
// It will raise EOFException in handleRxPacketThread
socket.shutdownInput();
// It will raise SocketException in sendRtmpPacket
socket.shutdownOutput();
} catch (IOException | UnsupportedOperationException e) {
Log.e(TAG, "Shutdown socket", e);
}
// shutdown rxPacketHandler
if (rxPacketHandler != null) {
rxPacketHandler.interrupt();
try {
rxPacketHandler.join(100);
} catch (InterruptedException ie) {
rxPacketHandler.interrupt();
}
rxPacketHandler = null;
}
// shutdown socket as well as its input and output stream
try {
socket.close();
Log.d(TAG, "socket closed");
} catch (IOException ex) {
Log.e(TAG, "shutdown(): failed to close socket", ex);
}
}
if (r) {
reset();
}
}
private void reset() {
connected = false;
publishPermitted = false;
netConnectionDescription = null;
tcUrl = null;
appName = null;
streamName = null;
publishType = null;
currentStreamId = 0;
transactionIdCounter = 0;
socket = null;
rtmpSessionInfo.reset();
}
@Override
public void publishAudioData(byte[] data, int size, int dts) {
if (data == null
|| data.length == 0
|| dts < 0
|| !connected
|| currentStreamId == 0
|| !publishPermitted) {
return;
}
Audio audio = new Audio();
audio.setData(data, size);
audio.getHeader().setAbsoluteTimestamp(dts);
audio.getHeader().setMessageStreamId(currentStreamId);
sendRtmpPacket(audio);
//bytes to bits
bitrateManager.calculateBitrate(size * 8);
}
@Override
public void publishVideoData(byte[] data, int size, int dts) {
if (data == null
|| data.length == 0
|| dts < 0
|| !connected
|| currentStreamId == 0
|| !publishPermitted) {
return;
}
Video video = new Video();
video.setData(data, size);
video.getHeader().setAbsoluteTimestamp(dts);
video.getHeader().setMessageStreamId(currentStreamId);
sendRtmpPacket(video);
//bytes to bits
bitrateManager.calculateBitrate(size * 8);
}
private void sendRtmpPacket(RtmpPacket rtmpPacket) {
try {
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(rtmpPacket.getHeader().getChunkStreamId());
chunkStreamInfo.setPrevHeaderTx(rtmpPacket.getHeader());
if (!(rtmpPacket instanceof Video || rtmpPacket instanceof Audio)) {
rtmpPacket.getHeader()
.setAbsoluteTimestamp((int) chunkStreamInfo.markAbsoluteTimestampTx());
}
rtmpPacket.writeTo(outputStream, rtmpSessionInfo.getTxChunkSize(), chunkStreamInfo);
if (isEnableLogs) {
Log.d(TAG,
"wrote packet: " + rtmpPacket + ", size: " + rtmpPacket.getHeader().getPacketLength());
}
if (rtmpPacket instanceof Command) {
rtmpSessionInfo.addInvokedCommand(((Command) rtmpPacket).getTransactionId(),
((Command) rtmpPacket).getCommandName());
}
outputStream.flush();
} catch (IOException ioe) {
connectCheckerRtmp.onConnectionFailedRtmp("Error send packet: " + ioe.getMessage());
Log.e(TAG, "Caught IOException during write loop, shutting down: " + ioe.getMessage());
Thread.currentThread().interrupt();
}
}
private void handleRxPacketLoop() {
// Handle all queued received RTMP packets
while (!Thread.interrupted()) {
try {
// It will be blocked when no data in input stream buffer
RtmpPacket rtmpPacket = rtmpDecoder.readPacket(inputStream);
if (rtmpPacket != null) {
//Log.d(TAG, "handleRxPacketLoop(): RTMP rx packet message type: " + rtmpPacket.getHeader().getMessageType());
switch (rtmpPacket.getHeader().getMessageType()) {
case ABORT:
rtmpSessionInfo.getChunkStreamInfo(((Abort) rtmpPacket).getChunkStreamId())
.clearStoredChunks();
break;
case USER_CONTROL_MESSAGE:
UserControl user = (UserControl) rtmpPacket;
switch (user.getType()) {
case STREAM_BEGIN:
break;
case PING_REQUEST:
ChunkStreamInfo channelInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_PROTOCOL_CONTROL);
Log.d(TAG, "handleRxPacketLoop(): Sending PONG reply..");
UserControl pong = new UserControl(user, channelInfo);
sendRtmpPacket(pong);
break;
case STREAM_EOF:
Log.i(TAG, "handleRxPacketLoop(): Stream EOF reached, closing RTMP writer...");
break;
default:
// Ignore...
break;
}
break;
case WINDOW_ACKNOWLEDGEMENT_SIZE:
WindowAckSize windowAckSize = (WindowAckSize) rtmpPacket;
int size = windowAckSize.getAcknowledgementWindowSize();
Log.d(TAG, "handleRxPacketLoop(): Setting acknowledgement window size: " + size);
rtmpSessionInfo.setAcknowledgmentWindowSize(size);
break;
case SET_PEER_BANDWIDTH:
rtmpSessionInfo.setAcknowledgmentWindowSize(socket.getSendBufferSize());
int acknowledgementWindowsize = rtmpSessionInfo.getAcknowledgementWindowSize();
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_PROTOCOL_CONTROL);
Log.d(TAG, "handleRxPacketLoop(): Send acknowledgement window size: "
+ acknowledgementWindowsize);
sendRtmpPacket(new WindowAckSize(acknowledgementWindowsize, chunkStreamInfo));
// Set socket option. This line could produce bps calculation problems.
//socket.setSendBufferSize(acknowledgementWindowsize);
break;
case COMMAND_AMF0:
handleRxInvoke((Command) rtmpPacket);
break;
default:
Log.w(TAG, "handleRxPacketLoop(): Not handling unimplemented/unknown packet of type: "
+ rtmpPacket.getHeader().getMessageType());
break;
}
}
} catch (EOFException eof) {
Thread.currentThread().interrupt();
} catch (IOException e) {
connectCheckerRtmp.onConnectionFailedRtmp("Error reading packet: " + e.getMessage());
Log.e(TAG, "Caught SocketException while reading/decoding packet, shutting down: "
+ e.getMessage());
Thread.currentThread().interrupt();
}
}
}
private void handleRxInvoke(Command invoke) {
String commandName = invoke.getCommandName();
switch (commandName) {
case "_error":
try {
String description = ((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty(
"description")).getValue();
Log.i(TAG, description);
if (description.contains("reason=authfail") || description.contains("reason=nosuchuser")) {
connectCheckerRtmp.onAuthErrorRtmp();
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
} else if (user != null && password != null
&& description.contains("challenge=") && description.contains("salt=") //adobe response
|| description.contains("nonce=")) { //llnw response
onAuth = true;
try {
shutdown(false);
} catch (Exception e) {
e.printStackTrace();
}
rtmpSessionInfo.reset();
if (!tlsEnabled) {
socket = new Socket(host, port);
} else {
socket = CreateSSLSocket.createSSlSocket(host, port);
if (socket == null) throw new IOException("Socket creation failed");
}
inputStream = new BufferedInputStream(socket.getInputStream());
outputStream = new BufferedOutputStream(socket.getOutputStream());
Log.d(TAG, "connect(): socket connection established, doing handshake...");
handshake(inputStream, outputStream);
rxPacketHandler = new Thread(new Runnable() {
@Override
public void run() {
handleRxPacketLoop();
}
});
rxPacketHandler.start();
if (description.contains("challenge=") && description.contains("salt=")) { //create adobe auth
String salt = Util.getSalt(description);
String challenge = Util.getChallenge(description);
String opaque = Util.getOpaque(description);
Log.i(TAG, "sending adobe auth response");
sendConnect(getAdobeAuthUserResult(user, password, salt, challenge, opaque));
} else if (description.contains("nonce=")){ //create llnw auth
String nonce = Util.getNonce(description);
Log.i(TAG, "sending llnw auth response");
sendConnect(getLlnwAuthUserResult(user, password, nonce, appName));
}
} else if (description.contains("code=403")) {
if (user != null && password != null) {
// few servers close connection after send code=403
if (socket == null || !socket.getKeepAlive()) {
establishConnection();
}
if (description.contains("authmod=adobe")) {
Log.i(TAG, "sending auth mode adobe");
sendConnect("?authmod=adobe&user=" + user);
return;
} else if (description.contains("authmod=llnw")) {
Log.i(TAG, "sending auth mode llnw");
sendConnect("?authmod=llnw&user=" + user);
return;
}
}
connectCheckerRtmp.onAuthErrorRtmp();
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
} else {
connectCheckerRtmp.onConnectionFailedRtmp(description);
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
}
} catch (Exception e) {
connectCheckerRtmp.onConnectionFailedRtmp(e.getMessage());
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
}
break;
case "_result":
// This is the result of one of the methods invoked by us
String method = rtmpSessionInfo.takeInvokedCommand(invoke.getTransactionId());
if (method == null) {
Log.i(TAG, "'_result' message received for unknown method: ");
return;
}
Log.i(TAG, "handleRxInvoke: Got result for invoked method: " + method);
if ("connect".equals(method)) {
if (onAuth) {
connectCheckerRtmp.onAuthSuccessRtmp();
onAuth = false;
}
// Capture server ip/pid/id information if any
// We can now send createStream commands
connected = true;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
} else if ("createStream".contains(method)) {
// Get stream id
currentStreamId = (int) ((AmfNumber) invoke.getData().get(1)).getValue();
Log.d(TAG, "handleRxInvoke(): Stream ID to publish: " + currentStreamId);
if (streamName != null && publishType != null) {
fmlePublish();
}
} else if ("releaseStream".contains(method)) {
Log.d(TAG, "handleRxInvoke(): 'releaseStream'");
} else if ("FCPublish".contains(method)) {
Log.d(TAG, "handleRxInvoke(): 'FCPublish'");
} else {
Log.w(TAG, "handleRxInvoke(): '_result' message received for unknown method: " + method);
}
break;
case "onBWDone":
Log.d(TAG, "handleRxInvoke(): 'onBWDone'");
break;
case "onFCPublish":
Log.d(TAG, "handleRxInvoke(): 'onFCPublish'");
break;
case "onStatus":
String code =
((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty("code")).getValue();
Log.d(TAG, "handleRxInvoke(): onStatus " + code);
switch (code) {
case "NetStream.Publish.Start":
onMetaData();
// We can now publish AV data
publishPermitted = true;
synchronized (publishLock) {
publishLock.notifyAll();
}
break;
case "NetConnection.Connect.Rejected":
netConnectionDescription =
((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty(
"description")).getValue();
publishPermitted = false;
synchronized (publishLock) {
publishLock.notifyAll();
}
break;
case "NetStream.Publish.BadName":
connectCheckerRtmp.onConnectionFailedRtmp("BadName received, endpoint in use.");
break;
default:
connectCheckerRtmp.onConnectionFailedRtmp("Unknown on status received");
break;
}
break;
default:
Log.e(TAG, "handleRxInvoke(): Unknown/unhandled server invoke: " + invoke);
break;
}
}
private long getConnectionTimeoutMs() {
final long defaultTimeoutMs = 5_000;
if (user != null && password != null) {
// Authorized connection may take about 3 times longer than a regular, that's why the timeout is longer.
return 3 * defaultTimeoutMs;
} else {
return defaultTimeoutMs;
}
}
@Override
public void setVideoResolution(int width, int height) {
videoWidth = width;
videoHeight = height;
}
@Override
public void setAuthorization(String user, String password) {
this.user = user;
this.password = password;
}
public void setLogs(boolean enable) {
isEnableLogs = enable;
}
}
| rtmp/src/main/java/com/github/faucamp/simplertmp/io/RtmpConnection.java | package com.github.faucamp.simplertmp.io;
import android.util.Log;
import com.github.faucamp.simplertmp.RtmpPublisher;
import com.github.faucamp.simplertmp.Util;
import com.github.faucamp.simplertmp.amf.AmfMap;
import com.github.faucamp.simplertmp.amf.AmfNull;
import com.github.faucamp.simplertmp.amf.AmfNumber;
import com.github.faucamp.simplertmp.amf.AmfObject;
import com.github.faucamp.simplertmp.amf.AmfString;
import com.github.faucamp.simplertmp.packets.Abort;
import com.github.faucamp.simplertmp.packets.Audio;
import com.github.faucamp.simplertmp.packets.Command;
import com.github.faucamp.simplertmp.packets.Data;
import com.github.faucamp.simplertmp.packets.Handshake;
import com.github.faucamp.simplertmp.packets.RtmpPacket;
import com.github.faucamp.simplertmp.packets.UserControl;
import com.github.faucamp.simplertmp.packets.Video;
import com.github.faucamp.simplertmp.packets.WindowAckSize;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.ossrs.rtmp.BitrateManager;
import net.ossrs.rtmp.ConnectCheckerRtmp;
import net.ossrs.rtmp.CreateSSLSocket;
/**
* Main RTMP connection implementation class
*
* @author francois, leoma, pedro
*/
public class RtmpConnection implements RtmpPublisher {
private static final String TAG = "RtmpConnection";
private static final Pattern rtmpUrlPattern =
Pattern.compile("^rtmps?://([^/:]+)(?::(\\d+))*/([^/]+)/?([^*]*)$");
private int port;
private String host;
private String appName;
private String streamName;
private String publishType;
private String tcUrl;
private Socket socket;
private final RtmpSessionInfo rtmpSessionInfo = new RtmpSessionInfo();
private final RtmpDecoder rtmpDecoder = new RtmpDecoder(rtmpSessionInfo);
private BufferedInputStream inputStream;
private BufferedOutputStream outputStream;
private Thread rxPacketHandler;
private volatile boolean connected = false;
private volatile boolean publishPermitted = false;
private final Object connectingLock = new Object();
private final Object publishLock = new Object();
private int currentStreamId = 0;
private int transactionIdCounter = 0;
private int videoWidth;
private int videoHeight;
private final ConnectCheckerRtmp connectCheckerRtmp;
//for secure transport
private boolean tlsEnabled;
//for auth
private String user = null;
private String password = null;
private boolean onAuth = false;
private String netConnectionDescription;
private final BitrateManager bitrateManager;
private boolean isEnableLogs = true;
public RtmpConnection(ConnectCheckerRtmp connectCheckerRtmp) {
this.connectCheckerRtmp = connectCheckerRtmp;
bitrateManager = new BitrateManager(connectCheckerRtmp);
}
private void handshake(InputStream in, OutputStream out) throws IOException {
Handshake handshake = new Handshake();
handshake.writeC0(out);
handshake.writeC1(out); // Write C1 without waiting for S0
out.flush();
handshake.readS0(in);
handshake.readS1(in);
handshake.writeC2(out);
out.flush();
handshake.readS2(in);
}
private String getAppName(String app, String name) {
if (!name.contains("/")) {
return app;
} else {
return app + "/" + name.substring(0, name.indexOf("/"));
}
}
private String getStreamName(String name) {
if (!name.contains("/")) {
return name;
} else {
return name.substring(name.indexOf("/") + 1);
}
}
private String getTcUrl(String url) {
if (url.endsWith("/")) {
return url.substring(0, url.length() - 1);
} else {
return url;
}
}
@Override
public boolean connect(String url) {
if (url == null) {
connectCheckerRtmp.onConnectionFailedRtmp(
"Endpoint malformed, should be: rtmp://ip:port/appname/streamname");
return false;
}
Matcher rtmpMatcher = rtmpUrlPattern.matcher(url);
if (rtmpMatcher.matches()) {
tlsEnabled = rtmpMatcher.group(0).startsWith("rtmps");
} else {
connectCheckerRtmp.onConnectionFailedRtmp(
"Endpoint malformed, should be: rtmp://ip:port/appname/streamname");
return false;
}
host = rtmpMatcher.group(1);
String portStr = rtmpMatcher.group(2);
port = portStr != null ? Integer.parseInt(portStr) : 1935;
appName = getAppName(rtmpMatcher.group(3), rtmpMatcher.group(4));
String streamName = getStreamName(rtmpMatcher.group(4));
tcUrl = getTcUrl(rtmpMatcher.group(0).substring(0, rtmpMatcher.group(0).length() - streamName.length()));
this.streamName = streamName;
// socket connection
Log.d(TAG, "connect() called. Host: "
+ host
+ ", port: "
+ port
+ ", appName: "
+ appName
+ ", publishPath: "
+ streamName);
rtmpSessionInfo.reset();
if (!establishConnection()) return false;
// Start the "main" handling thread
rxPacketHandler = new Thread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "starting main rx handler loop");
handleRxPacketLoop();
}
});
rxPacketHandler.start();
return rtmpConnect();
}
private boolean establishConnection() {
try {
if (!tlsEnabled) {
socket = new Socket();
SocketAddress socketAddress = new InetSocketAddress(host, port);
socket.connect(socketAddress, 5000);
} else {
socket = CreateSSLSocket.createSSlSocket(host, port);
if (socket == null) throw new IOException("Socket creation failed");
}
inputStream = new BufferedInputStream(socket.getInputStream());
outputStream = new BufferedOutputStream(socket.getOutputStream());
Log.d(TAG, "connect(): socket connection established, doing handhake...");
handshake(inputStream, outputStream);
Log.d(TAG, "connect(): handshake done");
return true;
} catch (Exception e) {
Log.e(TAG, "Error", e);
connectCheckerRtmp.onConnectionFailedRtmp("Connect error, " + e.getMessage());
return false;
}
}
private boolean rtmpConnect() {
if (connected) {
connectCheckerRtmp.onConnectionFailedRtmp("Already connected");
return false;
}
sendConnect("");
synchronized (connectingLock) {
try {
connectingLock.wait(getConnectionTimeoutMs());
} catch (InterruptedException ex) {
// do nothing
}
}
if (!connected) {
shutdown(true);
connectCheckerRtmp.onConnectionFailedRtmp("Fail to connect, time out");
}
return connected;
}
private void sendConnect(String user) {
ChunkStreamInfo.markSessionTimestampTx();
Log.d(TAG, "rtmpConnect(): Building 'connect' invoke packet");
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
Command invoke = new Command("connect", ++transactionIdCounter, chunkStreamInfo);
invoke.getHeader().setMessageStreamId(0);
AmfObject args = new AmfObject();
args.setProperty("app", appName + user);
args.setProperty("flashVer", "FMLE/3.0 (compatible; Lavf57.56.101)");
args.setProperty("swfUrl", "");
args.setProperty("tcUrl", tcUrl + user);
args.setProperty("fpad", false);
args.setProperty("capabilities", 239);
args.setProperty("audioCodecs", 3191);
args.setProperty("videoCodecs", 252);
args.setProperty("videoFunction", 1);
args.setProperty("pageUrl", "");
args.setProperty("objectEncoding", 0);
invoke.addData(args);
sendRtmpPacket(invoke);
}
private String getAdobeAuthUserResult(String user, String password, String salt, String challenge,
String opaque) {
String challenge2 = String.format("%08x", new Random().nextInt());
String response = Util.stringToMD5BASE64(user + salt + password);
if (!opaque.isEmpty()) {
response += opaque;
} else if (!challenge.isEmpty()) {
response += challenge;
}
response = Util.stringToMD5BASE64(response + challenge2);
String result = "?authmod=adobe&user=" + user + "&challenge=" + challenge2 + "&response=" + response;
if (!opaque.isEmpty()) {
result += "&opaque=" + opaque;
}
return result;
}
/**
* Limelight auth. This auth is closely to Digest auth
* http://tools.ietf.org/html/rfc2617
* http://en.wikipedia.org/wiki/Digest_access_authentication
*
* https://github.com/ossrs/librtmp/blob/feature/srs/librtmp/rtmp.c
*/
private String getLlnwAuthUserResult(String user, String password, String nonce, String app) {
String authMod = "llnw";
String realm = "live";
String method = "publish";
String qop = "auth";
String ncHex = String.format("%08x", 1);
String cNonce = String.format("%08x", new Random().nextInt());
String path = app;
//extract query parameters
int queryPos = path.indexOf("?");
if (queryPos >= 0) path = path.substring(0, queryPos);
if (!path.contains("/")) path += "/_definst_";
String hash1 = Util.getMd5Hash(user + ":" + realm + ":" + password);
String hash2 = Util.getMd5Hash(method + ":/" + path);
String hash3 = Util.getMd5Hash(hash1 + ":" + nonce + ":" + ncHex + ":" + cNonce + ":" + qop + ":" + hash2);
return "?authmod=" + authMod + "&user=" + user + "&nonce=" + nonce + "&cnonce=" + cNonce + "&nc=" + ncHex + "&response=" + hash3;
}
@Override
public boolean publish(String type) {
if (type == null) {
connectCheckerRtmp.onConnectionFailedRtmp("Null publish type");
return false;
}
publishType = type;
return createStream();
}
private boolean createStream() {
if (!connected || currentStreamId != 0) {
connectCheckerRtmp.onConnectionFailedRtmp(
"Create stream failed, connected= " + connected + ", StreamId= " + currentStreamId);
return false;
}
netConnectionDescription = null;
Log.d(TAG, "createStream(): Sending releaseStream command...");
// transactionId == 2
Command releaseStream = new Command("releaseStream", ++transactionIdCounter);
releaseStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
releaseStream.addData(new AmfNull()); // command object: null for "createStream"
releaseStream.addData(streamName); // command object: null for "releaseStream"
sendRtmpPacket(releaseStream);
Log.d(TAG, "createStream(): Sending FCPublish command...");
// transactionId == 3
Command FCPublish = new Command("FCPublish", ++transactionIdCounter);
FCPublish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
FCPublish.addData(new AmfNull()); // command object: null for "FCPublish"
FCPublish.addData(streamName);
sendRtmpPacket(FCPublish);
Log.d(TAG, "createStream(): Sending createStream command...");
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_OVER_CONNECTION);
// transactionId == 4
Command createStream = new Command("createStream", ++transactionIdCounter, chunkStreamInfo);
createStream.addData(new AmfNull()); // command object: null for "createStream"
sendRtmpPacket(createStream);
// Waiting for "NetStream.Publish.Start" response.
synchronized (publishLock) {
try {
publishLock.wait(5000);
} catch (InterruptedException ex) {
// do nothing
}
}
if (!publishPermitted) {
shutdown(true);
if (netConnectionDescription != null && !netConnectionDescription.isEmpty()) {
connectCheckerRtmp.onConnectionFailedRtmp(netConnectionDescription);
} else {
connectCheckerRtmp.onConnectionFailedRtmp(
"Error configure stream, publish permitted failed");
}
}
return publishPermitted;
}
private void fmlePublish() {
if (!connected || currentStreamId == 0) {
Log.e(TAG, "fmlePublish failed");
return;
}
Log.d(TAG, "fmlePublish(): Sending publish command...");
Command publish = new Command("publish", ++transactionIdCounter);
publish.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
publish.getHeader().setMessageStreamId(currentStreamId);
publish.addData(new AmfNull()); // command object: null for "publish"
publish.addData(streamName);
publish.addData(publishType);
sendRtmpPacket(publish);
}
private void onMetaData() {
if (!connected || currentStreamId == 0) {
Log.e(TAG, "onMetaData failed");
return;
}
Log.d(TAG, "onMetaData(): Sending empty onMetaData...");
Data metadata = new Data("@setDataFrame");
metadata.getHeader().setMessageStreamId(currentStreamId);
metadata.addData("onMetaData");
AmfMap ecmaArray = new AmfMap();
ecmaArray.setProperty("duration", 0);
ecmaArray.setProperty("width", videoWidth);
ecmaArray.setProperty("height", videoHeight);
ecmaArray.setProperty("videocodecid", 7);
ecmaArray.setProperty("framerate", 30);
ecmaArray.setProperty("videodatarate", 0);
// @see FLV video_file_format_spec_v10_1.pdf
// According to E.4.2.1 AUDIODATA
// "If the SoundFormat indicates AAC, the SoundType should be 1 (stereo) and the SoundRate should be 3 (44 kHz).
// However, this does not mean that AAC audio in FLV is always stereo, 44 kHz data. Instead, the Flash Player ignores
// these values and extracts the channel and sample rate data is encoded in the AAC bit stream."
ecmaArray.setProperty("audiocodecid", 10);
ecmaArray.setProperty("audiosamplerate", 44100);
ecmaArray.setProperty("audiosamplesize", 16);
ecmaArray.setProperty("audiodatarate", 0);
ecmaArray.setProperty("stereo", true);
ecmaArray.setProperty("filesize", 0);
metadata.addData(ecmaArray);
sendRtmpPacket(metadata);
}
@Override
public void close() {
if (socket != null) {
closeStream();
}
shutdown(true);
}
private void closeStream() {
if (!connected || currentStreamId == 0 || !publishPermitted) {
Log.e(TAG, "closeStream failed");
return;
}
Log.d(TAG, "closeStream(): setting current stream ID to 0");
Command closeStream = new Command("closeStream", ++transactionIdCounter);
closeStream.getHeader().setChunkStreamId(ChunkStreamInfo.RTMP_CID_OVER_STREAM);
closeStream.getHeader().setMessageStreamId(currentStreamId);
closeStream.addData(new AmfNull());
sendRtmpPacket(closeStream);
}
private synchronized void shutdown(boolean r) {
if (socket != null) {
try {
// It will raise EOFException in handleRxPacketThread
socket.shutdownInput();
// It will raise SocketException in sendRtmpPacket
socket.shutdownOutput();
} catch (IOException | UnsupportedOperationException e) {
Log.e(TAG, "Shutdown socket", e);
}
// shutdown rxPacketHandler
if (rxPacketHandler != null) {
rxPacketHandler.interrupt();
try {
rxPacketHandler.join(100);
} catch (InterruptedException ie) {
rxPacketHandler.interrupt();
}
rxPacketHandler = null;
}
// shutdown socket as well as its input and output stream
try {
socket.close();
Log.d(TAG, "socket closed");
} catch (IOException ex) {
Log.e(TAG, "shutdown(): failed to close socket", ex);
}
}
if (r) {
reset();
}
}
private void reset() {
connected = false;
publishPermitted = false;
netConnectionDescription = null;
tcUrl = null;
appName = null;
streamName = null;
publishType = null;
currentStreamId = 0;
transactionIdCounter = 0;
socket = null;
rtmpSessionInfo.reset();
}
@Override
public void publishAudioData(byte[] data, int size, int dts) {
if (data == null
|| data.length == 0
|| dts < 0
|| !connected
|| currentStreamId == 0
|| !publishPermitted) {
return;
}
Audio audio = new Audio();
audio.setData(data, size);
audio.getHeader().setAbsoluteTimestamp(dts);
audio.getHeader().setMessageStreamId(currentStreamId);
sendRtmpPacket(audio);
//bytes to bits
bitrateManager.calculateBitrate(size * 8);
}
@Override
public void publishVideoData(byte[] data, int size, int dts) {
if (data == null
|| data.length == 0
|| dts < 0
|| !connected
|| currentStreamId == 0
|| !publishPermitted) {
return;
}
Video video = new Video();
video.setData(data, size);
video.getHeader().setAbsoluteTimestamp(dts);
video.getHeader().setMessageStreamId(currentStreamId);
sendRtmpPacket(video);
//bytes to bits
bitrateManager.calculateBitrate(size * 8);
}
private void sendRtmpPacket(RtmpPacket rtmpPacket) {
try {
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(rtmpPacket.getHeader().getChunkStreamId());
chunkStreamInfo.setPrevHeaderTx(rtmpPacket.getHeader());
if (!(rtmpPacket instanceof Video || rtmpPacket instanceof Audio)) {
rtmpPacket.getHeader()
.setAbsoluteTimestamp((int) chunkStreamInfo.markAbsoluteTimestampTx());
}
rtmpPacket.writeTo(outputStream, rtmpSessionInfo.getTxChunkSize(), chunkStreamInfo);
if (isEnableLogs) {
Log.d(TAG,
"wrote packet: " + rtmpPacket + ", size: " + rtmpPacket.getHeader().getPacketLength());
}
if (rtmpPacket instanceof Command) {
rtmpSessionInfo.addInvokedCommand(((Command) rtmpPacket).getTransactionId(),
((Command) rtmpPacket).getCommandName());
}
outputStream.flush();
} catch (IOException ioe) {
connectCheckerRtmp.onConnectionFailedRtmp("Error send packet: " + ioe.getMessage());
Log.e(TAG, "Caught IOException during write loop, shutting down: " + ioe.getMessage());
Thread.currentThread().interrupt();
}
}
private void handleRxPacketLoop() {
// Handle all queued received RTMP packets
while (!Thread.interrupted()) {
try {
// It will be blocked when no data in input stream buffer
RtmpPacket rtmpPacket = rtmpDecoder.readPacket(inputStream);
if (rtmpPacket != null) {
//Log.d(TAG, "handleRxPacketLoop(): RTMP rx packet message type: " + rtmpPacket.getHeader().getMessageType());
switch (rtmpPacket.getHeader().getMessageType()) {
case ABORT:
rtmpSessionInfo.getChunkStreamInfo(((Abort) rtmpPacket).getChunkStreamId())
.clearStoredChunks();
break;
case USER_CONTROL_MESSAGE:
UserControl user = (UserControl) rtmpPacket;
switch (user.getType()) {
case STREAM_BEGIN:
break;
case PING_REQUEST:
ChunkStreamInfo channelInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_PROTOCOL_CONTROL);
Log.d(TAG, "handleRxPacketLoop(): Sending PONG reply..");
UserControl pong = new UserControl(user, channelInfo);
sendRtmpPacket(pong);
break;
case STREAM_EOF:
Log.i(TAG, "handleRxPacketLoop(): Stream EOF reached, closing RTMP writer...");
break;
default:
// Ignore...
break;
}
break;
case WINDOW_ACKNOWLEDGEMENT_SIZE:
WindowAckSize windowAckSize = (WindowAckSize) rtmpPacket;
int size = windowAckSize.getAcknowledgementWindowSize();
Log.d(TAG, "handleRxPacketLoop(): Setting acknowledgement window size: " + size);
rtmpSessionInfo.setAcknowledgmentWindowSize(size);
break;
case SET_PEER_BANDWIDTH:
rtmpSessionInfo.setAcknowledgmentWindowSize(socket.getSendBufferSize());
int acknowledgementWindowsize = rtmpSessionInfo.getAcknowledgementWindowSize();
ChunkStreamInfo chunkStreamInfo =
rtmpSessionInfo.getChunkStreamInfo(ChunkStreamInfo.RTMP_CID_PROTOCOL_CONTROL);
Log.d(TAG, "handleRxPacketLoop(): Send acknowledgement window size: "
+ acknowledgementWindowsize);
sendRtmpPacket(new WindowAckSize(acknowledgementWindowsize, chunkStreamInfo));
// Set socket option. This line could produce bps calculation problems.
//socket.setSendBufferSize(acknowledgementWindowsize);
break;
case COMMAND_AMF0:
handleRxInvoke((Command) rtmpPacket);
break;
default:
Log.w(TAG, "handleRxPacketLoop(): Not handling unimplemented/unknown packet of type: "
+ rtmpPacket.getHeader().getMessageType());
break;
}
}
} catch (EOFException eof) {
Thread.currentThread().interrupt();
} catch (IOException e) {
connectCheckerRtmp.onConnectionFailedRtmp("Error reading packet: " + e.getMessage());
Log.e(TAG, "Caught SocketException while reading/decoding packet, shutting down: "
+ e.getMessage());
Thread.currentThread().interrupt();
}
}
}
private void handleRxInvoke(Command invoke) {
String commandName = invoke.getCommandName();
switch (commandName) {
case "_error":
try {
String description = ((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty(
"description")).getValue();
Log.i(TAG, description);
if (description.contains("reason=authfail") || description.contains("reason=nosuchuser")) {
connectCheckerRtmp.onAuthErrorRtmp();
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
} else if (user != null && password != null
&& description.contains("challenge=") && description.contains("salt=") //adobe response
|| description.contains("nonce=")) { //llnw response
onAuth = true;
try {
shutdown(false);
} catch (Exception e) {
e.printStackTrace();
}
rtmpSessionInfo.reset();
if (!tlsEnabled) {
socket = new Socket(host, port);
} else {
socket = CreateSSLSocket.createSSlSocket(host, port);
if (socket == null) throw new IOException("Socket creation failed");
}
inputStream = new BufferedInputStream(socket.getInputStream());
outputStream = new BufferedOutputStream(socket.getOutputStream());
Log.d(TAG, "connect(): socket connection established, doing handshake...");
handshake(inputStream, outputStream);
rxPacketHandler = new Thread(new Runnable() {
@Override
public void run() {
handleRxPacketLoop();
}
});
rxPacketHandler.start();
if (description.contains("challenge=") && description.contains("salt=")) { //create adobe auth
String salt = Util.getSalt(description);
String challenge = Util.getChallenge(description);
String opaque = Util.getOpaque(description);
Log.i(TAG, "sending adobe auth response");
sendConnect(getAdobeAuthUserResult(user, password, salt, challenge, opaque));
} else if (description.contains("nonce=")){ //create llnw auth
String nonce = Util.getNonce(description);
Log.i(TAG, "sending llnw auth response");
sendConnect(getLlnwAuthUserResult(user, password, nonce, appName));
}
} else if (description.contains("code=403")) {
if (user != null && password != null) {
// few servers close connection after send code=403
if (socket == null || !socket.getKeepAlive()) {
establishConnection();
}
if (description.contains("authmod=adobe")) {
Log.i(TAG, "sending auth mode adobe");
sendConnect("?authmod=adobe&user=" + user);
return;
} else if (description.contains("authmod=llnw")) {
Log.i(TAG, "sending auth mode llnw");
sendConnect("?authmod=llnw&user=" + user);
return;
}
}
connectCheckerRtmp.onAuthErrorRtmp();
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
} else {
connectCheckerRtmp.onConnectionFailedRtmp(description);
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
}
} catch (Exception e) {
connectCheckerRtmp.onConnectionFailedRtmp(e.getMessage());
connected = false;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
}
break;
case "_result":
// This is the result of one of the methods invoked by us
String method = rtmpSessionInfo.takeInvokedCommand(invoke.getTransactionId());
if (method == null) {
Log.i(TAG, "'_result' message received for unknown method: ");
return;
}
Log.i(TAG, "handleRxInvoke: Got result for invoked method: " + method);
if ("connect".equals(method)) {
if (onAuth) {
connectCheckerRtmp.onAuthSuccessRtmp();
onAuth = false;
}
// Capture server ip/pid/id information if any
// We can now send createStream commands
connected = true;
synchronized (connectingLock) {
connectingLock.notifyAll();
}
} else if ("createStream".contains(method)) {
// Get stream id
currentStreamId = (int) ((AmfNumber) invoke.getData().get(1)).getValue();
Log.d(TAG, "handleRxInvoke(): Stream ID to publish: " + currentStreamId);
if (streamName != null && publishType != null) {
fmlePublish();
}
} else if ("releaseStream".contains(method)) {
Log.d(TAG, "handleRxInvoke(): 'releaseStream'");
} else if ("FCPublish".contains(method)) {
Log.d(TAG, "handleRxInvoke(): 'FCPublish'");
} else {
Log.w(TAG, "handleRxInvoke(): '_result' message received for unknown method: " + method);
}
break;
case "onBWDone":
Log.d(TAG, "handleRxInvoke(): 'onBWDone'");
break;
case "onFCPublish":
Log.d(TAG, "handleRxInvoke(): 'onFCPublish'");
break;
case "onStatus":
String code =
((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty("code")).getValue();
Log.d(TAG, "handleRxInvoke(): onStatus " + code);
switch (code) {
case "NetStream.Publish.Start":
onMetaData();
// We can now publish AV data
publishPermitted = true;
synchronized (publishLock) {
publishLock.notifyAll();
}
break;
case "NetConnection.Connect.Rejected":
netConnectionDescription =
((AmfString) ((AmfObject) invoke.getData().get(1)).getProperty(
"description")).getValue();
publishPermitted = false;
synchronized (publishLock) {
publishLock.notifyAll();
}
break;
case "NetStream.Unpublish.Success":
connectCheckerRtmp.onConnectionFailedRtmp("Unpublish received");
break;
case "NetStream.Publish.BadName":
connectCheckerRtmp.onConnectionFailedRtmp("BadName received, endpoint in use.");
break;
default:
connectCheckerRtmp.onConnectionFailedRtmp("Unknown on status received");
break;
}
break;
default:
Log.e(TAG, "handleRxInvoke(): Unknown/unhandled server invoke: " + invoke);
break;
}
}
private long getConnectionTimeoutMs() {
final long defaultTimeoutMs = 5_000;
if (user != null && password != null) {
// Authorized connection may take about 3 times longer than a regular, that's why the timeout is longer.
return 3 * defaultTimeoutMs;
} else {
return defaultTimeoutMs;
}
}
@Override
public void setVideoResolution(int width, int height) {
videoWidth = width;
videoHeight = height;
}
@Override
public void setAuthorization(String user, String password) {
this.user = user;
this.password = password;
}
public void setLogs(boolean enable) {
isEnableLogs = enable;
}
}
| remove failed callback on Unpublish.Success
| rtmp/src/main/java/com/github/faucamp/simplertmp/io/RtmpConnection.java | remove failed callback on Unpublish.Success | <ide><path>tmp/src/main/java/com/github/faucamp/simplertmp/io/RtmpConnection.java
<ide> publishLock.notifyAll();
<ide> }
<ide> break;
<del> case "NetStream.Unpublish.Success":
<del> connectCheckerRtmp.onConnectionFailedRtmp("Unpublish received");
<del> break;
<ide> case "NetStream.Publish.BadName":
<ide> connectCheckerRtmp.onConnectionFailedRtmp("BadName received, endpoint in use.");
<ide> break; |
|
Java | apache-2.0 | d4d4caa5dcaeba1fb92f0d8ee4a44fcad624d0ec | 0 | BURAI-team/burai | /*
* Copyright (C) 2016 Satomichi Nishihara
*
* This file is distributed under the terms of the
* GNU General Public License. See the file `LICENSE'
* in the root directory of the present distribution,
* or http://www.gnu.org/copyleft/gpl.txt .
*/
package burai.run;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import burai.app.QEFXMain;
import burai.app.path.QEPath;
import burai.com.env.Environments;
import burai.com.file.FileTools;
import burai.input.QEInput;
import burai.project.Project;
import burai.run.parser.LogParser;
public class RunningNode implements Runnable {
private static final RunningType DEFAULT_TYPE = RunningType.SCF;
private boolean alive;
private Project project;
private RunningStatus status;
private List<RunningStatusChanged> onStatusChangedList;
private RunningType type;
private int numProcesses;
private int numThreads;
private Process objProcess;
public RunningNode(Project project) {
if (project == null) {
throw new IllegalArgumentException("project is null.");
}
this.alive = true;
this.project = project;
this.status = RunningStatus.IDLE;
this.onStatusChangedList = null;
this.type = null;
this.numProcesses = 1;
this.numThreads = 1;
this.objProcess = null;
}
public Project getProject() {
return this.project;
}
public synchronized RunningStatus getStatus() {
return this.status;
}
protected synchronized void setStatus(RunningStatus status) {
if (status == null) {
return;
}
this.status = status;
if (this.onStatusChangedList != null) {
for (RunningStatusChanged onStatusChanged : this.onStatusChangedList) {
if (onStatusChanged != null) {
onStatusChanged.onRunningStatusChanged(this.status);
}
}
}
}
public synchronized void addOnStatusChanged(RunningStatusChanged onStatusChanged) {
if (onStatusChanged != null) {
if (this.onStatusChangedList == null) {
this.onStatusChangedList = new ArrayList<RunningStatusChanged>();
}
this.onStatusChangedList.add(onStatusChanged);
}
}
public synchronized void removeOnStatusChanged(RunningStatusChanged onStatusChanged) {
if (onStatusChanged != null) {
if (this.onStatusChangedList != null) {
this.onStatusChangedList.remove(onStatusChanged);
}
}
}
public synchronized RunningType getType() {
return this.type;
}
public synchronized void setType(RunningType type) {
this.type = type;
}
public synchronized int getNumProcesses() {
return this.numProcesses;
}
public synchronized void setNumProcesses(int numProcesses) {
this.numProcesses = numProcesses;
}
public synchronized int getNumThreads() {
return this.numThreads;
}
public synchronized void setNumThreads(int numThreads) {
this.numThreads = numThreads;
}
public synchronized void stop() {
this.alive = false;
if (this.objProcess != null) {
this.objProcess.destroy();
}
}
@Override
public void run() {
synchronized (this) {
if (!this.alive) {
return;
}
}
File directory = this.getDirectory();
if (directory == null) {
return;
}
RunningType type2 = null;
int numProcesses2 = -1;
int numThreads2 = -1;
synchronized (this) {
type2 = this.type;
numProcesses2 = this.numProcesses;
numThreads2 = this.numThreads;
}
if (type2 == null) {
type2 = DEFAULT_TYPE;
}
if (numProcesses2 < 1) {
numProcesses2 = 1;
}
if (numThreads2 < 1) {
numThreads2 = 1;
}
QEInput input = new FXQEInputFactory(type2).getQEInput(this.project);
if (input == null) {
return;
}
String inpName = this.project.getInpFileName();
inpName = inpName == null ? null : inpName.trim();
File inpFile = (inpName == null || inpName.isEmpty()) ? null : new File(directory, inpName);
if (inpFile == null) {
return;
}
List<String[]> commandList = type2.getCommandList(inpName, numProcesses2);
if (commandList == null || commandList.isEmpty()) {
return;
}
List<RunningCondition> conditionList = type2.getConditionList();
if (conditionList == null || conditionList.size() < commandList.size()) {
return;
}
List<InputEditor> inputEditorList = type2.getInputEditorList(this.project);
if (inputEditorList == null || inputEditorList.size() < commandList.size()) {
return;
}
List<LogParser> parserList = type2.getParserList(this.project);
if (parserList == null || parserList.size() < commandList.size()) {
return;
}
List<PostOperation> postList = type2.getPostList();
if (postList == null || postList.size() < commandList.size()) {
return;
}
this.deleteLogFiles(directory);
int iCommand = 0;
ProcessBuilder builder = null;
boolean errOccurred = false;
for (int i = 0; i < commandList.size(); i++) {
synchronized (this) {
if (!this.alive) {
return;
}
}
String[] command = commandList.get(i);
if (command == null || command.length < 1) {
continue;
}
RunningCondition condition = conditionList.get(i);
if (condition == null) {
continue;
}
InputEditor inputEditor = inputEditorList.get(i);
if (inputEditor == null) {
continue;
}
LogParser parser = parserList.get(i);
if (parser == null) {
continue;
}
PostOperation post = postList.get(i);
if (post == null) {
continue;
}
QEInput input2 = inputEditor.editInput(input);
if (input2 == null) {
continue;
}
if (!condition.toRun(this.project, input2)) {
continue;
}
boolean inpStatus = this.writeQEInput(input2, inpFile);
if (!inpStatus) {
continue;
}
String logName = this.project.getLogFileName(iCommand);
logName = logName == null ? null : logName.trim();
File logFile = (logName == null || logName.isEmpty()) ? null : new File(directory, logName);
if (logFile == null) {
continue;
}
String errName = this.project.getErrFileName(iCommand);
errName = errName == null ? null : errName.trim();
File errFile = (errName == null || errName.isEmpty()) ? null : new File(directory, errName);
if (errFile == null) {
continue;
}
builder = new ProcessBuilder();
builder.directory(directory);
builder.command(command);
builder.redirectOutput(logFile);
builder.redirectError(errFile);
builder.environment().put("OMP_NUM_THREADS", Integer.toString(numThreads2));
this.setPathToBuilder(builder);
try {
synchronized (this) {
this.objProcess = builder.start();
}
parser.startParsing(logFile);
if (this.objProcess != null) {
if (this.objProcess.waitFor() != 0) {
errOccurred = true;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
errOccurred = true;
break;
} finally {
synchronized (this) {
this.objProcess = null;
}
parser.endParsing();
}
if (!errOccurred) {
post.operate(this.project);
}
iCommand++;
}
if (!errOccurred) {
type2.setProjectStatus(this.project);
} else {
this.showErrorDialog(builder);
}
}
private File getDirectory() {
String dirPath = this.project.getDirectoryPath();
if (dirPath == null) {
return null;
}
File dirFile = new File(dirPath);
try {
if (!dirFile.isDirectory()) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dirFile;
}
private boolean writeQEInput(QEInput input, File file) {
if (input == null) {
return false;
}
if (file == null) {
return false;
}
String strInput = input.toString();
if (strInput == null) {
return false;
}
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
writer.println(strInput);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}
private void deleteLogFiles(File directory) {
if (directory == null) {
return;
}
final int maxIndex = 9;
for (int i = 0; true; i++) {
String logName = this.project.getLogFileName(i);
logName = logName == null ? null : logName.trim();
if (logName == null || logName.isEmpty()) {
continue;
}
boolean status = false;
try {
File logFile = new File(directory, logName);
if (logFile.exists()) {
status = FileTools.deleteAllFiles(logFile, false);
}
} catch (Exception e) {
e.printStackTrace();
}
if ((!status) && (i > maxIndex)) {
break;
}
}
for (int i = 0; true; i++) {
String errName = this.project.getErrFileName(i);
errName = errName == null ? null : errName.trim();
if (errName == null || errName.isEmpty()) {
continue;
}
boolean status = false;
try {
File errFile = new File(directory, errName);
if (errFile.exists()) {
status = FileTools.deleteAllFiles(errFile, false);
}
} catch (Exception e) {
e.printStackTrace();
}
if ((!status) && (i > maxIndex)) {
break;
}
}
String exitName = this.project.getExitFileName();
exitName = exitName == null ? null : exitName.trim();
if (exitName != null && (!exitName.isEmpty())) {
try {
File exitFile = new File(directory, exitName);
if (exitFile.exists()) {
FileTools.deleteAllFiles(exitFile, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void setPathToBuilder(ProcessBuilder builder) {
if (builder == null) {
return;
}
String delim = null;
if (Environments.isWindows()) {
delim = ";";
} else {
delim = ":";
}
String qePath = QEPath.getPath();
String mpiPath = QEPath.getMPIPath();
String orgPath = builder.environment().get("PATH");
if (orgPath == null) {
orgPath = builder.environment().get("Path");
}
if (orgPath == null) {
orgPath = builder.environment().get("path");
}
String path = null;
if (qePath != null && !(qePath.isEmpty())) {
path = path == null ? qePath : (path + delim + qePath);
}
if (mpiPath != null && !(mpiPath.isEmpty())) {
path = path == null ? mpiPath : (path + delim + mpiPath);
}
if (orgPath != null && !(orgPath.isEmpty())) {
path = path == null ? orgPath : (path + delim + orgPath);
}
if (path != null && !(path.isEmpty())) {
builder.environment().put("PATH", path);
builder.environment().put("Path", path);
builder.environment().put("path", path);
}
}
private void showErrorDialog(ProcessBuilder buider) {
File dirFile = buider == null ? null : buider.directory();
String dirStr = dirFile == null ? null : dirFile.getPath();
if (dirStr != null) {
dirStr = dirStr.trim();
}
final String message1;
if (dirStr == null || dirStr.isEmpty()) {
message1 = "ERROR in running the project.";
} else {
message1 = "ERROR in running the project: " + dirStr;
}
String cmdStr = null;
List<String> cmdList = buider == null ? null : buider.command();
if (cmdList != null) {
for (String cmd : cmdList) {
if (cmd != null) {
cmd = cmd.trim();
}
if (cmd == null || cmd.isEmpty()) {
continue;
}
if (cmdStr == null) {
cmdStr = cmd;
} else {
cmdStr = cmdStr + " " + cmd;
}
}
}
if (cmdStr != null) {
cmdStr = cmdStr.trim();
}
final String message2;
if (cmdStr == null || cmdStr.isEmpty()) {
message2 = "NO COMMAND.";
} else {
message2 = "COMMAND: " + cmdStr;
}
Platform.runLater(() -> {
Alert alert = new Alert(AlertType.ERROR);
QEFXMain.initializeDialogOwner(alert);
alert.setHeaderText(message1);
alert.setContentText(message2);
alert.showAndWait();
});
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
| src/burai/run/RunningNode.java | /*
* Copyright (C) 2016 Satomichi Nishihara
*
* This file is distributed under the terms of the
* GNU General Public License. See the file `LICENSE'
* in the root directory of the present distribution,
* or http://www.gnu.org/copyleft/gpl.txt .
*/
package burai.run;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import burai.app.QEFXMain;
import burai.app.path.QEPath;
import burai.com.env.Environments;
import burai.com.file.FileTools;
import burai.input.QEInput;
import burai.project.Project;
import burai.run.parser.LogParser;
public class RunningNode implements Runnable {
private static final RunningType DEFAULT_TYPE = RunningType.SCF;
private boolean alive;
private Project project;
private RunningStatus status;
private List<RunningStatusChanged> onStatusChangedList;
private RunningType type;
private int numProcesses;
private int numThreads;
private Process objProcess;
public RunningNode(Project project) {
if (project == null) {
throw new IllegalArgumentException("project is null.");
}
this.alive = true;
this.project = project;
this.status = RunningStatus.IDLE;
this.onStatusChangedList = null;
this.type = null;
this.numProcesses = 1;
this.numThreads = 1;
this.objProcess = null;
}
public Project getProject() {
return this.project;
}
public synchronized RunningStatus getStatus() {
return this.status;
}
protected synchronized void setStatus(RunningStatus status) {
if (status == null) {
return;
}
this.status = status;
if (this.onStatusChangedList != null) {
for (RunningStatusChanged onStatusChanged : this.onStatusChangedList) {
if (onStatusChanged != null) {
onStatusChanged.onRunningStatusChanged(this.status);
}
}
}
}
public synchronized void addOnStatusChanged(RunningStatusChanged onStatusChanged) {
if (onStatusChanged != null) {
if (this.onStatusChangedList == null) {
this.onStatusChangedList = new ArrayList<RunningStatusChanged>();
}
this.onStatusChangedList.add(onStatusChanged);
}
}
public synchronized void removeOnStatusChanged(RunningStatusChanged onStatusChanged) {
if (onStatusChanged != null) {
if (this.onStatusChangedList != null) {
this.onStatusChangedList.remove(onStatusChanged);
}
}
}
public synchronized RunningType getType() {
return this.type;
}
public synchronized void setType(RunningType type) {
this.type = type;
}
public synchronized int getNumProcesses() {
return this.numProcesses;
}
public synchronized void setNumProcesses(int numProcesses) {
this.numProcesses = numProcesses;
}
public synchronized int getNumThreads() {
return this.numThreads;
}
public synchronized void setNumThreads(int numThreads) {
this.numThreads = numThreads;
}
public synchronized void stop() {
this.alive = false;
if (this.objProcess != null) {
this.objProcess.destroy();
}
}
@Override
public void run() {
synchronized (this) {
if (!this.alive) {
return;
}
}
File directory = this.getDirectory();
if (directory == null) {
return;
}
RunningType type2 = null;
int numProcesses2 = -1;
int numThreads2 = -1;
synchronized (this) {
type2 = this.type;
numProcesses2 = this.numProcesses;
numThreads2 = this.numThreads;
}
if (type2 == null) {
type2 = DEFAULT_TYPE;
}
if (numProcesses2 < 1) {
numProcesses2 = 1;
}
if (numThreads2 < 1) {
numThreads2 = 1;
}
QEInput input = new FXQEInputFactory(type2).getQEInput(this.project);
if (input == null) {
return;
}
String inpName = this.project.getInpFileName();
inpName = inpName == null ? null : inpName.trim();
File inpFile = (inpName == null || inpName.isEmpty()) ? null : new File(directory, inpName);
if (inpFile == null) {
return;
}
List<String[]> commandList = type2.getCommandList(inpName, numProcesses2);
if (commandList == null || commandList.isEmpty()) {
return;
}
List<RunningCondition> conditionList = type2.getConditionList();
if (conditionList == null || conditionList.size() < commandList.size()) {
return;
}
List<InputEditor> inputEditorList = type2.getInputEditorList(this.project);
if (inputEditorList == null || inputEditorList.size() < commandList.size()) {
return;
}
List<LogParser> parserList = type2.getParserList(this.project);
if (parserList == null || parserList.size() < commandList.size()) {
return;
}
List<PostOperation> postList = type2.getPostList();
if (postList == null || postList.size() < commandList.size()) {
return;
}
this.deleteLogFiles(directory);
int iCommand = 0;
ProcessBuilder builder = null;
boolean errOccurred = false;
for (int i = 0; i < commandList.size(); i++) {
synchronized (this) {
if (!this.alive) {
return;
}
}
String[] command = commandList.get(i);
if (command == null || command.length < 1) {
continue;
}
RunningCondition condition = conditionList.get(i);
if (condition == null) {
continue;
}
InputEditor inputEditor = inputEditorList.get(i);
if (inputEditor == null) {
continue;
}
LogParser parser = parserList.get(i);
if (parser == null) {
continue;
}
PostOperation post = postList.get(i);
if (post == null) {
continue;
}
QEInput input2 = inputEditor.editInput(input);
if (input2 == null) {
continue;
}
if (!condition.toRun(this.project, input2)) {
continue;
}
boolean inpStatus = this.writeQEInput(input2, inpFile);
if (!inpStatus) {
continue;
}
String logName = this.project.getLogFileName(iCommand);
logName = logName == null ? null : logName.trim();
File logFile = (logName == null || logName.isEmpty()) ? null : new File(directory, logName);
if (logFile == null) {
continue;
}
String errName = this.project.getErrFileName(iCommand);
errName = errName == null ? null : errName.trim();
File errFile = (errName == null || errName.isEmpty()) ? null : new File(directory, errName);
if (errFile == null) {
continue;
}
builder = new ProcessBuilder();
builder.directory(directory);
builder.command(command);
builder.redirectOutput(logFile);
builder.redirectError(errFile);
builder.environment().put("OMP_NUM_THREADS", Integer.toString(numThreads2));
this.setPathToBuilder(builder);
try {
synchronized (this) {
this.objProcess = builder.start();
}
parser.startParsing(logFile);
if (this.objProcess != null) {
if (this.objProcess.waitFor() != 0) {
errOccurred = true;
break;
}
}
} catch (Exception e) {
e.printStackTrace();
errOccurred = true;
break;
} finally {
synchronized (this) {
this.objProcess = null;
}
parser.endParsing();
}
if (!errOccurred) {
post.operate(this.project);
}
iCommand++;
}
if (!errOccurred) {
type2.setProjectStatus(this.project);
} else {
this.showErrorDialog(builder);
}
}
private File getDirectory() {
String dirPath = this.project.getDirectoryPath();
if (dirPath == null) {
return null;
}
File dirFile = new File(dirPath);
try {
if (!dirFile.isDirectory()) {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return dirFile;
}
private boolean writeQEInput(QEInput input, File file) {
if (input == null) {
return false;
}
if (file == null) {
return false;
}
String strInput = input.toString();
if (strInput == null) {
return false;
}
PrintWriter writer = null;
try {
writer = new PrintWriter(new BufferedWriter(new FileWriter(file)));
writer.println(strInput);
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}
private void deleteLogFiles(File directory) {
if (directory == null) {
return;
}
final int maxIndex = 9;
for (int i = 0; true; i++) {
String logName = this.project.getLogFileName(i);
logName = logName == null ? null : logName.trim();
if (logName == null || logName.isEmpty()) {
continue;
}
boolean status = false;
try {
File logFile = new File(directory, logName);
if (logFile.exists()) {
status = FileTools.deleteAllFiles(logFile, false);
}
} catch (Exception e) {
e.printStackTrace();
}
if ((!status) && (i > maxIndex)) {
break;
}
}
for (int i = 0; true; i++) {
String errName = this.project.getErrFileName(i);
errName = errName == null ? null : errName.trim();
if (errName == null || errName.isEmpty()) {
continue;
}
boolean status = false;
try {
File errFile = new File(directory, errName);
if (errFile.exists()) {
status = FileTools.deleteAllFiles(errFile, false);
}
} catch (Exception e) {
e.printStackTrace();
}
if ((!status) && (i > maxIndex)) {
break;
}
}
String exitName = this.project.getExitFileName();
exitName = exitName == null ? null : exitName.trim();
if (exitName != null && (!exitName.isEmpty())) {
try {
File exitFile = new File(directory, exitName);
if (exitFile.exists()) {
FileTools.deleteAllFiles(exitFile, false);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private void setPathToBuilder(ProcessBuilder builder) {
if (builder == null) {
return;
}
String delim = null;
if (Environments.isWindows()) {
delim = ";";
} else {
delim = ":";
}
String qePath = QEPath.getPath();
String mpiPath = QEPath.getMPIPath();
String orgPath = builder.environment().get("PATH");
if (orgPath == null) {
orgPath = builder.environment().get("Path");
}
if (orgPath == null) {
orgPath = builder.environment().get("path");
}
String path = null;
if (qePath != null && !(qePath.isEmpty())) {
path = path == null ? qePath : (path + delim + qePath);
}
if (mpiPath != null && !(mpiPath.isEmpty())) {
path = path == null ? mpiPath : (path + delim + mpiPath);
}
if (orgPath != null && !(orgPath.isEmpty())) {
path = path == null ? orgPath : (path + delim + orgPath);
}
if (path != null && !(path.isEmpty())) {
builder.environment().put("PATH", path);
builder.environment().put("Path", path);
builder.environment().put("path", path);
}
}
private void showErrorDialog(ProcessBuilder buider) {
File dirFile = buider == null ? null : buider.directory();
String dirStr = dirFile == null ? null : dirFile.getPath();
if (dirStr != null) {
dirStr = dirStr.trim();
}
final String message1;
if (dirStr == null || dirStr.isEmpty()) {
message1 = "Error in running the project.";
} else {
message1 = "Error in running the project: " + dirStr;
}
String cmdStr = null;
List<String> cmdList = buider == null ? null : buider.command();
if (cmdList != null) {
for (String cmd : cmdList) {
if (cmd != null) {
cmd = cmd.trim();
}
if (cmd == null || cmd.isEmpty()) {
continue;
}
if (cmdStr == null) {
cmdStr = cmd;
} else {
cmdStr = cmdStr + " " + cmd;
}
}
}
if (cmdStr != null) {
cmdStr = cmdStr.trim();
}
final String message2;
if (cmdStr == null || cmdStr.isEmpty()) {
message2 = "Cannot execute command.";
} else {
message2 = "Cannot execute: " + cmdStr;
}
Platform.runLater(() -> {
Alert alert = new Alert(AlertType.ERROR);
QEFXMain.initializeDialogOwner(alert);
alert.setHeaderText(message1);
alert.setContentText(message2);
alert.showAndWait();
});
}
@Override
public int hashCode() {
return 0;
}
@Override
public boolean equals(Object obj) {
return this == obj;
}
}
| change error message of RunningNode | src/burai/run/RunningNode.java | change error message of RunningNode | <ide><path>rc/burai/run/RunningNode.java
<ide>
<ide> final String message1;
<ide> if (dirStr == null || dirStr.isEmpty()) {
<del> message1 = "Error in running the project.";
<add> message1 = "ERROR in running the project.";
<ide> } else {
<del> message1 = "Error in running the project: " + dirStr;
<add> message1 = "ERROR in running the project: " + dirStr;
<ide> }
<ide>
<ide> String cmdStr = null;
<ide>
<ide> final String message2;
<ide> if (cmdStr == null || cmdStr.isEmpty()) {
<del> message2 = "Cannot execute command.";
<add> message2 = "NO COMMAND.";
<ide> } else {
<del> message2 = "Cannot execute: " + cmdStr;
<add> message2 = "COMMAND: " + cmdStr;
<ide> }
<ide>
<ide> Platform.runLater(() -> { |
|
Java | apache-2.0 | 49013e2f8d9a54ae7ff7d426f9d3117561fddd06 | 0 | sirkkalap/DependencyCheck,sirkkalap/DependencyCheck,sirkkalap/DependencyCheck,sirkkalap/DependencyCheck,sirkkalap/DependencyCheck | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.InvalidAlgorithmParameterException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
/**
* A utility to download files from the Internet.
*
* @author Jeremy Long <[email protected]>
*/
public final class Downloader {
/**
* The logger.
*/
private static final Logger LOGGER = Logger.getLogger(Downloader.class.getName());
/**
* Private constructor for utility class.
*/
private Downloader() {
}
/**
* Retrieves a file from a given URL and saves it to the outputPath.
*
* @param url the URL of the file to download
* @param outputPath the path to the save the file to
* @throws DownloadFailedException is thrown if there is an error downloading the file
*/
public static void fetchFile(URL url, File outputPath) throws DownloadFailedException {
fetchFile(url, outputPath, true);
}
/**
* Retrieves a file from a given URL and saves it to the outputPath.
*
* @param url the URL of the file to download
* @param outputPath the path to the save the file to
* @param useProxy whether to use the configured proxy when downloading files
* @throws DownloadFailedException is thrown if there is an error downloading the file
*/
public static void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException {
if ("file".equalsIgnoreCase(url.getProtocol())) {
File file;
try {
file = new File(url.toURI());
} catch (URISyntaxException ex) {
final String msg = String.format("Download failed, unable to locate '%s'", url.toString());
throw new DownloadFailedException(msg);
}
if (file.exists()) {
try {
org.apache.commons.io.FileUtils.copyFile(file, outputPath);
} catch (IOException ex) {
final String msg = String.format("Download failed, unable to copy '%s' to '%s'", url.toString(), outputPath.getAbsolutePath());
throw new DownloadFailedException(msg);
}
} else {
final String msg = String.format("Download failed, file ('%s') does not exist", url.toString());
throw new DownloadFailedException(msg);
}
} else {
HttpURLConnection conn = null;
try {
conn = URLConnectionFactory.createHttpURLConnection(url, useProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
} catch (IOException ex) {
try {
if (conn != null) {
conn.disconnect();
}
} finally {
conn = null;
}
final String msg = String.format("Error downloading file %s; unable to connect.", url.toString());
throw new DownloadFailedException(msg, ex);
}
final String encoding = conn.getContentEncoding();
BufferedOutputStream writer = null;
InputStream reader = null;
try {
if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
reader = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
reader = new InflaterInputStream(conn.getInputStream());
} else {
reader = conn.getInputStream();
}
writer = new BufferedOutputStream(new FileOutputStream(outputPath));
final byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
analyzeException(ex);
final String msg = String.format("Error saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
} catch (Throwable ex) {
final String msg = String.format("Unexpected exception saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST,
"Error closing the writer in Downloader.", ex);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST,
"Error closing the reader in Downloader.", ex);
}
}
try {
conn.disconnect();
} finally {
conn = null;
}
}
}
}
/**
* Makes an HTTP Head request to retrieve the last modified date of the given URL. If the file:// protocol is
* specified, then the lastTimestamp of the file is returned.
*
* @param url the URL to retrieve the timestamp from
* @return an epoch timestamp
* @throws DownloadFailedException is thrown if an exception occurs making the HTTP request
*/
public static long getLastModified(URL url) throws DownloadFailedException {
long timestamp = 0;
//TODO add the FTP protocol?
if ("file".equalsIgnoreCase(url.getProtocol())) {
File lastModifiedFile;
try {
lastModifiedFile = new File(url.toURI());
} catch (URISyntaxException ex) {
final String msg = String.format("Unable to locate '%s'", url.toString());
throw new DownloadFailedException(msg);
}
timestamp = lastModifiedFile.lastModified();
} else {
HttpURLConnection conn = null;
try {
conn = URLConnectionFactory.createHttpURLConnection(url);
conn.setRequestMethod("HEAD");
conn.connect();
final int t = conn.getResponseCode();
if (t >= 200 && t < 300) {
timestamp = conn.getLastModified();
} else {
throw new DownloadFailedException("HEAD request returned a non-200 status code");
}
} catch (URLConnectionFailureException ex) {
throw new DownloadFailedException("Error creating URL Connection for HTTP HEAD request.", ex);
} catch (IOException ex) {
analyzeException(ex);
throw new DownloadFailedException("Error making HTTP HEAD request.", ex);
} finally {
if (conn != null) {
try {
conn.disconnect();
} finally {
conn = null;
}
}
}
}
return timestamp;
}
protected static void analyzeException(IOException ex) throws DownloadFailedException {
Throwable cause = ex;
do {
if (cause instanceof InvalidAlgorithmParameterException) {
String keystore = System.getProperty("javax.net.ssl.keyStore");
String version = System.getProperty("java.version");
String vendor = System.getProperty("java.vendor");
LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException");
LOGGER.info("There appears to be an issue with the installation of Java and the cacerts."
+ "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177");
LOGGER.info(String.format("Java Info:%njavax.net.ssl.keyStore='%s'%njava.version='%s'%njava.vendor='%s'",
keystore, version, vendor));
throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details.");
}
cause = cause.getCause();
} while (cause.getCause() != null);
}
}
| dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java | /*
* This file is part of dependency-check-core.
*
* 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.
*
* Copyright (c) 2012 Jeremy Long. All Rights Reserved.
*/
package org.owasp.dependencycheck.utils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
/**
* A utility to download files from the Internet.
*
* @author Jeremy Long <[email protected]>
*/
public final class Downloader {
/**
* The logger.
*/
private static final Logger LOGGER = Logger.getLogger(Downloader.class.getName());
/**
* Private constructor for utility class.
*/
private Downloader() {
}
/**
* Retrieves a file from a given URL and saves it to the outputPath.
*
* @param url the URL of the file to download
* @param outputPath the path to the save the file to
* @throws DownloadFailedException is thrown if there is an error downloading the file
*/
public static void fetchFile(URL url, File outputPath) throws DownloadFailedException {
fetchFile(url, outputPath, true);
}
/**
* Retrieves a file from a given URL and saves it to the outputPath.
*
* @param url the URL of the file to download
* @param outputPath the path to the save the file to
* @param useProxy whether to use the configured proxy when downloading files
* @throws DownloadFailedException is thrown if there is an error downloading the file
*/
public static void fetchFile(URL url, File outputPath, boolean useProxy) throws DownloadFailedException {
if ("file".equalsIgnoreCase(url.getProtocol())) {
File file;
try {
file = new File(url.toURI());
} catch (URISyntaxException ex) {
final String msg = String.format("Download failed, unable to locate '%s'", url.toString());
throw new DownloadFailedException(msg);
}
if (file.exists()) {
try {
org.apache.commons.io.FileUtils.copyFile(file, outputPath);
} catch (IOException ex) {
final String msg = String.format("Download failed, unable to copy '%s' to '%s'", url.toString(), outputPath.getAbsolutePath());
throw new DownloadFailedException(msg);
}
} else {
final String msg = String.format("Download failed, file ('%s') does not exist", url.toString());
throw new DownloadFailedException(msg);
}
} else {
HttpURLConnection conn = null;
try {
conn = URLConnectionFactory.createHttpURLConnection(url, useProxy);
conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
conn.connect();
} catch (IOException ex) {
try {
if (conn != null) {
conn.disconnect();
}
} finally {
conn = null;
}
final String msg = String.format("Error downloading file %s; unable to connect.", url.toString());
throw new DownloadFailedException(msg, ex);
}
final String encoding = conn.getContentEncoding();
BufferedOutputStream writer = null;
InputStream reader = null;
try {
if (encoding != null && "gzip".equalsIgnoreCase(encoding)) {
reader = new GZIPInputStream(conn.getInputStream());
} else if (encoding != null && "deflate".equalsIgnoreCase(encoding)) {
reader = new InflaterInputStream(conn.getInputStream());
} else {
reader = conn.getInputStream();
}
writer = new BufferedOutputStream(new FileOutputStream(outputPath));
final byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = reader.read(buffer)) > 0) {
writer.write(buffer, 0, bytesRead);
}
} catch (IOException ex) {
final String msg = String.format("Error saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
} catch (Throwable ex) {
final String msg = String.format("Unexpected exception saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
throw new DownloadFailedException(msg, ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST,
"Error closing the writer in Downloader.", ex);
}
}
if (reader != null) {
try {
reader.close();
} catch (IOException ex) {
LOGGER.log(Level.FINEST,
"Error closing the reader in Downloader.", ex);
}
}
try {
conn.disconnect();
} finally {
conn = null;
}
}
}
}
/**
* Makes an HTTP Head request to retrieve the last modified date of the given URL. If the file:// protocol is
* specified, then the lastTimestamp of the file is returned.
*
* @param url the URL to retrieve the timestamp from
* @return an epoch timestamp
* @throws DownloadFailedException is thrown if an exception occurs making the HTTP request
*/
public static long getLastModified(URL url) throws DownloadFailedException {
long timestamp = 0;
//TODO add the FTP protocol?
if ("file".equalsIgnoreCase(url.getProtocol())) {
File lastModifiedFile;
try {
lastModifiedFile = new File(url.toURI());
} catch (URISyntaxException ex) {
final String msg = String.format("Unable to locate '%s'", url.toString());
throw new DownloadFailedException(msg);
}
timestamp = lastModifiedFile.lastModified();
} else {
HttpURLConnection conn = null;
try {
conn = URLConnectionFactory.createHttpURLConnection(url);
conn.setRequestMethod("HEAD");
conn.connect();
final int t = conn.getResponseCode();
if (t >= 200 && t < 300) {
timestamp = conn.getLastModified();
} else {
throw new DownloadFailedException("HEAD request returned a non-200 status code");
}
} catch (URLConnectionFailureException ex) {
throw new DownloadFailedException("Error creating URL Connection for HTTP HEAD request.", ex);
} catch (IOException ex) {
throw new DownloadFailedException("Error making HTTP HEAD request.", ex);
} finally {
if (conn != null) {
try {
conn.disconnect();
} finally {
conn = null;
}
}
}
}
return timestamp;
}
}
| improved error reporting to assist users dealing with issue #177
| dependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java | improved error reporting to assist users dealing with issue #177 | <ide><path>ependency-check-utils/src/main/java/org/owasp/dependencycheck/utils/Downloader.java
<ide> import java.net.HttpURLConnection;
<ide> import java.net.URISyntaxException;
<ide> import java.net.URL;
<add>import java.security.InvalidAlgorithmParameterException;
<ide> import java.util.logging.Level;
<ide> import java.util.logging.Logger;
<ide> import java.util.zip.GZIPInputStream;
<ide> writer.write(buffer, 0, bytesRead);
<ide> }
<ide> } catch (IOException ex) {
<add> analyzeException(ex);
<ide> final String msg = String.format("Error saving '%s' to file '%s'%nConnection Timeout: %d%nEncoding: %s%n",
<ide> url.toString(), outputPath.getAbsolutePath(), conn.getConnectTimeout(), encoding);
<ide> throw new DownloadFailedException(msg, ex);
<ide> } catch (URLConnectionFailureException ex) {
<ide> throw new DownloadFailedException("Error creating URL Connection for HTTP HEAD request.", ex);
<ide> } catch (IOException ex) {
<add> analyzeException(ex);
<ide> throw new DownloadFailedException("Error making HTTP HEAD request.", ex);
<ide> } finally {
<ide> if (conn != null) {
<ide> }
<ide> return timestamp;
<ide> }
<add>
<add> protected static void analyzeException(IOException ex) throws DownloadFailedException {
<add> Throwable cause = ex;
<add> do {
<add> if (cause instanceof InvalidAlgorithmParameterException) {
<add> String keystore = System.getProperty("javax.net.ssl.keyStore");
<add> String version = System.getProperty("java.version");
<add> String vendor = System.getProperty("java.vendor");
<add> LOGGER.info("Error making HTTPS request - InvalidAlgorithmParameterException");
<add> LOGGER.info("There appears to be an issue with the installation of Java and the cacerts."
<add> + "See closed issue #177 here: https://github.com/jeremylong/DependencyCheck/issues/177");
<add> LOGGER.info(String.format("Java Info:%njavax.net.ssl.keyStore='%s'%njava.version='%s'%njava.vendor='%s'",
<add> keystore, version, vendor));
<add> throw new DownloadFailedException("Error making HTTPS request. Please see the log for more details.");
<add> }
<add> cause = cause.getCause();
<add> } while (cause.getCause() != null);
<add> }
<ide> } |
|
Java | apache-2.0 | error: pathspec 'Java_OOP/src/org/Liuxy/SHA.java' did not match any file(s) known to git
| e7add6ae6f048fad00bb9a5cd5bc40a645565534 | 1 | Liuxyly/Java_Learning,Liuxyly/Java_Learning | package org.Liuxy;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* SHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应用中重要的工具,
* 被广泛地应用于电子商务等信息安全领域。虽然,SHA与MD通过碰撞法都被破解了, 但是SHA仍然是公认的安全加密算法,较之MD更为安全
*/
public class SHA {
public static final String KEY_SHA = "SHA";
public static String getResult(String inputStr) {
BigInteger sha = null;
System.out.println("=======加密前的数据:" + inputStr);
byte[] inputData = inputStr.getBytes();
try {
MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA);
messageDigest.update(inputData);
sha = new BigInteger(messageDigest.digest());
System.out.println("SHA加密后:" + sha.toString());
} catch (Exception e) {
e.printStackTrace();
}
return sha.toString();
}
public static void main(String args[]) {
Encrypt en = new Encrypt();
try {
String inputStr = "简单加密";
inputStr.equals(inputStr);
System.out.println(en.SHA512(inputStr));
// getResult(inputStr);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class Encrypt
{
/**
* 传入文本内容,返回 SHA-256 串
*
* @param strText
* @return
*/
public String SHA256(final String strText)
{
return SHA(strText, "SHA-256");
}
/**
* 传入文本内容,返回 SHA-512 串
*
* @param strText
* @return
*/
public String SHA512(final String strText)
{
return SHA(strText, "SHA-512");
}
/**
* 字符串 SHA 加密
*
* @param strSourceText
* @return
*/
private String SHA(final String strText, final String strType)
{
// 返回值
String strResult = null;
// 是否是有效字符串
if (strText != null && strText.length() > 0)
{
try
{
// SHA 加密开始
// 创建加密对象 并傳入加密類型
MessageDigest messageDigest = MessageDigest.getInstance(strType);
// 传入要加密的字符串
messageDigest.update(strText.getBytes());
// 得到 byte 類型结果
byte byteBuffer[] = messageDigest.digest();
// 將 byte 轉換爲 string
StringBuffer strHexString = new StringBuffer();
// 遍歷 byte buffer
for (int i = 0; i < byteBuffer.length; i++)
{
String hex = Integer.toHexString(0xff & byteBuffer[i]);
if (hex.length() == 1)
{
strHexString.append('0');
}
strHexString.append(hex);
}
// 得到返回結果
strResult = strHexString.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
}
return strResult;
}
}
| Java_OOP/src/org/Liuxy/SHA.java | SHA-256
SHA-256的使用 | Java_OOP/src/org/Liuxy/SHA.java | SHA-256 | <ide><path>ava_OOP/src/org/Liuxy/SHA.java
<add>package org.Liuxy;
<add>
<add>import java.math.BigInteger;
<add>import java.security.MessageDigest;
<add>import java.security.NoSuchAlgorithmException;
<add>
<add>/**
<add> * SHA(Secure Hash Algorithm,安全散列算法),数字签名等密码学应用中重要的工具,
<add> * 被广泛地应用于电子商务等信息安全领域。虽然,SHA与MD通过碰撞法都被破解了, 但是SHA仍然是公认的安全加密算法,较之MD更为安全
<add> */
<add>
<add>public class SHA {
<add> public static final String KEY_SHA = "SHA";
<add>
<add> public static String getResult(String inputStr) {
<add> BigInteger sha = null;
<add> System.out.println("=======加密前的数据:" + inputStr);
<add> byte[] inputData = inputStr.getBytes();
<add> try {
<add> MessageDigest messageDigest = MessageDigest.getInstance(KEY_SHA);
<add> messageDigest.update(inputData);
<add> sha = new BigInteger(messageDigest.digest());
<add> System.out.println("SHA加密后:" + sha.toString());
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> }
<add> return sha.toString();
<add> }
<add>
<add> public static void main(String args[]) {
<add> Encrypt en = new Encrypt();
<add> try {
<add> String inputStr = "简单加密";
<add> inputStr.equals(inputStr);
<add> System.out.println(en.SHA512(inputStr));
<add>// getResult(inputStr);
<add> } catch (Exception e) {
<add> e.printStackTrace();
<add> }
<add> }
<add>}
<add>
<add>class Encrypt
<add>{
<add>
<add> /**
<add> * 传入文本内容,返回 SHA-256 串
<add> *
<add> * @param strText
<add> * @return
<add> */
<add> public String SHA256(final String strText)
<add> {
<add> return SHA(strText, "SHA-256");
<add> }
<add>
<add> /**
<add> * 传入文本内容,返回 SHA-512 串
<add> *
<add> * @param strText
<add> * @return
<add> */
<add> public String SHA512(final String strText)
<add> {
<add> return SHA(strText, "SHA-512");
<add> }
<add>
<add> /**
<add> * 字符串 SHA 加密
<add> *
<add> * @param strSourceText
<add> * @return
<add> */
<add> private String SHA(final String strText, final String strType)
<add> {
<add> // 返回值
<add> String strResult = null;
<add>
<add> // 是否是有效字符串
<add> if (strText != null && strText.length() > 0)
<add> {
<add> try
<add> {
<add> // SHA 加密开始
<add> // 创建加密对象 并傳入加密類型
<add> MessageDigest messageDigest = MessageDigest.getInstance(strType);
<add> // 传入要加密的字符串
<add> messageDigest.update(strText.getBytes());
<add> // 得到 byte 類型结果
<add> byte byteBuffer[] = messageDigest.digest();
<add>
<add> // 將 byte 轉換爲 string
<add> StringBuffer strHexString = new StringBuffer();
<add> // 遍歷 byte buffer
<add> for (int i = 0; i < byteBuffer.length; i++)
<add> {
<add> String hex = Integer.toHexString(0xff & byteBuffer[i]);
<add> if (hex.length() == 1)
<add> {
<add> strHexString.append('0');
<add> }
<add> strHexString.append(hex);
<add> }
<add> // 得到返回結果
<add> strResult = strHexString.toString();
<add> }
<add> catch (NoSuchAlgorithmException e)
<add> {
<add> e.printStackTrace();
<add> }
<add> }
<add>
<add> return strResult;
<add> }
<add>} |
|
Java | lgpl-2.1 | 5505c66109a0498805407f08a961880cc8d31efe | 0 | vaibhav345/lenskit,binweiwu/lenskit,blankazucenalg/lenskit,aglne/lenskit,vaibhav345/lenskit,kluver/lenskit,kluver/lenskit,vaibhav345/lenskit,kluver/lenskit,linjunleo/lenskit,kluver/lenskit,amaliujia/lenskit,vijayvani/Lenskit,aglne/lenskit,tajinder-txstate/lenskit,chrysalag/lenskit,tajinder-txstate/lenskit,amaliujia/lenskit,tajinder-txstate/lenskit,martinlaz/lenskit,vaibhav345/lenskit,binweiwu/lenskit,vijayvani/Lenskit,chrysalag/lenskit,martinlaz/lenskit,linjunleo/lenskit,blankazucenalg/lenskit,tajinder-txstate/lenskit,kluver/lenskit | /*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program 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 program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.lenskit.vectors;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterators;
import com.google.common.primitives.Longs;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.doubles.DoubleCollection;
import it.unimi.dsi.fastutil.doubles.DoubleIterator;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.longs.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.grouplens.lenskit.collections.*;
import org.grouplens.lenskit.symbols.Symbol;
import javax.annotation.Nonnull;
import java.io.Serializable;
import java.util.*;
/**
* Read-only interface to sparse vectors.
*
* <p>
* This vector class works a lot like a map, but it also caches some
* commonly-used statistics. The values are stored in parallel arrays sorted by
* key. This allows fast lookup and sorted iteration. All iterators access the
* items in key order.
*
* <p>
* Vectors have a <i>key domain</i>, which is a set containing all valid keys in
* the vector. This key domain is fixed at construction; mutable vectors cannot
* set values for keys not in this domain. Thinking of the vector as a function
* from longs to doubles, the key domain would actually be the codomain, and the
* key set the algebraic domain, but that gets cumbersome to write in code. So
* think of the key domain as the domain from which valid keys are drawn.
*
* <p>
* This class provides a <em>read-only</em> interface to sparse vectors. It may
* actually be a {@link MutableSparseVector}, so the data may be modified by
* code elsewhere that has access to the mutable representation. For sparse
* vectors that are guaranteed to be unchanging, see
* {@link ImmutableSparseVector}.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
* @compat Public
*/
public abstract class SparseVector implements Iterable<VectorEntry>, Serializable {
private static final long serialVersionUID = 1L;
final long[] keys;
final BitSet usedKeys;
double[] values;
final int domainSize; // How much of the key space is actually used by this vector.
/**
* Construct a new vector from existing arrays. It is assumed that the keys
* are sorted and duplicate-free, and that the values array is the same length. The
* key array is the key domain, and all keys are considered used.
* No new keys can be added to this vector. Clients should call
* the wrap() method rather than directly calling this constructor.
*
* @param ks The array of keys backing this vector. They must be sorted.
* @param vs The array of values backing this vector.
*/
// hard to test because it's not used externally
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
SparseVector(long[] ks, double[] vs) {
this(ks, vs, ks.length);
}
/**
* Construct a new vector from existing arrays. It is assumed that
* the keys are sorted and duplicate-free, and that the keys and
* values both have at least {@var length} items. The key set
* and key domain are both set to the keys array. Clients should
* call the wrap() method rather than directly calling this
* constructor.
*
* @param ks The array of keys backing the vector. It must be sorted.
* @param vs The array of values backing the vector.
* @param length Number of items to actually use.
*/
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
SparseVector(long[] ks, double[] vs, int length) {
Preconditions.checkArgument(MoreArrays.isSorted(ks, 0, length),
"The input array of keys must be in sorted order.");
keys = ks;
values = vs;
domainSize = length;
usedKeys = new BitSet(length);
for (int i = 0; i < length; i++) {
usedKeys.set(i);
}
}
/**
* Construct a new vector from existing arrays. It is assumed that
* the keys are sorted and duplicate-free, and that the keys and
* values both have at least {@var length} items. The key set
* and key domain are both set to the keys array. Clients should
* call the wrap() method rather than directly calling this
* constructor.
*
* @param ks The array of keys backing the vector. It must be sorted.
* @param vs The array of values backing the vector.
* @param length Number of items to actually use.
* @param used The used entry set.
*/
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
SparseVector(long[] ks, double[] vs, int length, BitSet used) {
Preconditions.checkArgument(MoreArrays.isSorted(ks, 0, length),
"The input array of keys must be in sorted order.");
keys = ks;
values = vs;
domainSize = length;
usedKeys = used;
}
/**
* Construct a new vector from the contents of a map. The key domain is the
* key set of the map. Therefore, no new keys can be added to this vector.
*
* @param keyValueMap A map providing the values for the vector.
*/
SparseVector(Long2DoubleMap keyValueMap) {
keys = keyValueMap.keySet().toLongArray();
domainSize = keys.length;
Arrays.sort(keys);
// untestable assertions, assuming Arrays works.
assert keys.length == keyValueMap.size();
assert MoreArrays.isSorted(keys, 0, domainSize);
values = new double[keys.length];
final int len = keys.length;
for (int i = 0; i < len; i++) {
values[i] = keyValueMap.get(keys[i]);
}
usedKeys = new BitSet(domainSize);
usedKeys.set(0, domainSize);
}
/**
* Construct a new empty vector with the specified key domain.
*
* @param domain The key domain.
*/
SparseVector(Collection<Long> domain) {
LongSortedArraySet set;
// since LSAS is immutable, we'll use its array if we can!
if (domain instanceof LongSortedArraySet) {
set = (LongSortedArraySet) domain;
} else {
set = new LongSortedArraySet(domain);
}
keys = set.unsafeArray();
domainSize = domain.size();
values = new double[domainSize];
usedKeys = new BitSet(domainSize);
}
/**
* Find the index of a particular key.
*
* @param key The key to search for.
* @return The index, or a negative value if the key is not in the key domain.
*/
protected int findIndex(long key) {
return Arrays.binarySearch(keys, 0, domainSize, key);
}
/**
* Query whether the vector contains an entry for the key in question.
*
* @param key The key to search for.
* @return {@code true} if the key exists.
*/
public boolean containsKey(long key) {
final int idx = findIndex(key);
return idx >= 0 && usedKeys.get(idx);
}
/**
* Get the value for {@var key}.
*
* @param key the key to look up
* @return the key's value (or {@link Double#NaN} if no such value
* exists)
* @see #get(long, double)
*/
public double get(long key) {
return get(key, Double.NaN);
}
/**
* Get the value for {@var key}.
*
* @param key the key to look up
* @param dft The value to return if the key is not in the vector
* @return the value (or {@var dft} if the key is not set to a value)
*/
public double get(long key, double dft) {
final int idx = findIndex(key);
if (idx >= 0 && usedKeys.get(idx)) {
return values[idx];
} else {
return dft;
}
}
/**
* Get the value for the entry's key.
*
* @param entry A {@code VectorEntry} with the key to look up
* @return the key's value (or {@link Double#NaN} if no such value exists)
*/
public double get(VectorEntry entry) {
final SparseVector evec = entry.getVector();
final int eind = entry.getIndex();
if (evec == null) {
throw new IllegalArgumentException("entry is not associated with a vector");
} else if (evec.keys != this.keys) {
throw new IllegalArgumentException("entry does not have safe key domain");
} else if (entry.getKey() != keys[eind]) {
throw new IllegalArgumentException("entry does not have the correct key for its index");
}
if (usedKeys.get(eind)) {
return values[eind];
} else {
return Double.NaN;
}
}
//region Iterators
/**
* Fast iterator over all set entries (it can reuse entry objects).
*
* @return a fast iterator over all key/value pairs
* @see #fastIterator(VectorEntry.State)
* @see it.unimi.dsi.fastutil.longs.Long2DoubleMap.FastEntrySet#fastIterator()
* Long2DoubleMap.FastEntrySet.fastIterator()
*/
public Iterator<VectorEntry> fastIterator() {
return fastIterator(VectorEntry.State.SET);
}
/**
* Fast iterator over entries (it can reuse entry objects).
*
* @param state The state of entries to iterate.
* @return a fast iterator over all key/value pairs
* @see it.unimi.dsi.fastutil.longs.Long2DoubleMap.FastEntrySet#fastIterator()
* Long2DoubleMap.FastEntrySet.fastIterator()
* @since 0.11
*/
public Iterator<VectorEntry> fastIterator(VectorEntry.State state) {
IntIterator iter;
switch (state) {
case SET:
iter = new BitSetIterator(usedKeys, 0, domainSize);
break;
case UNSET: {
BitSet unused = (BitSet) usedKeys.clone();
unused.flip(0, domainSize);
iter = new BitSetIterator(unused, 0, domainSize);
break;
}
case EITHER: {
iter = new IntIntervalList(0, domainSize).iterator();
break;
}
default: // should be impossible
throw new IllegalArgumentException("invalid entry state");
}
return new FastIterImpl(iter);
}
/**
* Return an iterable view of this vector using a fast iterator. This method
* delegates to {@link #fast(VectorEntry.State)} with state {@link VectorEntry.State#SET}.
*
* @return This object wrapped in an iterable that returns a fast iterator.
* @see #fastIterator()
*/
public Iterable<VectorEntry> fast() {
return fast(VectorEntry.State.SET);
}
/**
* Return an iterable view of this vector using a fast iterator.
*
* @param state The entries the resulting iterable should return.
* @return This object wrapped in an iterable that returns a fast iterator.
* @see #fastIterator(VectorEntry.State)
* @since 0.11
*/
public Iterable<VectorEntry> fast(final VectorEntry.State state) {
return new Iterable<VectorEntry>() {
@Override
public Iterator<VectorEntry> iterator() {
return fastIterator(state);
}
};
}
// The default iterator for this SparseVector iterates over
// entries that are "used". It uses an IterImpl class that
// generates a new VectorEntry for every element returned, so the
// client can safely keep around the VectorEntrys without concern
// they will mutate, at some cost in speed.
@Override
public Iterator<VectorEntry> iterator() {
return new IterImpl();
}
private class IterImpl implements Iterator<VectorEntry> {
private BitSetIterator iter = new BitSetIterator(usedKeys);
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
@Nonnull
public VectorEntry next() {
int pos = iter.nextInt();
return new VectorEntry(SparseVector.this, pos,
keys[pos], values[pos], true);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// Given an int iterator, iterates over the elements of the <key,
// value> pairs indexed by the int iterator. For efficiency, may
// reuse the VectorEntry returned at one step for a later step, so
// the client should not keep around old VectorEntrys.
private class FastIterImpl implements Iterator<VectorEntry> {
private VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
private IntIterator iter;
public FastIterImpl(IntIterator positions) {
iter = positions;
}
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
@Nonnull
public VectorEntry next() {
int pos = iter.nextInt();
boolean isSet = usedKeys.get(pos);
double v = isSet ? values[pos] : Double.NaN;
entry.set(pos, keys[pos], v, isSet);
return entry;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
//endregion
//region Pointers
/**
* Get a pointer over the set vector entries.
*
* @return A pointer to the first entry in this vector (or after the end, if the vector is
* empty).
*/
public Pointer<VectorEntry> pointer() {
return pointer(VectorEntry.State.SET);
}
/**
* Get a pointer over the vector entries.
*
* @param state The entries to include.
* @return A pointer to the first entry in this vector (or after the end, if the vector is
* empty).
*/
public Pointer<VectorEntry> pointer(VectorEntry.State state) {
return Pointers.transform(fastPointer(state), VectorEntry.copyFunction());
}
/**
* Get a fast pointer over the set vector entries.
*
* @return A pointer to the first entry in this vector (or after the end, if the vector is
* empty).
*/
public Pointer<VectorEntry> fastPointer() {
return fastPointer(VectorEntry.State.SET);
}
/**
* Get a fast pointer over the vector entries. It may modify and return the same object rather
* than creating new instances. When returned, it is pointing at the first entry, if such
* exists.
*
* @param state The entries to include.
* @return A (potentially) fast pointer over the vector entries.
*/
public Pointer<VectorEntry> fastPointer(VectorEntry.State state) {
switch (state) {
case SET:
return new FastMaskedPointer(false);
case UNSET:
return new FastMaskedPointer(true);
case EITHER:
return new FastPointer();
default:
throw new AssertionError("invalid entry state");
}
}
private class FastPointer implements Pointer<VectorEntry> {
private int pos = 0;
private final VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
@Override
public boolean advance() {
if (pos < domainSize) {
++pos;
}
return pos < domainSize;
}
@Override
public VectorEntry get() {
if (isAtEnd()) {
throw new NoSuchElementException("pointer out of bounds");
}
entry.set(pos, keys[pos], values[pos], usedKeys.get(pos));
return entry;
}
@Override
public boolean isAtEnd() {
return pos >= domainSize;
}
}
private class FastMaskedPointer implements Pointer<VectorEntry> {
private final BitSetPointer bsp;
private final boolean isSet;
private final VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
/**
* Construct a fast pointer that respects the usedKeys mask.
* @param invert Whether to invert the mask. If {@code true}, then the inverse of usedKeys
* is used (iterating over unset keys).
*/
public FastMaskedPointer(boolean invert) {
isSet = !invert;
if (invert) {
// this is an uncommon operation, so invert the key set
BitSet inverse = new BitSet();
inverse.or(usedKeys);
inverse.flip(0, domainSize);
bsp = new BitSetPointer(inverse, 0, domainSize);
} else {
bsp = new BitSetPointer(usedKeys, 0, domainSize);
}
}
@Override
public boolean advance() {
return bsp.advance();
}
@Override
public VectorEntry get() {
int idx = bsp.getInt();
assert idx >= 0 && idx < domainSize;
entry.set(idx, keys[idx], values[idx], isSet);
return entry;
}
@Override
public boolean isAtEnd() {
return bsp.isAtEnd();
}
}
//endregion
/**
* Get the key domain for this vector. All keys used are in this
* set. The keys will be in sorted order.
*
* @return The key domain for this vector.
*/
public LongSortedSet keyDomain() {
return LongSortedArraySet.wrap(keys, domainSize);
}
/**
* Get the set of keys of this vector. It is a subset of the key
* domain. The keys will be in sorted order.
*
* @return The set of keys used in this vector.
*/
public LongSortedSet keySet() {
return LongSortedArraySet.wrap(keys, domainSize, usedKeys);
}
/**
* Return the keys of this vector sorted by value.
*
* @return A list of keys in nondecreasing order of value.
* @see #keysByValue(boolean)
*/
public LongArrayList keysByValue() {
return keysByValue(false);
}
/**
* Get the collection of values of this vector.
*
* @return The collection of all values in this vector.
*/
public DoubleCollection values() {
DoubleArrayList lst = new DoubleArrayList(size());
BitSetIterator iter = new BitSetIterator(usedKeys, 0, domainSize);
while (iter.hasNext()) {
int idx = iter.nextInt();
lst.add(values[idx]);
}
return lst;
}
/**
* Get the keys of this vector sorted by the value of the items
* stored for each key.
*
* @param decreasing If {@var true}, sort in decreasing order.
* @return The sorted list of keys of this vector.
*/
public LongArrayList keysByValue(boolean decreasing) {
long[] skeys = keySet().toLongArray();
LongComparator cmp;
// Set up the comparator. We use the key as a secondary comparison to get
// a reproducible sort irrespective of sorting algorithm.
if (decreasing) {
cmp = new AbstractLongComparator() {
@Override
public int compare(long k1, long k2) {
int c = Double.compare(get(k2), get(k1));
if (c != 0) {
return c;
} else {
return Longs.compare(k1, k2);
}
}
};
} else {
cmp = new AbstractLongComparator() {
@Override
public int compare(long k1, long k2) {
int c = Double.compare(get(k1), get(k2));
if (c != 0) {
return c;
} else {
return Longs.compare(k1, k2);
}
}
};
}
LongArrays.quickSort(skeys, cmp);
return LongArrayList.wrap(skeys);
}
/**
* Get the size of this vector (the number of keys).
*
* @return The number of keys in the vector. This is at most the size of the
* key domain.
*/
public int size() {
return usedKeys.cardinality();
}
/**
* Query whether this vector is empty.
*
* @return {@code true} if the vector is empty.
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Compute and return the L2 norm (Euclidian length) of the vector.
*
* @return The L2 norm of the vector
*/
public double norm() {
double ssq = 0;
DoubleIterator iter = values().iterator();
while (iter.hasNext()) {
double v = iter.nextDouble();
ssq += v * v;
}
return Math.sqrt(ssq);
}
/**
* Compute and return the L1 norm (sum) of the vector.
*
* @return the sum of the vector's values
*/
public double sum() {
double result = 0;
DoubleIterator iter = values().iterator();
while (iter.hasNext()) {
result += iter.nextDouble();
}
return result;
}
/**
* Compute and return the mean of the vector's values.
*
* @return the mean of the vector
*/
public double mean() {
final int sz = size();
return sz > 0 ? sum() / sz : 0;
}
/**
* Compute the dot product between two vectors.
*
* @param o The other vector.
* @return The dot (inner) product between this vector and {@var o}.
*/
public double dot(SparseVector o) {
double dot = 0;
Pointer<VectorEntry> p1 = fastPointer();
Pointer<VectorEntry> p2 = o.fastPointer();
while (!p1.isAtEnd() && !p2.isAtEnd()) {
VectorEntry e1 = p1.get();
VectorEntry e2 = p2.get();
final long k1 = e1.getKey();
final long k2 = e2.getKey();
if (k1 < k2) {
p1.advance();
} else if (k2 < k1) {
p2.advance();
} else {
dot += e1.getValue() * e2.getValue();
p1.advance();
p2.advance();
}
}
return dot;
}
/**
* Count the common keys between two vectors.
*
* @param o The other vector.
* @return The number of keys appearing in both this and the other vector.
*/
public int countCommonKeys(SparseVector o) {
int count = 0;
Pointer<VectorEntry> p1 = fastPointer();
Pointer<VectorEntry> p2 = o.fastPointer();
while (!p1.isAtEnd() && !p2.isAtEnd()) {
VectorEntry e1 = p1.get();
VectorEntry e2 = p2.get();
final long k1 = e1.getKey();
final long k2 = e2.getKey();
if (k1 < k2) {
p1.advance();
} else if (k2 < k1) {
p2.advance();
} else {
count += 1;
p1.advance();
p2.advance();
}
}
return count;
}
@Override
public String toString() {
Function<VectorEntry, String> label = new Function<VectorEntry, String>() {
@Override
public String apply(VectorEntry e) {
return String.format("%d: %.3f", e.getKey(), e.getValue());
}
};
return "{" + StringUtils.join(Iterators.transform(fastIterator(), label), ", ") + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof SparseVector) {
SparseVector vo = (SparseVector) o;
int sz = size();
int osz = vo.size();
if (sz != osz) {
return false;
} else {
if (!this.keySet().equals(vo.keySet())) {
return false; // same keys
}
for (Pair<VectorEntry, VectorEntry> pair : Vectors.fastUnion(this, vo)) { // same values
if (Double.doubleToLongBits(pair.getLeft().getValue()) !=
Double.doubleToLongBits(pair.getRight().getValue())) { return false; }
}
return true;
}
} else {
return false;
}
}
@Override
public int hashCode() {
return keySet().hashCode() ^ values().hashCode();
}
/**
* Return an immutable snapshot of this sparse vector. The new vector's key
* domain will be equal to the {@link #keySet()} of this vector.
*
* @return An immutable sparse vector whose contents are the same as this
* vector. If the vector is already immutable, the returned object
* may be identical.
*/
public abstract ImmutableSparseVector immutable();
/**
* Return a mutable copy of this sparse vector. The key domain of the
* mutable vector will be the same as this vector's key domain.
*
* @return A mutable sparse vector which can be modified without modifying
* this vector.
*/
public abstract MutableSparseVector mutableCopy();
/**
* Return whether this sparse vector has a channel stored under a
* particular symbol. (Symbols are sort of like names, but more
* efficient.)
*
* @param channelSymbol the symbol under which the channel was
* stored in the vector.
* @return whether this vector has such a channel right now.
*/
public abstract boolean hasChannel(Symbol channelSymbol);
/**
* Fetch the channel stored under a particular symbol.
*
* @param channelSymbol the symbol under which the channel was/is
* stored in the vector.
* @return the channel, which is itself a sparse vector.
* @throws IllegalArgumentException if there is no channel under
* that symbol
*/
public abstract SparseVector channel(Symbol channelSymbol);
/**
* Retrieve all symbols that map to side channels for this vector.
* @return A set of symbols, each of which identifies a side channel
* of the vector.
*/
public abstract Set<Symbol> getChannels();
}
| lenskit-data-structures/src/main/java/org/grouplens/lenskit/vectors/SparseVector.java | /*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* This program 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 program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.lenskit.vectors;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.Iterables;
import com.google.common.collect.Iterators;
import com.google.common.primitives.Longs;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.doubles.DoubleCollection;
import it.unimi.dsi.fastutil.doubles.DoubleIterator;
import it.unimi.dsi.fastutil.ints.IntIterator;
import it.unimi.dsi.fastutil.longs.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.grouplens.lenskit.collections.*;
import org.grouplens.lenskit.symbols.Symbol;
import javax.annotation.Nonnull;
import java.io.Serializable;
import java.util.*;
/**
* Read-only interface to sparse vectors.
*
* <p>
* This vector class works a lot like a map, but it also caches some
* commonly-used statistics. The values are stored in parallel arrays sorted by
* key. This allows fast lookup and sorted iteration. All iterators access the
* items in key order.
*
* <p>
* Vectors have a <i>key domain</i>, which is a set containing all valid keys in
* the vector. This key domain is fixed at construction; mutable vectors cannot
* set values for keys not in this domain. Thinking of the vector as a function
* from longs to doubles, the key domain would actually be the codomain, and the
* key set the algebraic domain, but that gets cumbersome to write in code. So
* think of the key domain as the domain from which valid keys are drawn.
*
* <p>
* This class provides a <em>read-only</em> interface to sparse vectors. It may
* actually be a {@link MutableSparseVector}, so the data may be modified by
* code elsewhere that has access to the mutable representation. For sparse
* vectors that are guaranteed to be unchanging, see
* {@link ImmutableSparseVector}.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
* @compat Public
*/
public abstract class SparseVector implements Iterable<VectorEntry>, Serializable {
private static final long serialVersionUID = 1L;
final long[] keys;
final BitSet usedKeys;
double[] values;
final int domainSize; // How much of the key space is actually used by this vector.
/**
* Construct a new vector from existing arrays. It is assumed that the keys
* are sorted and duplicate-free, and that the values array is the same length. The
* key array is the key domain, and all keys are considered used.
* No new keys can be added to this vector. Clients should call
* the wrap() method rather than directly calling this constructor.
*
* @param ks The array of keys backing this vector. They must be sorted.
* @param vs The array of values backing this vector.
*/
// hard to test because it's not used externally
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
SparseVector(long[] ks, double[] vs) {
this(ks, vs, ks.length);
}
/**
* Construct a new vector from existing arrays. It is assumed that
* the keys are sorted and duplicate-free, and that the keys and
* values both have at least {@var length} items. The key set
* and key domain are both set to the keys array. Clients should
* call the wrap() method rather than directly calling this
* constructor.
*
* @param ks The array of keys backing the vector. It must be sorted.
* @param vs The array of values backing the vector.
* @param length Number of items to actually use.
*/
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
SparseVector(long[] ks, double[] vs, int length) {
Preconditions.checkArgument(MoreArrays.isSorted(ks, 0, length),
"The input array of keys must be in sorted order.");
keys = ks;
values = vs;
domainSize = length;
usedKeys = new BitSet(length);
for (int i = 0; i < length; i++) {
usedKeys.set(i);
}
}
/**
* Construct a new vector from existing arrays. It is assumed that
* the keys are sorted and duplicate-free, and that the keys and
* values both have at least {@var length} items. The key set
* and key domain are both set to the keys array. Clients should
* call the wrap() method rather than directly calling this
* constructor.
*
* @param ks The array of keys backing the vector. It must be sorted.
* @param vs The array of values backing the vector.
* @param length Number of items to actually use.
* @param used The used entry set.
*/
@SuppressWarnings("PMD.ArrayIsStoredDirectly")
SparseVector(long[] ks, double[] vs, int length, BitSet used) {
Preconditions.checkArgument(MoreArrays.isSorted(ks, 0, length),
"The input array of keys must be in sorted order.");
keys = ks;
values = vs;
domainSize = length;
usedKeys = used;
}
/**
* Construct a new vector from the contents of a map. The key domain is the
* key set of the map. Therefore, no new keys can be added to this vector.
*
* @param keyValueMap A map providing the values for the vector.
*/
SparseVector(Long2DoubleMap keyValueMap) {
keys = keyValueMap.keySet().toLongArray();
domainSize = keys.length;
Arrays.sort(keys);
// untestable assertions, assuming Arrays works.
assert keys.length == keyValueMap.size();
assert MoreArrays.isSorted(keys, 0, domainSize);
values = new double[keys.length];
final int len = keys.length;
for (int i = 0; i < len; i++) {
values[i] = keyValueMap.get(keys[i]);
}
usedKeys = new BitSet(domainSize);
usedKeys.set(0, domainSize);
}
/**
* Construct a new empty vector with the specified key domain.
*
* @param domain The key domain.
*/
SparseVector(Collection<Long> domain) {
LongSortedArraySet set;
// since LSAS is immutable, we'll use its array if we can!
if (domain instanceof LongSortedArraySet) {
set = (LongSortedArraySet) domain;
} else {
set = new LongSortedArraySet(domain);
}
keys = set.unsafeArray();
domainSize = domain.size();
values = new double[domainSize];
usedKeys = new BitSet(domainSize);
}
/**
* Find the index of a particular key.
*
* @param key The key to search for.
* @return The index, or a negative value if the key is not in the key domain.
*/
protected int findIndex(long key) {
return Arrays.binarySearch(keys, 0, domainSize, key);
}
/**
* Query whether the vector contains an entry for the key in question.
*
* @param key The key to search for.
* @return {@code true} if the key exists.
*/
public boolean containsKey(long key) {
final int idx = findIndex(key);
return idx >= 0 && usedKeys.get(idx);
}
/**
* Get the value for {@var key}.
*
* @param key the key to look up
* @return the key's value (or {@link Double#NaN} if no such value
* exists)
* @see #get(long, double)
*/
public double get(long key) {
return get(key, Double.NaN);
}
/**
* Get the value for {@var key}.
*
* @param key the key to look up
* @param dft The value to return if the key is not in the vector
* @return the value (or {@var dft} if the key is not set to a value)
*/
public double get(long key, double dft) {
final int idx = findIndex(key);
if (idx >= 0 && usedKeys.get(idx)) {
return values[idx];
} else {
return dft;
}
}
/**
* Get the value for the entry's key.
*
* @param entry A {@code VectorEntry} with the key to look up
* @return the key's value (or {@link Double#NaN} if no such value exists)
*/
public double get(VectorEntry entry) {
final SparseVector evec = entry.getVector();
final int eind = entry.getIndex();
if (evec == null) {
throw new IllegalArgumentException("entry is not associated with a vector");
} else if (evec.keys != this.keys) {
throw new IllegalArgumentException("entry does not have safe key domain");
} else if (entry.getKey() != keys[eind]) {
throw new IllegalArgumentException("entry does not have the correct key for its index");
}
if (usedKeys.get(eind)) {
return values[eind];
} else {
return Double.NaN;
}
}
//region Iterators
/**
* Fast iterator over all set entries (it can reuse entry objects).
*
* @return a fast iterator over all key/value pairs
* @see #fastIterator(VectorEntry.State)
* @see it.unimi.dsi.fastutil.longs.Long2DoubleMap.FastEntrySet#fastIterator()
* Long2DoubleMap.FastEntrySet.fastIterator()
*/
public Iterator<VectorEntry> fastIterator() {
return fastIterator(VectorEntry.State.SET);
}
/**
* Fast iterator over entries (it can reuse entry objects).
*
* @param state The state of entries to iterate.
* @return a fast iterator over all key/value pairs
* @see it.unimi.dsi.fastutil.longs.Long2DoubleMap.FastEntrySet#fastIterator()
* Long2DoubleMap.FastEntrySet.fastIterator()
* @since 0.11
*/
public Iterator<VectorEntry> fastIterator(VectorEntry.State state) {
IntIterator iter;
switch (state) {
case SET:
iter = new BitSetIterator(usedKeys, 0, domainSize);
break;
case UNSET: {
BitSet unused = (BitSet) usedKeys.clone();
unused.flip(0, domainSize);
iter = new BitSetIterator(unused, 0, domainSize);
break;
}
case EITHER: {
iter = new IntIntervalList(0, domainSize).iterator();
break;
}
default: // should be impossible
throw new IllegalArgumentException("invalid entry state");
}
return new FastIterImpl(iter);
}
/**
* Return an iterable view of this vector using a fast iterator. This method
* delegates to {@link #fast(VectorEntry.State)} with state {@link VectorEntry.State#SET}.
*
* @return This object wrapped in an iterable that returns a fast iterator.
* @see #fastIterator()
*/
public Iterable<VectorEntry> fast() {
return fast(VectorEntry.State.SET);
}
/**
* Return an iterable view of this vector using a fast iterator.
*
* @param state The entries the resulting iterable should return.
* @return This object wrapped in an iterable that returns a fast iterator.
* @see #fastIterator(VectorEntry.State)
* @since 0.11
*/
public Iterable<VectorEntry> fast(final VectorEntry.State state) {
return new Iterable<VectorEntry>() {
@Override
public Iterator<VectorEntry> iterator() {
return fastIterator(state);
}
};
}
// The default iterator for this SparseVector iterates over
// entries that are "used". It uses an IterImpl class that
// generates a new VectorEntry for every element returned, so the
// client can safely keep around the VectorEntrys without concern
// they will mutate, at some cost in speed.
@Override
public Iterator<VectorEntry> iterator() {
return new IterImpl();
}
private class IterImpl implements Iterator<VectorEntry> {
private BitSetIterator iter = new BitSetIterator(usedKeys);
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
@Nonnull
public VectorEntry next() {
int pos = iter.nextInt();
return new VectorEntry(SparseVector.this, pos,
keys[pos], values[pos], true);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
// Given an int iterator, iterates over the elements of the <key,
// value> pairs indexed by the int iterator. For efficiency, may
// reuse the VectorEntry returned at one step for a later step, so
// the client should not keep around old VectorEntrys.
private class FastIterImpl implements Iterator<VectorEntry> {
private VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
private IntIterator iter;
public FastIterImpl(IntIterator positions) {
iter = positions;
}
@Override
public boolean hasNext() {
return iter.hasNext();
}
@Override
@Nonnull
public VectorEntry next() {
int pos = iter.nextInt();
boolean isSet = usedKeys.get(pos);
double v = isSet ? values[pos] : Double.NaN;
entry.set(pos, keys[pos], v, isSet);
return entry;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
//endregion
//region Pointers
/**
* Get a pointer over the set vector entries.
*
* @return A pointer to the first entry in this vector (or after the end, if the vector is
* empty).
*/
public Pointer<VectorEntry> pointer() {
return pointer(VectorEntry.State.SET);
}
/**
* Get a pointer over the vector entries.
*
* @param state The entries to include.
* @return A pointer to the first entry in this vector (or after the end, if the vector is
* empty).
*/
public Pointer<VectorEntry> pointer(VectorEntry.State state) {
return Pointers.transform(fastPointer(state), VectorEntry.copyFunction());
}
/**
* Get a fast pointer over the set vector entries.
*
* @return A pointer to the first entry in this vector (or after the end, if the vector is
* empty).
*/
public Pointer<VectorEntry> fastPointer() {
return fastPointer(VectorEntry.State.SET);
}
/**
* Get a fast pointer over the vector entries. It may modify and return the same object rather
* than creating new instances. When returned, it is pointing at the first entry, if such
* exists.
*
* @param state The entries to include.
* @return A (potentially) fast pointer over the vector entries.
*/
public Pointer<VectorEntry> fastPointer(VectorEntry.State state) {
switch (state) {
case SET:
return new FastMaskedPointer(false);
case UNSET:
return new FastMaskedPointer(true);
case EITHER:
return new FastPointer();
default:
throw new AssertionError("invalid entry state");
}
}
private class FastPointer implements Pointer<VectorEntry> {
private int pos = 0;
private final VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
@Override
public boolean advance() {
if (pos < domainSize) {
++pos;
}
return pos < domainSize;
}
@Override
public VectorEntry get() {
if (isAtEnd()) {
throw new NoSuchElementException("pointer out of bounds");
}
entry.set(pos, keys[pos], values[pos], usedKeys.get(pos));
return entry;
}
@Override
public boolean isAtEnd() {
return pos >= domainSize;
}
}
private class FastMaskedPointer implements Pointer<VectorEntry> {
private final BitSetPointer bsp;
private final boolean isSet;
private final VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
public FastMaskedPointer(boolean invert) {
isSet = !invert;
if (invert) {
BitSet inverse = new BitSet();
inverse.or(usedKeys);
inverse.flip(0, domainSize);
bsp = new BitSetPointer(inverse, 0, domainSize);
} else {
bsp = new BitSetPointer(usedKeys, 0, domainSize);
}
}
@Override
public boolean advance() {
return bsp.advance();
}
@Override
public VectorEntry get() {
int idx = bsp.getInt();
assert idx >= 0 && idx < domainSize;
entry.set(idx, keys[idx], values[idx], isSet);
return entry;
}
@Override
public boolean isAtEnd() {
return bsp.isAtEnd();
}
}
//endregion
/**
* Get the key domain for this vector. All keys used are in this
* set. The keys will be in sorted order.
*
* @return The key domain for this vector.
*/
public LongSortedSet keyDomain() {
return LongSortedArraySet.wrap(keys, domainSize);
}
/**
* Get the set of keys of this vector. It is a subset of the key
* domain. The keys will be in sorted order.
*
* @return The set of keys used in this vector.
*/
public LongSortedSet keySet() {
return LongSortedArraySet.wrap(keys, domainSize, usedKeys);
}
/**
* Return the keys of this vector sorted by value.
*
* @return A list of keys in nondecreasing order of value.
* @see #keysByValue(boolean)
*/
public LongArrayList keysByValue() {
return keysByValue(false);
}
/**
* Get the collection of values of this vector.
*
* @return The collection of all values in this vector.
*/
public DoubleCollection values() {
DoubleArrayList lst = new DoubleArrayList(size());
BitSetIterator iter = new BitSetIterator(usedKeys, 0, domainSize);
while (iter.hasNext()) {
int idx = iter.nextInt();
lst.add(values[idx]);
}
return lst;
}
/**
* Get the keys of this vector sorted by the value of the items
* stored for each key.
*
* @param decreasing If {@var true}, sort in decreasing order.
* @return The sorted list of keys of this vector.
*/
public LongArrayList keysByValue(boolean decreasing) {
long[] skeys = keySet().toLongArray();
LongComparator cmp;
// Set up the comparator. We use the key as a secondary comparison to get
// a reproducible sort irrespective of sorting algorithm.
if (decreasing) {
cmp = new AbstractLongComparator() {
@Override
public int compare(long k1, long k2) {
int c = Double.compare(get(k2), get(k1));
if (c != 0) {
return c;
} else {
return Longs.compare(k1, k2);
}
}
};
} else {
cmp = new AbstractLongComparator() {
@Override
public int compare(long k1, long k2) {
int c = Double.compare(get(k1), get(k2));
if (c != 0) {
return c;
} else {
return Longs.compare(k1, k2);
}
}
};
}
LongArrays.quickSort(skeys, cmp);
return LongArrayList.wrap(skeys);
}
/**
* Get the size of this vector (the number of keys).
*
* @return The number of keys in the vector. This is at most the size of the
* key domain.
*/
public int size() {
return usedKeys.cardinality();
}
/**
* Query whether this vector is empty.
*
* @return {@code true} if the vector is empty.
*/
public boolean isEmpty() {
return size() == 0;
}
/**
* Compute and return the L2 norm (Euclidian length) of the vector.
*
* @return The L2 norm of the vector
*/
public double norm() {
double ssq = 0;
DoubleIterator iter = values().iterator();
while (iter.hasNext()) {
double v = iter.nextDouble();
ssq += v * v;
}
return Math.sqrt(ssq);
}
/**
* Compute and return the L1 norm (sum) of the vector.
*
* @return the sum of the vector's values
*/
public double sum() {
double result = 0;
DoubleIterator iter = values().iterator();
while (iter.hasNext()) {
result += iter.nextDouble();
}
return result;
}
/**
* Compute and return the mean of the vector's values.
*
* @return the mean of the vector
*/
public double mean() {
final int sz = size();
return sz > 0 ? sum() / sz : 0;
}
/**
* Compute the dot product between two vectors.
*
* @param o The other vector.
* @return The dot (inner) product between this vector and {@var o}.
*/
public double dot(SparseVector o) {
double dot = 0;
Pointer<VectorEntry> p1 = fastPointer();
Pointer<VectorEntry> p2 = o.fastPointer();
while (!p1.isAtEnd() && !p2.isAtEnd()) {
VectorEntry e1 = p1.get();
VectorEntry e2 = p2.get();
final long k1 = e1.getKey();
final long k2 = e2.getKey();
if (k1 < k2) {
p1.advance();
} else if (k2 < k1) {
p2.advance();
} else {
dot += e1.getValue() * e2.getValue();
p1.advance();
p2.advance();
}
}
return dot;
}
/**
* Count the common keys between two vectors.
*
* @param o The other vector.
* @return The number of keys appearing in both this and the other vector.
*/
public int countCommonKeys(SparseVector o) {
int count = 0;
Pointer<VectorEntry> p1 = fastPointer();
Pointer<VectorEntry> p2 = o.fastPointer();
while (!p1.isAtEnd() && !p2.isAtEnd()) {
VectorEntry e1 = p1.get();
VectorEntry e2 = p2.get();
final long k1 = e1.getKey();
final long k2 = e2.getKey();
if (k1 < k2) {
p1.advance();
} else if (k2 < k1) {
p2.advance();
} else {
count += 1;
p1.advance();
p2.advance();
}
}
return count;
}
@Override
public String toString() {
Function<VectorEntry, String> label = new Function<VectorEntry, String>() {
@Override
public String apply(VectorEntry e) {
return String.format("%d: %.3f", e.getKey(), e.getValue());
}
};
return "{" + StringUtils.join(Iterators.transform(fastIterator(), label), ", ") + "}";
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} else if (o instanceof SparseVector) {
SparseVector vo = (SparseVector) o;
int sz = size();
int osz = vo.size();
if (sz != osz) {
return false;
} else {
if (!this.keySet().equals(vo.keySet())) {
return false; // same keys
}
for (Pair<VectorEntry, VectorEntry> pair : Vectors.fastUnion(this, vo)) { // same values
if (Double.doubleToLongBits(pair.getLeft().getValue()) !=
Double.doubleToLongBits(pair.getRight().getValue())) { return false; }
}
return true;
}
} else {
return false;
}
}
@Override
public int hashCode() {
return keySet().hashCode() ^ values().hashCode();
}
/**
* Return an immutable snapshot of this sparse vector. The new vector's key
* domain will be equal to the {@link #keySet()} of this vector.
*
* @return An immutable sparse vector whose contents are the same as this
* vector. If the vector is already immutable, the returned object
* may be identical.
*/
public abstract ImmutableSparseVector immutable();
/**
* Return a mutable copy of this sparse vector. The key domain of the
* mutable vector will be the same as this vector's key domain.
*
* @return A mutable sparse vector which can be modified without modifying
* this vector.
*/
public abstract MutableSparseVector mutableCopy();
/**
* Return whether this sparse vector has a channel stored under a
* particular symbol. (Symbols are sort of like names, but more
* efficient.)
*
* @param channelSymbol the symbol under which the channel was
* stored in the vector.
* @return whether this vector has such a channel right now.
*/
public abstract boolean hasChannel(Symbol channelSymbol);
/**
* Fetch the channel stored under a particular symbol.
*
* @param channelSymbol the symbol under which the channel was/is
* stored in the vector.
* @return the channel, which is itself a sparse vector.
* @throws IllegalArgumentException if there is no channel under
* that symbol
*/
public abstract SparseVector channel(Symbol channelSymbol);
/**
* Retrieve all symbols that map to side channels for this vector.
* @return A set of symbols, each of which identifies a side channel
* of the vector.
*/
public abstract Set<Symbol> getChannels();
}
| Documentation & import cleanups
| lenskit-data-structures/src/main/java/org/grouplens/lenskit/vectors/SparseVector.java | Documentation & import cleanups | <ide><path>enskit-data-structures/src/main/java/org/grouplens/lenskit/vectors/SparseVector.java
<ide>
<ide> import com.google.common.base.Function;
<ide> import com.google.common.base.Preconditions;
<del>import com.google.common.collect.Iterables;
<ide> import com.google.common.collect.Iterators;
<ide> import com.google.common.primitives.Longs;
<ide> import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
<ide> private final boolean isSet;
<ide> private final VectorEntry entry = new VectorEntry(SparseVector.this, -1, 0, 0, false);
<ide>
<add> /**
<add> * Construct a fast pointer that respects the usedKeys mask.
<add> * @param invert Whether to invert the mask. If {@code true}, then the inverse of usedKeys
<add> * is used (iterating over unset keys).
<add> */
<ide> public FastMaskedPointer(boolean invert) {
<ide> isSet = !invert;
<ide> if (invert) {
<add> // this is an uncommon operation, so invert the key set
<ide> BitSet inverse = new BitSet();
<ide> inverse.or(usedKeys);
<ide> inverse.flip(0, domainSize); |
|
JavaScript | mit | c717c2a1e8aa19a1c75a0d36ee3a6ab73d71585e | 0 | dzknj/301portfolio,dzknj/301portfolio | var projects = [];
function ProjectItem(obj) {
this.title = obj.title;
this.author = obj.author;
this.projectUrl = obj.projectUrl;
this.description = obj.description;
this.publishedOn = obj.publishedOn;
};
/*
var el = new ProjectItem('busmall','david zalk', 'http://www.google.com', 'Test for placing projects in my webpage', '12/12/2012');
var el2 = new ProjectItem('busmall','james', 'http://www.google.com', 'Test for placing projects in my webpage', '12/12/2012');
*/
ProjectItem.prototype.toHtml = function() {
var template = Handlebars.compile($('#article-template').text());
this.daysAgo = parseInt((new Date() - new Date(this.publishedOn))/60/60/24/1000);
this.monthsAgo = parseInt((new Date() - new Date(this.publishedOn))/60/60/24/30/1000);
this.complete = this.daysAgo + ' days ago / ' + this.monthsAgo + ' months ago';
return template(this);
// var $newProjectList = $('article.template').clone();
//
// $newProjectList.find('.readon').html('Keep Reading »')
// //finds .readon in my article template and puts text into html
// $newProjectList.find('.description').html(this.description);
//
// $newProjectList.find('h2').html(this.title);
//
// $newProjectList.find('address').html('by' + this.author);
//
// $newProjectList.find('time').html('published' + this.publishedOn);
//
// $newProjectList.append('<hr>');
//
// $newProjectList.removeClass('template');
// return $newProjectList;
};
ProjectItem.loadAll = function(data) {
data.forEach(function(ele) {
projects.push(new ProjectItem(ele))
});
projects.forEach(function(a) {
$('section').append(a.toHtml())
});
};
ProjectItem.fetchAllFromServer = function() {
console.log('fetching data from server');
$.ajax({
async: false,
type: 'GET',
url: 'js/data.json',
success: function(data, message, xhr) {
localStorage.eTag = xhr.getResponseHeader('eTag');
ProjectItem.data = JSON.parse(data);
localStorage.data = JSON.stringify(data);
}
});
ProjectItem.loadAll(ProjectItem.data);
};
ProjectItem.fetchAllFromServer();
| js/app.js | var projects = [];
function ProjectItem(obj) {
this.title = obj.title;
this.author = obj.author;
this.projectUrl = obj.projectUrl;
this.description = obj.description;
this.publishedOn = obj.publishedOn;
};
/*
var el = new ProjectItem('busmall','david zalk', 'http://www.google.com', 'Test for placing projects in my webpage', '12/12/2012');
var el2 = new ProjectItem('busmall','james', 'http://www.google.com', 'Test for placing projects in my webpage', '12/12/2012');
*/
ProjectItem.prototype.toHtml = function() {
var template = Handlebars.compile($('#article-template').text());
this.daysAgo = parseInt((new Date() - new Date(this.publishedOn))/60/60/24/1000);
this.monthsAgo = parseInt((new Date() - new Date(this.publishedOn))/60/60/24/30/1000);
this.complete = this.daysAgo + ' days ago / ' + this.monthsAgo + ' months ago';
return template(this);
// var $newProjectList = $('article.template').clone();
//
// $newProjectList.find('.readon').html('Keep Reading »')
// //finds .readon in my article template and puts text into html
// $newProjectList.find('.description').html(this.description);
//
// $newProjectList.find('h2').html(this.title);
//
// $newProjectList.find('address').html('by' + this.author);
//
// $newProjectList.find('time').html('published' + this.publishedOn);
//
// $newProjectList.append('<hr>');
//
// $newProjectList.removeClass('template');
// return $newProjectList;
};
ProjectItem.loadAll = function(data) {
data.forEach(function(ele) {
projects.push(new ProjectItem(ele))
});
projects.forEach(function(a) {
$('section').append(a.toHtml())
});
};
ProjectItem.fetchAllFromServer = function() {
console.log('fetching data from server');
$.ajax({
type: 'GET',
url: 'js/data.json',
success: function(data, message, xhr) {
localStorage.eTag = xhr.getResponseHeader('eTag');
ProjectItem.data = JSON.parse(data);
localStorage.data = JSON.stringify(data);
}
});
};
ProjectItem.fetchAllFromServer();
ProjectItem.loadAll(ProjectItem.data);
| trying to get it to work
| js/app.js | trying to get it to work | <ide><path>s/app.js
<ide> ProjectItem.fetchAllFromServer = function() {
<ide> console.log('fetching data from server');
<ide> $.ajax({
<add> async: false,
<ide> type: 'GET',
<ide> url: 'js/data.json',
<ide> success: function(data, message, xhr) {
<ide> localStorage.data = JSON.stringify(data);
<ide> }
<ide> });
<add> ProjectItem.loadAll(ProjectItem.data);
<ide> };
<ide> ProjectItem.fetchAllFromServer();
<del>ProjectItem.loadAll(ProjectItem.data); |
|
Java | apache-2.0 | 26b3695c382e71c7e8dada66f164a1b8f40c52b0 | 0 | da1z/intellij-community,diorcety/intellij-community,TangHao1987/intellij-community,salguarnieri/intellij-community,caot/intellij-community,akosyakov/intellij-community,lucafavatella/intellij-community,robovm/robovm-studio,kdwink/intellij-community,dslomov/intellij-community,diorcety/intellij-community,ryano144/intellij-community,da1z/intellij-community,ivan-fedorov/intellij-community,fnouama/intellij-community,ThiagoGarciaAlves/intellij-community,samthor/intellij-community,ibinti/intellij-community,Distrotech/intellij-community,jagguli/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,alphafoobar/intellij-community,blademainer/intellij-community,blademainer/intellij-community,dslomov/intellij-community,MichaelNedzelsky/intellij-community,orekyuu/intellij-community,consulo/consulo,vvv1559/intellij-community,suncycheng/intellij-community,consulo/consulo,asedunov/intellij-community,ftomassetti/intellij-community,ivan-fedorov/intellij-community,signed/intellij-community,allotria/intellij-community,hurricup/intellij-community,asedunov/intellij-community,muntasirsyed/intellij-community,idea4bsd/idea4bsd,muntasirsyed/intellij-community,samthor/intellij-community,ftomassetti/intellij-community,asedunov/intellij-community,samthor/intellij-community,youdonghai/intellij-community,gnuhub/intellij-community,jexp/idea2,suncycheng/intellij-community,samthor/intellij-community,Lekanich/intellij-community,mglukhikh/intellij-community,suncycheng/intellij-community,michaelgallacher/intellij-community,ftomassetti/intellij-community,fengbaicanhe/intellij-community,TangHao1987/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,adedayo/intellij-community,amith01994/intellij-community,fnouama/intellij-community,vladmm/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,wreckJ/intellij-community,ivan-fedorov/intellij-community,apixandru/intellij-community,kdwink/intellij-community,asedunov/intellij-community,ivan-fedorov/intellij-community,idea4bsd/idea4bsd,MER-GROUP/intellij-community,jagguli/intellij-community,tmpgit/intellij-community,ivan-fedorov/intellij-community,kool79/intellij-community,gnuhub/intellij-community,ahb0327/intellij-community,youdonghai/intellij-community,holmes/intellij-community,SerCeMan/intellij-community,signed/intellij-community,muntasirsyed/intellij-community,pwoodworth/intellij-community,salguarnieri/intellij-community,slisson/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,youdonghai/intellij-community,FHannes/intellij-community,ibinti/intellij-community,vvv1559/intellij-community,robovm/robovm-studio,slisson/intellij-community,apixandru/intellij-community,TangHao1987/intellij-community,supersven/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,holmes/intellij-community,hurricup/intellij-community,consulo/consulo,suncycheng/intellij-community,signed/intellij-community,ibinti/intellij-community,ol-loginov/intellij-community,apixandru/intellij-community,vvv1559/intellij-community,petteyg/intellij-community,supersven/intellij-community,clumsy/intellij-community,clumsy/intellij-community,dslomov/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,mglukhikh/intellij-community,samthor/intellij-community,hurricup/intellij-community,supersven/intellij-community,vvv1559/intellij-community,diorcety/intellij-community,xfournet/intellij-community,asedunov/intellij-community,salguarnieri/intellij-community,Lekanich/intellij-community,adedayo/intellij-community,ibinti/intellij-community,vladmm/intellij-community,nicolargo/intellij-community,adedayo/intellij-community,retomerz/intellij-community,retomerz/intellij-community,samthor/intellij-community,vladmm/intellij-community,holmes/intellij-community,salguarnieri/intellij-community,FHannes/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,retomerz/intellij-community,samthor/intellij-community,allotria/intellij-community,slisson/intellij-community,ibinti/intellij-community,xfournet/intellij-community,michaelgallacher/intellij-community,joewalnes/idea-community,supersven/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,xfournet/intellij-community,izonder/intellij-community,slisson/intellij-community,semonte/intellij-community,pwoodworth/intellij-community,jagguli/intellij-community,caot/intellij-community,michaelgallacher/intellij-community,kdwink/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,ol-loginov/intellij-community,asedunov/intellij-community,dslomov/intellij-community,apixandru/intellij-community,petteyg/intellij-community,caot/intellij-community,ftomassetti/intellij-community,Distrotech/intellij-community,fengbaicanhe/intellij-community,youdonghai/intellij-community,tmpgit/intellij-community,gnuhub/intellij-community,idea4bsd/idea4bsd,hurricup/intellij-community,idea4bsd/idea4bsd,MichaelNedzelsky/intellij-community,kool79/intellij-community,joewalnes/idea-community,diorcety/intellij-community,fengbaicanhe/intellij-community,Distrotech/intellij-community,semonte/intellij-community,ernestp/consulo,ol-loginov/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,wreckJ/intellij-community,gnuhub/intellij-community,gnuhub/intellij-community,ThiagoGarciaAlves/intellij-community,blademainer/intellij-community,ivan-fedorov/intellij-community,consulo/consulo,nicolargo/intellij-community,robovm/robovm-studio,amith01994/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,kool79/intellij-community,da1z/intellij-community,tmpgit/intellij-community,TangHao1987/intellij-community,orekyuu/intellij-community,orekyuu/intellij-community,TangHao1987/intellij-community,lucafavatella/intellij-community,supersven/intellij-community,clumsy/intellij-community,adedayo/intellij-community,Lekanich/intellij-community,dslomov/intellij-community,pwoodworth/intellij-community,signed/intellij-community,lucafavatella/intellij-community,youdonghai/intellij-community,da1z/intellij-community,supersven/intellij-community,Distrotech/intellij-community,semonte/intellij-community,xfournet/intellij-community,dslomov/intellij-community,MER-GROUP/intellij-community,dslomov/intellij-community,FHannes/intellij-community,orekyuu/intellij-community,MER-GROUP/intellij-community,Distrotech/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,mglukhikh/intellij-community,kdwink/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,petteyg/intellij-community,clumsy/intellij-community,joewalnes/idea-community,Distrotech/intellij-community,joewalnes/idea-community,lucafavatella/intellij-community,alphafoobar/intellij-community,holmes/intellij-community,fengbaicanhe/intellij-community,blademainer/intellij-community,apixandru/intellij-community,nicolargo/intellij-community,da1z/intellij-community,SerCeMan/intellij-community,hurricup/intellij-community,allotria/intellij-community,ol-loginov/intellij-community,xfournet/intellij-community,wreckJ/intellij-community,Lekanich/intellij-community,fengbaicanhe/intellij-community,idea4bsd/idea4bsd,fnouama/intellij-community,kdwink/intellij-community,michaelgallacher/intellij-community,Lekanich/intellij-community,jexp/idea2,Lekanich/intellij-community,asedunov/intellij-community,ibinti/intellij-community,caot/intellij-community,blademainer/intellij-community,SerCeMan/intellij-community,ivan-fedorov/intellij-community,supersven/intellij-community,fitermay/intellij-community,akosyakov/intellij-community,ernestp/consulo,ryano144/intellij-community,ol-loginov/intellij-community,fitermay/intellij-community,pwoodworth/intellij-community,gnuhub/intellij-community,orekyuu/intellij-community,alphafoobar/intellij-community,FHannes/intellij-community,wreckJ/intellij-community,samthor/intellij-community,lucafavatella/intellij-community,kool79/intellij-community,fnouama/intellij-community,holmes/intellij-community,mglukhikh/intellij-community,fengbaicanhe/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,vladmm/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,adedayo/intellij-community,adedayo/intellij-community,jagguli/intellij-community,vladmm/intellij-community,amith01994/intellij-community,pwoodworth/intellij-community,michaelgallacher/intellij-community,fnouama/intellij-community,pwoodworth/intellij-community,vvv1559/intellij-community,signed/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,kool79/intellij-community,robovm/robovm-studio,apixandru/intellij-community,pwoodworth/intellij-community,ahb0327/intellij-community,ivan-fedorov/intellij-community,ibinti/intellij-community,MichaelNedzelsky/intellij-community,diorcety/intellij-community,fitermay/intellij-community,clumsy/intellij-community,ol-loginov/intellij-community,diorcety/intellij-community,SerCeMan/intellij-community,mglukhikh/intellij-community,ibinti/intellij-community,holmes/intellij-community,da1z/intellij-community,TangHao1987/intellij-community,jagguli/intellij-community,blademainer/intellij-community,xfournet/intellij-community,MER-GROUP/intellij-community,FHannes/intellij-community,blademainer/intellij-community,michaelgallacher/intellij-community,jexp/idea2,ryano144/intellij-community,holmes/intellij-community,allotria/intellij-community,nicolargo/intellij-community,SerCeMan/intellij-community,ftomassetti/intellij-community,semonte/intellij-community,retomerz/intellij-community,pwoodworth/intellij-community,caot/intellij-community,signed/intellij-community,slisson/intellij-community,blademainer/intellij-community,akosyakov/intellij-community,kdwink/intellij-community,pwoodworth/intellij-community,amith01994/intellij-community,ThiagoGarciaAlves/intellij-community,alphafoobar/intellij-community,caot/intellij-community,ftomassetti/intellij-community,fnouama/intellij-community,slisson/intellij-community,supersven/intellij-community,nicolargo/intellij-community,kool79/intellij-community,ftomassetti/intellij-community,amith01994/intellij-community,wreckJ/intellij-community,FHannes/intellij-community,SerCeMan/intellij-community,allotria/intellij-community,fitermay/intellij-community,izonder/intellij-community,diorcety/intellij-community,fnouama/intellij-community,dslomov/intellij-community,adedayo/intellij-community,da1z/intellij-community,ibinti/intellij-community,ernestp/consulo,semonte/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,FHannes/intellij-community,robovm/robovm-studio,muntasirsyed/intellij-community,adedayo/intellij-community,ThiagoGarciaAlves/intellij-community,ivan-fedorov/intellij-community,robovm/robovm-studio,kool79/intellij-community,muntasirsyed/intellij-community,signed/intellij-community,robovm/robovm-studio,jagguli/intellij-community,orekyuu/intellij-community,youdonghai/intellij-community,TangHao1987/intellij-community,kdwink/intellij-community,idea4bsd/idea4bsd,vladmm/intellij-community,diorcety/intellij-community,Lekanich/intellij-community,muntasirsyed/intellij-community,caot/intellij-community,dslomov/intellij-community,ol-loginov/intellij-community,ryano144/intellij-community,Lekanich/intellij-community,ThiagoGarciaAlves/intellij-community,jexp/idea2,diorcety/intellij-community,da1z/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,robovm/robovm-studio,ahb0327/intellij-community,MichaelNedzelsky/intellij-community,ivan-fedorov/intellij-community,izonder/intellij-community,retomerz/intellij-community,allotria/intellij-community,apixandru/intellij-community,akosyakov/intellij-community,joewalnes/idea-community,MichaelNedzelsky/intellij-community,caot/intellij-community,petteyg/intellij-community,ahb0327/intellij-community,slisson/intellij-community,fitermay/intellij-community,TangHao1987/intellij-community,muntasirsyed/intellij-community,ftomassetti/intellij-community,mglukhikh/intellij-community,izonder/intellij-community,ibinti/intellij-community,MER-GROUP/intellij-community,caot/intellij-community,izonder/intellij-community,da1z/intellij-community,vladmm/intellij-community,clumsy/intellij-community,MER-GROUP/intellij-community,allotria/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,muntasirsyed/intellij-community,apixandru/intellij-community,semonte/intellij-community,apixandru/intellij-community,asedunov/intellij-community,jagguli/intellij-community,retomerz/intellij-community,fitermay/intellij-community,semonte/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,akosyakov/intellij-community,salguarnieri/intellij-community,holmes/intellij-community,slisson/intellij-community,idea4bsd/idea4bsd,vvv1559/intellij-community,caot/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,consulo/consulo,alphafoobar/intellij-community,amith01994/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,signed/intellij-community,fengbaicanhe/intellij-community,xfournet/intellij-community,salguarnieri/intellij-community,wreckJ/intellij-community,vladmm/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,clumsy/intellij-community,idea4bsd/idea4bsd,youdonghai/intellij-community,kool79/intellij-community,wreckJ/intellij-community,semonte/intellij-community,gnuhub/intellij-community,ibinti/intellij-community,tmpgit/intellij-community,diorcety/intellij-community,ol-loginov/intellij-community,ol-loginov/intellij-community,caot/intellij-community,ivan-fedorov/intellij-community,akosyakov/intellij-community,izonder/intellij-community,signed/intellij-community,allotria/intellij-community,alphafoobar/intellij-community,ernestp/consulo,fnouama/intellij-community,adedayo/intellij-community,apixandru/intellij-community,tmpgit/intellij-community,retomerz/intellij-community,fengbaicanhe/intellij-community,jagguli/intellij-community,ftomassetti/intellij-community,hurricup/intellij-community,SerCeMan/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,ahb0327/intellij-community,akosyakov/intellij-community,ftomassetti/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,semonte/intellij-community,youdonghai/intellij-community,fitermay/intellij-community,asedunov/intellij-community,ThiagoGarciaAlves/intellij-community,Distrotech/intellij-community,ThiagoGarciaAlves/intellij-community,lucafavatella/intellij-community,mglukhikh/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,vladmm/intellij-community,suncycheng/intellij-community,kdwink/intellij-community,slisson/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,fengbaicanhe/intellij-community,supersven/intellij-community,supersven/intellij-community,dslomov/intellij-community,tmpgit/intellij-community,kool79/intellij-community,signed/intellij-community,TangHao1987/intellij-community,da1z/intellij-community,amith01994/intellij-community,mglukhikh/intellij-community,ernestp/consulo,mglukhikh/intellij-community,Distrotech/intellij-community,ahb0327/intellij-community,TangHao1987/intellij-community,joewalnes/idea-community,jagguli/intellij-community,robovm/robovm-studio,fnouama/intellij-community,MER-GROUP/intellij-community,kdwink/intellij-community,jexp/idea2,semonte/intellij-community,michaelgallacher/intellij-community,ryano144/intellij-community,ahb0327/intellij-community,lucafavatella/intellij-community,gnuhub/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,michaelgallacher/intellij-community,holmes/intellij-community,wreckJ/intellij-community,retomerz/intellij-community,mglukhikh/intellij-community,youdonghai/intellij-community,SerCeMan/intellij-community,vladmm/intellij-community,gnuhub/intellij-community,vladmm/intellij-community,hurricup/intellij-community,caot/intellij-community,vvv1559/intellij-community,FHannes/intellij-community,samthor/intellij-community,adedayo/intellij-community,blademainer/intellij-community,orekyuu/intellij-community,clumsy/intellij-community,apixandru/intellij-community,lucafavatella/intellij-community,kdwink/intellij-community,ahb0327/intellij-community,ryano144/intellij-community,xfournet/intellij-community,fnouama/intellij-community,Distrotech/intellij-community,ryano144/intellij-community,jexp/idea2,izonder/intellij-community,vvv1559/intellij-community,supersven/intellij-community,slisson/intellij-community,da1z/intellij-community,ryano144/intellij-community,kdwink/intellij-community,blademainer/intellij-community,samthor/intellij-community,fengbaicanhe/intellij-community,jexp/idea2,fengbaicanhe/intellij-community,tmpgit/intellij-community,fitermay/intellij-community,wreckJ/intellij-community,fitermay/intellij-community,tmpgit/intellij-community,ibinti/intellij-community,hurricup/intellij-community,xfournet/intellij-community,nicolargo/intellij-community,MichaelNedzelsky/intellij-community,michaelgallacher/intellij-community,amith01994/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,fnouama/intellij-community,signed/intellij-community,MichaelNedzelsky/intellij-community,allotria/intellij-community,apixandru/intellij-community,joewalnes/idea-community,supersven/intellij-community,Lekanich/intellij-community,ol-loginov/intellij-community,nicolargo/intellij-community,youdonghai/intellij-community,ol-loginov/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,wreckJ/intellij-community,tmpgit/intellij-community,semonte/intellij-community,asedunov/intellij-community,amith01994/intellij-community,muntasirsyed/intellij-community,semonte/intellij-community,SerCeMan/intellij-community,petteyg/intellij-community,Lekanich/intellij-community,semonte/intellij-community,xfournet/intellij-community,petteyg/intellij-community,alphafoobar/intellij-community,izonder/intellij-community,ryano144/intellij-community,signed/intellij-community,clumsy/intellij-community,FHannes/intellij-community,joewalnes/idea-community,kdwink/intellij-community,robovm/robovm-studio,FHannes/intellij-community,petteyg/intellij-community,gnuhub/intellij-community,slisson/intellij-community,hurricup/intellij-community,diorcety/intellij-community,asedunov/intellij-community,ryano144/intellij-community,clumsy/intellij-community,jagguli/intellij-community,Lekanich/intellij-community,blademainer/intellij-community,suncycheng/intellij-community,izonder/intellij-community,nicolargo/intellij-community,akosyakov/intellij-community,orekyuu/intellij-community,vvv1559/intellij-community,alphafoobar/intellij-community,pwoodworth/intellij-community,jexp/idea2,MichaelNedzelsky/intellij-community,pwoodworth/intellij-community,slisson/intellij-community,blademainer/intellij-community,MichaelNedzelsky/intellij-community,akosyakov/intellij-community,MER-GROUP/intellij-community,suncycheng/intellij-community,alphafoobar/intellij-community,hurricup/intellij-community,petteyg/intellij-community,clumsy/intellij-community,allotria/intellij-community,ernestp/consulo,MER-GROUP/intellij-community,ol-loginov/intellij-community,muntasirsyed/intellij-community,ThiagoGarciaAlves/intellij-community,petteyg/intellij-community,vvv1559/intellij-community,vladmm/intellij-community,wreckJ/intellij-community,lucafavatella/intellij-community,MichaelNedzelsky/intellij-community,asedunov/intellij-community,suncycheng/intellij-community,tmpgit/intellij-community,SerCeMan/intellij-community,lucafavatella/intellij-community,MER-GROUP/intellij-community,ahb0327/intellij-community,ahb0327/intellij-community,kool79/intellij-community,fnouama/intellij-community,kool79/intellij-community,da1z/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,FHannes/intellij-community,nicolargo/intellij-community,lucafavatella/intellij-community,izonder/intellij-community,apixandru/intellij-community,orekyuu/intellij-community,holmes/intellij-community,kool79/intellij-community,akosyakov/intellij-community,SerCeMan/intellij-community,ryano144/intellij-community,clumsy/intellij-community,holmes/intellij-community,idea4bsd/idea4bsd,jagguli/intellij-community,signed/intellij-community,mglukhikh/intellij-community,wreckJ/intellij-community,ahb0327/intellij-community,fitermay/intellij-community,samthor/intellij-community,vvv1559/intellij-community,samthor/intellij-community,TangHao1987/intellij-community,MichaelNedzelsky/intellij-community,adedayo/intellij-community,tmpgit/intellij-community,amith01994/intellij-community,orekyuu/intellij-community,adedayo/intellij-community,izonder/intellij-community,Distrotech/intellij-community,pwoodworth/intellij-community,fengbaicanhe/intellij-community,ahb0327/intellij-community,xfournet/intellij-community,ftomassetti/intellij-community,joewalnes/idea-community,youdonghai/intellij-community,hurricup/intellij-community,FHannes/intellij-community,muntasirsyed/intellij-community,youdonghai/intellij-community,MER-GROUP/intellij-community,ivan-fedorov/intellij-community,retomerz/intellij-community,consulo/consulo,akosyakov/intellij-community,robovm/robovm-studio,tmpgit/intellij-community,jagguli/intellij-community,allotria/intellij-community,diorcety/intellij-community,petteyg/intellij-community,michaelgallacher/intellij-community,alphafoobar/intellij-community,dslomov/intellij-community,fitermay/intellij-community,Distrotech/intellij-community,robovm/robovm-studio,da1z/intellij-community,dslomov/intellij-community | package com.intellij.lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.psi.jsp.el.ELTokenType;
import com.intellij.psi.jsp.JspSpiUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.util.text.CharArrayCharSequence;
public class HtmlHighlightingLexer extends BaseHtmlLexer {
private static final Logger LOG = Logger.getInstance("#com.intellij.lexer.HtmlHighlightingLexer");
private static final int EMBEDDED_LEXER_ON = 0x1 << BASE_STATE_SHIFT;
private static final int EMBEDDED_LEXER_STATE_SHIFT = BASE_STATE_SHIFT + 1;
private Lexer embeddedLexer;
private Lexer styleLexer;
private Lexer scriptLexer;
private Lexer elLexer;
private boolean hasNoEmbeddments;
private static FileType ourStyleFileType;
private static FileType ourScriptFileType;
public class XmlEmbeddmentHandler implements TokenHandler {
public void handleElement(Lexer lexer) {
if (!hasSeenStyle() && !hasSeenScript() || hasNoEmbeddments) return;
final IElementType tokenType = lexer.getTokenType();
if ((tokenType==XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN && hasSeenAttribute()) ||
(tokenType==XmlTokenType.XML_DATA_CHARACTERS && hasSeenTag()) ||
tokenType==XmlTokenType.XML_COMMENT_CHARACTERS && hasSeenTag()
) {
setEmbeddedLexer();
if (embeddedLexer!=null) {
embeddedLexer.start(
getBufferSequence(),
HtmlHighlightingLexer.super.getTokenStart(),
skipToTheEndOfTheEmbeddment(),
embeddedLexer instanceof EmbedmentLexer ? ((EmbedmentLexer)embeddedLexer).getEmbeddedInitialState(tokenType) : 0
);
if (embeddedLexer.getTokenType() == null) {
// no content for embeddment
embeddedLexer = null;
}
}
}
}
}
public class ElEmbeddmentHandler implements TokenHandler {
public void handleElement(Lexer lexer) {
setEmbeddedLexer();
if (embeddedLexer != null) {
embeddedLexer.start(getBufferSequence(),HtmlHighlightingLexer.super.getTokenStart(),HtmlHighlightingLexer.super.getTokenEnd(), 0);
}
}
}
public HtmlHighlightingLexer() {
this(new MergingLexerAdapter(new FlexAdapter(new _HtmlLexer()),TOKENS_TO_MERGE),true);
}
protected HtmlHighlightingLexer(Lexer lexer, boolean caseInsensitive) {
super(lexer,caseInsensitive);
XmlEmbeddmentHandler value = new XmlEmbeddmentHandler();
registerHandler(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN,value);
registerHandler(XmlTokenType.XML_DATA_CHARACTERS,value);
registerHandler(XmlTokenType.XML_COMMENT_CHARACTERS,value);
}
public void start(char[] buffer, int startOffset, int endOffset, int initialState) {
start(new CharArrayCharSequence(buffer),startOffset, endOffset, initialState);
}
public void start(CharSequence buffer, int startOffset, int endOffset, int initialState) {
super.start(buffer, startOffset, endOffset, initialState);
if ((initialState & EMBEDDED_LEXER_ON)!=0) {
int state = initialState >> EMBEDDED_LEXER_STATE_SHIFT;
setEmbeddedLexer();
LOG.assertTrue(embeddedLexer!=null);
embeddedLexer.start(buffer,startOffset,skipToTheEndOfTheEmbeddment(),state);
} else {
embeddedLexer = null;
}
}
private void setEmbeddedLexer() {
Lexer newLexer = null;
if (hasSeenStyle()) {
if (styleLexer==null) {
styleLexer = (ourStyleFileType!=null)? SyntaxHighlighter.PROVIDER.create(ourStyleFileType, null, null).getHighlightingLexer():null;
}
newLexer = styleLexer;
} else if (hasSeenScript()) {
if (scriptLexer==null) {
scriptLexer = (ourScriptFileType!=null)? SyntaxHighlighter.PROVIDER.create(ourScriptFileType, null, null).getHighlightingLexer():null;
}
newLexer = scriptLexer;
} else if (super.getTokenType() == ELTokenType.JSP_EL_CONTENT) {
if (elLexer==null) elLexer = JspSpiUtil.createElLexer();
newLexer = elLexer;
}
if (newLexer!=null) {
embeddedLexer = newLexer;
}
}
public void advance() {
if (embeddedLexer!=null) {
embeddedLexer.advance();
if (embeddedLexer.getTokenType()==null) {
embeddedLexer=null;
}
}
if (embeddedLexer==null) {
super.advance();
}
}
protected boolean isValidAttributeValueTokenType(final IElementType tokenType) {
return super.isValidAttributeValueTokenType(tokenType) ||
tokenType == ELTokenType.JSP_EL_CONTENT;
}
public IElementType getTokenType() {
if (embeddedLexer!=null) {
return embeddedLexer.getTokenType();
} else {
IElementType tokenType = super.getTokenType();
// TODO: fix no DOCTYPE highlighting
if (tokenType == null) return tokenType;
if (tokenType==XmlTokenType.XML_NAME) {
// we need to convert single xml_name for tag name and attribute name into to separate
// lex types for the highlighting!
final int state = getState() & BASE_STATE_MASK;
if (isHtmlTagState(state)) {
tokenType = XmlTokenType.XML_TAG_NAME;
}
}
else if (tokenType == XmlTokenType.XML_WHITE_SPACE || tokenType == XmlTokenType.XML_REAL_WHITE_SPACE) {
if (hasSeenTag() && (hasSeenStyle() || hasSeenScript())) {
tokenType = XmlTokenType.XML_WHITE_SPACE;
} else {
tokenType = (getState()!=0)?XmlTokenType.TAG_WHITE_SPACE:XmlTokenType.XML_REAL_WHITE_SPACE;
}
} else if (tokenType == XmlTokenType.XML_CHAR_ENTITY_REF ||
tokenType == XmlTokenType.XML_ENTITY_REF_TOKEN
) {
// we need to convert char entity ref & entity ref in comments as comment chars
final int state = getState() & BASE_STATE_MASK;
if (state == _HtmlLexer.COMMENT) return XmlTokenType.XML_COMMENT_CHARACTERS;
}
return tokenType;
}
}
public int getTokenStart() {
if (embeddedLexer!=null) {
return embeddedLexer.getTokenStart();
} else {
return super.getTokenStart();
}
}
public int getTokenEnd() {
if (embeddedLexer!=null) {
return embeddedLexer.getTokenEnd();
} else {
return super.getTokenEnd();
}
}
public static final void registerStyleFileType(FileType fileType) {
ourStyleFileType = fileType;
}
public static void registerScriptFileType(FileType _scriptFileType) {
ourScriptFileType = _scriptFileType;
}
public int getState() {
int state = super.getState();
state |= ((embeddedLexer!=null)?EMBEDDED_LEXER_ON:0);
if (embeddedLexer!=null) state |= (embeddedLexer.getState() << EMBEDDED_LEXER_STATE_SHIFT);
return state;
}
protected boolean isHtmlTagState(int state) {
return state == _HtmlLexer.START_TAG_NAME || state == _HtmlLexer.END_TAG_NAME ||
state == _HtmlLexer.START_TAG_NAME2 || state == _HtmlLexer.END_TAG_NAME2;
}
public void setHasNoEmbeddments(boolean hasNoEmbeddments) {
this.hasNoEmbeddments = hasNoEmbeddments;
}
} | xml/impl/src/com/intellij/lexer/HtmlHighlightingLexer.java | package com.intellij.lexer;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.fileTypes.SyntaxHighlighter;
import com.intellij.psi.jsp.el.ELTokenType;
import com.intellij.psi.jsp.JspSpiUtil;
import com.intellij.psi.tree.IElementType;
import com.intellij.psi.xml.XmlTokenType;
import com.intellij.util.text.CharArrayCharSequence;
public class HtmlHighlightingLexer extends BaseHtmlLexer {
private static final Logger LOG = Logger.getInstance("#com.intellij.lexer.HtmlHighlightingLexer");
private static final int EMBEDDED_LEXER_ON = 0x1 << BASE_STATE_SHIFT;
private static final int EMBEDDED_LEXER_STATE_SHIFT = BASE_STATE_SHIFT + 1;
private Lexer embeddedLexer;
private Lexer styleLexer;
private Lexer scriptLexer;
private Lexer elLexer;
private boolean hasNoEmbeddments;
private static FileType ourStyleFileType;
private static FileType ourScriptFileType;
class XmlEmbeddmentHandler implements TokenHandler {
public void handleElement(Lexer lexer) {
if (!hasSeenStyle() && !hasSeenScript() || hasNoEmbeddments) return;
final IElementType tokenType = lexer.getTokenType();
if ((tokenType==XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN && hasSeenAttribute()) ||
(tokenType==XmlTokenType.XML_DATA_CHARACTERS && hasSeenTag()) ||
tokenType==XmlTokenType.XML_COMMENT_CHARACTERS && hasSeenTag()
) {
setEmbeddedLexer();
if (embeddedLexer!=null) {
embeddedLexer.start(
getBufferSequence(),
HtmlHighlightingLexer.super.getTokenStart(),
skipToTheEndOfTheEmbeddment(),
embeddedLexer instanceof EmbedmentLexer ? ((EmbedmentLexer)embeddedLexer).getEmbeddedInitialState(tokenType) : 0
);
if (embeddedLexer.getTokenType() == null) {
// no content for embeddment
embeddedLexer = null;
}
}
}
}
}
public class ElEmbeddmentHandler implements TokenHandler {
public void handleElement(Lexer lexer) {
setEmbeddedLexer();
if (embeddedLexer != null) {
embeddedLexer.start(getBufferSequence(),HtmlHighlightingLexer.super.getTokenStart(),HtmlHighlightingLexer.super.getTokenEnd(), 0);
}
}
}
public HtmlHighlightingLexer() {
this(new MergingLexerAdapter(new FlexAdapter(new _HtmlLexer()),TOKENS_TO_MERGE),true);
}
protected HtmlHighlightingLexer(Lexer lexer, boolean caseInsensitive) {
super(lexer,caseInsensitive);
XmlEmbeddmentHandler value = new XmlEmbeddmentHandler();
registerHandler(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN,value);
registerHandler(XmlTokenType.XML_DATA_CHARACTERS,value);
registerHandler(XmlTokenType.XML_COMMENT_CHARACTERS,value);
}
public void start(char[] buffer, int startOffset, int endOffset, int initialState) {
start(new CharArrayCharSequence(buffer),startOffset, endOffset, initialState);
}
public void start(CharSequence buffer, int startOffset, int endOffset, int initialState) {
super.start(buffer, startOffset, endOffset, initialState);
if ((initialState & EMBEDDED_LEXER_ON)!=0) {
int state = initialState >> EMBEDDED_LEXER_STATE_SHIFT;
setEmbeddedLexer();
LOG.assertTrue(embeddedLexer!=null);
embeddedLexer.start(buffer,startOffset,skipToTheEndOfTheEmbeddment(),state);
} else {
embeddedLexer = null;
}
}
private void setEmbeddedLexer() {
Lexer newLexer = null;
if (hasSeenStyle()) {
if (styleLexer==null) {
styleLexer = (ourStyleFileType!=null)? SyntaxHighlighter.PROVIDER.create(ourStyleFileType, null, null).getHighlightingLexer():null;
}
newLexer = styleLexer;
} else if (hasSeenScript()) {
if (scriptLexer==null) {
scriptLexer = (ourScriptFileType!=null)? SyntaxHighlighter.PROVIDER.create(ourScriptFileType, null, null).getHighlightingLexer():null;
}
newLexer = scriptLexer;
} else if (super.getTokenType() == ELTokenType.JSP_EL_CONTENT) {
if (elLexer==null) elLexer = JspSpiUtil.createElLexer();
newLexer = elLexer;
}
if (newLexer!=null) {
embeddedLexer = newLexer;
}
}
public void advance() {
if (embeddedLexer!=null) {
embeddedLexer.advance();
if (embeddedLexer.getTokenType()==null) {
embeddedLexer=null;
}
}
if (embeddedLexer==null) {
super.advance();
}
}
protected boolean isValidAttributeValueTokenType(final IElementType tokenType) {
return super.isValidAttributeValueTokenType(tokenType) ||
tokenType == ELTokenType.JSP_EL_CONTENT;
}
public IElementType getTokenType() {
if (embeddedLexer!=null) {
return embeddedLexer.getTokenType();
} else {
IElementType tokenType = super.getTokenType();
// TODO: fix no DOCTYPE highlighting
if (tokenType == null) return tokenType;
if (tokenType==XmlTokenType.XML_NAME) {
// we need to convert single xml_name for tag name and attribute name into to separate
// lex types for the highlighting!
final int state = getState() & BASE_STATE_MASK;
if (isHtmlTagState(state)) {
tokenType = XmlTokenType.XML_TAG_NAME;
}
}
else if (tokenType == XmlTokenType.XML_WHITE_SPACE || tokenType == XmlTokenType.XML_REAL_WHITE_SPACE) {
if (hasSeenTag() && (hasSeenStyle() || hasSeenScript())) {
tokenType = XmlTokenType.XML_WHITE_SPACE;
} else {
tokenType = (getState()!=0)?XmlTokenType.TAG_WHITE_SPACE:XmlTokenType.XML_REAL_WHITE_SPACE;
}
} else if (tokenType == XmlTokenType.XML_CHAR_ENTITY_REF ||
tokenType == XmlTokenType.XML_ENTITY_REF_TOKEN
) {
// we need to convert char entity ref & entity ref in comments as comment chars
final int state = getState() & BASE_STATE_MASK;
if (state == _HtmlLexer.COMMENT) return XmlTokenType.XML_COMMENT_CHARACTERS;
}
return tokenType;
}
}
public int getTokenStart() {
if (embeddedLexer!=null) {
return embeddedLexer.getTokenStart();
} else {
return super.getTokenStart();
}
}
public int getTokenEnd() {
if (embeddedLexer!=null) {
return embeddedLexer.getTokenEnd();
} else {
return super.getTokenEnd();
}
}
public static final void registerStyleFileType(FileType fileType) {
ourStyleFileType = fileType;
}
public static void registerScriptFileType(FileType _scriptFileType) {
ourScriptFileType = _scriptFileType;
}
public int getState() {
int state = super.getState();
state |= ((embeddedLexer!=null)?EMBEDDED_LEXER_ON:0);
if (embeddedLexer!=null) state |= (embeddedLexer.getState() << EMBEDDED_LEXER_STATE_SHIFT);
return state;
}
protected boolean isHtmlTagState(int state) {
return state == _HtmlLexer.START_TAG_NAME || state == _HtmlLexer.END_TAG_NAME ||
state == _HtmlLexer.START_TAG_NAME2 || state == _HtmlLexer.END_TAG_NAME2;
}
public void setHasNoEmbeddments(boolean hasNoEmbeddments) {
this.hasNoEmbeddments = hasNoEmbeddments;
}
} | access problem
| xml/impl/src/com/intellij/lexer/HtmlHighlightingLexer.java | access problem | <ide><path>ml/impl/src/com/intellij/lexer/HtmlHighlightingLexer.java
<ide> private static FileType ourStyleFileType;
<ide> private static FileType ourScriptFileType;
<ide>
<del> class XmlEmbeddmentHandler implements TokenHandler {
<add> public class XmlEmbeddmentHandler implements TokenHandler {
<ide> public void handleElement(Lexer lexer) {
<ide> if (!hasSeenStyle() && !hasSeenScript() || hasNoEmbeddments) return;
<ide> final IElementType tokenType = lexer.getTokenType(); |
|
Java | apache-2.0 | 5e890de755f45b04290ef083505c3dcc8f850c75 | 0 | shadabkhaniet/greenhouse,patidarjitu/networking-project-details1,StetsiukRoman/greenhouse,rajacsp/greenhouse,mqprichard/spring-greenhouse-clickstart,abisare/greenhouse,spring-projects/greenhouse,gienini/GreenHouseItteria,spring-projects/greenhouse,shadabkhaniet/greenhouse,aliasnash/z-greenhouse | package com.springsource.greenhouse.updates;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Update {
private String text;
private Date timestamp;
private long userId;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Date getTimestamp() {
return timestamp;
}
public void setTimestamp(Date timestamp) {
this.timestamp = timestamp;
}
public void setTimestamp(Long milliseconds) {
this.timestamp = new Date(milliseconds);
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
| src/main/java/com/springsource/greenhouse/updates/Update.java | package com.springsource.greenhouse.updates;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Update {
private String text;
private String timestamp;
private long userId;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getTimestamp() {
return timestamp;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
public void setTimestamp(Long milliseconds) {
Date date = new Date(milliseconds);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss z");
this.timestamp = formatter.format(date);
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
}
| modified the update class to use a date object instead of a string for the timestamp | src/main/java/com/springsource/greenhouse/updates/Update.java | modified the update class to use a date object instead of a string for the timestamp | <ide><path>rc/main/java/com/springsource/greenhouse/updates/Update.java
<ide>
<ide> private String text;
<ide>
<del> private String timestamp;
<add> private Date timestamp;
<ide>
<ide> private long userId;
<ide>
<ide> this.text = text;
<ide> }
<ide>
<del> public String getTimestamp() {
<add> public Date getTimestamp() {
<ide> return timestamp;
<ide> }
<ide>
<del> public void setTimestamp(String timestamp) {
<add> public void setTimestamp(Date timestamp) {
<ide> this.timestamp = timestamp;
<ide> }
<ide>
<ide> public void setTimestamp(Long milliseconds) {
<del> Date date = new Date(milliseconds);
<del> SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd 'at' hh:mm:ss z");
<del> this.timestamp = formatter.format(date);
<add> this.timestamp = new Date(milliseconds);
<ide> }
<ide>
<ide> public long getUserId() { |
|
JavaScript | mit | eddf6d8e0bb3c9c7a6b0394cb44c3fb8044ede39 | 0 | lduan/retour,lduan/retour,lduan/retour,bison-2014/laika,bison-2014/laika,bison-2014/laika | //= require polyline
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = new google.maps.LatLng(41.953819, -87.654750); // Chicago
var end = new google.maps.LatLng(38.637548, -90.205010); // St. Louis
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status){
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var polyline = decodePolyline(response);
var polygonGeoJsonObject = createPolygonFromPolyline(polyline);
// comment this line out to prevent drawing of polygon
var polygonCoords = processPolygonCoordsIntoLatLong(polygonGeoJsonObject)
}
});
}
//------------------------------------------------------------
// Define the LatLng coordinates for the polygon's path.
function processPolygonCoordsIntoLatLong(polygonGeoJsonObject) {
var polygonCoords = createLatLongObjects(polygonGeoJsonObject);
drawPolygon(polygonCoords)
return polygonCoords
}
function createLatLongObjects(geoJsonObject){
var latLongArray = []
var coordArray = geoJsonObject.features[0].geometry.coordinates[0]
console.log(coordArray)
coordArray.forEach(function(coord){
console.log(coord)
latLongArray.push(new google.maps.LatLng(coord[1], coord[0]))
return latLongArray
})
return latLongArray
}
// // Construct the polygon.
function drawPolygon(coordsToDraw){
bufferedPolygon = new google.maps.Polygon({
paths: coordsToDraw,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bufferedPolygon.setMap(map);
}
//-------------------------------------------------------------
function decodePolyline(response) {
var coord_array = polyline.decode(response.routes[0].overview_polyline);
return coord_array.map(function(coordinate) {
return [coordinate[1], coordinate[0]];
})
}
function createPolygonFromPolyline(polyline) {
var line = {
type:"Feature",
geometry:{
type:"LineString",
coordinates: polyline,
},
properties:{}
}
var polygon = turf.buffer(line, 25, 'miles')
$.ajax({
url: '/maps/search',
type: 'post',
beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'))},
contentType: "application/json",
dataType: "json",
data: JSON.stringify(polygon),
})
.success(function(response){
console.log(response.attractions)
loadMarkers(response.attractions)
})
return polygon
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
function loadMarkers(markerObjects){
$.each(markerObjects, function(i,item){
loadMarker(item);
});
}
function loadMarker(markerObject){
var latitude = markerObject.longlat.coordinates[1];
var longitude = markerObject.longlat.coordinates[0];
var coords = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: coords,
map: map
});
addInfoWindow(markerObject, marker);
}
function addInfoWindow(markerObject, marker){
var contentString = "<div>" +
'<p>' +
markerObject.name +
'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addDomListener(marker, 'click', function(){
infoWindow.open(map, marker);
});
} | app/assets/javascripts/map.js | //= require polyline
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = new google.maps.LatLng(41.953819, -87.654750); // Chicago
var end = new google.maps.LatLng(38.637548, -90.205010); // St. Louis
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status){
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var polyline = decodePolyline(response);
var polygonGeoJsonObject = createPolygonFromPolyline(polyline);
// comment this line out to prevent drawing of polygon
var polygonCoords = processPolygonCoordsIntoLatLong(polygonGeoJsonObject)
}
});
}
//------------------------------------------------------------
// Define the LatLng coordinates for the polygon's path.
function processPolygonCoordsIntoLatLong(polygonGeoJsonObject) {
var polygonCoords = createLatLongObjects(polygonGeoJsonObject);
drawPolygon(polygonCoords)
return polygonCoords
}
function createLatLongObjects(geoJsonObject){
var latLongArray = []
var coordArray = geoJsonObject.features[0].geometry.coordinates[0]
console.log(coordArray)
coordArray.forEach(function(coord){
console.log(coord)
latLongArray.push(new google.maps.LatLng(coord[1], coord[0]))
return latLongArray
})
return latLongArray
}
// // Construct the polygon.
function drawPolygon(coordsToDraw){
bufferedPolygon = new google.maps.Polygon({
paths: coordsToDraw,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
bufferedPolygon.setMap(map);
}
//-------------------------------------------------------------
function decodePolyline(response) {
var coord_array = polyline.decode(response.routes[0].overview_polyline);
return coord_array.map(function(coordinate) {
return [coordinate[1], coordinate[0]];
})
}
function createPolygonFromPolyline(polyline) {
var line = {
type:"Feature",
geometry:{
type:"LineString",
coordinates: polyline,
},
properties:{}
}
var polygon = turf.buffer(line, 25, 'miles')
$.ajax({
url: '/maps/search',
type: 'post',
beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'))},
contentType: "application/json",
dataType: "json",
data: JSON.stringify(polygon),
})
.success(function(response){
console.log(response.attractions)
loadMarkers(response.attractions)
})
return polygon
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
function loadMarkers(markerObjects){
$.each(markerObjects, function(i,item){
loadMarker(item);
});
}
function loadMarker(markerObject){
var latitude = markerObject.longlat.coordinates[1];
var longitude = markerObject.longlat.coordinates[0];
var coords = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
position: coords,
map: map
});
addInfoWindow(markerObject, marker);
}
function addInfoWindow(markerObject, marker){
var contentString = "<div>" +
'<p>' +
markerObject.name +
'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addDomListener(marker, 'click', function(){
infoWindow.open(map, marker);
});
}
| fixed indentation
| app/assets/javascripts/map.js | fixed indentation | <ide><path>pp/assets/javascripts/map.js
<ide> //= require polyline
<ide>
<del> var directionsDisplay;
<del> var directionsService = new google.maps.DirectionsService();
<del> var map;
<add>var directionsDisplay;
<add>var directionsService = new google.maps.DirectionsService();
<add>var map;
<ide>
<del> function initialize() {
<del> directionsDisplay = new google.maps.DirectionsRenderer();
<add>function initialize() {
<add> directionsDisplay = new google.maps.DirectionsRenderer();
<ide>
<del> var mapOptions = {
<del> zoom: 4,
<del> mapTypeId: google.maps.MapTypeId.ROADMAP
<del> };
<add> var mapOptions = {
<add> zoom: 4,
<add> mapTypeId: google.maps.MapTypeId.ROADMAP
<add> };
<ide>
<del> map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
<del> directionsDisplay.setMap(map);
<add> map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
<add> directionsDisplay.setMap(map);
<ide>
<del> calcRoute();
<del> }
<add> calcRoute();
<add>}
<ide>
<del> function calcRoute() {
<add>function calcRoute() {
<ide>
<del> var start = new google.maps.LatLng(41.953819, -87.654750); // Chicago
<del> var end = new google.maps.LatLng(38.637548, -90.205010); // St. Louis
<del> var waypts = [];
<del> var checkboxArray = document.getElementById('waypoints');
<add> var start = new google.maps.LatLng(41.953819, -87.654750); // Chicago
<add> var end = new google.maps.LatLng(38.637548, -90.205010); // St. Louis
<add> var waypts = [];
<add> var checkboxArray = document.getElementById('waypoints');
<ide>
<del> for (var i = 0; i < checkboxArray.length; i++) {
<del> if (checkboxArray.options[i].selected == true) {
<del> waypts.push({
<del> location:checkboxArray[i].value,
<del> stopover:true});
<del> }
<del> }
<add> for (var i = 0; i < checkboxArray.length; i++) {
<add> if (checkboxArray.options[i].selected == true) {
<add> waypts.push({
<add> location:checkboxArray[i].value,
<add> stopover:true});
<add> }
<add> }
<ide>
<del> var request = {
<del> origin: start,
<del> destination: end,
<del> waypoints: waypts,
<del> optimizeWaypoints: true,
<del> travelMode: google.maps.TravelMode.DRIVING
<del> };
<add> var request = {
<add> origin: start,
<add> destination: end,
<add> waypoints: waypts,
<add> optimizeWaypoints: true,
<add> travelMode: google.maps.TravelMode.DRIVING
<add> };
<ide>
<del> directionsService.route(request, function(response, status){
<add> directionsService.route(request, function(response, status){
<ide>
<del> if (status == google.maps.DirectionsStatus.OK) {
<del> directionsDisplay.setDirections(response);
<add> if (status == google.maps.DirectionsStatus.OK) {
<add> directionsDisplay.setDirections(response);
<ide>
<del> var polyline = decodePolyline(response);
<del> var polygonGeoJsonObject = createPolygonFromPolyline(polyline);
<add> var polyline = decodePolyline(response);
<add> var polygonGeoJsonObject = createPolygonFromPolyline(polyline);
<ide>
<ide> // comment this line out to prevent drawing of polygon
<del> var polygonCoords = processPolygonCoordsIntoLatLong(polygonGeoJsonObject)
<del> }
<del> });
<del> }
<add> var polygonCoords = processPolygonCoordsIntoLatLong(polygonGeoJsonObject)
<add> }
<add> });
<add>}
<ide>
<ide> //------------------------------------------------------------
<ide>
<ide> // Define the LatLng coordinates for the polygon's path.
<del> function processPolygonCoordsIntoLatLong(polygonGeoJsonObject) {
<del> var polygonCoords = createLatLongObjects(polygonGeoJsonObject);
<del> drawPolygon(polygonCoords)
<del> return polygonCoords
<add>function processPolygonCoordsIntoLatLong(polygonGeoJsonObject) {
<add> var polygonCoords = createLatLongObjects(polygonGeoJsonObject);
<add> drawPolygon(polygonCoords)
<add> return polygonCoords
<ide>
<del> }
<add>}
<ide>
<del> function createLatLongObjects(geoJsonObject){
<del> var latLongArray = []
<del> var coordArray = geoJsonObject.features[0].geometry.coordinates[0]
<add>function createLatLongObjects(geoJsonObject){
<add> var latLongArray = []
<add> var coordArray = geoJsonObject.features[0].geometry.coordinates[0]
<ide>
<del> console.log(coordArray)
<add> console.log(coordArray)
<ide>
<del> coordArray.forEach(function(coord){
<del> console.log(coord)
<del> latLongArray.push(new google.maps.LatLng(coord[1], coord[0]))
<del> return latLongArray
<del> })
<add> coordArray.forEach(function(coord){
<add> console.log(coord)
<add> latLongArray.push(new google.maps.LatLng(coord[1], coord[0]))
<ide> return latLongArray
<del> }
<add> })
<add> return latLongArray
<add>}
<ide>
<del> // // Construct the polygon.
<del> function drawPolygon(coordsToDraw){
<del> bufferedPolygon = new google.maps.Polygon({
<del> paths: coordsToDraw,
<del> strokeColor: '#FF0000',
<del> strokeOpacity: 0.8,
<del> strokeWeight: 2,
<del> fillColor: '#FF0000',
<del> fillOpacity: 0.35
<del> });
<del> bufferedPolygon.setMap(map);
<del> }
<add>// // Construct the polygon.
<add>function drawPolygon(coordsToDraw){
<add> bufferedPolygon = new google.maps.Polygon({
<add> paths: coordsToDraw,
<add> strokeColor: '#FF0000',
<add> strokeOpacity: 0.8,
<add> strokeWeight: 2,
<add> fillColor: '#FF0000',
<add> fillOpacity: 0.35
<add> });
<add> bufferedPolygon.setMap(map);
<add>}
<ide>
<ide> //-------------------------------------------------------------
<ide>
<del> function decodePolyline(response) {
<del> var coord_array = polyline.decode(response.routes[0].overview_polyline);
<del> return coord_array.map(function(coordinate) {
<del> return [coordinate[1], coordinate[0]];
<del> })
<del> }
<add>function decodePolyline(response) {
<add> var coord_array = polyline.decode(response.routes[0].overview_polyline);
<add> return coord_array.map(function(coordinate) {
<add> return [coordinate[1], coordinate[0]];
<add> })
<add>}
<ide>
<del> function createPolygonFromPolyline(polyline) {
<del> var line = {
<del> type:"Feature",
<del> geometry:{
<del> type:"LineString",
<del> coordinates: polyline,
<del> },
<del> properties:{}
<del> }
<add>function createPolygonFromPolyline(polyline) {
<add> var line = {
<add> type:"Feature",
<add> geometry:{
<add> type:"LineString",
<add> coordinates: polyline,
<add> },
<add> properties:{}
<add> }
<ide>
<del> var polygon = turf.buffer(line, 25, 'miles')
<add> var polygon = turf.buffer(line, 25, 'miles')
<ide>
<del> $.ajax({
<del> url: '/maps/search',
<del> type: 'post',
<del> beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'))},
<del> contentType: "application/json",
<del> dataType: "json",
<del> data: JSON.stringify(polygon),
<del> })
<del> .success(function(response){
<del> console.log(response.attractions)
<del> loadMarkers(response.attractions)
<del> })
<add> $.ajax({
<add> url: '/maps/search',
<add> type: 'post',
<add> beforeSend: function(xhr) { xhr.setRequestHeader('X-CSRF-Token', $('meta[name=csrf-token]').attr('content'))},
<add> contentType: "application/json",
<add> dataType: "json",
<add> data: JSON.stringify(polygon),
<add> })
<add> .success(function(response){
<add> console.log(response.attractions)
<add> loadMarkers(response.attractions)
<add> })
<ide>
<del> return polygon
<del> }
<add> return polygon
<add>}
<ide>
<ide> google.maps.event.addDomListener(window, 'load', initialize);
<ide> google.maps.event.addDomListener(window, "resize", function() {
<ide> '</p>' +
<ide> '</div>';
<ide>
<del> var infoWindow = new google.maps.InfoWindow({
<del> content: contentString
<del> });
<add> var infoWindow = new google.maps.InfoWindow({
<add> content: contentString
<add> });
<ide>
<del> google.maps.event.addDomListener(marker, 'click', function(){
<del> infoWindow.open(map, marker);
<del> });
<add> google.maps.event.addDomListener(marker, 'click', function(){
<add> infoWindow.open(map, marker);
<add> });
<ide> } |
|
Java | apache-2.0 | 7e3cc007bddc613a2dd135370972de4bfc5bd43f | 0 | fitermay/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,vvv1559/intellij-community,fitermay/intellij-community,fitermay/intellij-community,retomerz/intellij-community,signed/intellij-community,signed/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,ThiagoGarciaAlves/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,vvv1559/intellij-community,allotria/intellij-community,idea4bsd/idea4bsd,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,xfournet/intellij-community,retomerz/intellij-community,semonte/intellij-community,michaelgallacher/intellij-community,salguarnieri/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,signed/intellij-community,retomerz/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,ThiagoGarciaAlves/intellij-community,vvv1559/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,allotria/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,xfournet/intellij-community,asedunov/intellij-community,allotria/intellij-community,fitermay/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,semonte/intellij-community,retomerz/intellij-community,ibinti/intellij-community,xfournet/intellij-community,xfournet/intellij-community,vvv1559/intellij-community,youdonghai/intellij-community,vvv1559/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,idea4bsd/idea4bsd,fitermay/intellij-community,michaelgallacher/intellij-community,youdonghai/intellij-community,idea4bsd/idea4bsd,apixandru/intellij-community,allotria/intellij-community,apixandru/intellij-community,hurricup/intellij-community,youdonghai/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fitermay/intellij-community,xfournet/intellij-community,retomerz/intellij-community,FHannes/intellij-community,vvv1559/intellij-community,da1z/intellij-community,youdonghai/intellij-community,suncycheng/intellij-community,retomerz/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,apixandru/intellij-community,asedunov/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,fitermay/intellij-community,signed/intellij-community,signed/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,idea4bsd/idea4bsd,mglukhikh/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,retomerz/intellij-community,michaelgallacher/intellij-community,allotria/intellij-community,vvv1559/intellij-community,idea4bsd/idea4bsd,allotria/intellij-community,youdonghai/intellij-community,da1z/intellij-community,asedunov/intellij-community,apixandru/intellij-community,FHannes/intellij-community,salguarnieri/intellij-community,da1z/intellij-community,fitermay/intellij-community,semonte/intellij-community,youdonghai/intellij-community,salguarnieri/intellij-community,idea4bsd/idea4bsd,michaelgallacher/intellij-community,allotria/intellij-community,mglukhikh/intellij-community,semonte/intellij-community,fitermay/intellij-community,da1z/intellij-community,da1z/intellij-community,ibinti/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,signed/intellij-community,salguarnieri/intellij-community,retomerz/intellij-community,hurricup/intellij-community,signed/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,xfournet/intellij-community,suncycheng/intellij-community,youdonghai/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,xfournet/intellij-community,da1z/intellij-community,hurricup/intellij-community,salguarnieri/intellij-community,semonte/intellij-community,retomerz/intellij-community,ibinti/intellij-community,allotria/intellij-community,signed/intellij-community,vvv1559/intellij-community,ibinti/intellij-community,signed/intellij-community,FHannes/intellij-community,FHannes/intellij-community,da1z/intellij-community,hurricup/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,apixandru/intellij-community,da1z/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,idea4bsd/idea4bsd,da1z/intellij-community,asedunov/intellij-community,mglukhikh/intellij-community,hurricup/intellij-community,vvv1559/intellij-community,semonte/intellij-community,retomerz/intellij-community,da1z/intellij-community,idea4bsd/idea4bsd,xfournet/intellij-community,asedunov/intellij-community,ibinti/intellij-community,allotria/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,apixandru/intellij-community,michaelgallacher/intellij-community,idea4bsd/idea4bsd,asedunov/intellij-community,semonte/intellij-community,suncycheng/intellij-community,xfournet/intellij-community,allotria/intellij-community,hurricup/intellij-community,allotria/intellij-community,retomerz/intellij-community,salguarnieri/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,mglukhikh/intellij-community,fitermay/intellij-community,FHannes/intellij-community,apixandru/intellij-community,idea4bsd/idea4bsd,suncycheng/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,allotria/intellij-community,ThiagoGarciaAlves/intellij-community,michaelgallacher/intellij-community,signed/intellij-community,ThiagoGarciaAlves/intellij-community,semonte/intellij-community,apixandru/intellij-community,mglukhikh/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,michaelgallacher/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,ibinti/intellij-community,apixandru/intellij-community,ibinti/intellij-community,FHannes/intellij-community,allotria/intellij-community,ibinti/intellij-community,mglukhikh/intellij-community,asedunov/intellij-community,retomerz/intellij-community,apixandru/intellij-community,asedunov/intellij-community,youdonghai/intellij-community,asedunov/intellij-community,asedunov/intellij-community,FHannes/intellij-community,FHannes/intellij-community,FHannes/intellij-community,FHannes/intellij-community,suncycheng/intellij-community,fitermay/intellij-community,suncycheng/intellij-community,ibinti/intellij-community,xfournet/intellij-community,FHannes/intellij-community,michaelgallacher/intellij-community,apixandru/intellij-community,xfournet/intellij-community,idea4bsd/idea4bsd,semonte/intellij-community,FHannes/intellij-community,semonte/intellij-community,signed/intellij-community,FHannes/intellij-community,da1z/intellij-community,salguarnieri/intellij-community,hurricup/intellij-community,ibinti/intellij-community,ThiagoGarciaAlves/intellij-community,suncycheng/intellij-community,salguarnieri/intellij-community,apixandru/intellij-community | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.terminal;
import com.intellij.execution.process.ColoredOutputTypeRegistry;
import com.intellij.execution.process.ConsoleHighlighter;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.jediterm.terminal.emulator.ColorPalette;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
/**
* @author traff
*/
public class JBTerminalSchemeColorPalette extends ColorPalette {
private final EditorColorsScheme myColorsScheme;
protected JBTerminalSchemeColorPalette(EditorColorsScheme scheme) {
super();
myColorsScheme = scheme;
}
@Override
public Color[] getIndexColors() {
Color[] result = new Color[ 16 ];
for (int i = 0; i < result.length; i++) {
result[i] = myColorsScheme.getAttributes(ColoredOutputTypeRegistry.getAnsiColorKey(i)).getForegroundColor();
}
return result;
}
}
| plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSchemeColorPalette.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.plugins.terminal;
import com.intellij.execution.process.ColoredOutputTypeRegistry;
import com.intellij.execution.process.ConsoleHighlighter;
import com.intellij.openapi.editor.colors.EditorColorsScheme;
import com.jediterm.terminal.emulator.ColorPalette;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.awt.*;
/**
* @author traff
*/
public class JBTerminalSchemeColorPalette extends ColorPalette {
private final EditorColorsScheme myColorsScheme;
protected JBTerminalSchemeColorPalette(EditorColorsScheme scheme) {
super();
myColorsScheme = scheme;
}
@Override
public Color[] getIndexColors() {
Color[] result = XTERM_PALETTE.getIndexColors();
for (int i = 1; i < 7; i++) {
result[i] = myColorsScheme.getAttributes(ColoredOutputTypeRegistry.getAnsiColorKey(i)).getForegroundColor();
}
return result;
}
}
| IDEA-118247 fix application of Color Scheme to Terminal.
Previously the Terminal view only used ANSI colors 1-6 (the non-bright
colors except for black and white) from the Color Scheme and inherited
colors 0 and 7-15 from the JediTerm defaults. That resulted in strange
partial application of the Color Scheme and, frequently, unreadable
text. This corrects the palette implementation to pull all 16 ANSI
colors from the Color Scheme.
| plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSchemeColorPalette.java | IDEA-118247 fix application of Color Scheme to Terminal. | <ide><path>lugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSchemeColorPalette.java
<ide>
<ide> @Override
<ide> public Color[] getIndexColors() {
<del> Color[] result = XTERM_PALETTE.getIndexColors();
<del> for (int i = 1; i < 7; i++) {
<add> Color[] result = new Color[ 16 ];
<add> for (int i = 0; i < result.length; i++) {
<ide> result[i] = myColorsScheme.getAttributes(ColoredOutputTypeRegistry.getAnsiColorKey(i)).getForegroundColor();
<ide> }
<ide> return result; |
|
Java | apache-2.0 | 82afcf663f27c8f096f089df9652a1434d8342cd | 0 | francescomari/jackrabbit-oak,catholicon/jackrabbit-oak,catholicon/jackrabbit-oak,ieb/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,afilimonov/jackrabbit-oak,leftouterjoin/jackrabbit-oak,mduerig/jackrabbit-oak,alexkli/jackrabbit-oak,davidegiannella/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,mduerig/jackrabbit-oak,code-distillery/jackrabbit-oak,ieb/jackrabbit-oak,tripodsan/jackrabbit-oak,meggermo/jackrabbit-oak,ieb/jackrabbit-oak,catholicon/jackrabbit-oak,tripodsan/jackrabbit-oak,davidegiannella/jackrabbit-oak,catholicon/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,bdelacretaz/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,anchela/jackrabbit-oak,chetanmeh/jackrabbit-oak,code-distillery/jackrabbit-oak,mduerig/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,stillalex/jackrabbit-oak,francescomari/jackrabbit-oak,alexparvulescu/jackrabbit-oak,francescomari/jackrabbit-oak,alexkli/jackrabbit-oak,rombert/jackrabbit-oak,meggermo/jackrabbit-oak,tripodsan/jackrabbit-oak,meggermo/jackrabbit-oak,davidegiannella/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,code-distillery/jackrabbit-oak,anchela/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,bdelacretaz/jackrabbit-oak,alexkli/jackrabbit-oak,joansmith/jackrabbit-oak,yesil/jackrabbit-oak,alexparvulescu/jackrabbit-oak,stillalex/jackrabbit-oak,kwin/jackrabbit-oak,alexparvulescu/jackrabbit-oak,kwin/jackrabbit-oak,mduerig/jackrabbit-oak,bdelacretaz/jackrabbit-oak,anchela/jackrabbit-oak,mduerig/jackrabbit-oak,tripodsan/jackrabbit-oak,joansmith/jackrabbit-oak,yesil/jackrabbit-oak,chetanmeh/jackrabbit-oak,yesil/jackrabbit-oak,joansmith/jackrabbit-oak,code-distillery/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,chetanmeh/jackrabbit-oak,leftouterjoin/jackrabbit-oak,anchela/jackrabbit-oak,catholicon/jackrabbit-oak,kwin/jackrabbit-oak,rombert/jackrabbit-oak,bdelacretaz/jackrabbit-oak,francescomari/jackrabbit-oak,davidegiannella/jackrabbit-oak,joansmith/jackrabbit-oak,leftouterjoin/jackrabbit-oak,anchela/jackrabbit-oak,alexparvulescu/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,rombert/jackrabbit-oak,leftouterjoin/jackrabbit-oak,yesil/jackrabbit-oak,joansmith/jackrabbit-oak,AndreasAbdi/jackrabbit-oak,alexkli/jackrabbit-oak,alexparvulescu/jackrabbit-oak,stillalex/jackrabbit-oak,kwin/jackrabbit-oak,alexkli/jackrabbit-oak,afilimonov/jackrabbit-oak,afilimonov/jackrabbit-oak,meggermo/jackrabbit-oak,afilimonov/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,chetanmeh/jackrabbit-oak,davidegiannella/jackrabbit-oak,FlakyTestDetection/jackrabbit-oak,stillalex/jackrabbit-oak,chetanmeh/jackrabbit-oak,Kast0rTr0y/jackrabbit-oak,rombert/jackrabbit-oak,ieb/jackrabbit-oak,francescomari/jackrabbit-oak,meggermo/jackrabbit-oak,kwin/jackrabbit-oak | /*
* 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.jackrabbit.oak.core;
import java.util.Iterator;
import java.util.Random;
import org.apache.jackrabbit.mk.api.MicroKernel;
import org.apache.jackrabbit.mk.core.MicroKernelImpl;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.Rebase;
import org.apache.jackrabbit.oak.kernel.KernelNodeStore;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.AddNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.CopyNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.MoveNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.RemoveNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.RemoveProperty;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.Save;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.SetProperty;
import static org.junit.Assert.assertEquals;
/**
* Fuzz test running random sequences of operations on {@link Tree}.
* Run with -DRootImplFuzzIT-seed=42 to set a specific seed (i.e. 42);
*/
public class RootImplFuzzIT {
static final Logger log = LoggerFactory.getLogger(RootImplFuzzIT.class);
private static final int OP_COUNT = 5000;
private static final int SEED = Integer.getInteger(
RootImplFuzzIT.class.getSimpleName() + "-seed",
new Random().nextInt());
private static final Random random = new Random(SEED);
private KernelNodeStore store1;
private RootImpl root1;
private KernelNodeStore store2;
private RootImpl root2;
private int counter;
@Before
public void setup() {
counter = 0;
MicroKernel mk1 = new MicroKernelImpl("./target/mk1/" + random.nextInt());
store1 = new KernelNodeStore(mk1);
mk1.commit("", "+\"/root\":{}", mk1.getHeadRevision(), "");
root1 = new RootImpl(store1);
MicroKernel mk2 = new MicroKernelImpl("./target/mk2/" + random.nextInt());
store2 = new KernelNodeStore(mk2);
mk2.commit("", "+\"/root\":{}", mk2.getHeadRevision(), "");
root2 = new RootImpl(store2);
}
@Test
public void fuzzTest() throws Exception {
for (Operation op : operations(OP_COUNT)) {
log.info("{}", op);
op.apply(root1);
op.apply(root2);
checkEqual(root1.getTree("/"), root2.getTree("/"));
root1.commit();
checkEqual(root1.getTree("/"), root2.getTree("/"));
if (op instanceof Save) {
root2.commit();
assertEquals("seed " + SEED, store1.getRoot(), store2.getRoot());
}
}
}
private Iterable<Operation> operations(final int count) {
return new Iterable<Operation>() {
int k = count;
@Override
public Iterator<Operation> iterator() {
return new Iterator<Operation>() {
@Override
public boolean hasNext() {
return k-- > 0;
}
@Override
public Operation next() {
return createOperation();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
abstract static class Operation {
abstract void apply(RootImpl root);
static class AddNode extends Operation {
private final String parentPath;
private final String name;
AddNode(String parentPath, String name) {
this.parentPath = parentPath;
this.name = name;
}
@Override
void apply(RootImpl root) {
root.getTree(parentPath).addChild(name);
}
@Override
public String toString() {
return '+' + PathUtils.concat(parentPath, name) + ":{}";
}
}
static class RemoveNode extends Operation {
private final String path;
RemoveNode(String path) {
this.path = path;
}
@Override
void apply(RootImpl root) {
String parentPath = PathUtils.getParentPath(path);
String name = PathUtils.getName(path);
root.getTree(parentPath).getChild(name).remove();
}
@Override
public String toString() {
return '-' + path;
}
}
static class MoveNode extends Operation {
private final String source;
private final String destination;
MoveNode(String source, String destParent, String destName) {
this.source = source;
destination = PathUtils.concat(destParent, destName);
}
@Override
void apply(RootImpl root) {
root.move(source, destination);
}
@Override
public String toString() {
return '>' + source + ':' + destination;
}
}
static class CopyNode extends Operation {
private final String source;
private final String destination;
CopyNode(String source, String destParent, String destName) {
this.source = source;
destination = PathUtils.concat(destParent, destName);
}
@Override
void apply(RootImpl root) {
root.copy(source, destination);
}
@Override
public String toString() {
return '*' + source + ':' + destination;
}
}
static class SetProperty extends Operation {
private final String parentPath;
private final String propertyName;
private final String propertyValue;
SetProperty(String parentPath, String name, String value) {
this.parentPath = parentPath;
this.propertyName = name;
this.propertyValue = value;
}
@Override
void apply(RootImpl root) {
root.getTree(parentPath).setProperty(propertyName, propertyValue);
}
@Override
public String toString() {
return '^' + PathUtils.concat(parentPath, propertyName) + ':'
+ propertyValue;
}
}
static class RemoveProperty extends Operation {
private final String parentPath;
private final String name;
RemoveProperty(String parentPath, String name) {
this.parentPath = parentPath;
this.name = name;
}
@Override
void apply(RootImpl root) {
root.getTree(parentPath).removeProperty(name);
}
@Override
public String toString() {
return '^' + PathUtils.concat(parentPath, name) + ":null";
}
}
static class Save extends Operation {
@Override
void apply(RootImpl root) {
// empty
}
@Override
public String toString() {
return "save";
}
}
static class Rebase extends Operation {
@Override
void apply(RootImpl root) {
root.rebase();
}
@Override
public String toString() {
return "rebase";
}
}
}
private Operation createOperation() {
Operation op;
do {
switch (random.nextInt(11)) {
case 0:
case 1:
case 2:
op = createAddNode();
break;
case 3:
op = createRemoveNode();
break;
case 4:
op = createMoveNode();
break;
case 5:
// Too many copy ops make the test way slow
op = random.nextInt(10) == 0 ? createCopyNode() : null;
break;
case 6:
op = createAddProperty();
break;
case 7:
op = createSetProperty();
break;
case 8:
op = createRemoveProperty();
break;
case 9:
op = new Save();
break;
case 10:
op = new Rebase();
break;
default:
throw new IllegalStateException();
}
} while (op == null);
return op;
}
private Operation createAddNode() {
String parentPath = chooseNodePath();
String name = createNodeName();
return new AddNode(parentPath, name);
}
private Operation createRemoveNode() {
String path = chooseNodePath();
return "/root".equals(path) ? null : new RemoveNode(path);
}
private Operation createMoveNode() {
String source = chooseNodePath();
String destParent = chooseNodePath();
String destName = createNodeName();
return "/root".equals(source) || destParent.startsWith(source)
? null
: new MoveNode(source, destParent, destName);
}
private Operation createCopyNode() {
String source = chooseNodePath();
String destParent = chooseNodePath();
String destName = createNodeName();
return "/root".equals(source)
? null
: new CopyNode(source, destParent, destName);
}
private Operation createAddProperty() {
String parent = chooseNodePath();
String name = createPropertyName();
String value = createValue();
return new SetProperty(parent, name, value);
}
private Operation createSetProperty() {
String path = choosePropertyPath();
if (path == null) {
return null;
}
String value = createValue();
return new SetProperty(PathUtils.getParentPath(path), PathUtils.getName(path), value);
}
private Operation createRemoveProperty() {
String path = choosePropertyPath();
if (path == null) {
return null;
}
return new RemoveProperty(PathUtils.getParentPath(path), PathUtils.getName(path));
}
private String createNodeName() {
return "N" + counter++;
}
private String createPropertyName() {
return "P" + counter++;
}
private String chooseNodePath() {
String path = "/root";
String next;
while ((next = chooseNode(path)) != null) {
path = next;
}
return path;
}
private String choosePropertyPath() {
return chooseProperty(chooseNodePath());
}
private String chooseNode(String parentPath) {
Tree state = root1.getTree(parentPath);
int k = random.nextInt((int) (state.getChildrenCount() + 1));
int c = 0;
for (Tree child : state.getChildren()) {
if (c++ == k) {
return PathUtils.concat(parentPath, child.getName());
}
}
return null;
}
private String chooseProperty(String parentPath) {
Tree state = root1.getTree(parentPath);
int k = random.nextInt((int) (state.getPropertyCount() + 1));
int c = 0;
for (PropertyState entry : state.getProperties()) {
if (c++ == k) {
return PathUtils.concat(parentPath, entry.getName());
}
}
return null;
}
private String createValue() {
return ("V" + counter++);
}
private static void checkEqual(Tree tree1, Tree tree2) {
String message =
tree1.getPath() + "!=" + tree2.getPath()
+ " (seed " + SEED + ')';
assertEquals(message, tree1.getPath(), tree2.getPath());
assertEquals(message, tree1.getChildrenCount(), tree2.getChildrenCount());
assertEquals(message, tree1.getPropertyCount(), tree2.getPropertyCount());
for (PropertyState property1 : tree1.getProperties()) {
PropertyState property2 = tree2.getProperty(property1.getName());
assertEquals(message, property1, property2);
}
for (Tree child1 : tree1.getChildren()) {
checkEqual(child1, tree2.getChild(child1.getName()));
}
}
}
| oak-core/src/test/java/org/apache/jackrabbit/oak/core/RootImplFuzzIT.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.jackrabbit.oak.core;
import java.util.Iterator;
import java.util.Random;
import org.apache.jackrabbit.mk.api.MicroKernel;
import org.apache.jackrabbit.mk.core.MicroKernelImpl;
import org.apache.jackrabbit.oak.api.PropertyState;
import org.apache.jackrabbit.oak.api.Tree;
import org.apache.jackrabbit.oak.commons.PathUtils;
import org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.Rebase;
import org.apache.jackrabbit.oak.kernel.KernelNodeStore;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.AddNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.CopyNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.MoveNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.RemoveNode;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.RemoveProperty;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.Save;
import static org.apache.jackrabbit.oak.core.RootImplFuzzIT.Operation.SetProperty;
import static org.junit.Assert.assertEquals;
/**
* Fuzz test running random sequences of operations on {@link Tree}.
* Run with -DKernelRootFuzzIT-seed=42 to set a specific seed (i.e. 42);
*/
public class RootImplFuzzIT {
static final Logger log = LoggerFactory.getLogger(RootImplFuzzIT.class);
private static final int OP_COUNT = 5000;
private static final int SEED = Integer.getInteger(
RootImplFuzzIT.class.getSimpleName() + "-seed",
new Random().nextInt());
private static final Random random = new Random(SEED);
private KernelNodeStore store1;
private RootImpl root1;
private KernelNodeStore store2;
private RootImpl root2;
private int counter;
@Before
public void setup() {
counter = 0;
MicroKernel mk1 = new MicroKernelImpl("./target/mk1/" + random.nextInt());
store1 = new KernelNodeStore(mk1);
mk1.commit("", "+\"/root\":{}", mk1.getHeadRevision(), "");
root1 = new RootImpl(store1);
MicroKernel mk2 = new MicroKernelImpl("./target/mk2/" + random.nextInt());
store2 = new KernelNodeStore(mk2);
mk2.commit("", "+\"/root\":{}", mk2.getHeadRevision(), "");
root2 = new RootImpl(store2);
}
@Test
public void fuzzTest() throws Exception {
for (Operation op : operations(OP_COUNT)) {
log.info("{}", op);
op.apply(root1);
op.apply(root2);
checkEqual(root1.getTree("/"), root2.getTree("/"));
root1.commit();
checkEqual(root1.getTree("/"), root2.getTree("/"));
if (op instanceof Save) {
root2.commit();
assertEquals("seed " + SEED, store1.getRoot(), store2.getRoot());
}
}
}
private Iterable<Operation> operations(final int count) {
return new Iterable<Operation>() {
int k = count;
@Override
public Iterator<Operation> iterator() {
return new Iterator<Operation>() {
@Override
public boolean hasNext() {
return k-- > 0;
}
@Override
public Operation next() {
return createOperation();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
}
abstract static class Operation {
abstract void apply(RootImpl root);
static class AddNode extends Operation {
private final String parentPath;
private final String name;
AddNode(String parentPath, String name) {
this.parentPath = parentPath;
this.name = name;
}
@Override
void apply(RootImpl root) {
root.getTree(parentPath).addChild(name);
}
@Override
public String toString() {
return '+' + PathUtils.concat(parentPath, name) + ":{}";
}
}
static class RemoveNode extends Operation {
private final String path;
RemoveNode(String path) {
this.path = path;
}
@Override
void apply(RootImpl root) {
String parentPath = PathUtils.getParentPath(path);
String name = PathUtils.getName(path);
root.getTree(parentPath).getChild(name).remove();
}
@Override
public String toString() {
return '-' + path;
}
}
static class MoveNode extends Operation {
private final String source;
private final String destination;
MoveNode(String source, String destParent, String destName) {
this.source = source;
destination = PathUtils.concat(destParent, destName);
}
@Override
void apply(RootImpl root) {
root.move(source, destination);
}
@Override
public String toString() {
return '>' + source + ':' + destination;
}
}
static class CopyNode extends Operation {
private final String source;
private final String destination;
CopyNode(String source, String destParent, String destName) {
this.source = source;
destination = PathUtils.concat(destParent, destName);
}
@Override
void apply(RootImpl root) {
root.copy(source, destination);
}
@Override
public String toString() {
return '*' + source + ':' + destination;
}
}
static class SetProperty extends Operation {
private final String parentPath;
private final String propertyName;
private final String propertyValue;
SetProperty(String parentPath, String name, String value) {
this.parentPath = parentPath;
this.propertyName = name;
this.propertyValue = value;
}
@Override
void apply(RootImpl root) {
root.getTree(parentPath).setProperty(propertyName, propertyValue);
}
@Override
public String toString() {
return '^' + PathUtils.concat(parentPath, propertyName) + ':'
+ propertyValue;
}
}
static class RemoveProperty extends Operation {
private final String parentPath;
private final String name;
RemoveProperty(String parentPath, String name) {
this.parentPath = parentPath;
this.name = name;
}
@Override
void apply(RootImpl root) {
root.getTree(parentPath).removeProperty(name);
}
@Override
public String toString() {
return '^' + PathUtils.concat(parentPath, name) + ":null";
}
}
static class Save extends Operation {
@Override
void apply(RootImpl root) {
// empty
}
@Override
public String toString() {
return "save";
}
}
static class Rebase extends Operation {
@Override
void apply(RootImpl root) {
root.rebase();
}
@Override
public String toString() {
return "rebase";
}
}
}
private Operation createOperation() {
Operation op;
do {
switch (random.nextInt(11)) {
case 0:
case 1:
case 2:
op = createAddNode();
break;
case 3:
op = createRemoveNode();
break;
case 4:
op = createMoveNode();
break;
case 5:
// Too many copy ops make the test way slow
op = random.nextInt(10) == 0 ? createCopyNode() : null;
break;
case 6:
op = createAddProperty();
break;
case 7:
op = createSetProperty();
break;
case 8:
op = createRemoveProperty();
break;
case 9:
op = new Save();
break;
case 10:
op = new Rebase();
break;
default:
throw new IllegalStateException();
}
} while (op == null);
return op;
}
private Operation createAddNode() {
String parentPath = chooseNodePath();
String name = createNodeName();
return new AddNode(parentPath, name);
}
private Operation createRemoveNode() {
String path = chooseNodePath();
return "/root".equals(path) ? null : new RemoveNode(path);
}
private Operation createMoveNode() {
String source = chooseNodePath();
String destParent = chooseNodePath();
String destName = createNodeName();
return "/root".equals(source) || destParent.startsWith(source)
? null
: new MoveNode(source, destParent, destName);
}
private Operation createCopyNode() {
String source = chooseNodePath();
String destParent = chooseNodePath();
String destName = createNodeName();
return "/root".equals(source)
? null
: new CopyNode(source, destParent, destName);
}
private Operation createAddProperty() {
String parent = chooseNodePath();
String name = createPropertyName();
String value = createValue();
return new SetProperty(parent, name, value);
}
private Operation createSetProperty() {
String path = choosePropertyPath();
if (path == null) {
return null;
}
String value = createValue();
return new SetProperty(PathUtils.getParentPath(path), PathUtils.getName(path), value);
}
private Operation createRemoveProperty() {
String path = choosePropertyPath();
if (path == null) {
return null;
}
return new RemoveProperty(PathUtils.getParentPath(path), PathUtils.getName(path));
}
private String createNodeName() {
return "N" + counter++;
}
private String createPropertyName() {
return "P" + counter++;
}
private String chooseNodePath() {
String path = "/root";
String next;
while ((next = chooseNode(path)) != null) {
path = next;
}
return path;
}
private String choosePropertyPath() {
return chooseProperty(chooseNodePath());
}
private String chooseNode(String parentPath) {
Tree state = root1.getTree(parentPath);
int k = random.nextInt((int) (state.getChildrenCount() + 1));
int c = 0;
for (Tree child : state.getChildren()) {
if (c++ == k) {
return PathUtils.concat(parentPath, child.getName());
}
}
return null;
}
private String chooseProperty(String parentPath) {
Tree state = root1.getTree(parentPath);
int k = random.nextInt((int) (state.getPropertyCount() + 1));
int c = 0;
for (PropertyState entry : state.getProperties()) {
if (c++ == k) {
return PathUtils.concat(parentPath, entry.getName());
}
}
return null;
}
private String createValue() {
return ("V" + counter++);
}
private static void checkEqual(Tree tree1, Tree tree2) {
String message =
tree1.getPath() + "!=" + tree2.getPath()
+ " (seed " + SEED + ')';
assertEquals(message, tree1.getPath(), tree2.getPath());
assertEquals(message, tree1.getChildrenCount(), tree2.getChildrenCount());
assertEquals(message, tree1.getPropertyCount(), tree2.getPropertyCount());
for (PropertyState property1 : tree1.getProperties()) {
PropertyState property2 = tree2.getProperty(property1.getName());
assertEquals(message, property1, property2);
}
for (Tree child1 : tree1.getChildren()) {
checkEqual(child1, tree2.getChild(child1.getName()));
}
}
}
| fix JavaDoc
git-svn-id: 67138be12999c61558c3dd34328380c8e4523e73@1447651 13f79535-47bb-0310-9956-ffa450edef68
| oak-core/src/test/java/org/apache/jackrabbit/oak/core/RootImplFuzzIT.java | fix JavaDoc | <ide><path>ak-core/src/test/java/org/apache/jackrabbit/oak/core/RootImplFuzzIT.java
<ide>
<ide> /**
<ide> * Fuzz test running random sequences of operations on {@link Tree}.
<del> * Run with -DKernelRootFuzzIT-seed=42 to set a specific seed (i.e. 42);
<add> * Run with -DRootImplFuzzIT-seed=42 to set a specific seed (i.e. 42);
<ide> */
<ide> public class RootImplFuzzIT {
<ide> |
|
Java | apache-2.0 | 0680df9edf5cb17798ed4aaa72bf39fa902cb97b | 0 | rapodaca/Terasology,kartikey0303/Terasology,CC4401-TeraCity/TeraCity,leelib/Terasology,sceptross/Terasology,dannyzhou98/Terasology,MovingBlocks/Terasology,mertserezli/Terasology,Halamix2/Terasology,indianajohn/Terasology,flo/Terasology,rapodaca/Terasology,Nanoware/Terasology,AWildBeard/Terasology,samuto/Terasology,Malanius/Terasology,mertserezli/Terasology,frankpunx/Terasology,immortius/Terasology,kaen/Terasology,Josharias/Terasology,neshume/Terasology,AWildBeard/Terasology,leelib/Terasology,Nanoware/Terasology,samuto/Terasology,dimamo5/Terasology,kaen/Terasology,kartikey0303/Terasology,Vizaxo/Terasology,immortius/Terasology,frankpunx/Terasology,dannyzhou98/Terasology,MovingBlocks/Terasology,MarcinSc/Terasology,rapodaca/Terasology,Ciclop/Terasology,CC4401-TeraCity/TeraCity,Josharias/Terasology,neshume/Terasology,jacklotusho/Terasology,Ciclop/Terasology,jacklotusho/Terasology,Vizaxo/Terasology,Halamix2/Terasology,DPirate/Terasology,dimamo5/Terasology,Felges/Terasology,sceptross/Terasology,indianajohn/Terasology,DPirate/Terasology,flo/Terasology,MarcinSc/Terasology,Nanoware/Terasology,Felges/Terasology,MovingBlocks/Terasology,Malanius/Terasology | /*
* Copyright 2011 Benjamin Glatzel <[email protected]>.
*
* 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.terasology.game;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.openal.AL;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.PixelFormat;
import org.terasology.game.modes.IGameMode;
import org.terasology.game.modes.ModeMainMenu;
import org.terasology.game.modes.ModePlayGame;
import org.terasology.logic.characters.Player;
import org.terasology.logic.manager.*;
import org.terasology.logic.world.IWorldProvider;
import org.terasology.model.blocks.management.BlockManager;
import org.terasology.model.shapes.BlockShapeManager;
import org.terasology.performanceMonitor.PerformanceMonitor;
import org.terasology.rendering.world.WorldRenderer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import static org.lwjgl.opengl.GL11.*;
/**
* The heart and soul of Terasology.
*
* @author Benjamin Glatzel <[email protected]>
* @author Kireev Anton <[email protected]>
*/
public final class Terasology {
private static Terasology _instance = new Terasology();
private final Logger _logger = Logger.getLogger("Terasology");
private final GroovyManager _groovyManager = new GroovyManager();
private final ThreadPoolExecutor _threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
private Timer _timer;
/* GAME LOOP */
private boolean _runGame = true, _saveWorldOnExit = true;
/* GAME MODES */
public enum GameMode {
undefined, mainMenu, runGame
}
static GameMode _state = GameMode.mainMenu;
private static Map<GameMode, IGameMode> _gameModes = Collections.synchronizedMap(new EnumMap<GameMode, IGameMode>(GameMode.class));
public static Terasology getInstance() {
return _instance;
}
private Terasology() {
}
public void init(){
_logger.log(Level.INFO, "Initializing Terasology...");
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
initLogger();
initNativeLibs();
initOpenAL();
initDisplay();
initOpenGL();
initControls();
initManagers();
initTimer(); //dependant on lwjgl
}
private void initNativeLibs() {
if (System.getProperty("os.name").equals("Mac OS X"))
addLibraryPath("natives/macosx");
else if (System.getProperty("os.name").equals("Linux"))
addLibraryPath("natives/linux");
else {
addLibraryPath("natives/windows");
if (System.getProperty("os.arch").equals("amd64") || System.getProperty("os.arch").equals("x86_64"))
System.loadLibrary("OpenAL64");
else
System.loadLibrary("OpenAL32");
}
}
private void addLibraryPath(String s){
try {
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
final String[] paths = (String[]) usrPathsField.get(null);
for (String path : paths) {
if (path.equals(s)) {
return;
}
}
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = s;
usrPathsField.set(null, newPaths);
} catch(Exception e){
_logger.log(Level.SEVERE, "Couldn't link static libraries. " + e.toString(), e);
//brutal...
System.exit(1);
}
}
private void initOpenAL() {
AudioManager.getInstance();
}
private void initDisplay() {
try {
if ((Boolean) SettingsManager.getInstance().getUserSetting("Game.Graphics.fullscreen")) {
Display.setDisplayMode(Display.getDesktopDisplayMode());
Display.setFullscreen(true);
} else {
Display.setDisplayMode((DisplayMode) SettingsManager.getInstance().getUserSetting("Game.Graphics.displayMode"));
Display.setResizable(true);
}
Display.setTitle("Terasology" + " | " + "Pre Alpha");
Display.create((PixelFormat) SettingsManager.getInstance().getUserSetting("Game.Graphics.pixelFormat"));
} catch (LWJGLException e){
_logger.log(Level.SEVERE, "Can not initialize graphics device.", e);
System.exit(1);
}
}
private void initOpenGL() {
checkOpenGL();
resizeViewport();
resetOpenGLParameters();
}
private void checkOpenGL(){
boolean canRunGame = GLContext.getCapabilities().OpenGL20
& GLContext.getCapabilities().OpenGL11
& GLContext.getCapabilities().OpenGL12
& GLContext.getCapabilities().OpenGL14
& GLContext.getCapabilities().OpenGL15;
if (!canRunGame) {
_logger.log(Level.SEVERE, "Your GPU driver is not supporting the mandatory versions of OpenGL. Considered updating your GPU drivers?");
System.exit(1);
}
}
private void resizeViewport() {
glViewport(0, 0, Display.getWidth(), Display.getHeight());
}
public void resetOpenGLParameters() {
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
}
private void initControls() {
try {
Keyboard.create();
Keyboard.enableRepeatEvents(true);
Mouse.create();
Mouse.setGrabbed(true);
} catch (LWJGLException e) {
_logger.log(Level.SEVERE, "Could not initialize controls.", e);
System.exit(1);
}
}
private void initManagers() {
ShaderManager.getInstance();
VertexBufferObjectManager.getInstance();
FontManager.getInstance();
BlockShapeManager.getInstance();
BlockManager.getInstance();
}
private void initTimer() {
_timer = new Timer();
}
public void run(){
PerformanceMonitor.startActivity("Other");
// MAIN GAME LOOP
IGameMode mode = null;
while (_runGame && !Display.isCloseRequested()) {
_timer.tick();
// Only process rendering and updating once a second
if (!Display.isActive()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
getInstance().getLogger().log(Level.SEVERE, e.toString(), e);
}
PerformanceMonitor.startActivity("Process Display");
Display.processMessages();
PerformanceMonitor.endActivity();
}
IGameMode prevMode = mode;
mode = getGameMode();
if (mode == null) {
_runGame = false;
break;
}
if (mode != prevMode) {
if (prevMode != null)
prevMode.deactivate();
mode.activate();
}
PerformanceMonitor.startActivity("Main Update");
mode.update();
PerformanceMonitor.endActivity();
PerformanceMonitor.startActivity("Render");
mode.render();
Display.update();
Display.sync(60);
PerformanceMonitor.endActivity();
PerformanceMonitor.startActivity("Input");
mode.processKeyboardInput();
mode.processMouseInput();
mode.updatePlayerInput();
PerformanceMonitor.endActivity();
PerformanceMonitor.rollCycle();
PerformanceMonitor.startActivity("Other");
mode.updateTimeAccumulator(_timer.getDelta());
if (Display.wasResized())
resizeViewport();
}
}
public void shutdown(){
_logger.log(Level.INFO, "Shutting down Terasology...");
saveWorld();
terminateThreads();
destroy();
}
private void saveWorld() {
//UGLY! why does dispose save the world...
if (_saveWorldOnExit) {
if (getActiveWorldRenderer() != null)
getGameMode().getActiveWorldRenderer().dispose();
}
}
private void terminateThreads() {
_threadPool.shutdown();
try {
_threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
getLogger().log(Level.SEVERE, e.toString(), e);
}
}
private void destroy() {
AL.destroy();
Mouse.destroy();
Keyboard.destroy();
Display.destroy();
}
public IGameMode getGameMode() {
IGameMode mode = _gameModes.get(_state);
if (mode != null) {
return mode;
}
switch (_state) {
case runGame:
mode = new ModePlayGame();
break;
case mainMenu:
mode = new ModeMainMenu();
break;
case undefined:
getLogger().log(Level.SEVERE, "Undefined game state - unable to run");
return null;
}
_gameModes.put(_state, mode);
mode.init();
return mode;
}
public void setGameMode(GameMode state) {
_state = state;
}
public void render() {
getGameMode().render();
}
public void update() {
getGameMode().update();
}
public void exit(boolean saveWorld) {
_saveWorldOnExit = saveWorld;
_runGame = false;
}
public void exit() {
exit(true);
}
public void addLogFileHandler(String s, Level logLevel) {
try {
FileHandler fh = new FileHandler(s, true);
fh.setLevel(logLevel);
fh.setFormatter(new SimpleFormatter());
_logger.addHandler(fh);
} catch (IOException ex) {
_logger.log(Level.WARNING, ex.toString(), ex);
}
}
private void initLogger() {
File dirPath = new File("logs");
if (!dirPath.exists()) {
if (!dirPath.mkdirs()) {
return;
}
}
addLogFileHandler("logs/Terasology.log", Level.INFO);
}
public String getWorldSavePath(String worldTitle) {
String path = String.format("SAVED_WORLDS/%s", worldTitle);
// Try to detect if we're getting a screwy save path (usually/always the case with an applet)
File f = new File(path);
//System.out.println("Suggested absolute save path is: " + f.getAbsolutePath());
if (!f.getAbsolutePath().contains("Terasology")) {
f = new File(System.getProperty("java.io.tmpdir"), path);
//System.out.println("Absolute TEMP save path is: " + f.getAbsolutePath());
return f.getAbsolutePath();
}
return path;
}
public Logger getLogger() {
return _logger;
}
public double getAverageFps() {
return _timer.getFps();
}
public WorldRenderer getActiveWorldRenderer() {
return getGameMode().getActiveWorldRenderer();
}
public IWorldProvider getActiveWorldProvider() {
if (getActiveWorldRenderer() != null)
return getActiveWorldRenderer().getWorldProvider();
return null;
}
public Player getActivePlayer() {
if (getActiveWorldRenderer() != null)
return getActiveWorldRenderer().getPlayer();
return null;
}
public long getTimeInMs() {
if (_timer == null) {
initTimer();
}
return _timer.getTimeInMs();
}
public void submitTask(final String name, final Runnable task) {
_threadPool.execute(new Runnable() {
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
PerformanceMonitor.startThread(name);
try {
task.run();
} finally {
PerformanceMonitor.endThread(name);
}
}
});
}
public int activeTasks() {
return _threadPool.getActiveCount();
}
public GroovyManager getGroovyManager() {
return _groovyManager;
}
public static void main(String[] args) {
_instance.init();
_instance.run();
_instance.shutdown();
System.exit(0);
}
}
| src/org/terasology/game/Terasology.java | /*
* Copyright 2011 Benjamin Glatzel <[email protected]>.
*
* 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.terasology.game;
import org.lwjgl.LWJGLException;
import org.lwjgl.input.Keyboard;
import org.lwjgl.input.Mouse;
import org.lwjgl.openal.AL;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.opengl.PixelFormat;
import org.terasology.game.modes.IGameMode;
import org.terasology.game.modes.ModeMainMenu;
import org.terasology.game.modes.ModePlayGame;
import org.terasology.logic.characters.Player;
import org.terasology.logic.manager.*;
import org.terasology.logic.world.IWorldProvider;
import org.terasology.model.blocks.management.BlockManager;
import org.terasology.model.shapes.BlockShapeManager;
import org.terasology.performanceMonitor.PerformanceMonitor;
import org.terasology.rendering.world.WorldRenderer;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import static org.lwjgl.opengl.GL11.*;
/**
* The heart and soul of Terasology.
*
* @author Benjamin Glatzel <[email protected]>
* @author Kireev Anton <[email protected]>
*/
public final class Terasology {
private static Terasology _instance = new Terasology();
private final Logger _logger = Logger.getLogger("Terasology");
private final GroovyManager _groovyManager = new GroovyManager();
private final ThreadPoolExecutor _threadPool = (ThreadPoolExecutor) Executors.newCachedThreadPool();
private Timer _timer;
/* GAME LOOP */
private boolean _runGame = true, _saveWorldOnExit = true;
/* GAME MODES */
public enum GameMode {
undefined, mainMenu, runGame
}
static GameMode _state = GameMode.mainMenu;
private static Map<GameMode, IGameMode> _gameModes = Collections.synchronizedMap(new EnumMap<GameMode, IGameMode>(GameMode.class));
public static Terasology getInstance() {
return _instance;
}
private Terasology() {
}
public void init(){
_logger.log(Level.INFO, "Initializing Terasology...");
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
initLogger();
initNativeLibs();
initOpenAL();
initDisplay();
initOpenGL();
initControls();
initManagers();
initTimer(); //dependant on lwjgl
}
private void initNativeLibs() {
if (System.getProperty("os.name").equals("Mac OS X"))
addLibraryPath("natives/macosx");
else if (System.getProperty("os.name").equals("Linux"))
addLibraryPath("natives/linux");
else {
addLibraryPath("natives/windows");
if (System.getProperty("os.arch").equals("amd64") || System.getProperty("os.arch").equals("x86_64"))
System.loadLibrary("OpenAL64");
else
System.loadLibrary("OpenAL32");
}
}
private void addLibraryPath(String s){
try {
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
final String[] paths = (String[]) usrPathsField.get(null);
for (String path : paths) {
if (path.equals(s)) {
return;
}
}
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = s;
usrPathsField.set(null, newPaths);
} catch(Exception e){
_logger.log(Level.SEVERE, "Couldn't link static libraries. " + e.toString(), e);
//brutal...
System.exit(1);
}
}
private void initOpenAL() {
AudioManager.getInstance();
}
private void initDisplay() {
try {
if ((Boolean) SettingsManager.getInstance().getUserSetting("Game.Graphics.fullscreen")) {
Display.setDisplayMode(Display.getDesktopDisplayMode());
Display.setFullscreen(true);
} else {
Display.setDisplayMode((DisplayMode) SettingsManager.getInstance().getUserSetting("Game.Graphics.displayMode"));
Display.setResizable(true);
}
Display.setTitle("Terasology" + " | " + "Pre Alpha");
Display.create((PixelFormat) SettingsManager.getInstance().getUserSetting("Game.Graphics.pixelFormat"));
} catch (LWJGLException e){
_logger.log(Level.SEVERE, "Can not initialize graphics device.", e);
System.exit(1);
}
}
private void initOpenGL() {
checkOpenGL();
resizeViewport();
resetOpenGLParameters();
}
private void checkOpenGL(){
boolean canRunGame = GLContext.getCapabilities().OpenGL20
& GLContext.getCapabilities().OpenGL11
& GLContext.getCapabilities().OpenGL12
& GLContext.getCapabilities().OpenGL14
& GLContext.getCapabilities().OpenGL15;
if (!canRunGame) {
_logger.log(Level.SEVERE, "Your GPU driver is not supporting the mandatory versions of OpenGL. Considered updating your GPU drivers?");
System.exit(1);
}
}
private void resizeViewport() {
glViewport(0, 0, Display.getWidth(), Display.getHeight());
}
public void resetOpenGLParameters() {
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
}
private void initControls() {
try {
Keyboard.create();
Keyboard.enableRepeatEvents(true);
Mouse.create();
Mouse.setGrabbed(true);
} catch (LWJGLException e) {
_logger.log(Level.SEVERE, "Could not initialize controls.", e);
System.exit(1);
}
}
private void initManagers() {
ShaderManager.getInstance();
VertexBufferObjectManager.getInstance();
FontManager.getInstance();
BlockShapeManager.getInstance();
BlockManager.getInstance();
}
private void initTimer() {
_timer = new Timer();
}
public void run(){
PerformanceMonitor.startActivity("Other");
// MAIN GAME LOOP
IGameMode mode = null;
while (_runGame && !Display.isCloseRequested()) {
_timer.tick();
// Only process rendering and updating once a second
if (!Display.isActive()) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
getInstance().getLogger().log(Level.SEVERE, e.toString(), e);
}
PerformanceMonitor.startActivity("Process Display");
Display.processMessages();
PerformanceMonitor.endActivity();
}
IGameMode prevMode = mode;
mode = getGameMode();
if (mode == null) {
_runGame = false;
break;
}
if (mode != prevMode) {
if (prevMode != null)
prevMode.deactivate();
mode.activate();
}
PerformanceMonitor.startActivity("Main Update");
mode.update();
PerformanceMonitor.endActivity();
PerformanceMonitor.startActivity("Render");
mode.render();
Display.update();
Display.sync(60);
PerformanceMonitor.endActivity();
PerformanceMonitor.startActivity("Input");
mode.processKeyboardInput();
mode.processMouseInput();
mode.updatePlayerInput();
PerformanceMonitor.endActivity();
PerformanceMonitor.rollCycle();
PerformanceMonitor.startActivity("Other");
mode.updateTimeAccumulator(_timer.getDelta());
if (Display.wasResized())
resizeViewport();
}
}
public void shutdown(){
_logger.log(Level.INFO, "Shutting down Terasology...");
saveWorld();
terminateThreads();
destroy();
}
private void saveWorld() {
//UGLY! why does dispose save the world...
if (_saveWorldOnExit) {
if (getActiveWorldRenderer() != null)
getGameMode().getActiveWorldRenderer().dispose();
}
}
private void terminateThreads() {
_threadPool.shutdown();
try {
_threadPool.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
getLogger().log(Level.SEVERE, e.toString(), e);
}
}
private void destroy() {
AL.destroy();
Mouse.destroy();
Keyboard.destroy();
Display.destroy();
}
public IGameMode getGameMode() {
IGameMode mode = _gameModes.get(_state);
if (mode != null) {
return mode;
}
switch (_state) {
case runGame:
mode = new ModePlayGame();
break;
case mainMenu:
mode = new ModeMainMenu();
break;
case undefined:
getLogger().log(Level.SEVERE, "Undefined game state - unable to run");
return null;
}
_gameModes.put(_state, mode);
mode.init();
return mode;
}
public void setGameMode(GameMode state) {
_state = state;
}
public void render() {
getGameMode().render();
}
public void update() {
getGameMode().update();
}
public void exit(boolean saveWorld) {
_saveWorldOnExit = saveWorld;
_runGame = false;
}
public void exit() {
exit(true);
}
public void addLogFileHandler(String s, Level logLevel) {
try {
FileHandler fh = new FileHandler(s, true);
fh.setLevel(logLevel);
fh.setFormatter(new SimpleFormatter());
_logger.addHandler(fh);
} catch (IOException ex) {
_logger.log(Level.WARNING, ex.toString(), ex);
}
}
private void initLogger() {
File dirPath = new File("logs");
if (!dirPath.exists()) {
if (!dirPath.mkdirs()) {
return;
}
}
addLogFileHandler("logs/Terasology.log", Level.INFO);
}
public String getWorldSavePath(String worldTitle) {
String path = String.format("SAVED_WORLDS/%s", worldTitle);
// Try to detect if we're getting a screwy save path (usually/always the case with an applet)
File f = new File(path);
//System.out.println("Suggested absolute save path is: " + f.getAbsolutePath());
if (!f.getAbsolutePath().contains("Terasology")) {
f = new File(System.getProperty("java.io.tmpdir"), path);
//System.out.println("Absolute TEMP save path is: " + f.getAbsolutePath());
return f.getAbsolutePath();
}
return path;
}
public Logger getLogger() {
return _logger;
}
public double getAverageFps() {
return _timer.getFps();
}
public WorldRenderer getActiveWorldRenderer() {
return getGameMode().getActiveWorldRenderer();
}
public IWorldProvider getActiveWorldProvider() {
if (getActiveWorldRenderer() != null)
return getActiveWorldRenderer().getWorldProvider();
return null;
}
public Player getActivePlayer() {
if (getActiveWorldRenderer() != null)
return getActiveWorldRenderer().getPlayer();
return null;
}
public long getTimeInMs() {
return _timer.getTimeInMs();
}
public void submitTask(final String name, final Runnable task) {
_threadPool.execute(new Runnable() {
public void run() {
Thread.currentThread().setPriority(Thread.MIN_PRIORITY);
PerformanceMonitor.startThread(name);
try {
task.run();
} finally {
PerformanceMonitor.endThread(name);
}
}
});
}
public int activeTasks() {
return _threadPool.getActiveCount();
}
public GroovyManager getGroovyManager() {
return _groovyManager;
}
public static void main(String[] args) {
_instance.init();
_instance.run();
_instance.shutdown();
System.exit(0);
}
}
| Fix broken performance test.
| src/org/terasology/game/Terasology.java | Fix broken performance test. | <ide><path>rc/org/terasology/game/Terasology.java
<ide> }
<ide>
<ide> public long getTimeInMs() {
<del>
<add> if (_timer == null) {
<add> initTimer();
<add> }
<ide> return _timer.getTimeInMs();
<ide> }
<ide> |
|
Java | mit | 1aff7b00883a679ac882b2ea9bf2e2b48d34a1ac | 0 | bcgit/bc-java,bcgit/bc-java,bcgit/bc-java | package org.bouncycastle.jsse.provider;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContextSpi;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.tls.CipherSuite;
import org.bouncycastle.tls.ProtocolVersion;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.TlsCrypto;
import org.bouncycastle.tls.crypto.TlsCryptoProvider;
class ProvSSLContextSpi
extends SSLContextSpi
{
private static final Map<String, Integer> supportedCipherSuites = createSupportedCipherSuites();
private static final Map<String, ProtocolVersion> supportedProtocols = createSupportedProtocols();
private static Map<String, Integer> createSupportedCipherSuites()
{
Map<String, Integer> cs = new HashMap<String, Integer>();
cs.put("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
cs.put("TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
cs.put("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);
cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
cs.put("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
cs.put("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
cs.put("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
cs.put("TLS_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384);
cs.put("TLS_RSA_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256);
cs.put("TLS_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);
cs.put("TLS_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256);
cs.put("TLS_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256);
cs.put("TLS_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA);
return Collections.unmodifiableMap(cs);
}
private static Map<String, ProtocolVersion> createSupportedProtocols()
{
Map<String, ProtocolVersion> ps = new HashMap<String, ProtocolVersion>();
// ps.put("SSLv3", ProtocolVersion.SSLv3);
ps.put("TLSv1", ProtocolVersion.TLSv10);
ps.put("TLSv1.1", ProtocolVersion.TLSv11);
ps.put("TLSv1.2", ProtocolVersion.TLSv12);
return Collections.unmodifiableMap(ps);
}
protected final TlsCryptoProvider cryptoProvider;
protected boolean initialized = false;
private TlsCrypto crypto;
private X509KeyManager km;
private X509TrustManager tm;
private ProvSSLSessionContext clientSessionContext;
private ProvSSLSessionContext serverSessionContext;
ProvSSLContextSpi(TlsCryptoProvider cryptoProvider)
{
this.cryptoProvider = cryptoProvider;
}
int[] convertCipherSuites(String[] suites)
{
int[] result = new int[suites.length];
for (int i = 0; i < suites.length; ++i)
{
result[i] = supportedCipherSuites.get(suites[i]);
}
return result;
}
ProvSSLSessionContext createSSLSessionContext()
{
return new ProvSSLSessionContext(this);
}
String getCipherSuiteString(int suite)
{
if (TlsUtils.isValidUint16(suite))
{
for (Map.Entry<String, Integer> entry : supportedCipherSuites.entrySet())
{
if (entry.getValue().intValue() == suite)
{
return entry.getKey();
}
}
}
return null;
}
String[] getDefaultCipherSuites()
{
return new String[]{
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
};
}
String[] getDefaultProtocols()
{
return new String[]{ "TLSv1.2" };
}
ProtocolVersion getMaximumVersion(String[] protocols)
{
ProtocolVersion max = null;
if (protocols != null)
{
for (String protocol : protocols)
{
if (protocol != null)
{
ProtocolVersion v = supportedProtocols.get(protocol);
if (v != null && (max == null || v.isLaterVersionOf(max)))
{
max = v;
}
}
}
}
return max;
}
ProtocolVersion getMinimumVersion(String[] protocols)
{
ProtocolVersion min = null;
if (protocols != null)
{
for (String protocol : protocols)
{
if (protocol != null)
{
ProtocolVersion v = supportedProtocols.get(protocol);
if (v != null && (min == null || min.isLaterVersionOf(v)))
{
min = v;
}
}
}
}
return min;
}
String getProtocolString(ProtocolVersion v)
{
if (v != null)
{
for (Map.Entry<String, ProtocolVersion> entry : supportedProtocols.entrySet())
{
if (v.equals(entry.getValue()))
{
return entry.getKey();
}
}
}
return null;
}
String[] getSupportedCipherSuites()
{
return supportedCipherSuites.keySet().toArray(new String[supportedCipherSuites.size()]);
}
String[] getSupportedProtocols()
{
return supportedProtocols.keySet().toArray(new String[supportedProtocols.size()]);
}
boolean isSupportedCipherSuites(String[] suites)
{
if (suites == null)
{
return false;
}
for (String suite : suites)
{
if (suite == null || !supportedCipherSuites.containsKey(suite))
{
return false;
}
}
return true;
}
boolean isSupportedProtocols(String[] protocols)
{
if (protocols == null)
{
return false;
}
for (String protocol : protocols)
{
if (protocol == null || !supportedProtocols.containsKey(protocol))
{
return false;
}
}
return true;
}
protected void checkInitialized()
{
if (!initialized)
{
throw new IllegalStateException("SSLContext has not been initialized.");
}
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine()
{
checkInitialized();
return new ProvSSLEngine(this, createContextData());
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine(String host, int port)
{
checkInitialized();
return new ProvSSLEngine(this, createContextData(), host, port);
}
@Override
protected synchronized SSLSessionContext engineGetClientSessionContext()
{
return clientSessionContext;
}
@Override
protected SSLParameters engineGetDefaultSSLParameters()
{
// TODO[jsse] Review initial values
SSLParameters r = new SSLParameters();
r.setCipherSuites(getDefaultCipherSuites());
r.setProtocols(getDefaultProtocols());
return r;
}
@Override
protected synchronized SSLSessionContext engineGetServerSessionContext()
{
return serverSessionContext;
}
@Override
protected SSLServerSocketFactory engineGetServerSocketFactory()
{
checkInitialized();
return new ProvSSLServerSocketFactory(this);
}
@Override
protected SSLSocketFactory engineGetSocketFactory()
{
checkInitialized();
return new ProvSSLSocketFactory(this);
}
@Override
protected SSLParameters engineGetSupportedSSLParameters()
{
// TODO[jsse] Review initial values
SSLParameters r = new SSLParameters();
r.setCipherSuites(getSupportedCipherSuites());
r.setProtocols(getSupportedProtocols());
return r;
}
@Override
protected synchronized void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) throws KeyManagementException
{
this.initialized = false;
this.crypto = cryptoProvider.create(sr);
this.km = selectKeyManager(kms);
this.tm = selectTrustManager(tms);
this.clientSessionContext = createSSLSessionContext();
this.serverSessionContext = createSSLSessionContext();
this.initialized = true;
}
protected ContextData createContextData()
{
return new ContextData(crypto, km, tm, clientSessionContext, serverSessionContext);
}
protected X509KeyManager findX509KeyManager(KeyManager[] kms)
{
if (kms != null)
{
for (KeyManager km : kms)
{
if (km instanceof X509KeyManager)
{
return (X509KeyManager)km;
}
}
}
return null;
}
protected X509TrustManager findX509TrustManager(TrustManager[] tms)
{
if (tms != null)
{
for (TrustManager tm : tms)
{
if (tm instanceof X509TrustManager)
{
return (X509TrustManager)tm;
}
}
}
return null;
}
protected X509KeyManager selectKeyManager(KeyManager[] kms) throws KeyManagementException
{
if (kms == null)
{
try
{
/*
* "[...] the installed security providers will be searched for the highest priority
* implementation of the appropriate factory."
*/
// TODO[jsse] Is PKIX a reasonable algorithm to use here?
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
// TODO[jsse] Is this supported generally?
kmf.init(null, null);
kms = kmf.getKeyManagers();
}
catch (GeneralSecurityException e)
{
throw new KeyManagementException(e);
}
}
return findX509KeyManager(kms);
}
protected X509TrustManager selectTrustManager(TrustManager[] tms) throws KeyManagementException
{
if (tms == null)
{
try
{
/*
* "[...] the installed security providers will be searched for the highest priority
* implementation of the appropriate factory."
*/
// TODO[jsse] Is PKIX a reasonable algorithm to use here?
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
// TODO[jsse] Is this supported generally?
tmf.init((KeyStore)null);
tms = tmf.getTrustManagers();
}
catch (GeneralSecurityException e)
{
throw new KeyManagementException(e);
}
}
return findX509TrustManager(tms);
}
}
| tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java | package org.bouncycastle.jsse.provider;
import java.security.GeneralSecurityException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContextSpi;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLServerSocketFactory;
import javax.net.ssl.SSLSessionContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509KeyManager;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.tls.CipherSuite;
import org.bouncycastle.tls.ProtocolVersion;
import org.bouncycastle.tls.TlsUtils;
import org.bouncycastle.tls.crypto.TlsCrypto;
import org.bouncycastle.tls.crypto.TlsCryptoProvider;
class ProvSSLContextSpi
extends SSLContextSpi
{
private static final Map<String, Integer> supportedCipherSuites = createSupportedCipherSuites();
private static final Map<String, ProtocolVersion> supportedProtocols = createSupportedProtocols();
private static Map<String, Integer> createSupportedCipherSuites()
{
Map<String, Integer> cs = new HashMap<String, Integer>();
cs.put("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
cs.put("TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
cs.put("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);
cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
cs.put("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
cs.put("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
cs.put("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
cs.put("TLS_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384);
cs.put("TLS_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256);
cs.put("TLS_RSA_WITH_AES_256_CBC", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);
cs.put("TLS_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256);
cs.put("TLS_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256);
cs.put("TLS_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA);
return Collections.unmodifiableMap(cs);
}
private static Map<String, ProtocolVersion> createSupportedProtocols()
{
Map<String, ProtocolVersion> ps = new HashMap<String, ProtocolVersion>();
// ps.put("SSLv3", ProtocolVersion.SSLv3);
ps.put("TLSv1", ProtocolVersion.TLSv10);
ps.put("TLSv1.1", ProtocolVersion.TLSv11);
ps.put("TLSv1.2", ProtocolVersion.TLSv12);
return Collections.unmodifiableMap(ps);
}
protected final TlsCryptoProvider cryptoProvider;
protected boolean initialized = false;
private TlsCrypto crypto;
private X509KeyManager km;
private X509TrustManager tm;
private ProvSSLSessionContext clientSessionContext;
private ProvSSLSessionContext serverSessionContext;
ProvSSLContextSpi(TlsCryptoProvider cryptoProvider)
{
this.cryptoProvider = cryptoProvider;
}
int[] convertCipherSuites(String[] suites)
{
int[] result = new int[suites.length];
for (int i = 0; i < suites.length; ++i)
{
result[i] = supportedCipherSuites.get(suites[i]);
}
return result;
}
ProvSSLSessionContext createSSLSessionContext()
{
return new ProvSSLSessionContext(this);
}
String getCipherSuiteString(int suite)
{
if (TlsUtils.isValidUint16(suite))
{
for (Map.Entry<String, Integer> entry : supportedCipherSuites.entrySet())
{
if (entry.getValue().intValue() == suite)
{
return entry.getKey();
}
}
}
return null;
}
String[] getDefaultCipherSuites()
{
return new String[]{
"TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256",
"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
};
}
String[] getDefaultProtocols()
{
return new String[]{ "TLSv1.2" };
}
ProtocolVersion getMaximumVersion(String[] protocols)
{
ProtocolVersion max = null;
if (protocols != null)
{
for (String protocol : protocols)
{
if (protocol != null)
{
ProtocolVersion v = supportedProtocols.get(protocol);
if (v != null && (max == null || v.isLaterVersionOf(max)))
{
max = v;
}
}
}
}
return max;
}
ProtocolVersion getMinimumVersion(String[] protocols)
{
ProtocolVersion min = null;
if (protocols != null)
{
for (String protocol : protocols)
{
if (protocol != null)
{
ProtocolVersion v = supportedProtocols.get(protocol);
if (v != null && (min == null || min.isLaterVersionOf(v)))
{
min = v;
}
}
}
}
return min;
}
String getProtocolString(ProtocolVersion v)
{
if (v != null)
{
for (Map.Entry<String, ProtocolVersion> entry : supportedProtocols.entrySet())
{
if (v.equals(entry.getValue()))
{
return entry.getKey();
}
}
}
return null;
}
String[] getSupportedCipherSuites()
{
return supportedCipherSuites.keySet().toArray(new String[supportedCipherSuites.size()]);
}
String[] getSupportedProtocols()
{
return supportedProtocols.keySet().toArray(new String[supportedProtocols.size()]);
}
boolean isSupportedCipherSuites(String[] suites)
{
if (suites == null)
{
return false;
}
for (String suite : suites)
{
if (suite == null || !supportedCipherSuites.containsKey(suite))
{
return false;
}
}
return true;
}
boolean isSupportedProtocols(String[] protocols)
{
if (protocols == null)
{
return false;
}
for (String protocol : protocols)
{
if (protocol == null || !supportedProtocols.containsKey(protocol))
{
return false;
}
}
return true;
}
protected void checkInitialized()
{
if (!initialized)
{
throw new IllegalStateException("SSLContext has not been initialized.");
}
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine()
{
checkInitialized();
return new ProvSSLEngine(this, createContextData());
}
@Override
protected synchronized SSLEngine engineCreateSSLEngine(String host, int port)
{
checkInitialized();
return new ProvSSLEngine(this, createContextData(), host, port);
}
@Override
protected synchronized SSLSessionContext engineGetClientSessionContext()
{
return clientSessionContext;
}
@Override
protected SSLParameters engineGetDefaultSSLParameters()
{
// TODO[jsse] Review initial values
SSLParameters r = new SSLParameters();
r.setCipherSuites(getDefaultCipherSuites());
r.setProtocols(getDefaultProtocols());
return r;
}
@Override
protected synchronized SSLSessionContext engineGetServerSessionContext()
{
return serverSessionContext;
}
@Override
protected SSLServerSocketFactory engineGetServerSocketFactory()
{
checkInitialized();
return new ProvSSLServerSocketFactory(this);
}
@Override
protected SSLSocketFactory engineGetSocketFactory()
{
checkInitialized();
return new ProvSSLSocketFactory(this);
}
@Override
protected SSLParameters engineGetSupportedSSLParameters()
{
// TODO[jsse] Review initial values
SSLParameters r = new SSLParameters();
r.setCipherSuites(getSupportedCipherSuites());
r.setProtocols(getSupportedProtocols());
return r;
}
@Override
protected synchronized void engineInit(KeyManager[] kms, TrustManager[] tms, SecureRandom sr) throws KeyManagementException
{
this.initialized = false;
this.crypto = cryptoProvider.create(sr);
this.km = selectKeyManager(kms);
this.tm = selectTrustManager(tms);
this.clientSessionContext = createSSLSessionContext();
this.serverSessionContext = createSSLSessionContext();
this.initialized = true;
}
protected ContextData createContextData()
{
return new ContextData(crypto, km, tm, clientSessionContext, serverSessionContext);
}
protected X509KeyManager findX509KeyManager(KeyManager[] kms)
{
if (kms != null)
{
for (KeyManager km : kms)
{
if (km instanceof X509KeyManager)
{
return (X509KeyManager)km;
}
}
}
return null;
}
protected X509TrustManager findX509TrustManager(TrustManager[] tms)
{
if (tms != null)
{
for (TrustManager tm : tms)
{
if (tm instanceof X509TrustManager)
{
return (X509TrustManager)tm;
}
}
}
return null;
}
protected X509KeyManager selectKeyManager(KeyManager[] kms) throws KeyManagementException
{
if (kms == null)
{
try
{
/*
* "[...] the installed security providers will be searched for the highest priority
* implementation of the appropriate factory."
*/
// TODO[jsse] Is PKIX a reasonable algorithm to use here?
KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
// TODO[jsse] Is this supported generally?
kmf.init(null, null);
kms = kmf.getKeyManagers();
}
catch (GeneralSecurityException e)
{
throw new KeyManagementException(e);
}
}
return findX509KeyManager(kms);
}
protected X509TrustManager selectTrustManager(TrustManager[] tms) throws KeyManagementException
{
if (tms == null)
{
try
{
/*
* "[...] the installed security providers will be searched for the highest priority
* implementation of the appropriate factory."
*/
// TODO[jsse] Is PKIX a reasonable algorithm to use here?
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
// TODO[jsse] Is this supported generally?
tmf.init((KeyStore)null);
tms = tmf.getTrustManagers();
}
catch (GeneralSecurityException e)
{
throw new KeyManagementException(e);
}
}
return findX509TrustManager(tms);
}
}
| Fix a few cipher suite name strings | tls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java | Fix a few cipher suite name strings | <ide><path>ls/src/main/java/org/bouncycastle/jsse/provider/ProvSSLContextSpi.java
<ide> cs.put("TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256);
<ide> cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384);
<ide> cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384);
<del> cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
<add> cs.put("TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA);
<ide> cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256);
<ide> cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256);
<ide> cs.put("TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA);
<ide> cs.put("TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256);
<ide> cs.put("TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384);
<ide> cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384);
<del> cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
<add> cs.put("TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA);
<ide> cs.put("TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256);
<ide> cs.put("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256);
<ide> cs.put("TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA);
<ide>
<ide> cs.put("TLS_RSA_WITH_AES_256_GCM_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_GCM_SHA384);
<del> cs.put("TLS_RSA_WITH_AES_256_CBC_SHA384", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256);
<del> cs.put("TLS_RSA_WITH_AES_256_CBC", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);
<add> cs.put("TLS_RSA_WITH_AES_256_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA256);
<add> cs.put("TLS_RSA_WITH_AES_256_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_256_CBC_SHA);
<ide> cs.put("TLS_RSA_WITH_AES_128_GCM_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_GCM_SHA256);
<ide> cs.put("TLS_RSA_WITH_AES_128_CBC_SHA256", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA256);
<ide> cs.put("TLS_RSA_WITH_AES_128_CBC_SHA", CipherSuite.TLS_RSA_WITH_AES_128_CBC_SHA); |
|
Java | apache-2.0 | b31ffde58160fced4430b703ecdd89dec7609d8a | 0 | lithiumtech/flow | /*
* Copyright 2015 Lithium Technologies, 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.lithium.flow.filer;
import static com.google.common.base.Preconditions.checkNotNull;
import com.lithium.flow.config.Config;
import com.lithium.flow.io.DecoratedOutputStream;
import com.lithium.flow.util.Caches;
import com.lithium.flow.util.CheckedFunction;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import com.google.common.cache.LoadingCache;
/**
* Decorates an instance of {@link Filer} to cache records for a specified amount of time.
*
* @author Matt Ayres
*/
public class CachedFiler extends DecoratedFiler {
private final LoadingCache<String, List<Record>> dirCache;
private final LoadingCache<String, Record> fileCache;
public CachedFiler(@Nonnull Filer delegate, @Nonnull Config config) {
super(checkNotNull(delegate));
checkNotNull(config);
int concurrency = config.getInt("cache.concurrency", 4);
long expireTime = config.getTime("cache.expireTime", "1m");
dirCache = Caches.build((CheckedFunction<String, List<Record>, Exception>) delegate::listRecords,
b -> b.softValues().concurrencyLevel(concurrency).expireAfterWrite(expireTime, TimeUnit.MILLISECONDS));
fileCache = Caches.build((CheckedFunction<String, Record, Exception>) delegate::getRecord,
b -> b.softValues().concurrencyLevel(concurrency).expireAfterWrite(expireTime, TimeUnit.MILLISECONDS));
}
@Override
@Nonnull
public List<Record> listRecords(@Nonnull String path) throws IOException {
try {
return dirCache.get(path);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new IOException(e);
}
}
}
@Override
@Nonnull
public Record getRecord(@Nonnull String path) throws IOException {
String parent = new File(path).getParent();
if (parent != null) {
for (Record record : listRecords(parent)) {
if (path.equals(record.getPath())) {
return record;
}
}
}
try {
return fileCache.get(path);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new IOException(e);
}
}
}
@Override
public void createDirs(@Nonnull String path) throws IOException {
checkNotNull(path);
if (!getRecord(path).exists()) {
super.createDirs(path);
dirCache.invalidate(path);
}
}
@Override
@Nonnull
public OutputStream writeFile(@Nonnull String path) throws IOException {
checkNotNull(path);
return new DecoratedOutputStream(super.writeFile(path)) {
@Override
public void close() throws IOException {
super.close();
dirCache.invalidate(new File(path).getParent());
fileCache.invalidate(path);
}
};
}
}
| src/main/java/com/lithium/flow/filer/CachedFiler.java | /*
* Copyright 2015 Lithium Technologies, 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.lithium.flow.filer;
import static com.google.common.base.Preconditions.checkNotNull;
import com.lithium.flow.config.Config;
import com.lithium.flow.util.Caches;
import com.lithium.flow.util.CheckedFunction;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nonnull;
import com.google.common.cache.LoadingCache;
/**
* Decorates an instance of {@link Filer} to cache records for a specified amount of time.
*
* @author Matt Ayres
*/
public class CachedFiler extends DecoratedFiler {
private final LoadingCache<String, List<Record>> dirCache;
private final LoadingCache<String, Record> fileCache;
public CachedFiler(@Nonnull Filer delegate, @Nonnull Config config) {
super(checkNotNull(delegate));
checkNotNull(config);
int concurrency = config.getInt("cache.concurrency", 4);
long expireTime = config.getTime("cache.expireTime", "1m");
dirCache = Caches.build((CheckedFunction<String, List<Record>, Exception>) delegate::listRecords,
b -> b.softValues().concurrencyLevel(concurrency).expireAfterWrite(expireTime, TimeUnit.MILLISECONDS));
fileCache = Caches.build((CheckedFunction<String, Record, Exception>) delegate::getRecord,
b -> b.softValues().concurrencyLevel(concurrency).expireAfterWrite(expireTime, TimeUnit.MILLISECONDS));
}
@Override
@Nonnull
public List<Record> listRecords(@Nonnull String path) throws IOException {
try {
return dirCache.get(path);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new IOException(e);
}
}
}
@Override
@Nonnull
public Record getRecord(@Nonnull String path) throws IOException {
String parent = new File(path).getParent();
if (parent != null) {
for (Record record : listRecords(parent)) {
if (path.equals(record.getPath())) {
return record;
}
}
}
try {
return fileCache.get(path);
} catch (ExecutionException e) {
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
} else {
throw new IOException(e);
}
}
}
@Override
public void createDirs(@Nonnull String path) throws IOException {
checkNotNull(path);
if (!getRecord(path).exists()) {
super.createDirs(path);
dirCache.invalidate(path);
}
}
}
| FLOW-10 Fixed CachedFiler to invalidate on write close
| src/main/java/com/lithium/flow/filer/CachedFiler.java | FLOW-10 Fixed CachedFiler to invalidate on write close | <ide><path>rc/main/java/com/lithium/flow/filer/CachedFiler.java
<ide> import static com.google.common.base.Preconditions.checkNotNull;
<ide>
<ide> import com.lithium.flow.config.Config;
<add>import com.lithium.flow.io.DecoratedOutputStream;
<ide> import com.lithium.flow.util.Caches;
<ide> import com.lithium.flow.util.CheckedFunction;
<ide>
<ide> import java.io.File;
<ide> import java.io.IOException;
<add>import java.io.OutputStream;
<ide> import java.util.List;
<ide> import java.util.concurrent.ExecutionException;
<ide> import java.util.concurrent.TimeUnit;
<ide> dirCache.invalidate(path);
<ide> }
<ide> }
<add>
<add> @Override
<add> @Nonnull
<add> public OutputStream writeFile(@Nonnull String path) throws IOException {
<add> checkNotNull(path);
<add> return new DecoratedOutputStream(super.writeFile(path)) {
<add> @Override
<add> public void close() throws IOException {
<add> super.close();
<add> dirCache.invalidate(new File(path).getParent());
<add> fileCache.invalidate(path);
<add> }
<add> };
<add> }
<ide> } |
|
Java | mit | 911395d0d727acf8fb0d775eeb9301edc48c27cc | 0 | tedliang/osworkflow,tedliang/osworkflow,tedliang/osworkflow,tedliang/osworkflow | /*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.workflow.spi;
import com.mckoi.database.jdbc.MSQLException;
import com.opensymphony.module.propertyset.hibernate.PropertySetItem;
import junit.framework.Assert;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
* @author Eric Pugh
*
* This helper class populates a test mckoi database.
*/
public class DatabaseHelper {
//~ Static fields/initializers /////////////////////////////////////////////
private static final Log log = LogFactory.getLog(DatabaseHelper.class);
//~ Methods ////////////////////////////////////////////////////////////////
/**
* Create the database by loading a URL pointing at a SQL script.
*/
public static void createDatabase(URL url) {
Assert.assertNotNull("Database url is null", url);
try {
String sql = getDatabaseCreationScript(url);
createDatabase(sql);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* Create a new database and initialize it with the specified sql script.
* @param sql the sql to execute
*/
public static void createDatabase(String sql) {
Connection connection;
Statement statement = null;
String sqlLine = null;
try {
InitialContext context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/CreateDS");
connection = ds.getConnection();
statement = connection.createStatement();
String[] sqls = StringUtils.split(sql, ";");
for (int i = 0; i < sqls.length; i++) {
sqlLine = StringUtils.stripToEmpty(sqls[i]);
sqlLine = StringUtils.replace(sqlLine, "\r", "");
sqlLine = StringUtils.replace(sqlLine, "\n", "");
//String s = sqls[i];
if ((sqlLine.length() > 0) && (sqlLine.charAt(0) != '#')) {
try {
statement.executeQuery(sqlLine);
} catch (MSQLException e) {
if (sqlLine.toLowerCase().indexOf("drop") == -1) {
log.error("Error executing " + sqlLine, e);
}
}
}
}
} catch (Exception e) {
log.error("Database creation error. sqlLine:" + sqlLine, e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (Exception ex) {
//not catch
}
}
}
}
/**
* Use the default Hibernate *.hbm.xml files. These build the primary keys
* based on an identity or sequence, whatever is native to the database.
* @throws Exception
*/
public static SessionFactory createHibernateSessionFactory() throws Exception {
Configuration configuration = new Configuration();
//cfg.addClass(HibernateHistoryStep.class);
URL currentStep = DatabaseHelper.class.getResource("/com/opensymphony/workflow/spi/hibernate/HibernateCurrentStep.hbm.xml");
URL historyStep = DatabaseHelper.class.getResource("/com/opensymphony/workflow/spi/hibernate/HibernateHistoryStep.hbm.xml");
URL workflowEntry = DatabaseHelper.class.getResource("/com/opensymphony/workflow/spi/hibernate/HibernateWorkflowEntry.hbm.xml");
Assert.assertTrue(currentStep != null);
Assert.assertTrue(historyStep != null);
Assert.assertTrue(workflowEntry != null);
configuration.addURL(currentStep);
configuration.addURL(historyStep);
configuration.addURL(workflowEntry);
configuration.addClass(PropertySetItem.class);
new SchemaExport(configuration).create(true, true);
return configuration.buildSessionFactory();
}
private static String getDatabaseCreationScript(URL url) throws IOException {
InputStreamReader reader = new InputStreamReader(url.openStream());
StringBuffer sb = new StringBuffer(100);
int c = 0;
while (c > -1) {
c = reader.read();
if (c > -1) {
sb.append((char) c);
}
}
return sb.toString();
}
}
| src/test/com/opensymphony/workflow/spi/DatabaseHelper.java | /*
* Copyright (c) 2002-2003 by OpenSymphony
* All rights reserved.
*/
package com.opensymphony.workflow.spi;
import com.mckoi.database.jdbc.MSQLException;
import com.opensymphony.module.propertyset.hibernate.PropertySetItem;
import junit.framework.Assert;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.cfg.Configuration;
import net.sf.hibernate.tool.hbm2ddl.SchemaExport;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.io.*;
import java.net.URL;
import java.sql.Connection;
import java.sql.Statement;
import javax.naming.InitialContext;
import javax.sql.DataSource;
/**
* @author Eric Pugh
*
* This helper class populates a test mckoi database.
*/
public class DatabaseHelper {
//~ Static fields/initializers /////////////////////////////////////////////
private static final Log log = LogFactory.getLog(DatabaseHelper.class);
//~ Methods ////////////////////////////////////////////////////////////////
public static void createDatabase(URL url) {
if (url == null) {
Assert.fail("database url is null");
}
try {
String sql = getDatabaseCreationScript(url);
createDatabase(sql);
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
/**
* Create a new database and initialize it with the specified sql script.
* @param sql the sql to execute
*/
public static void createDatabase(String sql) {
Connection connection;
Statement statement = null;
String sqlLine = null;
try {
InitialContext context = new InitialContext();
DataSource ds = (DataSource) context.lookup("jdbc/CreateDS");
connection = ds.getConnection();
statement = connection.createStatement();
String[] sqls = StringUtils.split(sql, ";");
for (int i = 0; i < sqls.length; i++) {
sqlLine = StringUtils.stripToEmpty(sqls[i]);
sqlLine = StringUtils.replace(sqlLine, "\r", "");
sqlLine = StringUtils.replace(sqlLine, "\n", "");
//String s = sqls[i];
if ((sqlLine.length() > 0) && (sqlLine.charAt(0) != '#')) {
try {
statement.executeQuery(sqlLine);
} catch (MSQLException e) {
if (sqlLine.toLowerCase().indexOf("drop") == -1) {
log.error("Error executing " + sqlLine, e);
}
}
}
}
} catch (Exception e) {
log.error("Database creation error. sqlLine:" + sqlLine, e);
} finally {
if (statement != null) {
try {
statement.close();
} catch (Exception ex) {
//not catch
}
}
}
// return connection;
}
/**
* Use the default Hibernate *.hbm.xml files. These build the primary keys
* based on an identity or sequence, whatever is native to the database.
* @throws Exception
*/
public static SessionFactory createHibernateSessionFactory() throws Exception {
Configuration configuration = new Configuration();
//cfg.addClass(HibernateHistoryStep.class);
URL currentStep = DatabaseHelper.class.getResource("/com/opensymphony/workflow/spi/hibernate/HibernateCurrentStep.hbm.xml");
URL historyStep = DatabaseHelper.class.getResource("/com/opensymphony/workflow/spi/hibernate/HibernateHistoryStep.hbm.xml");
URL workflowEntry = DatabaseHelper.class.getResource("/com/opensymphony/workflow/spi/hibernate/HibernateWorkflowEntry.hbm.xml");
Assert.assertTrue(currentStep != null);
Assert.assertTrue(historyStep != null);
Assert.assertTrue(workflowEntry != null);
configuration.addURL(currentStep);
configuration.addURL(historyStep);
configuration.addURL(workflowEntry);
configuration.addClass(PropertySetItem.class);
new SchemaExport(configuration).create(true, true);
return configuration.buildSessionFactory();
}
private static String getDatabaseCreationScript(URL url) throws IOException {
InputStreamReader reader = new InputStreamReader(url.openStream());
StringBuffer sb = new StringBuffer(100);
int c = 0;
while (c > -1) {
c = reader.read();
if (c > -1) {
sb.append((char) c);
}
}
return sb.toString();
}
}
| Slight cleanup of Database helper
| src/test/com/opensymphony/workflow/spi/DatabaseHelper.java | Slight cleanup of Database helper | <ide><path>rc/test/com/opensymphony/workflow/spi/DatabaseHelper.java
<ide>
<ide> //~ Methods ////////////////////////////////////////////////////////////////
<ide>
<add> /**
<add> * Create the database by loading a URL pointing at a SQL script.
<add> */
<ide> public static void createDatabase(URL url) {
<del> if (url == null) {
<del> Assert.fail("database url is null");
<del> }
<add> Assert.assertNotNull("Database url is null", url);
<ide>
<ide> try {
<ide> String sql = getDatabaseCreationScript(url);
<ide> }
<ide> }
<ide> }
<del>
<del> // return connection;
<ide> }
<ide>
<ide> /** |
|
Java | apache-2.0 | 7335807fbd4fff74a12ac865c3d8c4c40de422dc | 0 | folio-org/okapi,folio-org/okapi | package okapi;
import org.folio.okapi.MainVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.response.ValidatableResponse;
import guru.nidi.ramltester.RamlDefinition;
import guru.nidi.ramltester.RamlLoaders;
import guru.nidi.ramltester.restassured.RestAssuredClient;
@RunWith(VertxUnitRunner.class)
public class ModuleTest {
private final Logger logger = LoggerFactory.getLogger("okapi");
Vertx vertx;
Async async;
private String locationSampleDeployment;
private String locationHeaderDeployment;
private String locationAuthDeployment = null;
private String okapiToken;
private final String okapiTenant = "roskilde";
private HttpClient httpClient;
private static final String LS = System.lineSeparator();
private final int port = Integer.parseInt(System.getProperty("port", "9130"));
public ModuleTest() {
}
@Before
public void setUp(TestContext context) {
vertx = Vertx.vertx();
JsonObject conf = new JsonObject()
.put("storage", "inmemory");
DeploymentOptions opt = new DeploymentOptions()
.setConfig(conf);
vertx.deployVerticle(MainVerticle.class.getName(),
opt, context.asyncAssertSuccess());
httpClient = vertx.createHttpClient();
RestAssured.port = port;
}
@After
public void tearDown(TestContext context) {
logger.info("Cleaning up after ModuleTest");
async = context.async();
td(context);
}
public void td(TestContext context) {
if (locationAuthDeployment != null) {
httpClient.delete(port, "localhost", locationAuthDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationAuthDeployment = null;
td(context);
});
}).end();
return;
}
if (locationSampleDeployment != null) {
httpClient.delete(port, "localhost", locationSampleDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSampleDeployment = null;
td(context);
});
}).end();
return;
}
if (locationSampleDeployment != null) {
httpClient.delete(port, "localhost", locationSampleDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSampleDeployment = null;
td(context);
});
}).end();
return;
}
if (locationHeaderDeployment != null) {
httpClient.delete(port, "localhost", locationHeaderDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationHeaderDeployment = null;
td(context);
});
}).end();
return;
}
vertx.close(x -> {
async.complete();
});
}
/**
* Check that the tests have not left anything in the database. Since the
*
* @Tests are run in a nondeterministic order, each ought to clean up after
* itself. This should be called in the beginning and end of each @Test
*
* @param context
*/
private void checkDbIsEmpty(String label, TestContext context) {
logger.debug("Db check '" + label + "'");
// Check that we are not depending on td() to undeploy modules
Assert.assertNull("locationAuthDeployment", locationAuthDeployment);
Assert.assertNull("locationSampleDeployment", locationSampleDeployment);
Assert.assertNull("locationSample5Deployment", locationSampleDeployment);
Assert.assertNull("locationHeaderDeployment", locationHeaderDeployment);
String emptyListDoc = "[ ]";
given().get("/_/deployment/modules").then()
.log().ifError().statusCode(200)
.body(equalTo(emptyListDoc));
given().get("/_/discovery/nodes").then()
.log().ifError().statusCode(200); // we still have a node!
given().get("/_/discovery/modules").then()
.log().ifError().statusCode(200).body(equalTo(emptyListDoc));
given().get("/_/proxy/modules").then()
.log().ifError().statusCode(200).body(equalTo(emptyListDoc));
given().get("/_/proxy/tenants").then()
.log().ifError().statusCode(200).body(equalTo(emptyListDoc));
logger.debug("Db check '" + label + "' OK");
}
/**
* Helper to create a tenant. So it can be done in a one-liner without
* cluttering real tests. Actually testing the tenant stuff should be in its
* own test.
*
* @return the location, for deleting it later
*/
public String createTenant() {
final String docTenant = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"" + okapiTenant + " bibliotek\"" + LS
+ "}";
final String loc = given()
.header("Content-Type", "application/json")
.body(docTenant)
.post("/_/proxy/tenants")
.then()
.statusCode(201)
.log().ifError()
.extract().header("Location");
return loc;
}
/**
* Helper to create a module.
*
* @param md A full ModuleDescriptor
* @return the URL to delete when done
*/
public String createModule(String md) {
final String loc = given()
.header("Content-Type", "application/json")
.body(md)
.post("/_/proxy/modules")
.then()
.statusCode(201)
.log().ifError()
.extract().header("Location");
return loc;
}
/**
* Helper to deploy a module. Assumes that the ModuleDescriptor has a good
* LaunchDescriptor.
*
* @param modId Id of the module to be deployed.
* @return url to delete when done
*/
public String deployModule(String modId) {
final String instId = modId.replace("-module", "") + "-inst";
final String docDeploy = "{" + LS
+ " \"instId\" : \"" + instId + "\"," + LS
+ " \"srvcId\" : \"" + modId + "\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
final String loc = given()
.header("Content-Type", "application/json")
.body(docDeploy)
.post("/_/discovery/modules")
.then()
.statusCode(201)
.log().ifError()
.extract().header("Location");
return loc;
}
/**
* Helper to enable a module for our test tenant.
*
* @param modId The module to enable
* @return the location, so we can delete it later. Can safely be ignored.
*/
public String enableModule(String modId) {
final String docEnable = "{" + LS
+ " \"id\" : \"" + modId + "\"" + LS
+ "}";
final String location = given()
.header("Content-Type", "application/json")
.body(docEnable)
.post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then()
.statusCode(201)
.extract().header("Location");
return location;
}
/**
* Tests that declare one module. Declares a single module in many ways, often
* with errors. In the end the module gets deployed and enabled for a newly
* created tenant, and a request is made to it. Uses the test module, but not
* any auth module, that should be a separate test.
*
* @param context
*/
@Test
public void testOneModule(TestContext context) {
async = context.async();
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
Response r;
checkDbIsEmpty("testOneModule starting", context);
// Get an empty list of modules
c = api.createRestAssured();
c.given()
.get("/_/proxy/modules")
.then()
.statusCode(200)
.body(equalTo("[ ]"));
Assert.assertTrue(c.getLastReport().isEmpty());
// Check that we refuse the request with a trailing slash
given()
.get("/_/proxy/modules/")
.then()
.statusCode(404);
// This is a good ModuleDescriptor. For error tests, some things get
// replaced out.
final String testModJar = "../okapi-test-module/target/okapi-test-module-fat.jar";
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"" + LS
+ " } ]," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsRequired\" : [ \"sample.needed\" ]," + LS
+ " \"permissionsDesired\" : [ \"sample.extra\" ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]" + LS
+ " } ]" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"interfaceType\" : \"system\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"POST\", \"DELETE\" ]," + LS
+ " \"path\" : \"/_/tenant\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"system\"" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"permissionSets\" : [ {" + LS
+ " \"permissionName\" : \"everything\"," + LS
+ " \"displayName\" : \"every possible permission\"," + LS
+ " \"description\" : \"All permissions combined\"," + LS
+ " \"subPermissions\" : [ \"sample.needed\", \"sample.extra\" ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar " + testModJar + "\"" + LS
+ " }" + LS
+ "}";
// First some error checks: Missing id
String docBadId = docSampleModule.replace("sample-module", "bad module id?!");
given()
.header("Content-Type", "application/json")
.body(docBadId)
.post("/_/proxy/modules")
.then()
.statusCode(400);
// Bad interface type
String docBadIntType = docSampleModule.replace("system", "strange interface type");
given()
.header("Content-Type", "application/json")
.body(docBadIntType)
.post("/_/proxy/modules")
.then()
.statusCode(400);
// Bad RoutingEntry type
String docBadReType = docSampleModule.replace("request-response", "strange-re-type");
given()
.header("Content-Type", "application/json")
.body(docBadReType)
.post("/_/proxy/modules")
.then()
.statusCode(400);
String docMissingPath = docSampleModule.replace("/testb", "");
given()
.header("Content-Type", "application/json")
.body(docMissingPath)
.post("/_/proxy/modules")
.then()
.statusCode(400);
String docBadPathPat = docSampleModule.replace("path", "pathPattern")
.replace("/testb", "/test.*b(/?)"); // invalid characters in pattern
given()
.header("Content-Type", "application/json")
.body(docBadPathPat)
.post("/_/proxy/modules")
.then()
.statusCode(400);
// TODO - Tests for bad interface versions
// Actually create the module
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule)
.post("/_/proxy/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locSampleModule = r.getHeader("Location");
// Get the module
c = api.createRestAssured();
c.given()
.get(locSampleModule)
.then().statusCode(200).body(equalTo(docSampleModule));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// List the one module
final String expOneModList = "[ {" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"" + LS
+ "} ]";
c = api.createRestAssured();
c.given()
.get("/_/proxy/modules")
.then()
.statusCode(200)
.body(equalTo(expOneModList));
Assert.assertTrue(c.getLastReport().isEmpty());
// Deploy the module
final String docDeploy = "{" + LS
+ " \"instId\" : \"sample-inst\"," + LS
+ " \"srvcId\" : \"sample-module\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
r = c.given()
.header("Content-Type", "application/json")
.body(docDeploy)
.post("/_/discovery/modules")
.then()
.statusCode(201).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationSampleDeployment = r.header("Location");
// Create a tenant and enable the module
final String locTenant = createTenant();
final String locEnable = enableModule("sample-module");
// Make a simple request to the module
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testb")
.then().statusCode(200)
.body(containsString("It works"));
// Make a more complex request that returns all headers and parameters
// So the headers we check are those that the module sees and reports to
// us, not necessarily those that Okapi would return to us.
// Note that since this is the only module in the pipeline, Okapi assumes
// it is the auth module, and passes it those extra headers. Normally
// the auth module would have handled those, and indicated to Okapi that
// these are no longer needed, and Okapi would not pass them to regular
// modules.
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-all-headers", "H") // ask sample to report all headers
.get("/testb?query=foo&limit=10")
.then().statusCode(200)
.header("X-Okapi-Url", "http://localhost:9130") // no trailing slash!
.header("X-Url-Params", "query=foo&limit=10")
.header("X-Okapi-Permissions-Required", "sample.needed")
.header("X-Okapi-Module-Permissions", "{\"sample-module\":[\"sample.modperm\"]}")
.body(containsString("It works"));
// Check that the tenant API got called (exactly once)
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-tenant-reqs", "yes")
.get("/testb")
.then()
.statusCode(200)
.body(equalTo("It works Tenant requests: POST-roskilde "))
.log().ifError();
// Clean up, so the next test starts with a clean slate (in reverse order)
logger.debug("testOneModule cleaning up");
given().delete(locEnable).then().log().ifError().statusCode(204);
given().delete(locTenant).then().log().ifError().statusCode(204);
given().delete(locSampleModule).then().log().ifError().statusCode(204);
given().delete(locationSampleDeployment).then().log().ifError().statusCode(204);
locationSampleDeployment = null;
checkDbIsEmpty("testOneModule done", context);
async.complete();
}
/**
* Test system interfaces. Mostly about the system interfaces _tenant (on the
* module itself, to initialize stuff), and _tenantPermissions to pass its
* permissions to the permissions module.
*
* @param context
*/
@Test
public void testSystemInterfaces(TestContext context) {
async = context.async();
checkDbIsEmpty("testSystemInterfaces starting", context);
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
Response r;
// Set up a tenant to test with
final String locTenant = createTenant();
// Set up a module that does the _tenantPermissions interface that will
// get called when sample gets enabled. We (ab)use the header module for
// this.
final String testHdrJar = "../okapi-test-header-module/target/okapi-test-header-module-fat.jar";
final String docHdrModule = "{" + LS
+ " \"id\" : \"header\"," + LS
+ " \"name\" : \"header-module\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"_tenantPermissions\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"interfaceType\" : \"system\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/_/tenantPermissions\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar " + testHdrJar + "\"" + LS
+ " }" + LS
+ "}";
// Create, deploy, and enable the header module
final String locHdrModule = createModule(docHdrModule);
locationHeaderDeployment = deployModule("header");
final String locHdrEnable = enableModule("header");
// Set up the test module
// It provides a _tenant interface, but no _tenantPermissions
// Enabling it will end up invoking the _tenantPermissions in header
final String testModJar = "../okapi-test-module/target/okapi-test-module-fat.jar";
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"" + LS
+ " } ]," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsRequired\" : [ \"sample.needed\" ]," + LS
+ " \"permissionsDesired\" : [ \"sample.extra\" ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]" + LS
+ " } ]" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"interfaceType\" : \"system\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"POST\", \"DELETE\" ]," + LS
+ " \"path\" : \"/_/tenant\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"system\"" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"permissionSets\" : [ {" + LS
+ " \"permissionName\" : \"everything\"," + LS
+ " \"displayName\" : \"every possible permission\"," + LS
+ " \"description\" : \"All permissions combined\"," + LS
+ " \"subPermissions\" : [ \"sample.needed\", \"sample.extra\" ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar " + testModJar + "\"" + LS
+ " }" + LS
+ "}";
// Create and deploy the sample module
final String locSampleModule = createModule(docSampleModule);
locationSampleDeployment = deployModule("sample-module");
// Enable the sample module. Verify that the _tenantPermissions gets
// invoked.
final String docEnable = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
final String expPerms = "{ "
+ "\"moduleId\" : \"sample-module\", "
+ "\"perms\" : [ { "
+ "\"permissionName\" : \"everything\", "
+ "\"displayName\" : \"every possible permission\", "
+ "\"description\" : \"All permissions combined\", "
+ "\"subPermissions\" : [ \"sample.needed\", \"sample.extra\" ] "
+ "} ] }";
final String locSampleEnable = given()
.header("Content-Type", "application/json")
.body(docEnable)
.post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then()
.statusCode(201)
.log().ifError()
.header("X-Tenant-Perms-Result", expPerms)
.extract().header("Location");
// Clean up, so the next test starts with a clean slate (in reverse order)
logger.debug("testSystemInterfaces cleaning up");
given().delete(locSampleEnable).then().log().ifError().statusCode(204);
given().delete(locationSampleDeployment).then().log().ifError().statusCode(204);
given().delete(locSampleModule).then().log().ifError().statusCode(204);
locationSampleDeployment = null;
given().delete(locHdrEnable).then().log().ifError().statusCode(204);
given().delete(locationHeaderDeployment).then().log().ifError().statusCode(204);
locationHeaderDeployment = null;
given().delete(locHdrModule).then().log().ifError().statusCode(204);
given().delete(locTenant).then().log().ifError().statusCode(204);
checkDbIsEmpty("testSystemInterfaces done", context);
async.complete();
}
// TODO - This function is way too long and confusing
// Create smaller functions that test one thing at a time
// Later, move them into separate files
@Test
public void testProxy(TestContext context) {
async = context.async();
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
Response r;
String nodeListDoc = "[ {" + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"url\" : \"http://localhost:9130\"" + LS
+ "} ]";
c = api.createRestAssured();
c.given().get("/_/discovery/nodes").then().statusCode(200)
.body(equalTo(nodeListDoc));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/nodes/gyf").then().statusCode(404);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/nodes/localhost").then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body("{ }").post("/_/xyz").then().statusCode(404);
Assert.assertEquals("RamlReport{requestViolations=[Resource '/_/xyz' is not defined], "
+ "responseViolations=[], validationViolations=[]}",
c.getLastReport().toString());
final String badDoc = "{" + LS
+ " \"instId\" : \"BAD\"," + LS // the comma here makes it bad json!
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(badDoc).post("/_/deployment/modules")
.then().statusCode(400);
final String docUnknownJar = "{" + LS
+ " \"srvcId\" : \"auth\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-auth-module/target/okapi-unknown.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docUnknownJar).post("/_/deployment/modules")
.then()
.statusCode(500);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docAuthDeployment = "{" + LS
+ " \"srvcId\" : \"auth\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-auth-module/target/okapi-test-auth-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docAuthDeployment).post("/_/deployment/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationAuthDeployment = r.getHeader("Location");
c = api.createRestAssured();
String docAuthDiscovery = c.given().get(locationAuthDeployment)
.then().statusCode(200).extract().body().asString();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docAuthModule = "{" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"name\" : \"auth\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"*\" ]," + LS
+ " \"path\" : \"/\"," + LS // has to be plain '/' for the filter detection
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsDesired\" : [ \"auth.extra\" ]" + LS
+ " }, {"
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/login\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
// Check that we fail on unknown route types
final String docBadTypeModule
= docAuthModule.replaceAll("request-response", "UNKNOWN-ROUTE-TYPE");
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docBadTypeModule).post("/_/proxy/modules")
.then().statusCode(400);
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docAuthModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationAuthModule = r.getHeader("Location");
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docAuthModule).put(locationAuthModule).then().statusCode(200)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docAuthModule2 = "{" + LS
+ " \"id\" : \"auth2\"," + LS
+ " \"name\" : \"auth2\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"auth2\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"*\" ]," + LS
+ " \"path\" : \"/\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsDesired\" : [ \"auth.extra\" ]" + LS
+ " }, {"
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/login\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
final String locationAuthModule2 = locationAuthModule + "2";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docAuthModule2).put(locationAuthModule2).then().statusCode(200)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().delete(locationAuthModule2).then().statusCode(204);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docSampleDeployment = "{" + LS
+ " \"srvcId\" : \"sample-module\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"," + LS
+ " \"value\" : \"hej\"" + LS
+ " } ]" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleDeployment).post("/_/deployment/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationSampleDeployment = r.getHeader("Location");
c = api.createRestAssured();
String docSampleDiscovery = c.given().get(locationSampleDeployment)
.then().statusCode(200).extract().body().asString();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docSampleModuleBadRequire = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"requires\" : [ {" + LS
+ " \"id\" : \"SOMETHINGWEDONOTHAVE\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ ] " + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docSampleModuleBadRequire).post("/_/proxy/modules").then().statusCode(400)
.extract().response();
final String docSampleModuleBadVersion = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"requires\" : [ {" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"version\" : \"9.9.3\"" + LS // We only have 1.2.3
+ " } ]," + LS
+ " \"routingEntries\" : [ ] " + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docSampleModuleBadVersion).post("/_/proxy/modules").then().statusCode(400)
.extract().response();
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"" + LS
+ " } ]," + LS
+ " \"requires\" : [ {" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS // TODO - Define paths - add test
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsRequired\" : [ \"sample.needed\" ]," + LS
+ " \"permissionsDesired\" : [ \"sample.extra\" ]" + LS
+ " } ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"/usr/bin/false\"" + LS
+ " }" + LS
+ "}";
logger.debug(docSampleModule);
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSampleModule = r.getHeader("Location");
// Commented-out tests have been moved to testOneModule, no need to repeat here
// TODO - Remove these when refactoring complete
//c = api.createRestAssured(); // trailing slash is no good
//c.given().get("/_/proxy/modules/").then().statusCode(404);
//c = api.createRestAssured();
//c.given().get("/_/proxy/modules").then().statusCode(200);
//Assert.assertTrue(c.getLastReport().isEmpty());
//c = api.createRestAssured();
//c.given()
// .get(locationSampleModule)
// .then().statusCode(200).body(equalTo(docSampleModule));
//Assert.assertTrue("raml: " + c.getLastReport().toString(),
// c.getLastReport().isEmpty());
// Try to delete the auth module that our sample depends on
c.given().delete(locationAuthModule).then().statusCode(400);
// Try to update the auth module to a lower version, would break
// sample dependency
final String docAuthLowerVersion = docAuthModule.replace("1.2.3", "1.1.1");
c.given()
.header("Content-Type", "application/json")
.body(docAuthLowerVersion)
.put(locationAuthModule)
.then().statusCode(400);
// Update the auth module to a bit higher version
final String docAuthhigherVersion = docAuthModule.replace("1.2.3", "1.2.4");
c.given()
.header("Content-Type", "application/json")
.body(docAuthhigherVersion)
.put(locationAuthModule)
.then().statusCode(200);
// Create our tenant
final String docTenantRoskilde = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants/") // trailing slash fails
.then().statusCode(404);
Assert.assertEquals("RamlReport{requestViolations=[Resource '/_/proxy/tenants/' is not defined], "
+ "responseViolations=[], validationViolations=[]}",
c.getLastReport().toString());
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants")
.then().statusCode(201)
.body(equalTo(docTenantRoskilde))
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationTenantRoskilde = r.getHeader("Location");
// Try to enable sample without the auth that it requires
final String docEnableWithoutDep = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
c.given()
.header("Content-Type", "application/json")
.body(docEnableWithoutDep).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(400);
// try to enable a module we don't know
final String docEnableAuthBad = "{" + LS
+ " \"id\" : \"UnknonwModule\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableAuthBad).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(400);
final String docEnableAuth = "{" + LS
+ " \"id\" : \"auth\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableAuth).post("/_/proxy/tenants/" + okapiTenant + "/modules/")
.then().statusCode(404); // trailing slash is no good
// Actually enable the auith
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableAuth).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201).body(equalTo(docEnableAuth));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules/")
.then().statusCode(404); // trailing slash again
// Get the list of one enabled module
c = api.createRestAssured();
final String exp1 = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "} ]";
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200).body(equalTo(exp1));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// get the auth enabled record
final String expAuthEnabled = "{" + LS
+ " \"id\" : \"auth\"" + LS
+ "}";
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules/auth")
.then().statusCode(200).body(equalTo(expAuthEnabled));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Enablæe the sample
final String docEnableSample = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Try to enable it again, should fail
given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(400)
.body(containsString("already provided"));
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules/")
.then().statusCode(404); // trailing slash
c = api.createRestAssured();
final String expEnabledBoth = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "} ]";
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200).body(equalTo(expEnabledBoth));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Try to disable the auth module for the tenant.
// Ought to fail, because it is needed by sample module
c.given().delete("/_/proxy/tenants/" + okapiTenant + "/modules/auth")
.then().statusCode(400);
// Update the tenant
String docTenant = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"Roskilde-library\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docTenant).put("/_/proxy/tenants/" + okapiTenant)
.then().statusCode(200)
.body(equalTo(docTenant));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Check that both modules are still enabled
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200).body(equalTo(expEnabledBoth));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Request without any X-Okapi headers
given()
.get("/testb")
.then().statusCode(403);
// Request with a header, to unknown path
// (note, should fail without invoking the auth module)
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/something.we.do.not.have")
.then().statusCode(404);
// Request without an auth token
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testb")
.then()
.statusCode(401);
// Failed login
final String docWrongLogin = "{" + LS
+ " \"tenant\" : \"t1\"," + LS
+ " \"username\" : \"peter\"," + LS
+ " \"password\" : \"peter-wrong-password\"" + LS
+ "}";
given().header("Content-Type", "application/json").body(docWrongLogin)
.header("X-Okapi-Tenant", okapiTenant).post("/login")
.then().statusCode(401);
// Ok login, get token
final String docLogin = "{" + LS
+ " \"tenant\" : \"" + okapiTenant + "\"," + LS
+ " \"username\" : \"peter\"," + LS
+ " \"password\" : \"peter-password\"" + LS
+ "}";
okapiToken = given().header("Content-Type", "application/json").body(docLogin)
.header("X-Okapi-Tenant", okapiTenant).post("/login")
.then().statusCode(200).extract().header("X-Okapi-Token");
// Actual requests to the module
// Check that okapi sets up the permission headers.
// Check also the X-Okapi-Url header in the same go, as well as
// URL parameters.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-all-headers", "HB") // ask sample to report all headers
.get("/testb?query=foo&limit=10")
.then().statusCode(200)
.header("X-Okapi-Permissions-Required", "sample.needed")
.header("X-Okapi-Module-Permissions", "{\"sample-module\":[\"sample.modperm\"]}")
.header("X-Okapi-Url", "http://localhost:9130") // no trailing slash!
.header("X-Url-Params", "query=foo&limit=10")
.body(containsString("It works"));
// Check only the required permission bit, since there is only one.
// There are wanted bits too, two of them, but their order is not
// well defined.
// Check the CORS headers.
// The presence of the Origin header should provoke the two extra headers.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Origin", "http://foobar.com")
.get("/testb")
.then().statusCode(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Expose-Headers", "Location,X-Okapi-Trace,X-Okapi-Token,Authorization")
.body(equalTo("It works"));
// Post request.
// Test also URL parameters.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Content-Type", "text/xml")
.header("X-all-headers", "H") // ask sample to report all headers
.body("Okapi").post("/testb?query=foo")
.then().statusCode(200)
.header("X-Url-Params", "query=foo")
.body(equalTo("hej (XML) Okapi"));
// Verify that the path matching is case sensitive
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/TESTB")
.then().statusCode(404);
// See that a delete fails - we only match auth, which is a filter
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.delete("/testb")
.then().statusCode(404);
// Check that we don't do prefix matching
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/testbXXX")
.then().statusCode(404);
// Check that parameters don't mess with the routing
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/testb?p=parameters&q=query")
.then().statusCode(200);
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-tenant-reqs", "yes")
.get("/testb")
.then()
.statusCode(200) // No longer expects a DELETE. See Okapi-252
.body(equalTo("It works Tenant requests: POST-roskilde POST-roskilde POST-roskilde "))
.log().ifError();
// Check that we refuse unknown paths, even with auth module
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/something.we.do.not.have")
.then().statusCode(404);
// Check that we accept Authorization: Bearer <token> instead of X-Okapi-Token,
// and that we can extract the tenant from it.
given()
.header("X-all-headers", "H") // ask sample to report all headers
.header("Authorization", "Bearer " + okapiToken)
.get("/testb")
.then().log().ifError()
.header("X-Okapi-Tenant", okapiTenant)
.statusCode(200);
// Note that we can not check the token, the module sees a different token,
// created by the auth module, when it saw a ModulePermission for the sample
// module. This is all right, since we explicitly ask sample to pass its
// request headers into its response. See Okapi-266.
// Check that we fail on conflicting X-Okapi-Token and Auth tokens
given().header("X-all-headers", "H") // ask sample to report all headers
.header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Authorization", "Bearer " + okapiToken + "WRONG")
.get("/testb")
.then().log().ifError()
.statusCode(400);
// 2nd sample module. We only create it in discovery and give it same URL as
// for sample-module (first one). Then we delete it again.
c = api.createRestAssured();
final String docSample2Deployment = "{" + LS
+ " \"instId\" : \"sample2-inst\"," + LS
+ " \"srvcId\" : \"sample-module2\"," + LS
// + " \"nodeId\" : null," + LS // no nodeId, we aren't deploying on any node
+ " \"url\" : \"http://localhost:9132\"" + LS
+ "}";
r = c.given()
.header("Content-Type", "application/json")
.body(docSample2Deployment).post("/_/discovery/modules")
.then()
.statusCode(201).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample2Discovery = r.header("Location");
// Get the sample-2
c = api.createRestAssured();
c.given().get("/_/discovery/modules/sample-module2")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// and its instance
c = api.createRestAssured();
c.given().get("/_/discovery/modules/sample-module2/sample2-inst")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// health check
c = api.createRestAssured();
c.given().get("/_/discovery/health")
.then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// health for sample2
c = api.createRestAssured();
c.given().get("/_/discovery/health/sample-module2")
.then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// health for an instance
c = api.createRestAssured();
c.given().get("/_/discovery/health/sample-module2/sample2-inst")
.then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Declare sample2
final String docSample2Module = "{" + LS
+ " \"id\" : \"sample-module2\"," + LS
+ " \"name\" : \"another-sample-module2\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"31\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]," + LS
+ " \"tenantInterface\" : \"/tenant\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSample2Module).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample2Module = r.getHeader("Location");
// enable sample2
final String docEnableSample2 = "{" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample2).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample2));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// disable it, and re-enable.
// Later we will check that we got the right calls in its
// tenant interface.
given()
.delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module2")
.then().statusCode(204);
given()
.header("Content-Type", "application/json")
.body(docEnableSample2).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample2));
// 3rd sample module. We only create it in discovery and give it same URL as
// for sample-module (first one), just like sample2 above.
c = api.createRestAssured();
final String docSample3Deployment = "{" + LS
+ " \"instId\" : \"sample3-instance\"," + LS
+ " \"srvcId\" : \"sample-module3\"," + LS
+ " \"url\" : \"http://localhost:9132\"" + LS
+ "}";
r = c.given()
.header("Content-Type", "application/json")
.body(docSample3Deployment).post("/_/discovery/modules")
.then()
.statusCode(201).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample3Inst = r.getHeader("Location");
logger.debug("Deployed: locationSample3Inst " + locationSample3Inst);
final String docSample3Module = "{" + LS
+ " \"id\" : \"sample-module3\"," + LS
+ " \"name\" : \"sample-module3\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"05\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"45\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"33\"," + LS
+ " \"type\" : \"request-only\"" + LS
+ " } ]" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSample3Module).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample3Module = r.getHeader("Location");
final String docEnableSample3 = "{" + LS
+ " \"id\" : \"sample-module3\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample3).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.header("Location", equalTo("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module3"))
.log().ifError()
.body(equalTo(docEnableSample3));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given()
.get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200)
.log().all();
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/testb")
.then().statusCode(200).body(equalTo("It works"));
// Verify that both modules get executed
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.body("OkapiX").post("/testb")
.then().statusCode(200)
.body(equalTo("hej hej OkapiX"));
// Verify that we have seen tenant requests to POST and DELETE
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-tenant-reqs", "yes")
.get("/testb")
.then()
.statusCode(200) // No longer expects a DELETE. See Okapi-252
.body(containsString("POST-roskilde POST-roskilde"))
.log().ifError();
// Check that the X-Okapi-Stop trick works. Sample will set it if it sees
// a X-Stop-Here header.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-Stop-Here", "Enough!")
.body("OkapiX").post("/testb")
.then().statusCode(200)
.header("X-Okapi-Stop", "Enough!")
.body(equalTo("hej OkapiX")); // only one "Hello"
given().get("/_/test/reloadmodules")
.then().statusCode(204);
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Content-Type", "text/xml")
.get("/testb")
.then().statusCode(200).body(equalTo("It works (XML) "));
c = api.createRestAssured();
final String exp4Modules = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module3\"" + LS
+ "} ]";
c.given().get(locationTenantRoskilde + "/modules")
.then().statusCode(200)
.body(equalTo(exp4Modules));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().delete(locationTenantRoskilde + "/modules/sample-module3")
.then().statusCode(204);
Assert.assertTrue(c.getLastReport().isEmpty());
c = api.createRestAssured();
final String exp3Modules = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "} ]";
c.given().get(locationTenantRoskilde + "/modules")
.then().statusCode(200)
.body(equalTo(exp3Modules));
Assert.assertTrue(c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/modules")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// make sample 2 disappear from discovery!
c = api.createRestAssured();
c.given().delete(locationSample2Discovery)
.then().statusCode(204);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/modules")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Content-Type", "text/xml")
.get("/testb")
.then().statusCode(404); // because sample2 was removed
// Disable the sample module. No tenant-destroy for sample
given()
.delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module")
.then().statusCode(204);
// Disable the sample2 module. It has a tenant request handler which is
// no longer invoked, so it does not matter we don't have a running instance
given()
.delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module2")
.then().statusCode(204);
c = api.createRestAssured();
c.given().delete(locationTenantRoskilde)
.then().statusCode(204);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Clean up, so the next test starts with a clean slate
logger.debug("testproxy cleaning up");
given().delete(locationSample3Inst).then().log().ifError().statusCode(204);
given().delete(locationSample3Module).then().log().ifError().statusCode(204);
given().delete("/_/proxy/modules/sample-module").then().log().ifError().statusCode(204);
given().delete("/_/proxy/modules/sample-module2").then().log().ifError().statusCode(204);
given().delete("/_/proxy/modules/auth").then().log().ifError().statusCode(204);
given().delete(locationAuthDeployment).then().log().ifError().statusCode(204);
locationAuthDeployment = null;
given().delete(locationSampleDeployment).then().log().ifError().statusCode(204);
locationSampleDeployment = null;
checkDbIsEmpty("testproxy done", context);
async.complete();
}
@Test
public void testDeployment(TestContext context) {
async = context.async();
Response r;
given().get("/_/deployment/modules")
.then().statusCode(200)
.body(equalTo("[ ]"));
given().get("/_/deployment/modules/not_found")
.then().statusCode(404);
given().get("/_/discovery/modules")
.then().statusCode(200)
.body(equalTo("[ ]"));
given().get("/_/discovery/modules/not_found")
.then().statusCode(404);
final String doc1 = "{" + LS
+ " \"srvcId\" : \"sample-module5\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
given().header("Content-Type", "application/json")
.body(doc1).post("/_/discovery/modules/") // extra slash !
.then().statusCode(404);
final String doc2 = "{" + LS
+ " \"instId\" : \"localhost-9131\"," + LS
+ " \"srvcId\" : \"sample-module5\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"url\" : \"http://localhost:9131\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(doc1).post("/_/discovery/modules")
.then().statusCode(201)
.body(equalTo(doc2))
.extract().response();
locationSampleDeployment = r.getHeader("Location");
given().get(locationSampleDeployment).then().statusCode(200)
.body(equalTo(doc2));
given().get("/_/deployment/modules")
.then().statusCode(200)
.body(equalTo("[ " + doc2 + " ]"));
given().header("Content-Type", "application/json")
.body(doc2).post("/_/discovery/modules")
.then().statusCode(400);
given().get("/_/discovery/modules/sample-module5")
.then().statusCode(200)
.body(equalTo("[ " + doc2 + " ]"));
given().get("/_/discovery/modules")
.then().statusCode(200)
.log().ifError()
.body(equalTo("[ " + doc2 + " ]"));
System.out.println("delete: " + locationSampleDeployment);
given().delete(locationSampleDeployment).then().statusCode(204);
locationSampleDeployment = null;
// Verify that the list works also after delete
given().get("/_/deployment/modules")
.then().statusCode(200)
.body(equalTo("[ ]"));
// verify that module5 is no longer there
given().get("/_/discovery/modules/sample-module5")
.then().statusCode(404);
// verify that a never-seen module returns the same
given().get("/_/discovery/modules/UNKNOWN-MODULE")
.then().statusCode(404);
// Deploy a module via its own LaunchDescriptor
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module-depl\"," + LS
+ " \"name\" : \"sample module for deployment test\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules")
.then()
//.log().all()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSampleModule = r.getHeader("Location");
final String docDeploy = "{" + LS
+ " \"srvcId\" : \"sample-module-depl\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
final String DeployResp = "{" + LS
+ " \"instId\" : \"localhost-9131\"," + LS
+ " \"srvcId\" : \"sample-module-depl\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"url\" : \"http://localhost:9131\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(docDeploy).post("/_/discovery/modules")
.then().statusCode(201)
.body(equalTo(DeployResp))
.extract().response();
locationSampleDeployment = r.getHeader("Location");
// Would be nice to verify that the module works, but too much hassle with
// tenants etc.
// Undeploy.
given().delete(locationSampleDeployment).then().statusCode(204);
// Undeploy again, to see it is gone
given().delete(locationSampleDeployment).then().statusCode(404);
locationSampleDeployment = null;
// and delete from the proxy
given().delete(locationSampleModule)
.then().statusCode(204);
checkDbIsEmpty("testDeployment done", context);
async.complete();
}
@Test
public void testHeader(TestContext context) {
async = context.async();
Response r;
ValidatableResponse then;
final String docLaunch1 = "{" + LS
+ " \"srvcId\" : \"sample-module5\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(docLaunch1).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
locationSampleDeployment = r.getHeader("Location");
final String docLaunch2 = "{" + LS
+ " \"srvcId\" : \"header-module\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-header-module/target/okapi-test-header-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(docLaunch2).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
locationHeaderDeployment = r.getHeader("Location");
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module5\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
r = given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationSampleModule = r.getHeader("Location");
final String docHeaderModule = "{" + LS
+ " \"id\" : \"header-module\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " } ]" + LS
+ "}";
r = given()
.header("Content-Type", "application/json")
.body(docHeaderModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationHeaderModule = r.getHeader("Location");
final String docTenantRoskilde = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
r = given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants")
.then().statusCode(201)
.body(equalTo(docTenantRoskilde))
.extract().response();
final String locationTenantRoskilde = r.getHeader("Location");
final String docEnableSample = "{" + LS
+ " \"id\" : \"sample-module5\"" + LS
+ "}";
given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample));
final String docEnableHeader = "{" + LS
+ " \"id\" : \"header-module\"" + LS
+ "}";
given()
.header("Content-Type", "application/json")
.body(docEnableHeader).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableHeader));
given().header("X-Okapi-Tenant", okapiTenant)
.body("bar").post("/testb")
.then().statusCode(200).body(equalTo("Hello foobar"))
.extract().response();
given().delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module5")
.then().statusCode(204);
given().delete(locationSampleModule)
.then().statusCode(204);
final String docSampleModule2 = "{" + LS
+ " \"id\" : \"sample-module5\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"5\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
given()
.header("Content-Type", "application/json")
.body(docSampleModule2).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationSampleModule2 = r.getHeader("Location");
given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample));
given().header("X-Okapi-Tenant", okapiTenant)
.body("bar").post("/testb")
.then().statusCode(200).body(equalTo("Hello foobar"))
.extract().response();
logger.debug("testHeader cleaning up");
given().delete(locationTenantRoskilde)
.then().statusCode(204);
given().delete(locationSampleModule)
.then().statusCode(204);
given().delete(locationSampleDeployment).then().statusCode(204);
locationSampleDeployment = null;
given().delete(locationHeaderDeployment)
.then().statusCode(204);
locationHeaderDeployment = null;
given().delete(locationHeaderModule)
.then().statusCode(204);
checkDbIsEmpty("testHeader done", context);
async.complete();
}
@Test
public void testUiModule(TestContext context) {
async = context.async();
Response r;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
final String docUiModuleInput = "{" + LS
+ " \"id\" : \"11-22-11-22-11\"," + LS
+ " \"name\" : \"sample-ui\"," + LS
+ " \"routingEntries\" : [ ]," + LS
+ " \"uiDescriptor\" : {" + LS
+ " \"npm\" : \"name-of-module-in-npm\"" + LS
+ " }" + LS
+ "}";
final String docUiModuleOutput = "{" + LS
+ " \"id\" : \"11-22-11-22-11\"," + LS
+ " \"name\" : \"sample-ui\"," + LS
+ " \"routingEntries\" : [ ]," + LS
+ " \"uiDescriptor\" : {" + LS
+ " \"npm\" : \"name-of-module-in-npm\"" + LS
+ " }" + LS
+ "}";
RestAssuredClient c;
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docUiModuleInput).post("/_/proxy/modules").then().statusCode(201)
.body(equalTo(docUiModuleOutput)).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
String location = r.getHeader("Location");
c = api.createRestAssured();
c.given()
.get(location)
.then().statusCode(200).body(equalTo(docUiModuleOutput));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given().delete(location)
.then().statusCode(204);
checkDbIsEmpty("testUiModule done", context);
async.complete();
}
/*
* Test redirect types. Sets up two modules, our sample, and the header test
* module.
*
* Both modules support the /testb path.
* Test also supports /testr path.
* Header will redirect /red path to /testr, which will end up in the test module.
* Header will also attempt to support /loop, /loop1, and /loop2 for testing
* looping redirects. These are expected to fail.
*
*/
@Test
public void testRedirect(TestContext context) {
logger.info("Redirect test starting");
async = context.async();
RestAssuredClient c;
Response r;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml")
.load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
// Set up a tenant to test with
final String docTenantRoskilde = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants")
.then().statusCode(201)
.log().ifError()
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationTenantRoskilde = r.getHeader("Location");
// Set up, deploy, and enable a sample module
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"50\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testr\"," + LS
+ " \"level\" : \"59\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsDesired\" : [ \"sample.testr\" ]" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/loop2\"," + LS
+ " \"level\" : \"52\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/loop1\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/chain3\"," + LS
+ " \"level\" : \"53\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"," + LS
+ " \"permissionsDesired\" : [ \"sample.chain3\" ]" + LS
+ " } ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationSampleModule = r.getHeader("Location");
final String docSampleDeploy = "{" + LS
+ " \"srvcId\" : \"sample-module\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given().header("Content-Type", "application/json")
.body(docSampleDeploy).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationSampleDeployment = r.getHeader("Location");
final String docEnableSample = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201).body(equalTo(docEnableSample));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testr")
.then().statusCode(200)
.body(containsString("It works"))
.log().ifError();
// Set up, deploy, and enable the header module
final String docHeaderModule = "{" + LS
+ " \"id\" : \"header-module\"," + LS
+ " \"filters\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/red\"," + LS
+ " \"level\" : \"21\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/badredirect\"," + LS
+ " \"level\" : \"22\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/nonexisting\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/simpleloop\"," + LS
+ " \"level\" : \"23\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/simpleloop\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/loop1\"," + LS
+ " \"level\" : \"24\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/loop2\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/chain1\"," + LS
+ " \"level\" : \"25\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/chain2\"," + LS
+ " \"permissionsDesired\" : [ \"hdr.chain1\" ]" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/chain2\"," + LS
+ " \"level\" : \"26\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/chain3\"," + LS
+ " \"permissionsDesired\" : [ \"hdr.chain2\" ]" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/multiple\"," + LS
+ " \"level\" : \"27\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/multiple\"," + LS
+ " \"level\" : \"28\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"" + LS
+ " } ]," + LS
+ " \"modulePermissions\" : [ \"hdr.modperm\" ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-header-module/target/okapi-test-header-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docHeaderModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationHeaderModule = r.getHeader("Location");
final String docHeaderDeploy = "{" + LS
+ " \"srvcId\" : \"header-module\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given().header("Content-Type", "application/json")
.body(docHeaderDeploy).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationHeaderDeployment = r.getHeader("Location");
final String docEnableHeader = "{" + LS
+ " \"id\" : \"header-module\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableHeader).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201).body(equalTo(docEnableHeader));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testb")
.then().statusCode(200)
.body(containsString("It works"))
.log().ifError();
// Actual redirecting request
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/red")
.then().statusCode(200)
.body(containsString("It works"))
.header("X-Okapi-Trace", containsString("GET sample-module http://localhost:9131/testr"))
.log().ifError();
// Bad redirect
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/badredirect")
.then().statusCode(500)
.body(containsString("No suitable module found"))
.log().ifError();
// catch redirect loops
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/simpleloop")
.then().statusCode(500)
.body(containsString("loop:"))
.log().ifError();
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/loop1")
.then().statusCode(500)
.body(containsString("loop:"))
.log().ifError();
// redirect to multiple modules
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("Content-Type", "application/json")
.body("{}")
.post("/multiple")
.then().statusCode(200)
.body(containsString("Hello Hello")) // test-module run twice
.log().ifError();
// Redirect with parameters
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/red?foo=bar")
.then().statusCode(200)
.body(containsString("It works"))
.log().ifError();
// A longer chain of redirects
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-all-headers", "B")
.get("/chain1")
.then().statusCode(200)
.body(containsString("It works"))
.body(containsString("X-Okapi-Permissions-Desired:hdr.chain1,hdr.chain2,sample.testr,sample.chain3"))
.body(containsString("X-Okapi-Extra-Permissions:[\"hdr.modperm\",\"sample.modperm\"]"))
.log().ifError();
// What happens on prefix match
// /red matches, replaces with /testr, getting /testrlight which is not found
// This is odd, and subotimal, but not a serious failure. okapi-253
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/redlight")
.then().statusCode(404)
.header("X-Okapi-Trace", containsString("sample-module http://localhost:9131/testrlight : 404"))
.log().ifError();
// Verify that we replace only the beginning of the path
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/red/blue/red?color=/red")
.then().statusCode(404)
.log().ifError();
// Clean up
logger.info("Redirect test done. Cleaning up");
given().delete(locationTenantRoskilde)
.then().statusCode(204);
given().delete(locationSampleModule)
.then().statusCode(204);
given().delete(locationSampleDeployment)
.then().statusCode(204);
locationSampleDeployment = null;
given().delete(locationHeaderModule)
.then().statusCode(204);
given().delete(locationHeaderDeployment)
.then().statusCode(204);
locationHeaderDeployment = null;
checkDbIsEmpty("testRedirect done", context);
async.complete();
}
}
| okapi-core/src/test/java/okapi/ModuleTest.java | package okapi;
import org.folio.okapi.MainVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.json.JsonObject;
import io.vertx.core.logging.Logger;
import io.vertx.core.logging.LoggerFactory;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import com.jayway.restassured.RestAssured;
import static com.jayway.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import com.jayway.restassured.response.Response;
import com.jayway.restassured.response.ValidatableResponse;
import guru.nidi.ramltester.RamlDefinition;
import guru.nidi.ramltester.RamlLoaders;
import guru.nidi.ramltester.restassured.RestAssuredClient;
@RunWith(VertxUnitRunner.class)
public class ModuleTest {
private final Logger logger = LoggerFactory.getLogger("okapi");
Vertx vertx;
Async async;
private String locationSampleDeployment;
private String locationHeaderDeployment;
private String locationAuthDeployment = null;
private String okapiToken;
private final String okapiTenant = "roskilde";
private HttpClient httpClient;
private static final String LS = System.lineSeparator();
private final int port = Integer.parseInt(System.getProperty("port", "9130"));
public ModuleTest() {
}
@Before
public void setUp(TestContext context) {
vertx = Vertx.vertx();
JsonObject conf = new JsonObject()
.put("storage", "inmemory");
DeploymentOptions opt = new DeploymentOptions()
.setConfig(conf);
vertx.deployVerticle(MainVerticle.class.getName(),
opt, context.asyncAssertSuccess());
httpClient = vertx.createHttpClient();
RestAssured.port = port;
}
@After
public void tearDown(TestContext context) {
logger.info("Cleaning up after ModuleTest");
async = context.async();
td(context);
}
public void td(TestContext context) {
if (locationAuthDeployment != null) {
httpClient.delete(port, "localhost", locationAuthDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationAuthDeployment = null;
td(context);
});
}).end();
return;
}
if (locationSampleDeployment != null) {
httpClient.delete(port, "localhost", locationSampleDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSampleDeployment = null;
td(context);
});
}).end();
return;
}
if (locationSampleDeployment != null) {
httpClient.delete(port, "localhost", locationSampleDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationSampleDeployment = null;
td(context);
});
}).end();
return;
}
if (locationHeaderDeployment != null) {
httpClient.delete(port, "localhost", locationHeaderDeployment, response -> {
context.assertEquals(204, response.statusCode());
response.endHandler(x -> {
locationHeaderDeployment = null;
td(context);
});
}).end();
return;
}
vertx.close(x -> {
async.complete();
});
}
/**
* Check that the tests have not left anything in the database. Since the
*
* @Tests are run in a nondeterministic order, each ought to clean up after
* itself. This should be called in the beginning and end of each @Test
*
* @param context
*/
private void checkDbIsEmpty(String label, TestContext context) {
logger.debug("Db check '" + label + "'");
// Check that we are not depending on td() to undeploy modules
Assert.assertNull("locationAuthDeployment", locationAuthDeployment);
Assert.assertNull("locationSampleDeployment", locationSampleDeployment);
Assert.assertNull("locationSample5Deployment", locationSampleDeployment);
Assert.assertNull("locationHeaderDeployment", locationHeaderDeployment);
String emptyListDoc = "[ ]";
given().get("/_/deployment/modules").then()
.log().ifError().statusCode(200)
.body(equalTo(emptyListDoc));
given().get("/_/discovery/nodes").then()
.log().ifError().statusCode(200); // we still have a node!
given().get("/_/discovery/modules").then()
.log().ifError().statusCode(200).body(equalTo(emptyListDoc));
given().get("/_/proxy/modules").then()
.log().ifError().statusCode(200).body(equalTo(emptyListDoc));
given().get("/_/proxy/tenants").then()
.log().ifError().statusCode(200).body(equalTo(emptyListDoc));
logger.debug("Db check '" + label + "' OK");
}
/**
* Helper to create a tenant. So it can be done in a one-liner without
* cluttering real tests. Actually testing the tenant stuff should be in its
* own test.
*
* @return the location, for deleting it later
*/
public String createTenant() {
final String docTenant = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"" + okapiTenant + " bibliotek\"" + LS
+ "}";
final String loc = given()
.header("Content-Type", "application/json")
.body(docTenant)
.post("/_/proxy/tenants")
.then()
.statusCode(201)
.log().ifError()
.extract().header("Location");
return loc;
}
/**
* Helper to create a module.
*
* @param md A full ModuleDescriptor
* @return the URL to delete when done
*/
public String createModule(String md) {
final String loc = given()
.header("Content-Type", "application/json")
.body(md)
.post("/_/proxy/modules")
.then()
.statusCode(201)
.log().ifError()
.extract().header("Location");
return loc;
}
/**
* Helper to deploy a module. Assumes that the ModuleDescriptor has a good
* LaunchDescriptor.
*
* @param modId Id of the module to be deployed.
* @return url to delete when done
*/
public String deployModule(String modId) {
final String instId = modId.replace("-module", "") + "-inst";
final String docDeploy = "{" + LS
+ " \"instId\" : \"" + instId + "\"," + LS
+ " \"srvcId\" : \"" + modId + "\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
final String loc = given()
.header("Content-Type", "application/json")
.body(docDeploy)
.post("/_/discovery/modules")
.then()
.statusCode(201)
.log().ifError()
.extract().header("Location");
return loc;
}
/**
* Helper to enable a module for our test tenant.
*
* @param modId The module to enable
* @return the location, so we can delete it later. Can safely be ignored.
*/
public String enableModule(String modId) {
final String docEnable = "{" + LS
+ " \"id\" : \"" + modId + "\"" + LS
+ "}";
final String location = given()
.header("Content-Type", "application/json")
.body(docEnable)
.post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then()
.statusCode(201)
.extract().header("Location");
return location;
}
/**
* Tests that declare one module. Declares a single module in many ways, often
* with errors. In the end the module gets deployed and enabled for a newly
* created tenant, and a request is made to it. Uses the test module, but not
* any auth module, that should be a separate test.
*
* @param context
*/
@Test
public void testOneModule(TestContext context) {
async = context.async();
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
Response r;
checkDbIsEmpty("testOneModule starting", context);
// Get an empty list of modules
c = api.createRestAssured();
c.given()
.get("/_/proxy/modules")
.then()
.statusCode(200)
.body(equalTo("[ ]"));
Assert.assertTrue(c.getLastReport().isEmpty());
// Check that we refuse the request with a trailing slash
given()
.get("/_/proxy/modules/")
.then()
.statusCode(404);
// This is a good ModuleDescriptor. For error tests, some things get
// replaced out.
final String testModJar = "../okapi-test-module/target/okapi-test-module-fat.jar";
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"" + LS
+ " } ]," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsRequired\" : [ \"sample.needed\" ]," + LS
+ " \"permissionsDesired\" : [ \"sample.extra\" ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]" + LS
+ " } ]" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"interfaceType\" : \"system\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"POST\", \"DELETE\" ]," + LS
+ " \"path\" : \"/_/tenant\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"system\"" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"permissionSets\" : [ {" + LS
+ " \"permissionName\" : \"everything\"," + LS
+ " \"displayName\" : \"every possible permission\"," + LS
+ " \"description\" : \"All permissions combined\"," + LS
+ " \"subPermissions\" : [ \"sample.needed\", \"sample.extra\" ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar " + testModJar + "\"" + LS
+ " }" + LS
+ "}";
// First some error checks: Missing id
String docBadId = docSampleModule.replace("sample-module", "bad module id?!");
given()
.header("Content-Type", "application/json")
.body(docBadId)
.post("/_/proxy/modules")
.then()
.statusCode(400);
// Bad interface type
String docBadIntType = docSampleModule.replace("system", "strange interface type");
given()
.header("Content-Type", "application/json")
.body(docBadIntType)
.post("/_/proxy/modules")
.then()
.statusCode(400);
// Bad RoutingEntry type
String docBadReType = docSampleModule.replace("request-response", "strange-re-type");
given()
.header("Content-Type", "application/json")
.body(docBadReType)
.post("/_/proxy/modules")
.then()
.statusCode(400);
String docMissingPath = docSampleModule.replace("/testb", "");
given()
.header("Content-Type", "application/json")
.body(docMissingPath)
.post("/_/proxy/modules")
.then()
.statusCode(400);
String docBadPathPat = docSampleModule.replace("path", "pathPattern")
.replace("/testb", "/test.*b(/?)"); // invalid characters in pattern
given()
.header("Content-Type", "application/json")
.body(docBadPathPat)
.post("/_/proxy/modules")
.then()
.statusCode(400);
// TODO - Tests for bad interface versions
// Actually create the module
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule)
.post("/_/proxy/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locSampleModule = r.getHeader("Location");
// Get the module
c = api.createRestAssured();
c.given()
.get(locSampleModule)
.then().statusCode(200).body(equalTo(docSampleModule));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// List the one module
final String expOneModList = "[ {" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"" + LS
+ "} ]";
c = api.createRestAssured();
c.given()
.get("/_/proxy/modules")
.then()
.statusCode(200)
.body(equalTo(expOneModList));
Assert.assertTrue(c.getLastReport().isEmpty());
// Deploy the module
final String docDeploy = "{" + LS
+ " \"instId\" : \"sample-inst\"," + LS
+ " \"srvcId\" : \"sample-module\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
r = c.given()
.header("Content-Type", "application/json")
.body(docDeploy)
.post("/_/discovery/modules")
.then()
.statusCode(201).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationSampleDeployment = r.header("Location");
// Create a tenant and enable the module
final String locTenant = createTenant();
final String locEnable = enableModule("sample-module");
// Make a simple request to the module
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testb")
.then().statusCode(200)
.body(containsString("It works"));
// Make a more complex request that returns all headers and parameters
// So the headers we check are those that the module sees and reports to
// us, not necessarily those that Okapi would return to us.
// Note that since this is the only module in the pipeline, Okapi assumes
// it is the auth module, and passes it those extra headers. Normally
// the auth module would have handled those, and indicated to Okapi that
// these are no longer needed, and Okapi would not pass them to regular
// modules.
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-all-headers", "H") // ask sample to report all headers
.get("/testb?query=foo&limit=10")
.then().statusCode(200)
.header("X-Okapi-Url", "http://localhost:9130") // no trailing slash!
.header("X-Url-Params", "query=foo&limit=10")
.header("X-Okapi-Permissions-Required", "sample.needed")
.header("X-Okapi-Module-Permissions", "{\"sample-module\":[\"sample.modperm\"]}")
.body(containsString("It works"));
// Check that the tenant API got called (exactly once)
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-tenant-reqs", "yes")
.get("/testb")
.then()
.statusCode(200)
.body(equalTo("It works Tenant requests: POST-roskilde "))
.log().ifError();
// Clean up, so the next test starts with a clean slate (in reverse order)
logger.debug("testOneModule cleaning up");
given().delete(locEnable).then().log().ifError().statusCode(204);
given().delete(locTenant).then().log().ifError().statusCode(204);
given().delete(locSampleModule).then().log().ifError().statusCode(204);
given().delete(locationSampleDeployment).then().log().ifError().statusCode(204);
locationSampleDeployment = null;
checkDbIsEmpty("testOneModule done", context);
async.complete();
}
/**
* Test system interfaces. Mostly about the system interfaces _tenant (on the
* module itself, to initialize stuff), and _tenantPermissions to pass its
* permissions to the permissions module.
*
* @param context
*/
@Test
public void testSystemInterfaces(TestContext context) {
async = context.async();
checkDbIsEmpty("testSystemInterfaces starting", context);
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
Response r;
// Set up a tenant to test with
final String locTenant = createTenant();
// Set up a module that does the _tenantPermissions interface that will
// get called when sample gets enabled. We (ab)use the header module for
// this.
final String testHdrJar = "../okapi-test-header-module/target/okapi-test-header-module-fat.jar";
final String docHdrModule = "{" + LS
+ " \"id\" : \"header\"," + LS
+ " \"name\" : \"header-module\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"_tenantPermissions\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"interfaceType\" : \"system\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/_/tenantPermissions\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar " + testHdrJar + "\"" + LS
+ " }" + LS
+ "}";
// Create, deploy, and enable the header module
final String locHdrModule = createModule(docHdrModule);
locationHeaderDeployment = deployModule("header");
final String locHdrEnable = enableModule("header");
// Set up the test module
// It provides a _tenant interface, but no _tenantPermissions
// Enabling it will end up invoking the _tenantPermissions in header
final String testModJar = "../okapi-test-module/target/okapi-test-module-fat.jar";
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"" + LS
+ " } ]," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsRequired\" : [ \"sample.needed\" ]," + LS
+ " \"permissionsDesired\" : [ \"sample.extra\" ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]" + LS
+ " } ]" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"," + LS
+ " \"interfaceType\" : \"system\"," + LS
+ " \"handlers\" : [ {" + LS
+ " \"methods\" : [ \"POST\", \"DELETE\" ]," + LS
+ " \"path\" : \"/_/tenant\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"system\"" + LS
+ " } ]" + LS
+ " } ]," + LS
+ " \"permissionSets\" : [ {" + LS
+ " \"permissionName\" : \"everything\"," + LS
+ " \"displayName\" : \"every possible permission\"," + LS
+ " \"description\" : \"All permissions combined\"," + LS
+ " \"subPermissions\" : [ \"sample.needed\", \"sample.extra\" ]" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar " + testModJar + "\"" + LS
+ " }" + LS
+ "}";
// Create and deploy the sample module
final String locSampleModule = createModule(docSampleModule);
locationSampleDeployment = deployModule("sample-module");
// Enable the sample module. Verify that the _tenantPermissions gets
// invoked.
final String docEnable = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
final String expPerms = "{ "
+ "\"moduleId\" : \"sample-module\", "
+ "\"perms\" : [ { "
+ "\"permissionName\" : \"everything\", "
+ "\"displayName\" : \"every possible permission\", "
+ "\"description\" : \"All permissions combined\", "
+ "\"subPermissions\" : [ \"sample.needed\", \"sample.extra\" ] "
+ "} ] }";
final String locSampleEnable = given()
.header("Content-Type", "application/json")
.body(docEnable)
.post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then()
.statusCode(201)
.log().ifError()
.header("X-Tenant-Perms-Result", expPerms)
.extract().header("Location");
// Clean up, so the next test starts with a clean slate (in reverse order)
logger.debug("testSystemInterfaces cleaning up");
given().delete(locSampleEnable).then().log().ifError().statusCode(204);
given().delete(locationSampleDeployment).then().log().ifError().statusCode(204);
given().delete(locSampleModule).then().log().ifError().statusCode(204);
locationSampleDeployment = null;
given().delete(locHdrEnable).then().log().ifError().statusCode(204);
given().delete(locationHeaderDeployment).then().log().ifError().statusCode(204);
locationHeaderDeployment = null;
given().delete(locHdrModule).then().log().ifError().statusCode(204);
given().delete(locTenant).then().log().ifError().statusCode(204);
checkDbIsEmpty("testSystemInterfaces done", context);
async.complete();
}
// TODO - This function is way too long and confusing
// Create smaller functions that test one thing at a time
// Later, move them into separate files
@Test
public void testProxy(TestContext context) {
async = context.async();
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
Response r;
String nodeListDoc = "[ {" + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"url\" : \"http://localhost:9130\"" + LS
+ "} ]";
c = api.createRestAssured();
c.given().get("/_/discovery/nodes").then().statusCode(200)
.body(equalTo(nodeListDoc));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/nodes/gyf").then().statusCode(404);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/nodes/localhost").then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body("{ }").post("/_/xyz").then().statusCode(404);
Assert.assertEquals("RamlReport{requestViolations=[Resource '/_/xyz' is not defined], "
+ "responseViolations=[], validationViolations=[]}",
c.getLastReport().toString());
final String badDoc = "{" + LS
+ " \"instId\" : \"BAD\"," + LS // the comma here makes it bad json!
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(badDoc).post("/_/deployment/modules")
.then().statusCode(400);
final String docUnknownJar = "{" + LS
+ " \"srvcId\" : \"auth\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-auth-module/target/okapi-unknown.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docUnknownJar).post("/_/deployment/modules")
.then()
.statusCode(500);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docAuthDeployment = "{" + LS
+ " \"srvcId\" : \"auth\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-auth-module/target/okapi-test-auth-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docAuthDeployment).post("/_/deployment/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationAuthDeployment = r.getHeader("Location");
c = api.createRestAssured();
String docAuthDiscovery = c.given().get(locationAuthDeployment)
.then().statusCode(200).extract().body().asString();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docAuthModule = "{" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"name\" : \"auth\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"*\" ]," + LS
+ " \"path\" : \"/\"," + LS // has to be plain '/' for the filter detection
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsDesired\" : [ \"auth.extra\" ]" + LS
+ " }, {"
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/login\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
// Check that we fail on unknown route types
final String docBadTypeModule
= docAuthModule.replaceAll("request-response", "UNKNOWN-ROUTE-TYPE");
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docBadTypeModule).post("/_/proxy/modules")
.then().statusCode(400);
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docAuthModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationAuthModule = r.getHeader("Location");
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docAuthModule).put(locationAuthModule).then().statusCode(200)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docAuthModule2 = "{" + LS
+ " \"id\" : \"auth2\"," + LS
+ " \"name\" : \"auth2\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"auth2\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"*\" ]," + LS
+ " \"path\" : \"/\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsDesired\" : [ \"auth.extra\" ]" + LS
+ " }, {"
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/login\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
final String locationAuthModule2 = locationAuthModule + "2";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docAuthModule2).put(locationAuthModule2).then().statusCode(200)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().delete(locationAuthModule2).then().statusCode(204);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docSampleDeployment = "{" + LS
+ " \"srvcId\" : \"sample-module\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"," + LS
+ " \"value\" : \"hej\"" + LS
+ " } ]" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleDeployment).post("/_/deployment/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationSampleDeployment = r.getHeader("Location");
c = api.createRestAssured();
String docSampleDiscovery = c.given().get(locationSampleDeployment)
.then().statusCode(200).extract().body().asString();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String docSampleModuleBadRequire = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"requires\" : [ {" + LS
+ " \"id\" : \"SOMETHINGWEDONOTHAVE\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ ] " + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docSampleModuleBadRequire).post("/_/proxy/modules").then().statusCode(400)
.extract().response();
final String docSampleModuleBadVersion = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"requires\" : [ {" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"version\" : \"9.9.3\"" + LS // We only have 1.2.3
+ " } ]," + LS
+ " \"routingEntries\" : [ ] " + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docSampleModuleBadVersion).post("/_/proxy/modules").then().statusCode(400)
.extract().response();
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"name\" : \"sample module\"," + LS
+ " \"env\" : [ {" + LS
+ " \"name\" : \"helloGreeting\"" + LS
+ " } ]," + LS
+ " \"requires\" : [ {" + LS
+ " \"id\" : \"auth\"," + LS
+ " \"version\" : \"1.2.3\"" + LS
+ " } ]," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS // TODO - Define paths - add test
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsRequired\" : [ \"sample.needed\" ]," + LS
+ " \"permissionsDesired\" : [ \"sample.extra\" ]" + LS
+ " } ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"/usr/bin/false\"" + LS
+ " }" + LS
+ "}";
logger.debug(docSampleModule);
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules")
.then()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSampleModule = r.getHeader("Location");
// Commented-out tests have been moved to testOneModule, no need to repeat here
// TODO - Remove these when refactoring complete
//c = api.createRestAssured(); // trailing slash is no good
//c.given().get("/_/proxy/modules/").then().statusCode(404);
//c = api.createRestAssured();
//c.given().get("/_/proxy/modules").then().statusCode(200);
//Assert.assertTrue(c.getLastReport().isEmpty());
//c = api.createRestAssured();
//c.given()
// .get(locationSampleModule)
// .then().statusCode(200).body(equalTo(docSampleModule));
//Assert.assertTrue("raml: " + c.getLastReport().toString(),
// c.getLastReport().isEmpty());
// Try to delete the auth module that our sample depends on
c.given().delete(locationAuthModule).then().statusCode(400);
// Try to update the auth module to a lower version, would break
// sample dependency
final String docAuthLowerVersion = docAuthModule.replace("1.2.3", "1.1.1");
c.given()
.header("Content-Type", "application/json")
.body(docAuthLowerVersion)
.put(locationAuthModule)
.then().statusCode(400);
// Update the auth module to a bit higher version
final String docAuthhigherVersion = docAuthModule.replace("1.2.3", "1.2.4");
c.given()
.header("Content-Type", "application/json")
.body(docAuthhigherVersion)
.put(locationAuthModule)
.then().statusCode(200);
// Create our tenant
final String docTenantRoskilde = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants/") // trailing slash fails
.then().statusCode(404);
Assert.assertEquals("RamlReport{requestViolations=[Resource '/_/proxy/tenants/' is not defined], "
+ "responseViolations=[], validationViolations=[]}",
c.getLastReport().toString());
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants")
.then().statusCode(201)
.body(equalTo(docTenantRoskilde))
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationTenantRoskilde = r.getHeader("Location");
// Try to enable sample without the auth that it requires
final String docEnableWithoutDep = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
c.given()
.header("Content-Type", "application/json")
.body(docEnableWithoutDep).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(400);
// try to enable a module we don't know
final String docEnableAuthBad = "{" + LS
+ " \"id\" : \"UnknonwModule\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableAuthBad).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(400);
final String docEnableAuth = "{" + LS
+ " \"id\" : \"auth\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableAuth).post("/_/proxy/tenants/" + okapiTenant + "/modules/")
.then().statusCode(404); // trailing slash is no good
// Actually enable the auith
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableAuth).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201).body(equalTo(docEnableAuth));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules/")
.then().statusCode(404); // trailing slash again
// Get the list of one enabled module
c = api.createRestAssured();
final String exp1 = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "} ]";
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200).body(equalTo(exp1));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// get the auth enabled record
final String expAuthEnabled = "{" + LS
+ " \"id\" : \"auth\"" + LS
+ "}";
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules/auth")
.then().statusCode(200).body(equalTo(expAuthEnabled));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Enablæe the sample
final String docEnableSample = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Try to enable it again, should fail
given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(400)
.body(containsString("already provided"));
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules/")
.then().statusCode(404); // trailing slash
c = api.createRestAssured();
final String expEnabledBoth = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "} ]";
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200).body(equalTo(expEnabledBoth));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Try to disable the auth module for the tenant.
// Ought to fail, because it is needed by sample module
c.given().delete("/_/proxy/tenants/" + okapiTenant + "/modules/auth")
.then().statusCode(400);
// Update the tenant
String docTenant = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"Roskilde-library\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docTenant).put("/_/proxy/tenants/" + okapiTenant)
.then().statusCode(200)
.body(equalTo(docTenant));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Check that both modules are still enabled
c = api.createRestAssured();
c.given().get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200).body(equalTo(expEnabledBoth));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Request without any X-Okapi headers
given()
.get("/testb")
.then().statusCode(403);
// Request with a header, to unknown path
// (note, should fail without invoking the auth module)
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/something.we.do.not.have")
.then().statusCode(404);
// Request without an auth token
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testb")
.then()
.statusCode(401);
// Failed login
final String docWrongLogin = "{" + LS
+ " \"tenant\" : \"t1\"," + LS
+ " \"username\" : \"peter\"," + LS
+ " \"password\" : \"peter-wrong-password\"" + LS
+ "}";
given().header("Content-Type", "application/json").body(docWrongLogin)
.header("X-Okapi-Tenant", okapiTenant).post("/login")
.then().statusCode(401);
// Ok login, get token
final String docLogin = "{" + LS
+ " \"tenant\" : \"" + okapiTenant + "\"," + LS
+ " \"username\" : \"peter\"," + LS
+ " \"password\" : \"peter-password\"" + LS
+ "}";
okapiToken = given().header("Content-Type", "application/json").body(docLogin)
.header("X-Okapi-Tenant", okapiTenant).post("/login")
.then().statusCode(200).extract().header("X-Okapi-Token");
// Actual requests to the module
// Check that okapi sets up the permission headers.
// Check also the X-Okapi-Url header in the same go, as well as
// URL parameters.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-all-headers", "HB") // ask sample to report all headers
.get("/testb?query=foo&limit=10")
.then().statusCode(200)
.header("X-Okapi-Permissions-Required", "sample.needed")
.header("X-Okapi-Module-Permissions", "{\"sample-module\":[\"sample.modperm\"]}")
.header("X-Okapi-Url", "http://localhost:9130") // no trailing slash!
.header("X-Url-Params", "query=foo&limit=10")
.body(containsString("It works"));
// Check only the required permission bit, since there is only one.
// There are wanted bits too, two of them, but their order is not
// well defined.
// Check the CORS headers.
// The presence of the Origin header should provoke the two extra headers.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Origin", "http://foobar.com")
.get("/testb")
.then().statusCode(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Expose-Headers", "Location,X-Okapi-Trace,X-Okapi-Token,Authorization")
.body(equalTo("It works"));
// Post request.
// Test also URL parameters.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Content-Type", "text/xml")
.header("X-all-headers", "H") // ask sample to report all headers
.body("Okapi").post("/testb?query=foo")
.then().statusCode(200)
.header("X-Url-Params", "query=foo")
.body(equalTo("hej (XML) Okapi"));
// Verify that the path matching is case sensitive
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/TESTB")
.then().statusCode(404);
// See that a delete fails - we only match auth, which is a filter
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.delete("/testb")
.then().statusCode(404);
// Check that we don't do prefix matching
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/testbXXX")
.then().statusCode(404);
// Check that parameters don't mess with the routing
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/testb?p=parameters&q=query")
.then().statusCode(200);
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-tenant-reqs", "yes")
.get("/testb")
.then()
.statusCode(200) // No longer expects a DELETE. See Okapi-252
.body(equalTo("It works Tenant requests: POST-roskilde POST-roskilde POST-roskilde "))
.log().ifError();
// Check that we refuse unknown paths, even with auth module
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/something.we.do.not.have")
.then().statusCode(404);
// Check that we accept Authorization: Bearer <token> instead of X-Okapi-Token,
// and that we can extract the tenant from it.
given()
.header("X-all-headers", "H") // ask sample to report all headers
.header("Authorization", "Bearer " + okapiToken)
.get("/testb")
.then().log().ifError()
.header("X-Okapi-Tenant", okapiTenant)
.statusCode(200);
// Note that we can not check the token, the module sees a different token,
// created by the auth module, when it saw a ModulePermission for the sample
// module. This is all right, since we explicitly ask sample to pass its
// request headers into its response. See Okapi-266.
// Check that we fail on conflicting X-Okapi-Token and Auth tokens
given().header("X-all-headers", "H") // ask sample to report all headers
.header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Authorization", "Bearer " + okapiToken + "WRONG")
.get("/testb")
.then().log().ifError()
.statusCode(400);
// 2nd sample module. We only create it in discovery and give it same URL as
// for sample-module (first one). Then we delete it again.
c = api.createRestAssured();
final String docSample2Deployment = "{" + LS
+ " \"instId\" : \"sample2-inst\"," + LS
+ " \"srvcId\" : \"sample-module2\"," + LS
// + " \"nodeId\" : null," + LS // no nodeId, we aren't deploying on any node
+ " \"url\" : \"http://localhost:9132\"" + LS
+ "}";
r = c.given()
.header("Content-Type", "application/json")
.body(docSample2Deployment).post("/_/discovery/modules")
.then()
.statusCode(201).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample2Discovery = r.header("Location");
// Get the sample-2
c = api.createRestAssured();
c.given().get("/_/discovery/modules/sample-module2")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// and its instance
c = api.createRestAssured();
c.given().get("/_/discovery/modules/sample-module2/sample2-inst")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// health check
c = api.createRestAssured();
c.given().get("/_/discovery/health")
.then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// health for sample2
c = api.createRestAssured();
c.given().get("/_/discovery/health/sample-module2")
.then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// health for an instance
c = api.createRestAssured();
c.given().get("/_/discovery/health/sample-module2/sample2-inst")
.then().statusCode(200);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Declare sample2
final String docSample2Module = "{" + LS
+ " \"id\" : \"sample-module2\"," + LS
+ " \"name\" : \"another-sample-module2\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"31\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]," + LS
+ " \"tenantInterface\" : \"/tenant\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSample2Module).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample2Module = r.getHeader("Location");
// enable sample2
final String docEnableSample2 = "{" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample2).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample2));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// disable it, and re-enable.
// Later we will check that we got the right calls in its
// tenant interface.
given()
.delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module2")
.then().statusCode(204);
given()
.header("Content-Type", "application/json")
.body(docEnableSample2).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample2));
// 3rd sample module. We only create it in discovery and give it same URL as
// for sample-module (first one), just like sample2 above.
c = api.createRestAssured();
final String docSample3Deployment = "{" + LS
+ " \"instId\" : \"sample3-instance\"," + LS
+ " \"srvcId\" : \"sample-module3\"," + LS
+ " \"url\" : \"http://localhost:9132\"" + LS
+ "}";
r = c.given()
.header("Content-Type", "application/json")
.body(docSample3Deployment).post("/_/discovery/modules")
.then()
.statusCode(201).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample3Inst = r.getHeader("Location");
logger.debug("Deployed: locationSample3Inst " + locationSample3Inst);
final String docSample3Module = "{" + LS
+ " \"id\" : \"sample-module3\"," + LS
+ " \"name\" : \"sample-module3\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"05\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"45\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"33\"," + LS
+ " \"type\" : \"request-only\"" + LS
+ " } ]" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSample3Module).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSample3Module = r.getHeader("Location");
final String docEnableSample3 = "{" + LS
+ " \"id\" : \"sample-module3\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample3).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.header("Location", equalTo("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module3"))
.log().ifError()
.body(equalTo(docEnableSample3));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given()
.get("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(200)
.log().all();
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.get("/testb")
.then().statusCode(200).body(equalTo("It works"));
// Verify that both modules get executed
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.body("OkapiX").post("/testb")
.then().statusCode(200)
.body(equalTo("hej hej OkapiX"));
// Verify that we have seen tenant requests to POST and DELETE
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-tenant-reqs", "yes")
.get("/testb")
.then()
.statusCode(200) // No longer expects a DELETE. See Okapi-252
.body(containsString("POST-roskilde POST-roskilde"))
.log().ifError();
// Check that the X-Okapi-Stop trick works. Sample will set it if it sees
// a X-Stop-Here header.
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("X-Stop-Here", "Enough!")
.body("OkapiX").post("/testb")
.then().statusCode(200)
.header("X-Okapi-Stop", "Enough!")
.body(equalTo("hej OkapiX")); // only one "Hello"
given().get("/_/test/reloadmodules")
.then().statusCode(204);
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Content-Type", "text/xml")
.get("/testb")
.then().statusCode(200).body(equalTo("It works (XML) "));
c = api.createRestAssured();
final String exp4Modules = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module3\"" + LS
+ "} ]";
c.given().get(locationTenantRoskilde + "/modules")
.then().statusCode(200)
.body(equalTo(exp4Modules));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().delete(locationTenantRoskilde + "/modules/sample-module3")
.then().statusCode(204);
Assert.assertTrue(c.getLastReport().isEmpty());
c = api.createRestAssured();
final String exp3Modules = "[ {" + LS
+ " \"id\" : \"auth\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}, {" + LS
+ " \"id\" : \"sample-module2\"" + LS
+ "} ]";
c.given().get(locationTenantRoskilde + "/modules")
.then().statusCode(200)
.body(equalTo(exp3Modules));
Assert.assertTrue(c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/modules")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// make sample 2 disappear from discovery!
c = api.createRestAssured();
c.given().delete(locationSample2Discovery)
.then().statusCode(204);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
c = api.createRestAssured();
c.given().get("/_/discovery/modules")
.then().statusCode(200)
.log().ifError();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given().header("X-Okapi-Tenant", okapiTenant)
.header("X-Okapi-Token", okapiToken)
.header("Content-Type", "text/xml")
.get("/testb")
.then().statusCode(404); // because sample2 was removed
// Disable the sample module. No tenant-destroy for sample
given()
.delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module")
.then().statusCode(204);
// Disable the sample2 module. It has a tenant request handler which is
// no longer invoked, so it does not matter we don't have a running instance
given()
.delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module2")
.then().statusCode(204);
c = api.createRestAssured();
c.given().delete(locationTenantRoskilde)
.then().statusCode(204);
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
// Clean up, so the next test starts with a clean slate
logger.debug("testproxy cleaning up");
given().delete(locationSample3Inst).then().log().ifError().statusCode(204);
given().delete(locationSample3Module).then().log().ifError().statusCode(204);
given().delete("/_/proxy/modules/sample-module").then().log().ifError().statusCode(204);
given().delete("/_/proxy/modules/sample-module2").then().log().ifError().statusCode(204);
given().delete("/_/proxy/modules/auth").then().log().ifError().statusCode(204);
given().delete(locationAuthDeployment).then().log().ifError().statusCode(204);
locationAuthDeployment = null;
given().delete(locationSampleDeployment).then().log().ifError().statusCode(204);
locationSampleDeployment = null;
checkDbIsEmpty("testproxy done", context);
async.complete();
}
@Test
public void testDeployment(TestContext context) {
async = context.async();
Response r;
given().get("/_/deployment/modules")
.then().statusCode(200)
.body(equalTo("[ ]"));
given().get("/_/deployment/modules/not_found")
.then().statusCode(404);
given().get("/_/discovery/modules")
.then().statusCode(200)
.body(equalTo("[ ]"));
given().get("/_/discovery/modules/not_found")
.then().statusCode(404);
final String doc1 = "{" + LS
+ " \"srvcId\" : \"sample-module5\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
given().header("Content-Type", "application/json")
.body(doc1).post("/_/discovery/modules/") // extra slash !
.then().statusCode(404);
final String doc2 = "{" + LS
+ " \"instId\" : \"localhost-9131\"," + LS
+ " \"srvcId\" : \"sample-module5\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"url\" : \"http://localhost:9131\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(doc1).post("/_/discovery/modules")
.then().statusCode(201)
.body(equalTo(doc2))
.extract().response();
locationSampleDeployment = r.getHeader("Location");
given().get(locationSampleDeployment).then().statusCode(200)
.body(equalTo(doc2));
given().get("/_/deployment/modules")
.then().statusCode(200)
.body(equalTo("[ " + doc2 + " ]"));
given().header("Content-Type", "application/json")
.body(doc2).post("/_/discovery/modules")
.then().statusCode(400);
given().get("/_/discovery/modules/sample-module5")
.then().statusCode(200)
.body(equalTo("[ " + doc2 + " ]"));
given().get("/_/discovery/modules")
.then().statusCode(200)
.log().ifError()
.body(equalTo("[ " + doc2 + " ]"));
System.out.println("delete: " + locationSampleDeployment);
given().delete(locationSampleDeployment).then().statusCode(204);
locationSampleDeployment = null;
// Verify that the list works also after delete
given().get("/_/deployment/modules")
.then().statusCode(200)
.body(equalTo("[ ]"));
// verify that module5 is no longer there
given().get("/_/discovery/modules/sample-module5")
.then().statusCode(404);
// verify that a never-seen module returns the same
given().get("/_/discovery/modules/UNKNOWN-MODULE")
.then().statusCode(404);
// Deploy a module via its own LaunchDescriptor
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module-depl\"," + LS
+ " \"name\" : \"sample module for deployment test\"," + LS
+ " \"provides\" : [ {" + LS
+ " \"id\" : \"sample\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " }, {" + LS
+ " \"id\" : \"_tenant\"," + LS
+ " \"version\" : \"1.0.0\"" + LS
+ " } ]," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"30\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
RestAssuredClient c;
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules")
.then()
//.log().all()
.statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationSampleModule = r.getHeader("Location");
final String docDeploy = "{" + LS
+ " \"srvcId\" : \"sample-module-depl\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
final String DeployResp = "{" + LS
+ " \"instId\" : \"localhost-9131\"," + LS
+ " \"srvcId\" : \"sample-module-depl\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"url\" : \"http://localhost:9131\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(docDeploy).post("/_/discovery/modules")
.then().statusCode(201)
.body(equalTo(DeployResp))
.extract().response();
locationSampleDeployment = r.getHeader("Location");
// Would be nice to verify that the module works, but too much hassle with
// tenants etc.
// Undeploy.
given().delete(locationSampleDeployment).then().statusCode(204);
// Undeploy again, to see it is gone
given().delete(locationSampleDeployment).then().statusCode(404);
locationSampleDeployment = null;
// and delete from the proxy
given().delete(locationSampleModule)
.then().statusCode(204);
checkDbIsEmpty("testDeployment done", context);
async.complete();
}
@Test
public void testHeader(TestContext context) {
async = context.async();
Response r;
ValidatableResponse then;
final String docLaunch1 = "{" + LS
+ " \"srvcId\" : \"sample-module5\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(docLaunch1).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
locationSampleDeployment = r.getHeader("Location");
final String docLaunch2 = "{" + LS
+ " \"srvcId\" : \"header-module\"," + LS
+ " \"nodeId\" : \"localhost\"," + LS
+ " \"descriptor\" : {" + LS
+ " \"exec\" : "
+ "\"java -Dport=%p -jar ../okapi-test-header-module/target/okapi-test-header-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
r = given().header("Content-Type", "application/json")
.body(docLaunch2).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
locationHeaderDeployment = r.getHeader("Location");
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module5\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
r = given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationSampleModule = r.getHeader("Location");
final String docHeaderModule = "{" + LS
+ " \"id\" : \"header-module\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"10\"," + LS
+ " \"type\" : \"headers\"" + LS
+ " } ]" + LS
+ "}";
r = given()
.header("Content-Type", "application/json")
.body(docHeaderModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationHeaderModule = r.getHeader("Location");
final String docTenantRoskilde = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
r = given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants")
.then().statusCode(201)
.body(equalTo(docTenantRoskilde))
.extract().response();
final String locationTenantRoskilde = r.getHeader("Location");
final String docEnableSample = "{" + LS
+ " \"id\" : \"sample-module5\"" + LS
+ "}";
given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample));
final String docEnableHeader = "{" + LS
+ " \"id\" : \"header-module\"" + LS
+ "}";
given()
.header("Content-Type", "application/json")
.body(docEnableHeader).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableHeader));
given().header("X-Okapi-Tenant", okapiTenant)
.body("bar").post("/testb")
.then().statusCode(200).body(equalTo("Hello foobar"))
.extract().response();
given().delete("/_/proxy/tenants/" + okapiTenant + "/modules/sample-module5")
.then().statusCode(204);
given().delete(locationSampleModule)
.then().statusCode(204);
final String docSampleModule2 = "{" + LS
+ " \"id\" : \"sample-module5\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"5\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " } ]" + LS
+ "}";
given()
.header("Content-Type", "application/json")
.body(docSampleModule2).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationSampleModule2 = r.getHeader("Location");
given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201)
.body(equalTo(docEnableSample));
given().header("X-Okapi-Tenant", okapiTenant)
.body("bar").post("/testb")
.then().statusCode(200).body(equalTo("Hello foobar"))
.extract().response();
logger.debug("testHeader cleaning up");
given().delete(locationTenantRoskilde)
.then().statusCode(204);
given().delete(locationSampleModule)
.then().statusCode(204);
given().delete(locationSampleDeployment).then().statusCode(204);
locationSampleDeployment = null;
given().delete(locationHeaderDeployment)
.then().statusCode(204);
locationHeaderDeployment = null;
given().delete(locationHeaderModule)
.then().statusCode(204);
checkDbIsEmpty("testHeader done", context);
async.complete();
}
@Test
public void testUiModule(TestContext context) {
async = context.async();
Response r;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml").load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
final String docUiModuleInput = "{" + LS
+ " \"id\" : \"11-22-11-22-11\"," + LS
+ " \"name\" : \"sample-ui\"," + LS
+ " \"routingEntries\" : [ ]," + LS
+ " \"uiDescriptor\" : {" + LS
+ " \"npm\" : \"name-of-module-in-npm\"" + LS
+ " }" + LS
+ "}";
final String docUiModuleOutput = "{" + LS
+ " \"id\" : \"11-22-11-22-11\"," + LS
+ " \"name\" : \"sample-ui\"," + LS
+ " \"routingEntries\" : [ ]," + LS
+ " \"uiDescriptor\" : {" + LS
+ " \"npm\" : \"name-of-module-in-npm\"" + LS
+ " }" + LS
+ "}";
RestAssuredClient c;
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docUiModuleInput).post("/_/proxy/modules").then().statusCode(201)
.body(equalTo(docUiModuleOutput)).extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
String location = r.getHeader("Location");
c = api.createRestAssured();
c.given()
.get(location)
.then().statusCode(200).body(equalTo(docUiModuleOutput));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given().delete(location)
.then().statusCode(204);
checkDbIsEmpty("testUiModule done", context);
async.complete();
}
/*
* Test redirect types. Sets up two modules, our sample, and the header test
* module.
*
* Both modules support the /testb path.
* Test also supports /testr path.
* Header will redirect /red path to /testr, which will end up in the test module.
* Header will also attempt to support /loop, /loop1, and /loop2 for testing
* looping redirects. These are expected to fail.
*
*/
@Test
public void testRedirect(TestContext context) {
logger.info("Redirect test starting");
async = context.async();
RestAssuredClient c;
Response r;
RamlDefinition api = RamlLoaders.fromFile("src/main/raml")
.load("okapi.raml")
.assumingBaseUri("https://okapi.cloud");
// Set up a tenant to test with
final String docTenantRoskilde = "{" + LS
+ " \"id\" : \"" + okapiTenant + "\"," + LS
+ " \"name\" : \"" + okapiTenant + "\"," + LS
+ " \"description\" : \"Roskilde bibliotek\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docTenantRoskilde).post("/_/proxy/tenants")
.then().statusCode(201)
.log().ifError()
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
final String locationTenantRoskilde = r.getHeader("Location");
// Set up, deploy, and enable a sample module
final String docSampleModule = "{" + LS
+ " \"id\" : \"sample-module\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"50\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testr\"," + LS
+ " \"level\" : \"59\"," + LS
+ " \"type\" : \"request-response\"," + LS
+ " \"permissionsDesired\" : [ \"sample.testr\" ]" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/loop2\"," + LS
+ " \"level\" : \"52\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/loop1\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/chain3\"," + LS
+ " \"level\" : \"53\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"," + LS
+ " \"permissionsDesired\" : [ \"sample.chain3\" ]" + LS
+ " } ]," + LS
+ " \"modulePermissions\" : [ \"sample.modperm\" ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-module/target/okapi-test-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docSampleModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationSampleModule = r.getHeader("Location");
final String docSampleDeploy = "{" + LS
+ " \"srvcId\" : \"sample-module\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given().header("Content-Type", "application/json")
.body(docSampleDeploy).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationSampleDeployment = r.getHeader("Location");
final String docEnableSample = "{" + LS
+ " \"id\" : \"sample-module\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableSample).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201).body(equalTo(docEnableSample));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testr")
.then().statusCode(200)
.body(containsString("It works"))
.log().ifError();
// Set up, deploy, and enable the header module
final String docHeaderModule = "{" + LS
+ " \"id\" : \"header-module\"," + LS
+ " \"routingEntries\" : [ {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/testb\"," + LS
+ " \"level\" : \"20\"," + LS
+ " \"type\" : \"request-response\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\", \"POST\" ]," + LS
+ " \"path\" : \"/red\"," + LS
+ " \"level\" : \"21\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/badredirect\"," + LS
+ " \"level\" : \"22\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/nonexisting\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/simpleloop\"," + LS
+ " \"level\" : \"23\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/simpleloop\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/loop1\"," + LS
+ " \"level\" : \"24\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/loop2\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/chain1\"," + LS
+ " \"level\" : \"25\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/chain2\"," + LS
+ " \"permissionsDesired\" : [ \"hdr.chain1\" ]" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"GET\" ]," + LS
+ " \"path\" : \"/chain2\"," + LS
+ " \"level\" : \"26\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/chain3\"," + LS
+ " \"permissionsDesired\" : [ \"hdr.chain2\" ]" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/multiple\"," + LS
+ " \"level\" : \"27\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"" + LS
+ " }, {" + LS
+ " \"methods\" : [ \"POST\" ]," + LS
+ " \"path\" : \"/multiple\"," + LS
+ " \"level\" : \"28\"," + LS
+ " \"type\" : \"redirect\"," + LS
+ " \"redirectPath\" : \"/testr\"" + LS
+ " } ]," + LS
+ " \"modulePermissions\" : [ \"hdr.modperm\" ]," + LS
+ " \"launchDescriptor\" : {" + LS
+ " \"exec\" : \"java -Dport=%p -jar ../okapi-test-header-module/target/okapi-test-header-module-fat.jar\"" + LS
+ " }" + LS
+ "}";
c = api.createRestAssured();
r = c.given()
.header("Content-Type", "application/json")
.body(docHeaderModule).post("/_/proxy/modules").then().statusCode(201)
.extract().response();
final String locationHeaderModule = r.getHeader("Location");
final String docHeaderDeploy = "{" + LS
+ " \"srvcId\" : \"header-module\"," + LS
+ " \"nodeId\" : \"localhost\"" + LS
+ "}";
c = api.createRestAssured();
r = c.given().header("Content-Type", "application/json")
.body(docHeaderDeploy).post("/_/discovery/modules")
.then().statusCode(201)
.extract().response();
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
locationHeaderDeployment = r.getHeader("Location");
final String docEnableHeader = "{" + LS
+ " \"id\" : \"header-module\"" + LS
+ "}";
c = api.createRestAssured();
c.given()
.header("Content-Type", "application/json")
.body(docEnableHeader).post("/_/proxy/tenants/" + okapiTenant + "/modules")
.then().statusCode(201).body(equalTo(docEnableHeader));
Assert.assertTrue("raml: " + c.getLastReport().toString(),
c.getLastReport().isEmpty());
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/testb")
.then().statusCode(200)
.body(containsString("It works"))
.log().ifError();
// Actual redirecting request
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/red")
.then().statusCode(200)
.body(containsString("It works"))
.header("X-Okapi-Trace", containsString("GET sample-module http://localhost:9131/testr"))
.log().ifError();
// Bad redirect
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/badredirect")
.then().statusCode(500)
.body(containsString("No suitable module found"))
.log().ifError();
// catch redirect loops
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/simpleloop")
.then().statusCode(500)
.body(containsString("loop:"))
.log().ifError();
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/loop1")
.then().statusCode(500)
.body(containsString("loop:"))
.log().ifError();
// redirect to multiple modules
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("Content-Type", "application/json")
.body("{}")
.post("/multiple")
.then().statusCode(200)
.body(containsString("Hello Hello")) // test-module run twice
.log().ifError();
// Redirect with parameters
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/red?foo=bar")
.then().statusCode(200)
.body(containsString("It works"))
.log().ifError();
// A longer chain of redirects
given()
.header("X-Okapi-Tenant", okapiTenant)
.header("X-all-headers", "B")
.get("/chain1")
.then().statusCode(200)
.body(containsString("It works"))
.body(containsString("X-Okapi-Permissions-Desired:hdr.chain1,hdr.chain2,sample.testr,sample.chain3"))
.body(containsString("X-Okapi-Extra-Permissions:[\"hdr.modperm\",\"sample.modperm\"]"))
.log().ifError();
// What happens on prefix match
// /red matches, replaces with /testr, getting /testrlight which is not found
// This is odd, and subotimal, but not a serious failure. okapi-253
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/redlight")
.then().statusCode(404)
.header("X-Okapi-Trace", containsString("sample-module http://localhost:9131/testrlight : 404"))
.log().ifError();
// Verify that we replace only the beginning of the path
given()
.header("X-Okapi-Tenant", okapiTenant)
.get("/red/blue/red?color=/red")
.then().statusCode(404)
.log().ifError();
// Clean up
logger.info("Redirect test done. Cleaning up");
given().delete(locationTenantRoskilde)
.then().statusCode(204);
given().delete(locationSampleModule)
.then().statusCode(204);
given().delete(locationSampleDeployment)
.then().statusCode(204);
locationSampleDeployment = null;
given().delete(locationHeaderModule)
.then().statusCode(204);
given().delete(locationHeaderDeployment)
.then().statusCode(204);
locationHeaderDeployment = null;
checkDbIsEmpty("testRedirect done", context);
async.complete();
}
}
| Change one test to use filters rather than routingEntries
| okapi-core/src/test/java/okapi/ModuleTest.java | Change one test to use filters rather than routingEntries | <ide><path>kapi-core/src/test/java/okapi/ModuleTest.java
<ide> // Set up, deploy, and enable the header module
<ide> final String docHeaderModule = "{" + LS
<ide> + " \"id\" : \"header-module\"," + LS
<del> + " \"routingEntries\" : [ {" + LS
<add> + " \"filters\" : [ {" + LS
<ide> + " \"methods\" : [ \"GET\", \"POST\" ]," + LS
<ide> + " \"path\" : \"/testb\"," + LS
<ide> + " \"level\" : \"20\"," + LS |
|
JavaScript | apache-2.0 | cd30f3aa978c8b590e6b1b7b285341634a212810 | 0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | 'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
// VARIABLES //
var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
'skip': IS_BROWSER || IS_WINDOWS
};
// FIXTURES //
var PKG_VERSION = require('./../package.json' ).version;
// TESTS //
tape( 'command-line interface', function test( t ) {
t.ok( true, __filename );
t.end();
});
tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
var expected;
var cmd;
expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
'encoding': 'utf8'
});
cmd = [
process.execPath,
fpath,
'--help'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
}
t.end();
}
});
tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
var expected;
var cmd;
expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
'encoding': 'utf8'
});
cmd = [
process.execPath,
fpath,
'-h'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
}
t.end();
}
});
tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
var cmd = [
process.execPath,
fpath,
'--version'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
}
t.end();
}
});
tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
var cmd = [
process.execPath,
fpath,
'-V'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
}
t.end();
}
});
// TODO: additional tests
| tools/snippets/test/test.cli.js | 'use strict';
// MODULES //
var resolve = require( 'path' ).resolve;
var exec = require( 'child_process' ).exec;
var tape = require( 'tape' );
var IS_BROWSER = require( '@stdlib/assert/is-browser' );
var readFileSync = require( '@stdlib/fs/read-file' ).sync;
// VARIABLES //
var fpath = resolve( __dirname, '..', 'bin', 'cli' );
var opts = {
'skip': IS_BROWSER
};
// FIXTURES //
var PKG_VERSION = require('./../package.json' ).version;
// TESTS //
tape( 'command-line interface', function test( t ) {
t.ok( true, __filename );
t.end();
});
tape( 'when invoked with a `--help` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
var expected;
var cmd;
expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
'encoding': 'utf8'
});
cmd = [
process.execPath,
fpath,
'--help'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
}
t.end();
}
});
tape( 'when invoked with a `-h` flag, the command-line interface prints the help text to `stderr`', opts, function test( t ) {
var expected;
var cmd;
expected = readFileSync( resolve( __dirname, '..', 'bin', 'usage.txt' ), {
'encoding': 'utf8'
});
cmd = [
process.execPath,
fpath,
'-h'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), expected+'\n', 'expected value' );
}
t.end();
}
});
tape( 'when invoked with a `--version` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
var cmd = [
process.execPath,
fpath,
'--version'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
}
t.end();
}
});
tape( 'when invoked with a `-V` flag, the command-line interface prints the version to `stderr`', opts, function test( t ) {
var cmd = [
process.execPath,
fpath,
'-V'
];
exec( cmd.join( ' ' ), done );
function done( error, stdout, stderr ) {
if ( error ) {
t.fail( error.message );
} else {
t.strictEqual( stdout.toString(), '', 'does not print to `stdout`' );
t.strictEqual( stderr.toString(), PKG_VERSION+'\n', 'expected value' );
}
t.end();
}
});
// TODO: additional tests
| Update snippet
| tools/snippets/test/test.cli.js | Update snippet | <ide><path>ools/snippets/test/test.cli.js
<ide> var exec = require( 'child_process' ).exec;
<ide> var tape = require( 'tape' );
<ide> var IS_BROWSER = require( '@stdlib/assert/is-browser' );
<add>var IS_WINDOWS = require( '@stdlib/assert/is-windows' );
<ide> var readFileSync = require( '@stdlib/fs/read-file' ).sync;
<ide>
<ide>
<ide>
<ide> var fpath = resolve( __dirname, '..', 'bin', 'cli' );
<ide> var opts = {
<del> 'skip': IS_BROWSER
<add> 'skip': IS_BROWSER || IS_WINDOWS
<ide> };
<ide>
<ide> |
|
Java | apache-2.0 | 9be65873158f39ae1cc0c893727d1d29f73583d4 | 0 | hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform,hbs/warp10-platform | //
// Copyright 2018 SenX S.A.S.
//
// 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.warp10.script;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.warp10.WarpClassLoader;
import io.warp10.WarpConfig;
import io.warp10.WarpManager;
import io.warp10.continuum.Configuration;
import io.warp10.continuum.gts.CORRELATE;
import io.warp10.continuum.gts.DISCORDS;
import io.warp10.continuum.gts.FFT;
import io.warp10.continuum.gts.GeoTimeSerie.TYPE;
import io.warp10.continuum.gts.IFFT;
import io.warp10.continuum.gts.INTERPOLATE;
import io.warp10.continuum.gts.LOCATIONOFFSET;
import io.warp10.continuum.gts.ZIP;
import io.warp10.script.WarpScriptStack.Macro;
import io.warp10.script.aggregator.And;
import io.warp10.script.aggregator.Argminmax;
import io.warp10.script.aggregator.CircularMean;
import io.warp10.script.aggregator.Count;
import io.warp10.script.aggregator.Delta;
import io.warp10.script.aggregator.First;
import io.warp10.script.aggregator.HDist;
import io.warp10.script.aggregator.HSpeed;
import io.warp10.script.aggregator.Highest;
import io.warp10.script.aggregator.Join;
import io.warp10.script.aggregator.Last;
import io.warp10.script.aggregator.Lowest;
import io.warp10.script.aggregator.MAD;
import io.warp10.script.aggregator.Max;
import io.warp10.script.aggregator.Mean;
import io.warp10.script.aggregator.Median;
import io.warp10.script.aggregator.Min;
import io.warp10.script.aggregator.Or;
import io.warp10.script.aggregator.Percentile;
import io.warp10.script.aggregator.RMS;
import io.warp10.script.aggregator.Rate;
import io.warp10.script.aggregator.ShannonEntropy;
import io.warp10.script.aggregator.StandardDeviation;
import io.warp10.script.aggregator.Sum;
import io.warp10.script.aggregator.TrueCourse;
import io.warp10.script.aggregator.VDist;
import io.warp10.script.aggregator.VSpeed;
import io.warp10.script.aggregator.Variance;
import io.warp10.script.binary.ADD;
import io.warp10.script.binary.BitwiseAND;
import io.warp10.script.binary.BitwiseOR;
import io.warp10.script.binary.BitwiseXOR;
import io.warp10.script.binary.CondAND;
import io.warp10.script.binary.CondOR;
import io.warp10.script.binary.DIV;
import io.warp10.script.binary.EQ;
import io.warp10.script.binary.GE;
import io.warp10.script.binary.GT;
import io.warp10.script.binary.INPLACEADD;
import io.warp10.script.binary.LE;
import io.warp10.script.binary.LT;
import io.warp10.script.binary.MOD;
import io.warp10.script.binary.MUL;
import io.warp10.script.binary.NE;
import io.warp10.script.binary.POW;
import io.warp10.script.binary.SHIFTLEFT;
import io.warp10.script.binary.SHIFTRIGHT;
import io.warp10.script.binary.SUB;
import io.warp10.script.filler.FillerInterpolate;
import io.warp10.script.filler.FillerNext;
import io.warp10.script.filler.FillerPrevious;
import io.warp10.script.filler.FillerTrend;
import io.warp10.script.filter.FilterByClass;
import io.warp10.script.filter.FilterByLabels;
import io.warp10.script.filter.FilterByMetadata;
import io.warp10.script.filter.FilterLastEQ;
import io.warp10.script.filter.FilterLastGE;
import io.warp10.script.filter.FilterLastGT;
import io.warp10.script.filter.FilterLastLE;
import io.warp10.script.filter.FilterLastLT;
import io.warp10.script.filter.FilterLastNE;
import io.warp10.script.filter.LatencyFilter;
import io.warp10.script.functions.*;
import io.warp10.script.functions.math.ACOS;
import io.warp10.script.functions.math.ADDEXACT;
import io.warp10.script.functions.math.ASIN;
import io.warp10.script.functions.math.ATAN;
import io.warp10.script.functions.math.ATAN2;
import io.warp10.script.functions.math.CBRT;
import io.warp10.script.functions.math.CEIL;
import io.warp10.script.functions.math.COPYSIGN;
import io.warp10.script.functions.math.COS;
import io.warp10.script.functions.math.COSH;
import io.warp10.script.functions.math.DECREMENTEXACT;
import io.warp10.script.functions.math.EXP;
import io.warp10.script.functions.math.EXPM1;
import io.warp10.script.functions.math.FLOOR;
import io.warp10.script.functions.math.FLOORDIV;
import io.warp10.script.functions.math.FLOORMOD;
import io.warp10.script.functions.math.GETEXPONENT;
import io.warp10.script.functions.math.HYPOT;
import io.warp10.script.functions.math.IEEEREMAINDER;
import io.warp10.script.functions.math.INCREMENTEXACT;
import io.warp10.script.functions.math.LOG;
import io.warp10.script.functions.math.LOG10;
import io.warp10.script.functions.math.LOG1P;
import io.warp10.script.functions.math.MAX;
import io.warp10.script.functions.math.MIN;
import io.warp10.script.functions.math.MULTIPLYEXACT;
import io.warp10.script.functions.math.NEGATEEXACT;
import io.warp10.script.functions.math.NEXTAFTER;
import io.warp10.script.functions.math.NEXTDOWN;
import io.warp10.script.functions.math.NEXTUP;
import io.warp10.script.functions.math.RANDOM;
import io.warp10.script.functions.math.RINT;
import io.warp10.script.functions.math.ROUND;
import io.warp10.script.functions.math.SCALB;
import io.warp10.script.functions.math.SIGNUM;
import io.warp10.script.functions.math.SIN;
import io.warp10.script.functions.math.SINH;
import io.warp10.script.functions.math.SQRT;
import io.warp10.script.functions.math.SUBTRACTEXACT;
import io.warp10.script.functions.math.TAN;
import io.warp10.script.functions.math.TANH;
import io.warp10.script.functions.math.TODEGREES;
import io.warp10.script.functions.math.TOINTEXACT;
import io.warp10.script.functions.math.TORADIANS;
import io.warp10.script.functions.math.ULP;
import io.warp10.script.mapper.MapperAbs;
import io.warp10.script.mapper.MapperAdd;
import io.warp10.script.mapper.MapperCeil;
import io.warp10.script.mapper.MapperDayOfMonth;
import io.warp10.script.mapper.MapperDayOfWeek;
import io.warp10.script.mapper.MapperDotProduct;
import io.warp10.script.mapper.MapperDotProductPositive;
import io.warp10.script.mapper.MapperDotProductSigmoid;
import io.warp10.script.mapper.MapperDotProductTanh;
import io.warp10.script.mapper.MapperExp;
import io.warp10.script.mapper.MapperFinite;
import io.warp10.script.mapper.MapperFloor;
import io.warp10.script.mapper.MapperGeoApproximate;
import io.warp10.script.mapper.MapperGeoClearPosition;
import io.warp10.script.mapper.MapperGeoOutside;
import io.warp10.script.mapper.MapperGeoWithin;
import io.warp10.script.mapper.MapperHourOfDay;
import io.warp10.script.mapper.MapperKernelCosine;
import io.warp10.script.mapper.MapperKernelEpanechnikov;
import io.warp10.script.mapper.MapperKernelGaussian;
import io.warp10.script.mapper.MapperKernelLogistic;
import io.warp10.script.mapper.MapperKernelQuartic;
import io.warp10.script.mapper.MapperKernelSilverman;
import io.warp10.script.mapper.MapperKernelTriangular;
import io.warp10.script.mapper.MapperKernelTricube;
import io.warp10.script.mapper.MapperKernelTriweight;
import io.warp10.script.mapper.MapperKernelUniform;
import io.warp10.script.mapper.MapperLog;
import io.warp10.script.mapper.MapperMaxX;
import io.warp10.script.mapper.MapperMinX;
import io.warp10.script.mapper.MapperMinuteOfHour;
import io.warp10.script.mapper.MapperMod;
import io.warp10.script.mapper.MapperMonthOfYear;
import io.warp10.script.mapper.MapperMul;
import io.warp10.script.mapper.MapperNPDF;
import io.warp10.script.mapper.MapperParseDouble;
import io.warp10.script.mapper.MapperPow;
import io.warp10.script.mapper.MapperProduct;
import io.warp10.script.mapper.MapperReplace;
import io.warp10.script.mapper.MapperRound;
import io.warp10.script.mapper.MapperSecondOfMinute;
import io.warp10.script.mapper.MapperSigmoid;
import io.warp10.script.mapper.MapperTanh;
import io.warp10.script.mapper.MapperTick;
import io.warp10.script.mapper.MapperToBoolean;
import io.warp10.script.mapper.MapperToDouble;
import io.warp10.script.mapper.MapperToLong;
import io.warp10.script.mapper.MapperToString;
import io.warp10.script.mapper.MapperYear;
import io.warp10.script.mapper.STRICTMAPPER;
import io.warp10.script.op.OpAND;
import io.warp10.script.op.OpAdd;
import io.warp10.script.op.OpDiv;
import io.warp10.script.op.OpEQ;
import io.warp10.script.op.OpGE;
import io.warp10.script.op.OpGT;
import io.warp10.script.op.OpLE;
import io.warp10.script.op.OpLT;
import io.warp10.script.op.OpMask;
import io.warp10.script.op.OpMul;
import io.warp10.script.op.OpNE;
import io.warp10.script.op.OpOR;
import io.warp10.script.op.OpSub;
import io.warp10.script.processing.Pencode;
import io.warp10.script.processing.color.Palpha;
import io.warp10.script.processing.color.Pbackground;
import io.warp10.script.processing.color.Pblue;
import io.warp10.script.processing.color.Pbrightness;
import io.warp10.script.processing.color.Pclear;
import io.warp10.script.processing.color.Pcolor;
import io.warp10.script.processing.color.PcolorMode;
import io.warp10.script.processing.color.Pfill;
import io.warp10.script.processing.color.Pgreen;
import io.warp10.script.processing.color.Phue;
import io.warp10.script.processing.color.PlerpColor;
import io.warp10.script.processing.color.PnoFill;
import io.warp10.script.processing.color.PnoStroke;
import io.warp10.script.processing.color.Pred;
import io.warp10.script.processing.color.Psaturation;
import io.warp10.script.processing.color.Pstroke;
import io.warp10.script.processing.image.Pblend;
import io.warp10.script.processing.image.Pcopy;
import io.warp10.script.processing.image.Pdecode;
import io.warp10.script.processing.image.Pfilter;
import io.warp10.script.processing.image.Pget;
import io.warp10.script.processing.image.Pimage;
import io.warp10.script.processing.image.PimageMode;
import io.warp10.script.processing.image.PnoTint;
import io.warp10.script.processing.image.Ppixels;
import io.warp10.script.processing.image.Pset;
import io.warp10.script.processing.image.Ptint;
import io.warp10.script.processing.image.PtoImage;
import io.warp10.script.processing.image.PupdatePixels;
import io.warp10.script.processing.math.Pconstrain;
import io.warp10.script.processing.math.Pdist;
import io.warp10.script.processing.math.Plerp;
import io.warp10.script.processing.math.Pmag;
import io.warp10.script.processing.math.Pmap;
import io.warp10.script.processing.math.Pnorm;
import io.warp10.script.processing.rendering.PGraphics;
import io.warp10.script.processing.rendering.PblendMode;
import io.warp10.script.processing.rendering.Pclip;
import io.warp10.script.processing.rendering.PnoClip;
import io.warp10.script.processing.shape.Parc;
import io.warp10.script.processing.shape.PbeginContour;
import io.warp10.script.processing.shape.PbeginShape;
import io.warp10.script.processing.shape.Pbezier;
import io.warp10.script.processing.shape.PbezierDetail;
import io.warp10.script.processing.shape.PbezierPoint;
import io.warp10.script.processing.shape.PbezierTangent;
import io.warp10.script.processing.shape.PbezierVertex;
import io.warp10.script.processing.shape.Pbox;
import io.warp10.script.processing.shape.Pcurve;
import io.warp10.script.processing.shape.PcurveDetail;
import io.warp10.script.processing.shape.PcurvePoint;
import io.warp10.script.processing.shape.PcurveTangent;
import io.warp10.script.processing.shape.PcurveTightness;
import io.warp10.script.processing.shape.PcurveVertex;
import io.warp10.script.processing.shape.Pellipse;
import io.warp10.script.processing.shape.PellipseMode;
import io.warp10.script.processing.shape.PendContour;
import io.warp10.script.processing.shape.PendShape;
import io.warp10.script.processing.shape.Pline;
import io.warp10.script.processing.shape.PloadShape;
import io.warp10.script.processing.shape.Ppoint;
import io.warp10.script.processing.shape.Pquad;
import io.warp10.script.processing.shape.PquadraticVertex;
import io.warp10.script.processing.shape.Prect;
import io.warp10.script.processing.shape.PrectMode;
import io.warp10.script.processing.shape.Pshape;
import io.warp10.script.processing.shape.PshapeMode;
import io.warp10.script.processing.shape.Psphere;
import io.warp10.script.processing.shape.PsphereDetail;
import io.warp10.script.processing.shape.PstrokeCap;
import io.warp10.script.processing.shape.PstrokeJoin;
import io.warp10.script.processing.shape.PstrokeWeight;
import io.warp10.script.processing.shape.Ptriangle;
import io.warp10.script.processing.shape.Pvertex;
import io.warp10.script.processing.structure.PpopStyle;
import io.warp10.script.processing.structure.PpushStyle;
import io.warp10.script.processing.transform.PpopMatrix;
import io.warp10.script.processing.transform.PpushMatrix;
import io.warp10.script.processing.transform.PresetMatrix;
import io.warp10.script.processing.transform.Protate;
import io.warp10.script.processing.transform.ProtateX;
import io.warp10.script.processing.transform.ProtateY;
import io.warp10.script.processing.transform.ProtateZ;
import io.warp10.script.processing.transform.Pscale;
import io.warp10.script.processing.transform.PshearX;
import io.warp10.script.processing.transform.PshearY;
import io.warp10.script.processing.transform.Ptranslate;
import io.warp10.script.processing.typography.PcreateFont;
import io.warp10.script.processing.typography.Ptext;
import io.warp10.script.processing.typography.PtextAlign;
import io.warp10.script.processing.typography.PtextAscent;
import io.warp10.script.processing.typography.PtextDescent;
import io.warp10.script.processing.typography.PtextFont;
import io.warp10.script.processing.typography.PtextLeading;
import io.warp10.script.processing.typography.PtextMode;
import io.warp10.script.processing.typography.PtextSize;
import io.warp10.script.processing.typography.PtextWidth;
import io.warp10.script.unary.ABS;
import io.warp10.script.unary.COMPLEMENT;
import io.warp10.script.unary.FROMBIN;
import io.warp10.script.unary.FROMBITS;
import io.warp10.script.unary.FROMHEX;
import io.warp10.script.unary.NOT;
import io.warp10.script.unary.REVERSEBITS;
import io.warp10.script.unary.TOBIN;
import io.warp10.script.unary.TOBITS;
import io.warp10.script.unary.TOBOOLEAN;
import io.warp10.script.unary.TODOUBLE;
import io.warp10.script.unary.TOHEX;
import io.warp10.script.unary.TOLONG;
import io.warp10.script.unary.TOSTRING;
import io.warp10.script.unary.TOTIMESTAMP;
import io.warp10.script.unary.UNIT;
import io.warp10.warp.sdk.WarpScriptExtension;
/**
* Library of functions used to manipulate Geo Time Series
* and more generally interact with a WarpScriptStack
*/
public class WarpScriptLib {
private static final Logger LOG = LoggerFactory.getLogger(WarpScriptLib.class);
private static Map<String,Object> functions = new HashMap<String, Object>();
private static Set<String> extloaded = new LinkedHashSet<String>();
/**
* Static definition of name so it can be reused outside of WarpScriptLib
*/
public static final String NULL = "NULL";
public static final String COUNTER = "COUNTER";
public static final String COUNTERSET = "COUNTERSET";
public static final String REF = "REF";
public static final String COMPILE = "COMPILE";
public static final String SAFECOMPILE = "SAFECOMPILE";
public static final String COMPILED = "COMPILED";
public static final String EVAL = "EVAL";
public static final String EVALSECURE = "EVALSECURE";
public static final String SNAPSHOT = "SNAPSHOT";
public static final String SNAPSHOTALL = "SNAPSHOTALL";
public static final String LOAD = "LOAD";
public static final String POPR = "POPR";
public static final String CPOPR = "CPOPR";
public static final String PUSHR = "PUSHR";
public static final String CLEARREGS = "CLEARREGS";
public static final String RUN = "RUN";
public static final String BOOTSTRAP = "BOOTSTRAP";
public static final String NOOP = "NOOP";
public static final String MAP_START = "{";
public static final String MAP_END = "}";
public static final String LIST_START = "[";
public static final String LIST_END = "]";
public static final String SET_START = "(";
public static final String SET_END = ")";
public static final String VECTOR_START = "[[";
public static final String VECTOR_END = "]]";
public static final String TO_VECTOR = "->V";
public static final String TO_SET = "->SET";
public static final String NEWGTS = "NEWGTS";
public static final String SWAP = "SWAP";
public static final String RELABEL = "RELABEL";
public static final String RENAME = "RENAME";
public static final String PARSESELECTOR = "PARSESELECTOR";
public static final String GEO_WKT = "GEO.WKT";
public static final String GEO_WKT_UNIFORM = "GEO.WKT.UNIFORM";
public static final String GEO_JSON = "GEO.JSON";
public static final String GEO_JSON_UNIFORM = "GEO.JSON.UNIFORM";
public static final String GEO_INTERSECTION = "GEO.INTERSECTION";
public static final String GEO_DIFFERENCE = "GEO.DIFFERENCE";
public static final String GEO_UNION = "GEO.UNION";
public static final String GEOPACK = "GEOPACK";
public static final String GEOUNPACK = "GEOUNPACK";
public static final String SECTION = "SECTION";
public static final String UNWRAP = "UNWRAP";
public static final String UNWRAPENCODER = "UNWRAPENCODER";
public static final String OPB64TO = "OPB64->";
public static final String TOOPB64 = "->OPB64";
public static final String BYTESTO = "BYTES->";
public static final String BYTESTOBITS = "BYTESTOBITS";
public static final String MARK = "MARK";
public static final String STORE = "STORE";
public static final String MAPPER_HIGHEST = "mapper.highest";
public static final String MAPPER_LOWEST = "mapper.lowest";
public static final String MAPPER_MAX = "mapper.max";
public static final String MAPPER_MIN = "mapper.min";
public static final String RSAPUBLIC = "RSAPUBLIC";
public static final String RSAPRIVATE = "RSAPRIVATE";
public static final String MSGFAIL = "MSGFAIL";
public static final String INPLACEADD = "+!";
public static final String PUT = "PUT";
public static final String SAVE = "SAVE";
public static final String RESTORE = "RESTORE";
public static final String CHRONOSTART = "CHRONOSTART";
public static final String CHRONOEND = "CHRONOEND";
public static final String TRY = "TRY";
public static final String RETHROW = "RETHROW";
static {
addNamedWarpScriptFunction(new REV("REV"));
addNamedWarpScriptFunction(new REPORT("REPORT"));
addNamedWarpScriptFunction(new MINREV("MINREV"));
addNamedWarpScriptFunction(new MANAGERONOFF("UPDATEON", WarpManager.UPDATE_DISABLED, true));
addNamedWarpScriptFunction(new MANAGERONOFF("UPDATEOFF", WarpManager.UPDATE_DISABLED, false));
addNamedWarpScriptFunction(new MANAGERONOFF("METAON", WarpManager.META_DISABLED, true));
addNamedWarpScriptFunction(new MANAGERONOFF("METAOFF", WarpManager.META_DISABLED, false));
addNamedWarpScriptFunction(new MANAGERONOFF("DELETEON", WarpManager.DELETE_DISABLED, true));
addNamedWarpScriptFunction(new MANAGERONOFF("DELETEOFF", WarpManager.DELETE_DISABLED, false));
addNamedWarpScriptFunction(new NOOP(BOOTSTRAP));
addNamedWarpScriptFunction(new RTFM("RTFM"));
addNamedWarpScriptFunction(new MAN("MAN"));
//
// Stack manipulation functions
//
addNamedWarpScriptFunction(new PIGSCHEMA("PIGSCHEMA"));
addNamedWarpScriptFunction(new MARK(MARK));
addNamedWarpScriptFunction(new CLEARTOMARK("CLEARTOMARK"));
addNamedWarpScriptFunction(new COUNTTOMARK("COUNTTOMARK"));
addNamedWarpScriptFunction(new AUTHENTICATE("AUTHENTICATE"));
addNamedWarpScriptFunction(new ISAUTHENTICATED("ISAUTHENTICATED"));
addNamedWarpScriptFunction(new STACKATTRIBUTE("STACKATTRIBUTE")); // NOT TO BE DOCUMENTED
addNamedWarpScriptFunction(new EXPORT("EXPORT"));
addNamedWarpScriptFunction(new TIMINGS("TIMINGS")); // NOT TO BE DOCUMENTED (YET)
addNamedWarpScriptFunction(new NOTIMINGS("NOTIMINGS")); // NOT TO BE DOCUMENTED (YET)
addNamedWarpScriptFunction(new ELAPSED("ELAPSED")); // NOT TO BE DOCUMENTED (YET)
addNamedWarpScriptFunction(new TIMED("TIMED"));
addNamedWarpScriptFunction(new CHRONOSTART(CHRONOSTART));
addNamedWarpScriptFunction(new CHRONOEND(CHRONOEND));
addNamedWarpScriptFunction(new CHRONOSTATS("CHRONOSTATS"));
addNamedWarpScriptFunction(new TOLIST("->LIST"));
addNamedWarpScriptFunction(new LISTTO("LIST->"));
addNamedWarpScriptFunction(new UNLIST("UNLIST"));
addNamedWarpScriptFunction(new TOSET(TO_SET));
addNamedWarpScriptFunction(new SETTO("SET->"));
addNamedWarpScriptFunction(new TOVECTOR(TO_VECTOR));
addNamedWarpScriptFunction(new VECTORTO("V->"));
addNamedWarpScriptFunction(new UNION("UNION"));
addNamedWarpScriptFunction(new INTERSECTION("INTERSECTION"));
addNamedWarpScriptFunction(new DIFFERENCE("DIFFERENCE"));
addNamedWarpScriptFunction(new TOMAP("->MAP"));
addNamedWarpScriptFunction(new MAPTO("MAP->"));
addNamedWarpScriptFunction(new UNMAP("UNMAP"));
addNamedWarpScriptFunction(new MAPID("MAPID"));
addNamedWarpScriptFunction(new TOJSON("->JSON"));
addNamedWarpScriptFunction(new JSONTO("JSON->"));
addNamedWarpScriptFunction(new TOPICKLE("->PICKLE"));
addNamedWarpScriptFunction(new PICKLETO("PICKLE->"));
addNamedWarpScriptFunction(new GET("GET"));
addNamedWarpScriptFunction(new SET("SET"));
addNamedWarpScriptFunction(new PUT(PUT));
addNamedWarpScriptFunction(new SUBMAP("SUBMAP"));
addNamedWarpScriptFunction(new SUBLIST("SUBLIST"));
addNamedWarpScriptFunction(new KEYLIST("KEYLIST"));
addNamedWarpScriptFunction(new VALUELIST("VALUELIST"));
addNamedWarpScriptFunction(new SIZE("SIZE"));
addNamedWarpScriptFunction(new SHRINK("SHRINK"));
addNamedWarpScriptFunction(new REMOVE("REMOVE"));
addNamedWarpScriptFunction(new UNIQUE("UNIQUE"));
addNamedWarpScriptFunction(new CONTAINS("CONTAINS"));
addNamedWarpScriptFunction(new CONTAINSKEY("CONTAINSKEY"));
addNamedWarpScriptFunction(new CONTAINSVALUE("CONTAINSVALUE"));
addNamedWarpScriptFunction(new REVERSE("REVERSE", true));
addNamedWarpScriptFunction(new REVERSE("CLONEREVERSE", false));
addNamedWarpScriptFunction(new DUP("DUP"));
addNamedWarpScriptFunction(new DUPN("DUPN"));
addNamedWarpScriptFunction(new SWAP(SWAP));
addNamedWarpScriptFunction(new DROP("DROP"));
addNamedWarpScriptFunction(new SAVE(SAVE));
addNamedWarpScriptFunction(new RESTORE(RESTORE));
addNamedWarpScriptFunction(new CLEAR("CLEAR"));
addNamedWarpScriptFunction(new CLEARDEFS("CLEARDEFS"));
addNamedWarpScriptFunction(new CLEARSYMBOLS("CLEARSYMBOLS"));
addNamedWarpScriptFunction(new DROPN("DROPN"));
addNamedWarpScriptFunction(new ROT("ROT"));
addNamedWarpScriptFunction(new ROLL("ROLL"));
addNamedWarpScriptFunction(new ROLLD("ROLLD"));
addNamedWarpScriptFunction(new PICK("PICK"));
addNamedWarpScriptFunction(new DEPTH("DEPTH"));
addNamedWarpScriptFunction(new MAXDEPTH("MAXDEPTH"));
addNamedWarpScriptFunction(new RESET("RESET"));
addNamedWarpScriptFunction(new MAXOPS("MAXOPS"));
addNamedWarpScriptFunction(new MAXLOOP("MAXLOOP"));
addNamedWarpScriptFunction(new MAXBUCKETS("MAXBUCKETS"));
addNamedWarpScriptFunction(new MAXGEOCELLS("MAXGEOCELLS"));
addNamedWarpScriptFunction(new MAXPIXELS("MAXPIXELS"));
addNamedWarpScriptFunction(new MAXRECURSION("MAXRECURSION"));
addNamedWarpScriptFunction(new OPS("OPS"));
addNamedWarpScriptFunction(new MAXSYMBOLS("MAXSYMBOLS"));
addNamedWarpScriptFunction(new EVAL(EVAL));
addNamedWarpScriptFunction(new NOW("NOW"));
addNamedWarpScriptFunction(new AGO("AGO"));
addNamedWarpScriptFunction(new MSTU("MSTU"));
addNamedWarpScriptFunction(new STU("STU"));
addNamedWarpScriptFunction(new APPEND("APPEND"));
addNamedWarpScriptFunction(new STORE(STORE));
addNamedWarpScriptFunction(new CSTORE("CSTORE"));
addNamedWarpScriptFunction(new LOAD(LOAD));
addNamedWarpScriptFunction(new IMPORT("IMPORT"));
addNamedWarpScriptFunction(new RUN(RUN));
addNamedWarpScriptFunction(new DEF("DEF"));
addNamedWarpScriptFunction(new UDF("UDF", false));
addNamedWarpScriptFunction(new UDF("CUDF", true));
addNamedWarpScriptFunction(new CALL("CALL"));
addNamedWarpScriptFunction(new FORGET("FORGET"));
addNamedWarpScriptFunction(new DEFINED("DEFINED"));
addNamedWarpScriptFunction(new REDEFS("REDEFS"));
addNamedWarpScriptFunction(new DEFINEDMACRO("DEFINEDMACRO"));
addNamedWarpScriptFunction(new DEFINEDMACRO("CHECKMACRO", true));
addNamedWarpScriptFunction(new NaN("NaN"));
addNamedWarpScriptFunction(new ISNaN("ISNaN"));
addNamedWarpScriptFunction(new TYPEOF("TYPEOF"));
addNamedWarpScriptFunction(new EXTLOADED("EXTLOADED"));
addNamedWarpScriptFunction(new ASSERT("ASSERT"));
addNamedWarpScriptFunction(new ASSERTMSG("ASSERTMSG"));
addNamedWarpScriptFunction(new FAIL("FAIL"));
addNamedWarpScriptFunction(new MSGFAIL(MSGFAIL));
addNamedWarpScriptFunction(new STOP("STOP"));
addNamedWarpScriptFunction(new TRY(TRY));
addNamedWarpScriptFunction(new RETHROW(RETHROW));
addNamedWarpScriptFunction(new ERROR("ERROR"));
addNamedWarpScriptFunction(new TIMEBOX("TIMEBOX"));
addNamedWarpScriptFunction(new JSONSTRICT("JSONSTRICT"));
addNamedWarpScriptFunction(new JSONLOOSE("JSONLOOSE"));
addNamedWarpScriptFunction(new DEBUGON("DEBUGON"));
addNamedWarpScriptFunction(new NDEBUGON("NDEBUGON"));
addNamedWarpScriptFunction(new DEBUGOFF("DEBUGOFF"));
addNamedWarpScriptFunction(new LINEON("LINEON"));
addNamedWarpScriptFunction(new LINEOFF("LINEOFF"));
addNamedWarpScriptFunction(new LMAP("LMAP"));
addNamedWarpScriptFunction(new NONNULL("NONNULL"));
addNamedWarpScriptFunction(new LFLATMAP("LFLATMAP"));
addNamedWarpScriptFunction(new EMPTYLIST("[]"));
addNamedWarpScriptFunction(new MARK(LIST_START));
addNamedWarpScriptFunction(new ENDLIST(LIST_END));
addNamedWarpScriptFunction(new STACKTOLIST("STACKTOLIST"));
addNamedWarpScriptFunction(new MARK(SET_START));
addNamedWarpScriptFunction(new ENDSET(SET_END));
addNamedWarpScriptFunction(new EMPTYSET("()"));
addNamedWarpScriptFunction(new MARK(VECTOR_START));
addNamedWarpScriptFunction(new ENDVECTOR(VECTOR_END));
addNamedWarpScriptFunction(new EMPTYVECTOR("[[]]"));
addNamedWarpScriptFunction(new EMPTYMAP("{}"));
addNamedWarpScriptFunction(new IMMUTABLE("IMMUTABLE"));
addNamedWarpScriptFunction(new MARK(MAP_START));
addNamedWarpScriptFunction(new ENDMAP(MAP_END));
addNamedWarpScriptFunction(new SECUREKEY("SECUREKEY"));
addNamedWarpScriptFunction(new SECURE("SECURE"));
addNamedWarpScriptFunction(new UNSECURE("UNSECURE", true));
addNamedWarpScriptFunction(new EVALSECURE(EVALSECURE));
addNamedWarpScriptFunction(new NOOP("NOOP"));
addNamedWarpScriptFunction(new DOC("DOC"));
addNamedWarpScriptFunction(new DOCMODE("DOCMODE"));
addNamedWarpScriptFunction(new INFO("INFO"));
addNamedWarpScriptFunction(new INFOMODE("INFOMODE"));
addNamedWarpScriptFunction(new SECTION(SECTION));
addNamedWarpScriptFunction(new GETSECTION("GETSECTION"));
addNamedWarpScriptFunction(new SNAPSHOT(SNAPSHOT, false, false, true, false));
addNamedWarpScriptFunction(new SNAPSHOT(SNAPSHOTALL, true, false, true, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTTOMARK", false, true, true, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTALLTOMARK", true, true, true, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPY", false, false, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYALL", true, false, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYTOMARK", false, true, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYALLTOMARK", true, true, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTN", false, false, true, true));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYN", false, false, false, true));
addNamedWarpScriptFunction(new HEADER("HEADER"));
addNamedWarpScriptFunction(new ECHOON("ECHOON"));
addNamedWarpScriptFunction(new ECHOOFF("ECHOOFF"));
addNamedWarpScriptFunction(new JSONSTACK("JSONSTACK"));
addNamedWarpScriptFunction(new WSSTACK("WSSTACK"));
addNamedWarpScriptFunction(new PEEK("PEEK"));
addNamedWarpScriptFunction(new PEEKN("PEEKN"));
addNamedWarpScriptFunction(new NPEEK("NPEEK"));
addNamedWarpScriptFunction(new PSTACK("PSTACK"));
addNamedWarpScriptFunction(new TIMEON("TIMEON"));
addNamedWarpScriptFunction(new TIMEOFF("TIMEOFF"));
//
// Compilation related dummy functions
//
addNamedWarpScriptFunction(new FAIL(COMPILE, "Not supported"));
addNamedWarpScriptFunction(new NOOP(SAFECOMPILE));
addNamedWarpScriptFunction(new FAIL(COMPILED, "Not supported"));
addNamedWarpScriptFunction(new REF(REF));
addNamedWarpScriptFunction(new MACROTTL("MACROTTL"));
addNamedWarpScriptFunction(new WFON("WFON"));
addNamedWarpScriptFunction(new WFOFF("WFOFF"));
addNamedWarpScriptFunction(new SETMACROCONFIG("SETMACROCONFIG"));
addNamedWarpScriptFunction(new MACROCONFIGSECRET("MACROCONFIGSECRET"));
addNamedWarpScriptFunction(new MACROCONFIG("MACROCONFIG", false));
addNamedWarpScriptFunction(new MACROCONFIG("MACROCONFIGDEFAULT", true));
addNamedWarpScriptFunction(new MACROMAPPER("MACROMAPPER"));
addNamedWarpScriptFunction(new MACROMAPPER("MACROREDUCER"));
addNamedWarpScriptFunction(new MACROMAPPER("MACROBUCKETIZER"));
addNamedWarpScriptFunction(new MACROFILTER("MACROFILTER"));
addNamedWarpScriptFunction(new MACROFILLER("MACROFILLER"));
addNamedWarpScriptFunction(new STRICTMAPPER("STRICTMAPPER"));
addNamedWarpScriptFunction(new STRICTREDUCER("STRICTREDUCER"));
addNamedWarpScriptFunction(new PARSESELECTOR(PARSESELECTOR));
addNamedWarpScriptFunction(new TOSELECTOR("TOSELECTOR"));
addNamedWarpScriptFunction(new PARSE("PARSE"));
addNamedWarpScriptFunction(new SMARTPARSE("SMARTPARSE"));
// We do not expose DUMP, it might allocate too much memory
//addNamedWarpScriptFunction(new DUMP("DUMP"));
// Binary ops
addNamedWarpScriptFunction(new ADD("+"));
addNamedWarpScriptFunction(new INPLACEADD(INPLACEADD));
addNamedWarpScriptFunction(new SUB("-"));
addNamedWarpScriptFunction(new DIV("/"));
addNamedWarpScriptFunction(new MUL("*"));
addNamedWarpScriptFunction(new POW("**"));
addNamedWarpScriptFunction(new MOD("%"));
addNamedWarpScriptFunction(new EQ("=="));
addNamedWarpScriptFunction(new NE("!="));
addNamedWarpScriptFunction(new LT("<"));
addNamedWarpScriptFunction(new GT(">"));
addNamedWarpScriptFunction(new LE("<="));
addNamedWarpScriptFunction(new GE(">="));
addNamedWarpScriptFunction(new CondAND("&&"));
addNamedWarpScriptFunction(new CondAND("AND"));
addNamedWarpScriptFunction(new CondOR("||"));
addNamedWarpScriptFunction(new CondOR("OR"));
addNamedWarpScriptFunction(new BitwiseAND("&"));
addNamedWarpScriptFunction(new SHIFTRIGHT(">>", true));
addNamedWarpScriptFunction(new SHIFTRIGHT(">>>", false));
addNamedWarpScriptFunction(new SHIFTLEFT("<<"));
addNamedWarpScriptFunction(new BitwiseOR("|"));
addNamedWarpScriptFunction(new BitwiseXOR("^"));
addNamedWarpScriptFunction(new ALMOSTEQ("~="));
// Bitset ops
addNamedWarpScriptFunction(new BITGET("BITGET"));
addNamedWarpScriptFunction(new BITCOUNT("BITCOUNT"));
addNamedWarpScriptFunction(new BITSTOBYTES("BITSTOBYTES"));
addNamedWarpScriptFunction(new BYTESTOBITS("BYTESTOBITS"));
// Unary ops
addNamedWarpScriptFunction(new NOT("!"));
addNamedWarpScriptFunction(new COMPLEMENT("~"));
addNamedWarpScriptFunction(new REVERSEBITS("REVBITS"));
addNamedWarpScriptFunction(new NOT("NOT"));
addNamedWarpScriptFunction(new ABS("ABS"));
addNamedWarpScriptFunction(new TODOUBLE("TODOUBLE"));
addNamedWarpScriptFunction(new TOBOOLEAN("TOBOOLEAN"));
addNamedWarpScriptFunction(new TOLONG("TOLONG"));
addNamedWarpScriptFunction(new TOSTRING("TOSTRING"));
addNamedWarpScriptFunction(new TOHEX("TOHEX"));
addNamedWarpScriptFunction(new TOBIN("TOBIN"));
addNamedWarpScriptFunction(new FROMHEX("FROMHEX"));
addNamedWarpScriptFunction(new FROMBIN("FROMBIN"));
addNamedWarpScriptFunction(new TOBITS("TOBITS", false));
addNamedWarpScriptFunction(new FROMBITS("FROMBITS", false));
addNamedWarpScriptFunction(new TOLONGBYTES("->LONGBYTES"));
addNamedWarpScriptFunction(new TOBITS("->DOUBLEBITS", false));
addNamedWarpScriptFunction(new FROMBITS("DOUBLEBITS->", false));
addNamedWarpScriptFunction(new TOBITS("->FLOATBITS", true));
addNamedWarpScriptFunction(new FROMBITS("FLOATBITS->", true));
addNamedWarpScriptFunction(new TOKENINFO("TOKENINFO"));
addNamedWarpScriptFunction(new GETHOOK("GETHOOK"));
// Unit converters
addNamedWarpScriptFunction(new UNIT("w", 7 * 24 * 60 * 60 * 1000));
addNamedWarpScriptFunction(new UNIT("d", 24 * 60 * 60 * 1000));
addNamedWarpScriptFunction(new UNIT("h", 60 * 60 * 1000));
addNamedWarpScriptFunction(new UNIT("m", 60 * 1000));
addNamedWarpScriptFunction(new UNIT("s", 1000));
addNamedWarpScriptFunction(new UNIT("ms", 1));
addNamedWarpScriptFunction(new UNIT("us", 0.001));
addNamedWarpScriptFunction(new UNIT("ns", 0.000001));
addNamedWarpScriptFunction(new UNIT("ps", 0.000000001));
// Crypto functions
addNamedWarpScriptFunction(new HASH("HASH"));
addNamedWarpScriptFunction(new DIGEST("MD5", MD5Digest.class));
addNamedWarpScriptFunction(new DIGEST("SHA1", SHA1Digest.class));
addNamedWarpScriptFunction(new DIGEST("SHA256", SHA256Digest.class));
addNamedWarpScriptFunction(new HMAC("SHA256HMAC", SHA256Digest.class));
addNamedWarpScriptFunction(new HMAC("SHA1HMAC", SHA1Digest.class));
addNamedWarpScriptFunction(new AESWRAP("AESWRAP"));
addNamedWarpScriptFunction(new AESUNWRAP("AESUNWRAP"));
addNamedWarpScriptFunction(new RUNNERNONCE("RUNNERNONCE"));
addNamedWarpScriptFunction(new GZIP("GZIP"));
addNamedWarpScriptFunction(new UNGZIP("UNGZIP"));
addNamedWarpScriptFunction(new DEFLATE("DEFLATE"));
addNamedWarpScriptFunction(new INFLATE("INFLATE"));
addNamedWarpScriptFunction(new RSAGEN("RSAGEN"));
addNamedWarpScriptFunction(new RSAPUBLIC(RSAPUBLIC));
addNamedWarpScriptFunction(new RSAPRIVATE(RSAPRIVATE));
addNamedWarpScriptFunction(new RSAENCRYPT("RSAENCRYPT"));
addNamedWarpScriptFunction(new RSADECRYPT("RSADECRYPT"));
addNamedWarpScriptFunction(new RSASIGN("RSASIGN"));
addNamedWarpScriptFunction(new RSAVERIFY("RSAVERIFY"));
//
// String functions
//
addNamedWarpScriptFunction(new URLDECODE("URLDECODE"));
addNamedWarpScriptFunction(new URLENCODE("URLENCODE"));
addNamedWarpScriptFunction(new SPLIT("SPLIT"));
addNamedWarpScriptFunction(new UUID("UUID"));
addNamedWarpScriptFunction(new JOIN("JOIN"));
addNamedWarpScriptFunction(new SUBSTRING("SUBSTRING"));
addNamedWarpScriptFunction(new TOUPPER("TOUPPER"));
addNamedWarpScriptFunction(new TOLOWER("TOLOWER"));
addNamedWarpScriptFunction(new TRIM("TRIM"));
addNamedWarpScriptFunction(new B64TOHEX("B64TOHEX"));
addNamedWarpScriptFunction(new HEXTOB64("HEXTOB64"));
addNamedWarpScriptFunction(new BINTOHEX("BINTOHEX"));
addNamedWarpScriptFunction(new HEXTOBIN("HEXTOBIN"));
addNamedWarpScriptFunction(new BINTO("BIN->"));
addNamedWarpScriptFunction(new HEXTO("HEX->"));
addNamedWarpScriptFunction(new B64TO("B64->"));
addNamedWarpScriptFunction(new B64URLTO("B64URL->"));
addNamedWarpScriptFunction(new BYTESTO(BYTESTO));
addNamedWarpScriptFunction(new TOBYTES("->BYTES"));
addNamedWarpScriptFunction(new io.warp10.script.functions.TOBIN("->BIN"));
addNamedWarpScriptFunction(new io.warp10.script.functions.TOHEX("->HEX"));
addNamedWarpScriptFunction(new TOB64("->B64"));
addNamedWarpScriptFunction(new TOB64URL("->B64URL"));
addNamedWarpScriptFunction(new TOOPB64(TOOPB64));
addNamedWarpScriptFunction(new OPB64TO(OPB64TO));
addNamedWarpScriptFunction(new OPB64TOHEX("OPB64TOHEX"));
//
// Conditionals
//
addNamedWarpScriptFunction(new IFT("IFT"));
addNamedWarpScriptFunction(new IFTE("IFTE"));
addNamedWarpScriptFunction(new SWITCH("SWITCH"));
//
// Loops
//
addNamedWarpScriptFunction(new WHILE("WHILE"));
addNamedWarpScriptFunction(new UNTIL("UNTIL"));
addNamedWarpScriptFunction(new FOR("FOR"));
addNamedWarpScriptFunction(new FORSTEP("FORSTEP"));
addNamedWarpScriptFunction(new FOREACH("FOREACH"));
addNamedWarpScriptFunction(new BREAK("BREAK"));
addNamedWarpScriptFunction(new CONTINUE("CONTINUE"));
addNamedWarpScriptFunction(new EVERY("EVERY"));
addNamedWarpScriptFunction(new RANGE("RANGE"));
//
// Macro end
//
addNamedWarpScriptFunction(new RETURN("RETURN"));
addNamedWarpScriptFunction(new NRETURN("NRETURN"));
//
// GTS standalone functions
//
addNamedWarpScriptFunction(new NEWENCODER("NEWENCODER"));
addNamedWarpScriptFunction(new CHUNKENCODER("CHUNKENCODER", true));
addNamedWarpScriptFunction(new TOENCODER("->ENCODER"));
addNamedWarpScriptFunction(new ENCODERTO("ENCODER->"));
addNamedWarpScriptFunction(new TOGTS("->GTS"));
addNamedWarpScriptFunction(new OPTIMIZE("OPTIMIZE"));
addNamedWarpScriptFunction(new NEWGTS(NEWGTS));
addNamedWarpScriptFunction(new MAKEGTS("MAKEGTS"));
addNamedWarpScriptFunction(new ADDVALUE("ADDVALUE", false));
addNamedWarpScriptFunction(new ADDVALUE("SETVALUE", true));
addNamedWarpScriptFunction(new REMOVETICK("REMOVETICK"));
addNamedWarpScriptFunction(new FETCH("FETCH", false, null));
addNamedWarpScriptFunction(new FETCH("FETCHLONG", false, TYPE.LONG));
addNamedWarpScriptFunction(new FETCH("FETCHDOUBLE", false, TYPE.DOUBLE));
addNamedWarpScriptFunction(new FETCH("FETCHSTRING", false, TYPE.STRING));
addNamedWarpScriptFunction(new FETCH("FETCHBOOLEAN", false, TYPE.BOOLEAN));
addNamedWarpScriptFunction(new LIMIT("LIMIT"));
addNamedWarpScriptFunction(new MAXGTS("MAXGTS"));
addNamedWarpScriptFunction(new FIND("FIND", false));
addNamedWarpScriptFunction(new FIND("FINDSETS", true));
addNamedWarpScriptFunction(new FIND("METASET", false, true));
addNamedWarpScriptFunction(new FINDSTATS("FINDSTATS"));
addNamedWarpScriptFunction(new DEDUP("DEDUP"));
addNamedWarpScriptFunction(new ONLYBUCKETS("ONLYBUCKETS"));
addNamedWarpScriptFunction(new VALUEDEDUP("VALUEDEDUP"));
addNamedWarpScriptFunction(new CLONEEMPTY("CLONEEMPTY"));
addNamedWarpScriptFunction(new COMPACT("COMPACT"));
addNamedWarpScriptFunction(new RANGECOMPACT("RANGECOMPACT"));
addNamedWarpScriptFunction(new STANDARDIZE("STANDARDIZE"));
addNamedWarpScriptFunction(new NORMALIZE("NORMALIZE"));
addNamedWarpScriptFunction(new ISONORMALIZE("ISONORMALIZE"));
addNamedWarpScriptFunction(new ZSCORE("ZSCORE"));
addNamedWarpScriptFunction(new FILL("FILL"));
addNamedWarpScriptFunction(new FILLPREVIOUS("FILLPREVIOUS"));
addNamedWarpScriptFunction(new FILLNEXT("FILLNEXT"));
addNamedWarpScriptFunction(new FILLVALUE("FILLVALUE"));
addNamedWarpScriptFunction(new FILLTICKS("FILLTICKS"));
addNamedWarpScriptFunction(new INTERPOLATE("INTERPOLATE"));
addNamedWarpScriptFunction(new FIRSTTICK("FIRSTTICK"));
addNamedWarpScriptFunction(new LASTTICK("LASTTICK"));
addNamedWarpScriptFunction(new MERGE("MERGE"));
addNamedWarpScriptFunction(new RESETS("RESETS"));
addNamedWarpScriptFunction(new MONOTONIC("MONOTONIC"));
addNamedWarpScriptFunction(new TIMESPLIT("TIMESPLIT"));
addNamedWarpScriptFunction(new TIMECLIP("TIMECLIP"));
addNamedWarpScriptFunction(new CLIP("CLIP"));
addNamedWarpScriptFunction(new TIMEMODULO("TIMEMODULO"));
addNamedWarpScriptFunction(new CHUNK("CHUNK", true));
addNamedWarpScriptFunction(new FUSE("FUSE"));
addNamedWarpScriptFunction(new RENAME(RENAME));
addNamedWarpScriptFunction(new RELABEL(RELABEL));
addNamedWarpScriptFunction(new SETATTRIBUTES("SETATTRIBUTES"));
addNamedWarpScriptFunction(new CROP("CROP"));
addNamedWarpScriptFunction(new TIMESHIFT("TIMESHIFT"));
addNamedWarpScriptFunction(new TIMESCALE("TIMESCALE"));
addNamedWarpScriptFunction(new TICKINDEX("TICKINDEX"));
addNamedWarpScriptFunction(new FFT.Builder("FFT", true));
addNamedWarpScriptFunction(new FFT.Builder("FFTAP", false));
addNamedWarpScriptFunction(new IFFT.Builder("IFFT"));
addNamedWarpScriptFunction(new FFTWINDOW("FFTWINDOW"));
addNamedWarpScriptFunction(new FDWT("FDWT"));
addNamedWarpScriptFunction(new IDWT("IDWT"));
addNamedWarpScriptFunction(new DWTSPLIT("DWTSPLIT"));
addNamedWarpScriptFunction(new EMPTY("EMPTY"));
addNamedWarpScriptFunction(new NONEMPTY("NONEMPTY"));
addNamedWarpScriptFunction(new PARTITION("PARTITION"));
addNamedWarpScriptFunction(new PARTITION("STRICTPARTITION", true));
addNamedWarpScriptFunction(new ZIP("ZIP"));
addNamedWarpScriptFunction(new PATTERNS("PATTERNS", true));
addNamedWarpScriptFunction(new PATTERNDETECTION("PATTERNDETECTION", true));
addNamedWarpScriptFunction(new PATTERNS("ZPATTERNS", false));
addNamedWarpScriptFunction(new PATTERNDETECTION("ZPATTERNDETECTION", false));
addNamedWarpScriptFunction(new DTW("DTW", true, false));
addNamedWarpScriptFunction(new OPTDTW("OPTDTW"));
addNamedWarpScriptFunction(new DTW("ZDTW", true, true));
addNamedWarpScriptFunction(new DTW("RAWDTW", false, false));
addNamedWarpScriptFunction(new VALUEHISTOGRAM("VALUEHISTOGRAM"));
addNamedWarpScriptFunction(new PROBABILITY.Builder("PROBABILITY"));
addNamedWarpScriptFunction(new PROB("PROB"));
addNamedWarpScriptFunction(new CPROB("CPROB"));
addNamedWarpScriptFunction(new RANDPDF.Builder("RANDPDF"));
addNamedWarpScriptFunction(new SINGLEEXPONENTIALSMOOTHING("SINGLEEXPONENTIALSMOOTHING"));
addNamedWarpScriptFunction(new DOUBLEEXPONENTIALSMOOTHING("DOUBLEEXPONENTIALSMOOTHING"));
addNamedWarpScriptFunction(new LOWESS("LOWESS"));
addNamedWarpScriptFunction(new RLOWESS("RLOWESS"));
addNamedWarpScriptFunction(new STL("STL"));
addNamedWarpScriptFunction(new LTTB("LTTB", false));
addNamedWarpScriptFunction(new LTTB("TLTTB", true));
addNamedWarpScriptFunction(new LOCATIONOFFSET("LOCATIONOFFSET"));
addNamedWarpScriptFunction(new FLATTEN("FLATTEN"));
addNamedWarpScriptFunction(new RESHAPE("RESHAPE"));
addNamedWarpScriptFunction(new PERMUTE("PERMUTE"));
addNamedWarpScriptFunction(new CHECKSHAPE("CHECKSHAPE"));
addNamedWarpScriptFunction(new SHAPE("SHAPE"));
addNamedWarpScriptFunction(new HULLSHAPE("HULLSHAPE"));
addNamedWarpScriptFunction(new CORRELATE.Builder("CORRELATE"));
addNamedWarpScriptFunction(new SORT("SORT"));
addNamedWarpScriptFunction(new SORTBY("SORTBY"));
addNamedWarpScriptFunction(new RSORT("RSORT"));
addNamedWarpScriptFunction(new LASTSORT("LASTSORT"));
addNamedWarpScriptFunction(new METASORT("METASORT"));
addNamedWarpScriptFunction(new VALUESORT("VALUESORT"));
addNamedWarpScriptFunction(new RVALUESORT("RVALUESORT"));
addNamedWarpScriptFunction(new LSORT("LSORT"));
addNamedWarpScriptFunction(new SHUFFLE("SHUFFLE"));
addNamedWarpScriptFunction(new MSORT("MSORT"));
addNamedWarpScriptFunction(new GROUPBY("GROUPBY"));
addNamedWarpScriptFunction(new FILTERBY("FILTERBY"));
addNamedWarpScriptFunction(new UPDATE("UPDATE"));
addNamedWarpScriptFunction(new META("META"));
addNamedWarpScriptFunction(new DELETE("DELETE"));
addNamedWarpScriptFunction(new WEBCALL("WEBCALL"));
addNamedWarpScriptFunction(new MATCH("MATCH"));
addNamedWarpScriptFunction(new MATCHER("MATCHER"));
addNamedWarpScriptFunction(new REPLACE("REPLACE", false));
addNamedWarpScriptFunction(new REPLACE("REPLACEALL", true));
addNamedWarpScriptFunction(new REOPTALT("REOPTALT"));
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
addNamedWarpScriptFunction(new TEMPLATE("TEMPLATE"));
addNamedWarpScriptFunction(new TOTIMESTAMP("TOTIMESTAMP"));
} else {
addNamedWarpScriptFunction(new FAIL("TEMPLATE", "Requires JAVA 1.8+"));
addNamedWarpScriptFunction(new FAIL("TOTIMESTAMP", "Requires JAVA 1.8+"));
}
addNamedWarpScriptFunction(new DISCORDS("DISCORDS", true));
addNamedWarpScriptFunction(new DISCORDS("ZDISCORDS", false));
addNamedWarpScriptFunction(new INTEGRATE("INTEGRATE"));
addNamedWarpScriptFunction(new BUCKETSPAN("BUCKETSPAN"));
addNamedWarpScriptFunction(new BUCKETCOUNT("BUCKETCOUNT"));
addNamedWarpScriptFunction(new UNBUCKETIZE("UNBUCKETIZE"));
addNamedWarpScriptFunction(new LASTBUCKET("LASTBUCKET"));
addNamedWarpScriptFunction(new NAME("NAME"));
addNamedWarpScriptFunction(new LABELS("LABELS"));
addNamedWarpScriptFunction(new ATTRIBUTES("ATTRIBUTES"));
addNamedWarpScriptFunction(new LASTACTIVITY("LASTACTIVITY"));
addNamedWarpScriptFunction(new TICKS("TICKS"));
addNamedWarpScriptFunction(new LOCATIONS("LOCATIONS"));
addNamedWarpScriptFunction(new LOCSTRINGS("LOCSTRINGS"));
addNamedWarpScriptFunction(new ELEVATIONS("ELEVATIONS"));
addNamedWarpScriptFunction(new VALUES("VALUES"));
addNamedWarpScriptFunction(new VALUESPLIT("VALUESPLIT"));
addNamedWarpScriptFunction(new TICKLIST("TICKLIST"));
addNamedWarpScriptFunction(new COMMONTICKS("COMMONTICKS"));
addNamedWarpScriptFunction(new WRAP("WRAP"));
addNamedWarpScriptFunction(new WRAPRAW("WRAPRAW"));
addNamedWarpScriptFunction(new WRAPRAW("WRAPFAST", false, false));
addNamedWarpScriptFunction(new WRAP("WRAPOPT", true));
addNamedWarpScriptFunction(new WRAPRAW("WRAPRAWOPT", true));
addNamedWarpScriptFunction(new UNWRAP(UNWRAP));
addNamedWarpScriptFunction(new UNWRAP("UNWRAPEMPTY", true));
addNamedWarpScriptFunction(new UNWRAPSIZE("UNWRAPSIZE"));
addNamedWarpScriptFunction(new UNWRAPENCODER(UNWRAPENCODER));
//
// Outlier detection
//
addNamedWarpScriptFunction(new THRESHOLDTEST("THRESHOLDTEST"));
addNamedWarpScriptFunction(new ZSCORETEST("ZSCORETEST"));
addNamedWarpScriptFunction(new GRUBBSTEST("GRUBBSTEST"));
addNamedWarpScriptFunction(new ESDTEST("ESDTEST"));
addNamedWarpScriptFunction(new STLESDTEST("STLESDTEST"));
addNamedWarpScriptFunction(new HYBRIDTEST("HYBRIDTEST"));
addNamedWarpScriptFunction(new HYBRIDTEST2("HYBRIDTEST2"));
//
// Quaternion related functions
//
addNamedWarpScriptFunction(new TOQUATERNION("->Q"));
addNamedWarpScriptFunction(new QUATERNIONTO("Q->"));
addNamedWarpScriptFunction(new QCONJUGATE("QCONJUGATE"));
addNamedWarpScriptFunction(new QDIVIDE("QDIVIDE"));
addNamedWarpScriptFunction(new QMULTIPLY("QMULTIPLY"));
addNamedWarpScriptFunction(new QROTATE("QROTATE"));
addNamedWarpScriptFunction(new QROTATION("QROTATION"));
addNamedWarpScriptFunction(new ROTATIONQ("ROTATIONQ"));
addNamedWarpScriptFunction(new ATINDEX("ATINDEX"));
addNamedWarpScriptFunction(new ATTICK("ATTICK"));
addNamedWarpScriptFunction(new ATBUCKET("ATBUCKET"));
addNamedWarpScriptFunction(new CLONE("CLONE"));
addNamedWarpScriptFunction(new DURATION("DURATION"));
addNamedWarpScriptFunction(new HUMANDURATION("HUMANDURATION"));
addNamedWarpScriptFunction(new ISODURATION("ISODURATION"));
addNamedWarpScriptFunction(new ISO8601("ISO8601"));
addNamedWarpScriptFunction(new NOTBEFORE("NOTBEFORE"));
addNamedWarpScriptFunction(new NOTAFTER("NOTAFTER"));
addNamedWarpScriptFunction(new TSELEMENTS("TSELEMENTS"));
addNamedWarpScriptFunction(new TSELEMENTS("->TSELEMENTS"));
addNamedWarpScriptFunction(new FROMTSELEMENTS("TSELEMENTS->"));
addNamedWarpScriptFunction(new ADDDAYS("ADDDAYS"));
addNamedWarpScriptFunction(new ADDMONTHS("ADDMONTHS"));
addNamedWarpScriptFunction(new ADDYEARS("ADDYEARS"));
addNamedWarpScriptFunction(new QUANTIZE("QUANTIZE"));
addNamedWarpScriptFunction(new NBOUNDS("NBOUNDS"));
addNamedWarpScriptFunction(new LBOUNDS("LBOUNDS"));
//NFIRST -> Retain at most the N first values
//NLAST -> Retain at most the N last values
//
// GTS manipulation frameworks
//
addNamedWarpScriptFunction(new BUCKETIZE("BUCKETIZE"));
addNamedWarpScriptFunction(new MAP("MAP"));
addNamedWarpScriptFunction(new FILTER("FILTER", true));
addNamedWarpScriptFunction(new APPLY("APPLY", true));
addNamedWarpScriptFunction(new FILTER("PFILTER", false));
addNamedWarpScriptFunction(new APPLY("PAPPLY", false));
addNamedWarpScriptFunction(new REDUCE("REDUCE", true));
addNamedWarpScriptFunction(new REDUCE("PREDUCE", false));
addNamedWarpScriptFunction(new MaxTickSlidingWindow("max.tick.sliding.window"));
addNamedWarpScriptFunction(new MaxTimeSlidingWindow("max.time.sliding.window"));
addNamedWarpScriptFunction(new NULL(NULL));
addNamedWarpScriptFunction(new ISNULL("ISNULL"));
addNamedWarpScriptFunction(new MapperReplace.Builder("mapper.replace"));
addNamedWarpScriptFunction(new MAPPERGT("mapper.gt"));
addNamedWarpScriptFunction(new MAPPERGE("mapper.ge"));
addNamedWarpScriptFunction(new MAPPEREQ("mapper.eq"));
addNamedWarpScriptFunction(new MAPPERNE("mapper.ne"));
addNamedWarpScriptFunction(new MAPPERLE("mapper.le"));
addNamedWarpScriptFunction(new MAPPERLT("mapper.lt"));
addNamedWarpScriptFunction(new MapperAdd.Builder("mapper.add"));
addNamedWarpScriptFunction(new MapperMul.Builder("mapper.mul"));
addNamedWarpScriptFunction(new MapperPow.Builder("mapper.pow"));
try {
addNamedWarpScriptFunction(new MapperPow("mapper.sqrt", 0.5D));
} catch (WarpScriptException wse) {
throw new RuntimeException(wse);
}
addNamedWarpScriptFunction(new MapperExp.Builder("mapper.exp"));
addNamedWarpScriptFunction(new MapperLog.Builder("mapper.log"));
addNamedWarpScriptFunction(new MapperMinX.Builder("mapper.min.x"));
addNamedWarpScriptFunction(new MapperMaxX.Builder("mapper.max.x"));
addNamedWarpScriptFunction(new MapperParseDouble.Builder("mapper.parsedouble"));
addNamedWarpScriptFunction(new MapperTick.Builder("mapper.tick"));
addNamedWarpScriptFunction(new MapperYear.Builder("mapper.year"));
addNamedWarpScriptFunction(new MapperMonthOfYear.Builder("mapper.month"));
addNamedWarpScriptFunction(new MapperDayOfMonth.Builder("mapper.day"));
addNamedWarpScriptFunction(new MapperDayOfWeek.Builder("mapper.weekday"));
addNamedWarpScriptFunction(new MapperHourOfDay.Builder("mapper.hour"));
addNamedWarpScriptFunction(new MapperMinuteOfHour.Builder("mapper.minute"));
addNamedWarpScriptFunction(new MapperSecondOfMinute.Builder("mapper.second"));
addNamedWarpScriptFunction(new MapperNPDF.Builder("mapper.npdf"));
addNamedWarpScriptFunction(new MapperDotProduct.Builder("mapper.dotproduct"));
addNamedWarpScriptFunction(new MapperDotProductTanh.Builder("mapper.dotproduct.tanh"));
addNamedWarpScriptFunction(new MapperDotProductSigmoid.Builder("mapper.dotproduct.sigmoid"));
addNamedWarpScriptFunction(new MapperDotProductPositive.Builder("mapper.dotproduct.positive"));
// Kernel mappers
addNamedWarpScriptFunction(new MapperKernelCosine("mapper.kernel.cosine"));
addNamedWarpScriptFunction(new MapperKernelEpanechnikov("mapper.kernel.epanechnikov"));
addNamedWarpScriptFunction(new MapperKernelGaussian("mapper.kernel.gaussian"));
addNamedWarpScriptFunction(new MapperKernelLogistic("mapper.kernel.logistic"));
addNamedWarpScriptFunction(new MapperKernelQuartic("mapper.kernel.quartic"));
addNamedWarpScriptFunction(new MapperKernelSilverman("mapper.kernel.silverman"));
addNamedWarpScriptFunction(new MapperKernelTriangular("mapper.kernel.triangular"));
addNamedWarpScriptFunction(new MapperKernelTricube("mapper.kernel.tricube"));
addNamedWarpScriptFunction(new MapperKernelTriweight("mapper.kernel.triweight"));
addNamedWarpScriptFunction(new MapperKernelUniform("mapper.kernel.uniform"));
addNamedWarpScriptFunction(new Percentile.Builder("mapper.percentile"));
//functions.put("mapper.abscissa", new MapperSAX.Builder());
addNamedWarpScriptFunction(new FilterByClass.Builder("filter.byclass"));
addNamedWarpScriptFunction(new FilterByLabels.Builder("filter.bylabels", true, false));
addNamedWarpScriptFunction(new FilterByLabels.Builder("filter.byattr", false, true));
addNamedWarpScriptFunction(new FilterByLabels.Builder("filter.bylabelsattr", true, true));
addNamedWarpScriptFunction(new FilterByMetadata.Builder("filter.bymetadata"));
addNamedWarpScriptFunction(new FilterLastEQ.Builder("filter.last.eq"));
addNamedWarpScriptFunction(new FilterLastGE.Builder("filter.last.ge"));
addNamedWarpScriptFunction(new FilterLastGT.Builder("filter.last.gt"));
addNamedWarpScriptFunction(new FilterLastLE.Builder("filter.last.le"));
addNamedWarpScriptFunction(new FilterLastLT.Builder("filter.last.lt"));
addNamedWarpScriptFunction(new FilterLastNE.Builder("filter.last.ne"));
addNamedWarpScriptFunction(new LatencyFilter.Builder("filter.latencies"));
//
// Fillers
//
addNamedWarpScriptFunction(new FillerNext("filler.next"));
addNamedWarpScriptFunction(new FillerPrevious("filler.previous"));
addNamedWarpScriptFunction(new FillerInterpolate("filler.interpolate"));
addNamedWarpScriptFunction(new FillerTrend("filler.trend"));
//
// Geo Manipulation functions
//
addNamedWarpScriptFunction(new TOHHCODE("->HHCODE", true));
addNamedWarpScriptFunction(new TOHHCODE("->HHCODELONG", false));
addNamedWarpScriptFunction(new HHCODETO("HHCODE->"));
addNamedWarpScriptFunction(new GEOREGEXP("GEO.REGEXP"));
addNamedWarpScriptFunction(new GeoWKT(GEO_WKT, false));
addNamedWarpScriptFunction(new GeoWKT(GEO_WKT_UNIFORM, true));
addNamedWarpScriptFunction(new GeoJSON(GEO_JSON, false));
addNamedWarpScriptFunction(new GeoJSON(GEO_JSON_UNIFORM, true));
addNamedWarpScriptFunction(new GEOOPTIMIZE("GEO.OPTIMIZE"));
addNamedWarpScriptFunction(new GeoIntersection(GEO_INTERSECTION));
addNamedWarpScriptFunction(new GeoUnion(GEO_UNION));
addNamedWarpScriptFunction(new GeoSubtraction(GEO_DIFFERENCE));
addNamedWarpScriptFunction(new GEOWITHIN("GEO.WITHIN"));
addNamedWarpScriptFunction(new GEOINTERSECTS("GEO.INTERSECTS"));
addNamedWarpScriptFunction(new HAVERSINE("HAVERSINE"));
addNamedWarpScriptFunction(new GEOPACK(GEOPACK));
addNamedWarpScriptFunction(new GEOUNPACK(GEOUNPACK));
addNamedWarpScriptFunction(new MapperGeoWithin.Builder("mapper.geo.within"));
addNamedWarpScriptFunction(new MapperGeoOutside.Builder("mapper.geo.outside"));
addNamedWarpScriptFunction(new MapperGeoApproximate.Builder("mapper.geo.approximate"));
addNamedWarpScriptFunction(new COPYGEO("COPYGEO"));
addNamedWarpScriptFunction(new BBOX("BBOX"));
addNamedWarpScriptFunction(new TOGEOHASH("->GEOHASH"));
addNamedWarpScriptFunction(new GEOHASHTO("GEOHASH->"));
//
// Counters
//
addNamedWarpScriptFunction(new COUNTER(COUNTER));
addNamedWarpScriptFunction(new COUNTERVALUE("COUNTERVALUE"));
addNamedWarpScriptFunction(new COUNTERDELTA("COUNTERDELTA"));
addNamedWarpScriptFunction(new COUNTERSET(COUNTERSET));
//
// Math functions
//
addNamedWarpScriptFunction(new Pi("pi"));
addNamedWarpScriptFunction(new Pi("PI"));
addNamedWarpScriptFunction(new E("e"));
addNamedWarpScriptFunction(new E("E"));
addNamedWarpScriptFunction(new MINLONG("MINLONG"));
addNamedWarpScriptFunction(new MAXLONG("MAXLONG"));
addNamedWarpScriptFunction(new RAND("RAND"));
addNamedWarpScriptFunction(new PRNG("PRNG"));
addNamedWarpScriptFunction(new SRAND("SRAND"));
addNamedWarpScriptFunction(new NPDF.Builder("NPDF"));
addNamedWarpScriptFunction(new MUSIGMA("MUSIGMA"));
addNamedWarpScriptFunction(new KURTOSIS("KURTOSIS"));
addNamedWarpScriptFunction(new SKEWNESS("SKEWNESS"));
addNamedWarpScriptFunction(new NSUMSUMSQ("NSUMSUMSQ"));
addNamedWarpScriptFunction(new LR("LR"));
addNamedWarpScriptFunction(new MODE("MODE"));
addNamedWarpScriptFunction(new TOZ("->Z"));
addNamedWarpScriptFunction(new ZTO("Z->"));
addNamedWarpScriptFunction(new PACK("PACK"));
addNamedWarpScriptFunction(new UNPACK("UNPACK"));
//
// Linear Algebra
//
addNamedWarpScriptFunction(new TOMAT("->MAT"));
addNamedWarpScriptFunction(new MATTO("MAT->"));
addNamedWarpScriptFunction(new TR("TR"));
addNamedWarpScriptFunction(new TRANSPOSE("TRANSPOSE"));
addNamedWarpScriptFunction(new DET("DET"));
addNamedWarpScriptFunction(new INV("INV"));
addNamedWarpScriptFunction(new TOVEC("->VEC"));
addNamedWarpScriptFunction(new VECTO("VEC->"));
addNamedWarpScriptFunction(new COS("COS"));
addNamedWarpScriptFunction(new COSH("COSH"));
addNamedWarpScriptFunction(new ACOS("ACOS"));
addNamedWarpScriptFunction(new SIN("SIN"));
addNamedWarpScriptFunction(new SINH("SINH"));
addNamedWarpScriptFunction(new ASIN("ASIN"));
addNamedWarpScriptFunction(new TAN("TAN"));
addNamedWarpScriptFunction(new TANH("TANH"));
addNamedWarpScriptFunction(new ATAN("ATAN"));
addNamedWarpScriptFunction(new SIGNUM("SIGNUM"));
addNamedWarpScriptFunction(new FLOOR("FLOOR"));
addNamedWarpScriptFunction(new CEIL("CEIL"));
addNamedWarpScriptFunction(new ROUND("ROUND"));
addNamedWarpScriptFunction(new RINT("RINT"));
addNamedWarpScriptFunction(new NEXTUP("NEXTUP"));
addNamedWarpScriptFunction(new ULP("ULP"));
addNamedWarpScriptFunction(new SQRT("SQRT"));
addNamedWarpScriptFunction(new CBRT("CBRT"));
addNamedWarpScriptFunction(new EXP("EXP"));
addNamedWarpScriptFunction(new EXPM1("EXPM1"));
addNamedWarpScriptFunction(new LOG("LOG"));
addNamedWarpScriptFunction(new LOG10("LOG10"));
addNamedWarpScriptFunction(new LOG1P("LOG1P"));
addNamedWarpScriptFunction(new TORADIANS("TORADIANS"));
addNamedWarpScriptFunction(new TODEGREES("TODEGREES"));
addNamedWarpScriptFunction(new MAX("MAX"));
addNamedWarpScriptFunction(new MIN("MIN"));
addNamedWarpScriptFunction(new COPYSIGN("COPYSIGN"));
addNamedWarpScriptFunction(new HYPOT("HYPOT"));
addNamedWarpScriptFunction(new IEEEREMAINDER("IEEEREMAINDER"));
addNamedWarpScriptFunction(new NEXTAFTER("NEXTAFTER"));
addNamedWarpScriptFunction(new ATAN2("ATAN2"));
addNamedWarpScriptFunction(new FLOORDIV("FLOORDIV"));
addNamedWarpScriptFunction(new FLOORMOD("FLOORMOD"));
addNamedWarpScriptFunction(new ADDEXACT("ADDEXACT"));
addNamedWarpScriptFunction(new SUBTRACTEXACT("SUBTRACTEXACT"));
addNamedWarpScriptFunction(new MULTIPLYEXACT("MULTIPLYEXACT"));
addNamedWarpScriptFunction(new INCREMENTEXACT("INCREMENTEXACT"));
addNamedWarpScriptFunction(new DECREMENTEXACT("DECREMENTEXACT"));
addNamedWarpScriptFunction(new NEGATEEXACT("NEGATEEXACT"));
addNamedWarpScriptFunction(new TOINTEXACT("TOINTEXACT"));
addNamedWarpScriptFunction(new SCALB("SCALB"));
addNamedWarpScriptFunction(new RANDOM("RANDOM"));
addNamedWarpScriptFunction(new NEXTDOWN("NEXTDOWN"));
addNamedWarpScriptFunction(new GETEXPONENT("GETEXPONENT"));
addNamedWarpScriptFunction(new IDENT("IDENT"));
//
// Processing
//
addNamedWarpScriptFunction(new Pencode("Pencode"));
// Structure
addNamedWarpScriptFunction(new PpushStyle("PpushStyle"));
addNamedWarpScriptFunction(new PpopStyle("PpopStyle"));
// Environment
// Shape
addNamedWarpScriptFunction(new Parc("Parc"));
addNamedWarpScriptFunction(new Pellipse("Pellipse"));
addNamedWarpScriptFunction(new Ppoint("Ppoint"));
addNamedWarpScriptFunction(new Pline("Pline"));
addNamedWarpScriptFunction(new Ptriangle("Ptriangle"));
addNamedWarpScriptFunction(new Prect("Prect"));
addNamedWarpScriptFunction(new Pquad("Pquad"));
addNamedWarpScriptFunction(new Pbezier("Pbezier"));
addNamedWarpScriptFunction(new PbezierPoint("PbezierPoint"));
addNamedWarpScriptFunction(new PbezierTangent("PbezierTangent"));
addNamedWarpScriptFunction(new PbezierDetail("PbezierDetail"));
addNamedWarpScriptFunction(new Pcurve("Pcurve"));
addNamedWarpScriptFunction(new PcurvePoint("PcurvePoint"));
addNamedWarpScriptFunction(new PcurveTangent("PcurveTangent"));
addNamedWarpScriptFunction(new PcurveDetail("PcurveDetail"));
addNamedWarpScriptFunction(new PcurveTightness("PcurveTightness"));
addNamedWarpScriptFunction(new Pbox("Pbox"));
addNamedWarpScriptFunction(new Psphere("Psphere"));
addNamedWarpScriptFunction(new PsphereDetail("PsphereDetail"));
addNamedWarpScriptFunction(new PellipseMode("PellipseMode"));
addNamedWarpScriptFunction(new PrectMode("PrectMode"));
addNamedWarpScriptFunction(new PstrokeCap("PstrokeCap"));
addNamedWarpScriptFunction(new PstrokeJoin("PstrokeJoin"));
addNamedWarpScriptFunction(new PstrokeWeight("PstrokeWeight"));
addNamedWarpScriptFunction(new PbeginShape("PbeginShape"));
addNamedWarpScriptFunction(new PendShape("PendShape"));
addNamedWarpScriptFunction(new PloadShape("PloadShape"));
addNamedWarpScriptFunction(new PbeginContour("PbeginContour"));
addNamedWarpScriptFunction(new PendContour("PendContour"));
addNamedWarpScriptFunction(new Pvertex("Pvertex"));
addNamedWarpScriptFunction(new PcurveVertex("PcurveVertex"));
addNamedWarpScriptFunction(new PbezierVertex("PbezierVertex"));
addNamedWarpScriptFunction(new PquadraticVertex("PquadraticVertex"));
// TODO(hbs): support PShape (need to support PbeginShape etc applied to PShape instances)
addNamedWarpScriptFunction(new PshapeMode("PshapeMode"));
addNamedWarpScriptFunction(new Pshape("Pshape"));
// Transform
addNamedWarpScriptFunction(new PpushMatrix("PpushMatrix"));
addNamedWarpScriptFunction(new PpopMatrix("PpopMatrix"));
addNamedWarpScriptFunction(new PresetMatrix("PresetMatrix"));
addNamedWarpScriptFunction(new Protate("Protate"));
addNamedWarpScriptFunction(new ProtateX("ProtateX"));
addNamedWarpScriptFunction(new ProtateY("ProtateY"));
addNamedWarpScriptFunction(new ProtateZ("ProtateZ"));
addNamedWarpScriptFunction(new Pscale("Pscale"));
addNamedWarpScriptFunction(new PshearX("PshearX"));
addNamedWarpScriptFunction(new PshearY("PshearY"));
addNamedWarpScriptFunction(new Ptranslate("Ptranslate"));
// Color
addNamedWarpScriptFunction(new Pbackground("Pbackground"));
addNamedWarpScriptFunction(new PcolorMode("PcolorMode"));
addNamedWarpScriptFunction(new Pclear("Pclear"));
addNamedWarpScriptFunction(new Pfill("Pfill"));
addNamedWarpScriptFunction(new PnoFill("PnoFill"));
addNamedWarpScriptFunction(new Pstroke("Pstroke"));
addNamedWarpScriptFunction(new PnoStroke("PnoStroke"));
addNamedWarpScriptFunction(new Palpha("Palpha"));
addNamedWarpScriptFunction(new Pblue("Pblue"));
addNamedWarpScriptFunction(new Pbrightness("Pbrightness"));
addNamedWarpScriptFunction(new Pcolor("Pcolor"));
addNamedWarpScriptFunction(new Pgreen("Pgreen"));
addNamedWarpScriptFunction(new Phue("Phue"));
addNamedWarpScriptFunction(new PlerpColor("PlerpColor"));
addNamedWarpScriptFunction(new Pred("Pred"));
addNamedWarpScriptFunction(new Psaturation("Psaturation"));
// Image
addNamedWarpScriptFunction(new Pdecode("Pdecode"));
addNamedWarpScriptFunction(new Pimage("Pimage"));
addNamedWarpScriptFunction(new PimageMode("PimageMode"));
addNamedWarpScriptFunction(new Ptint("Ptint"));
addNamedWarpScriptFunction(new PnoTint("PnoTint"));
addNamedWarpScriptFunction(new Ppixels("Ppixels"));
addNamedWarpScriptFunction(new PupdatePixels("PupdatePixels"));
addNamedWarpScriptFunction(new PtoImage("PtoImage"));
// TODO(hbs): support texture related functions?
addNamedWarpScriptFunction(new Pblend("Pblend"));
addNamedWarpScriptFunction(new Pcopy("Pcopy"));
addNamedWarpScriptFunction(new Pget("Pget"));
addNamedWarpScriptFunction(new Pset("Pset"));
addNamedWarpScriptFunction(new Pfilter("Pfilter"));
// Rendering
addNamedWarpScriptFunction(new PblendMode("PblendMode"));
addNamedWarpScriptFunction(new Pclip("Pclip"));
addNamedWarpScriptFunction(new PnoClip("PnoClip"));
addNamedWarpScriptFunction(new PGraphics("PGraphics"));
// TODO(hbs): support shaders?
// Typography
addNamedWarpScriptFunction(new PcreateFont("PcreateFont"));
addNamedWarpScriptFunction(new Ptext("Ptext"));
addNamedWarpScriptFunction(new PtextAlign("PtextAlign"));
addNamedWarpScriptFunction(new PtextAscent("PtextAscent"));
addNamedWarpScriptFunction(new PtextDescent("PtextDescent"));
addNamedWarpScriptFunction(new PtextFont("PtextFont"));
addNamedWarpScriptFunction(new PtextLeading("PtextLeading"));
addNamedWarpScriptFunction(new PtextMode("PtextMode"));
addNamedWarpScriptFunction(new PtextSize("PtextSize"));
addNamedWarpScriptFunction(new PtextWidth("PtextWidth"));
// Math
addNamedWarpScriptFunction(new Pconstrain("Pconstrain"));
addNamedWarpScriptFunction(new Pdist("Pdist"));
addNamedWarpScriptFunction(new Plerp("Plerp"));
addNamedWarpScriptFunction(new Pmag("Pmag"));
addNamedWarpScriptFunction(new Pmap("Pmap"));
addNamedWarpScriptFunction(new Pnorm("Pnorm"));
////////////////////////////////////////////////////////////////////////////
//
// Moved from JavaLibrary
//
/////////////////////////
//
// Bucketizers
//
addNamedWarpScriptFunction(new And("bucketizer.and", false));
addNamedWarpScriptFunction(new First("bucketizer.first"));
addNamedWarpScriptFunction(new Last("bucketizer.last"));
addNamedWarpScriptFunction(new Min("bucketizer.min", true));
addNamedWarpScriptFunction(new Max("bucketizer.max", true));
addNamedWarpScriptFunction(new Mean("bucketizer.mean", false));
addNamedWarpScriptFunction(new Median("bucketizer.median"));
addNamedWarpScriptFunction(new MAD("bucketizer.mad"));
addNamedWarpScriptFunction(new Or("bucketizer.or", false));
addNamedWarpScriptFunction(new Sum("bucketizer.sum", true));
addNamedWarpScriptFunction(new Join.Builder("bucketizer.join", true, false, null));
addNamedWarpScriptFunction(new Count("bucketizer.count", false));
addNamedWarpScriptFunction(new Percentile.Builder("bucketizer.percentile"));
addNamedWarpScriptFunction(new Min("bucketizer.min.forbid-nulls", false));
addNamedWarpScriptFunction(new Max("bucketizer.max.forbid-nulls", false));
addNamedWarpScriptFunction(new Mean("bucketizer.mean.exclude-nulls", true));
addNamedWarpScriptFunction(new Sum("bucketizer.sum.forbid-nulls", false));
addNamedWarpScriptFunction(new Join.Builder("bucketizer.join.forbid-nulls", false, false, null));
addNamedWarpScriptFunction(new Count("bucketizer.count.exclude-nulls", true));
addNamedWarpScriptFunction(new Count("bucketizer.count.include-nulls", false));
addNamedWarpScriptFunction(new Count("bucketizer.count.nonnull", true));
addNamedWarpScriptFunction(new CircularMean.Builder("bucketizer.mean.circular", true));
addNamedWarpScriptFunction(new CircularMean.Builder("bucketizer.mean.circular.exclude-nulls", false));
addNamedWarpScriptFunction(new RMS("bucketizer.rms", false));
//
// Mappers
//
addNamedWarpScriptFunction(new And("mapper.and", false));
addNamedWarpScriptFunction(new Count("mapper.count", false));
addNamedWarpScriptFunction(new First("mapper.first"));
addNamedWarpScriptFunction(new Last("mapper.last"));
addNamedWarpScriptFunction(new Min(MAPPER_MIN, true));
addNamedWarpScriptFunction(new Max(MAPPER_MAX, true));
addNamedWarpScriptFunction(new Mean("mapper.mean", false));
addNamedWarpScriptFunction(new Median("mapper.median"));
addNamedWarpScriptFunction(new MAD("mapper.mad"));
addNamedWarpScriptFunction(new Or("mapper.or", false));
addNamedWarpScriptFunction(new Highest(MAPPER_HIGHEST));
addNamedWarpScriptFunction(new Lowest(MAPPER_LOWEST));
addNamedWarpScriptFunction(new Sum("mapper.sum", true));
addNamedWarpScriptFunction(new Join.Builder("mapper.join", true, false, null));
addNamedWarpScriptFunction(new Delta("mapper.delta"));
addNamedWarpScriptFunction(new Rate("mapper.rate"));
addNamedWarpScriptFunction(new HSpeed("mapper.hspeed"));
addNamedWarpScriptFunction(new HDist("mapper.hdist"));
addNamedWarpScriptFunction(new TrueCourse("mapper.truecourse"));
addNamedWarpScriptFunction(new VSpeed("mapper.vspeed"));
addNamedWarpScriptFunction(new VDist("mapper.vdist"));
addNamedWarpScriptFunction(new Variance.Builder("mapper.var", false));
addNamedWarpScriptFunction(new StandardDeviation.Builder("mapper.sd", false));
addNamedWarpScriptFunction(new MapperAbs("mapper.abs"));
addNamedWarpScriptFunction(new MapperCeil("mapper.ceil"));
addNamedWarpScriptFunction(new MapperFloor("mapper.floor"));
addNamedWarpScriptFunction(new MapperFinite("mapper.finite"));
addNamedWarpScriptFunction(new MapperRound("mapper.round"));
addNamedWarpScriptFunction(new MapperToBoolean("mapper.toboolean"));
addNamedWarpScriptFunction(new MapperToLong("mapper.tolong"));
addNamedWarpScriptFunction(new MapperToDouble("mapper.todouble"));
addNamedWarpScriptFunction(new MapperToString("mapper.tostring"));
addNamedWarpScriptFunction(new MapperTanh("mapper.tanh"));
addNamedWarpScriptFunction(new MapperSigmoid("mapper.sigmoid"));
addNamedWarpScriptFunction(new MapperProduct("mapper.product"));
addNamedWarpScriptFunction(new MapperGeoClearPosition("mapper.geo.clear"));
addNamedWarpScriptFunction(new Count("mapper.count.exclude-nulls", true));
addNamedWarpScriptFunction(new Count("mapper.count.include-nulls", false));
addNamedWarpScriptFunction(new Count("mapper.count.nonnull", true));
addNamedWarpScriptFunction(new Min("mapper.min.forbid-nulls", false));
addNamedWarpScriptFunction(new Max("mapper.max.forbid-nulls", false));
addNamedWarpScriptFunction(new Mean("mapper.mean.exclude-nulls", true));
addNamedWarpScriptFunction(new Sum("mapper.sum.forbid-nulls", false));
addNamedWarpScriptFunction(new Join.Builder("mapper.join.forbid-nulls", false, false, null));
addNamedWarpScriptFunction(new Variance.Builder("mapper.var.forbid-nulls", true));
addNamedWarpScriptFunction(new StandardDeviation.Builder("mapper.sd.forbid-nulls", true));
addNamedWarpScriptFunction(new CircularMean.Builder("mapper.mean.circular", true));
addNamedWarpScriptFunction(new CircularMean.Builder("mapper.mean.circular.exclude-nulls", false));
addNamedWarpScriptFunction(new MapperMod.Builder("mapper.mod"));
addNamedWarpScriptFunction(new RMS("mapper.rms", false));
//
// Reducers
//
addNamedWarpScriptFunction(new And("reducer.and", false));
addNamedWarpScriptFunction(new And("reducer.and.exclude-nulls", true));
addNamedWarpScriptFunction(new Min("reducer.min", true));
addNamedWarpScriptFunction(new Min("reducer.min.forbid-nulls", false));
addNamedWarpScriptFunction(new Min("reducer.min.nonnull", false));
addNamedWarpScriptFunction(new Max("reducer.max", true));
addNamedWarpScriptFunction(new Max("reducer.max.forbid-nulls", false));
addNamedWarpScriptFunction(new Max("reducer.max.nonnull", false));
addNamedWarpScriptFunction(new Mean("reducer.mean", false));
addNamedWarpScriptFunction(new Mean("reducer.mean.exclude-nulls", true));
addNamedWarpScriptFunction(new Median("reducer.median"));
addNamedWarpScriptFunction(new MAD("reducer.mad"));
addNamedWarpScriptFunction(new Or("reducer.or", false));
addNamedWarpScriptFunction(new Or("reducer.or.exclude-nulls", true));
addNamedWarpScriptFunction(new Sum("reducer.sum", true));
addNamedWarpScriptFunction(new Sum("reducer.sum.forbid-nulls", false));
addNamedWarpScriptFunction(new Sum("reducer.sum.nonnull", false));
addNamedWarpScriptFunction(new Join.Builder("reducer.join", true, false, null));
addNamedWarpScriptFunction(new Join.Builder("reducer.join.forbid-nulls", false, false, null));
addNamedWarpScriptFunction(new Join.Builder("reducer.join.nonnull", false, false, null));
addNamedWarpScriptFunction(new Join.Builder("reducer.join.urlencoded", false, true, ""));
addNamedWarpScriptFunction(new Variance.Builder("reducer.var", false));
addNamedWarpScriptFunction(new Variance.Builder("reducer.var.forbid-nulls", false));
addNamedWarpScriptFunction(new StandardDeviation.Builder("reducer.sd", false));
addNamedWarpScriptFunction(new StandardDeviation.Builder("reducer.sd.forbid-nulls", false));
addNamedWarpScriptFunction(new Argminmax.Builder("reducer.argmin", true));
addNamedWarpScriptFunction(new Argminmax.Builder("reducer.argmax", false));
addNamedWarpScriptFunction(new MapperProduct("reducer.product"));
addNamedWarpScriptFunction(new Count("reducer.count", false));
addNamedWarpScriptFunction(new Count("reducer.count.include-nulls", false));
addNamedWarpScriptFunction(new Count("reducer.count.exclude-nulls", true));
addNamedWarpScriptFunction(new Count("reducer.count.nonnull", true));
addNamedWarpScriptFunction(new ShannonEntropy("reducer.shannonentropy.0", false));
addNamedWarpScriptFunction(new ShannonEntropy("reducer.shannonentropy.1", true));
addNamedWarpScriptFunction(new Percentile.Builder("reducer.percentile"));
addNamedWarpScriptFunction(new CircularMean.Builder("reducer.mean.circular", true));
addNamedWarpScriptFunction(new CircularMean.Builder("reducer.mean.circular.exclude-nulls", false));
addNamedWarpScriptFunction(new RMS("reducer.rms", false));
addNamedWarpScriptFunction(new RMS("reducer.rms.exclude-nulls", true));
//
// Filters
//
//
// N-ary ops
//
addNamedWarpScriptFunction(new OpAdd("op.add", true));
addNamedWarpScriptFunction(new OpAdd("op.add.ignore-nulls", false));
addNamedWarpScriptFunction(new OpSub("op.sub"));
addNamedWarpScriptFunction(new OpMul("op.mul", true));
addNamedWarpScriptFunction(new OpMul("op.mul.ignore-nulls", false));
addNamedWarpScriptFunction(new OpDiv("op.div"));
addNamedWarpScriptFunction(new OpMask("op.mask", false));
addNamedWarpScriptFunction(new OpMask("op.negmask", true));
addNamedWarpScriptFunction(new OpNE("op.ne"));
addNamedWarpScriptFunction(new OpEQ("op.eq"));
addNamedWarpScriptFunction(new OpLT("op.lt"));
addNamedWarpScriptFunction(new OpGT("op.gt"));
addNamedWarpScriptFunction(new OpLE("op.le"));
addNamedWarpScriptFunction(new OpGE("op.ge"));
addNamedWarpScriptFunction(new OpAND("op.and.ignore-nulls", false));
addNamedWarpScriptFunction(new OpAND("op.and", true));
addNamedWarpScriptFunction(new OpOR("op.or.ignore-nulls", false));
addNamedWarpScriptFunction(new OpOR("op.or", true));
/////////////////////////
int nregs = Integer.parseInt(WarpConfig.getProperty(Configuration.CONFIG_WARPSCRIPT_REGISTERS, String.valueOf(WarpScriptStack.DEFAULT_REGISTERS)));
addNamedWarpScriptFunction(new CLEARREGS(CLEARREGS));
addNamedWarpScriptFunction(new VARS("VARS"));
addNamedWarpScriptFunction(new ASREGS("ASREGS"));
for (int i = 0; i < nregs; i++) {
addNamedWarpScriptFunction(new POPR(POPR + i, i));
addNamedWarpScriptFunction(new POPR(CPOPR + i, i, true));
addNamedWarpScriptFunction(new PUSHR(PUSHR + i, i));
}
}
public static void addNamedWarpScriptFunction(NamedWarpScriptFunction namedFunction) {
functions.put(namedFunction.getName(), namedFunction);
}
public static Object getFunction(String name) {
return functions.get(name);
}
public static void registerExtensions() {
Properties props = WarpConfig.getProperties();
if (null == props) {
return;
}
//
// Extract the list of extensions
//
Set<String> ext = new LinkedHashSet<String>();
if (props.containsKey(Configuration.CONFIG_WARPSCRIPT_EXTENSIONS)) {
String[] extensions = props.getProperty(Configuration.CONFIG_WARPSCRIPT_EXTENSIONS).split(",");
for (String extension: extensions) {
ext.add(extension.trim());
}
}
for (Object key: props.keySet()) {
if (!key.toString().startsWith(Configuration.CONFIG_WARPSCRIPT_EXTENSION_PREFIX)) {
continue;
}
ext.add(props.get(key).toString().trim());
}
// Sort the extensions
List<String> sortedext = new ArrayList<String>(ext);
sortedext.sort(null);
List<String> failedExt = new ArrayList<String>();
//
// Determine the possible jar from which WarpScriptLib was loaded
//
String wsljar = null;
URL wslurl = WarpScriptLib.class.getResource('/' + WarpScriptLib.class.getCanonicalName().replace('.', '/') + ".class");
if (null != wslurl && "jar".equals(wslurl.getProtocol())) {
wsljar = wslurl.toString().replaceAll("!/.*", "").replaceAll("jar:file:", "");
}
for (String extension: sortedext) {
// If the extension name contains '#', remove everything up to the last '#', this was used as a sorting prefix
if (extension.contains("#")) {
extension = extension.replaceAll("^.*#", "");
}
try {
//
// Locate the class using the current class loader
//
URL url = WarpScriptLib.class.getResource('/' + extension.replace('.', '/') + ".class");
if (null == url) {
LOG.error("Unable to load extension '" + extension + "', make sure it is in the class path.");
failedExt.add(extension);
continue;
}
Class cls = null;
//
// If the class was located in a jar, load it using a specific class loader
// so we can have fat jars with specific deps, unless the jar is the same as
// the one from which WarpScriptLib was loaded, in which case we use the same
// class loader.
//
if ("jar".equals(url.getProtocol())) {
String jarfile = url.toString().replaceAll("!/.*", "").replaceAll("jar:file:", "");
ClassLoader cl = WarpScriptLib.class.getClassLoader();
// If the jar differs from that from which WarpScriptLib was loaded, create a dedicated class loader
if (!jarfile.equals(wsljar) && !"true".equals(props.getProperty(Configuration.CONFIG_WARPSCRIPT_DEFAULTCL_PREFIX + extension))) {
cl = new WarpClassLoader(jarfile, WarpScriptLib.class.getClassLoader());
}
cls = Class.forName(extension, true, cl);
} else {
cls = Class.forName(extension, true, WarpScriptLib.class.getClassLoader());
}
//Class cls = Class.forName(extension);
WarpScriptExtension wse = (WarpScriptExtension) cls.newInstance();
wse.register();
String namespace = props.getProperty(Configuration.CONFIG_WARPSCRIPT_NAMESPACE_PREFIX + wse.getClass().getName(), "").trim();
if (null != namespace && !"".equals(namespace)) {
if (namespace.contains("%")) {
namespace = URLDecoder.decode(namespace, "UTF-8");
}
LOG.info("LOADED extension '" + extension + "'" + " under namespace '" + namespace + "'.");
} else {
LOG.info("LOADED extension '" + extension + "'");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (!failedExt.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("The following WarpScript extensions could not be loaded, aborting:");
for (String extension: failedExt) {
sb.append(" '");
sb.append(extension);
sb.append("'");
}
LOG.error(sb.toString());
throw new RuntimeException(sb.toString());
}
}
public static void register(WarpScriptExtension extension) {
String namespace = WarpConfig.getProperty(Configuration.CONFIG_WARPSCRIPT_NAMESPACE_PREFIX + extension.getClass().getName(), "").trim();
if (namespace.contains("%")) {
try {
namespace = URLDecoder.decode(namespace, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
register(namespace, extension);
}
public static void register(String namespace, WarpScriptExtension extension) {
extloaded.add(extension.getClass().getCanonicalName());
Map<String,Object> extfuncs = extension.getFunctions();
if (null == extfuncs) {
return;
}
for (Entry<String,Object> entry: extfuncs.entrySet()) {
if (null == entry.getValue()) {
functions.remove(namespace + entry.getKey());
} else {
functions.put(namespace + entry.getKey(), entry.getValue());
}
}
}
public static boolean extloaded(String name) {
return extloaded.contains(name);
}
public static List<String> extensions() {
return new ArrayList<String>(extloaded);
}
/**
* Check whether or not an object is castable to a macro
* @param o
* @return
*/
public static boolean isMacro(Object o) {
if (null == o) {
return false;
}
return o instanceof Macro;
}
public static ArrayList getFunctionNames() {
List<Object> list = new ArrayList<Object>();
list.addAll(functions.keySet());
return (ArrayList)list;
}
}
| warp10/src/main/java/io/warp10/script/WarpScriptLib.java | //
// Copyright 2018 SenX S.A.S.
//
// 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.warp10.script;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import org.apache.commons.lang3.JavaVersion;
import org.apache.commons.lang3.SystemUtils;
import org.bouncycastle.crypto.digests.MD5Digest;
import org.bouncycastle.crypto.digests.SHA1Digest;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.warp10.WarpClassLoader;
import io.warp10.WarpConfig;
import io.warp10.WarpManager;
import io.warp10.continuum.Configuration;
import io.warp10.continuum.gts.CORRELATE;
import io.warp10.continuum.gts.DISCORDS;
import io.warp10.continuum.gts.FFT;
import io.warp10.continuum.gts.GeoTimeSerie.TYPE;
import io.warp10.continuum.gts.IFFT;
import io.warp10.continuum.gts.INTERPOLATE;
import io.warp10.continuum.gts.LOCATIONOFFSET;
import io.warp10.continuum.gts.ZIP;
import io.warp10.script.WarpScriptStack.Macro;
import io.warp10.script.aggregator.And;
import io.warp10.script.aggregator.Argminmax;
import io.warp10.script.aggregator.CircularMean;
import io.warp10.script.aggregator.Count;
import io.warp10.script.aggregator.Delta;
import io.warp10.script.aggregator.First;
import io.warp10.script.aggregator.HDist;
import io.warp10.script.aggregator.HSpeed;
import io.warp10.script.aggregator.Highest;
import io.warp10.script.aggregator.Join;
import io.warp10.script.aggregator.Last;
import io.warp10.script.aggregator.Lowest;
import io.warp10.script.aggregator.MAD;
import io.warp10.script.aggregator.Max;
import io.warp10.script.aggregator.Mean;
import io.warp10.script.aggregator.Median;
import io.warp10.script.aggregator.Min;
import io.warp10.script.aggregator.Or;
import io.warp10.script.aggregator.Percentile;
import io.warp10.script.aggregator.RMS;
import io.warp10.script.aggregator.Rate;
import io.warp10.script.aggregator.ShannonEntropy;
import io.warp10.script.aggregator.StandardDeviation;
import io.warp10.script.aggregator.Sum;
import io.warp10.script.aggregator.TrueCourse;
import io.warp10.script.aggregator.VDist;
import io.warp10.script.aggregator.VSpeed;
import io.warp10.script.aggregator.Variance;
import io.warp10.script.binary.ADD;
import io.warp10.script.binary.BitwiseAND;
import io.warp10.script.binary.BitwiseOR;
import io.warp10.script.binary.BitwiseXOR;
import io.warp10.script.binary.CondAND;
import io.warp10.script.binary.CondOR;
import io.warp10.script.binary.DIV;
import io.warp10.script.binary.EQ;
import io.warp10.script.binary.GE;
import io.warp10.script.binary.GT;
import io.warp10.script.binary.INPLACEADD;
import io.warp10.script.binary.LE;
import io.warp10.script.binary.LT;
import io.warp10.script.binary.MOD;
import io.warp10.script.binary.MUL;
import io.warp10.script.binary.NE;
import io.warp10.script.binary.POW;
import io.warp10.script.binary.SHIFTLEFT;
import io.warp10.script.binary.SHIFTRIGHT;
import io.warp10.script.binary.SUB;
import io.warp10.script.filler.FillerInterpolate;
import io.warp10.script.filler.FillerNext;
import io.warp10.script.filler.FillerPrevious;
import io.warp10.script.filler.FillerTrend;
import io.warp10.script.filter.FilterByClass;
import io.warp10.script.filter.FilterByLabels;
import io.warp10.script.filter.FilterByMetadata;
import io.warp10.script.filter.FilterLastEQ;
import io.warp10.script.filter.FilterLastGE;
import io.warp10.script.filter.FilterLastGT;
import io.warp10.script.filter.FilterLastLE;
import io.warp10.script.filter.FilterLastLT;
import io.warp10.script.filter.FilterLastNE;
import io.warp10.script.filter.LatencyFilter;
import io.warp10.script.functions.*;
import io.warp10.script.functions.math.ACOS;
import io.warp10.script.functions.math.ADDEXACT;
import io.warp10.script.functions.math.ASIN;
import io.warp10.script.functions.math.ATAN;
import io.warp10.script.functions.math.ATAN2;
import io.warp10.script.functions.math.CBRT;
import io.warp10.script.functions.math.CEIL;
import io.warp10.script.functions.math.COPYSIGN;
import io.warp10.script.functions.math.COS;
import io.warp10.script.functions.math.COSH;
import io.warp10.script.functions.math.DECREMENTEXACT;
import io.warp10.script.functions.math.EXP;
import io.warp10.script.functions.math.EXPM1;
import io.warp10.script.functions.math.FLOOR;
import io.warp10.script.functions.math.FLOORDIV;
import io.warp10.script.functions.math.FLOORMOD;
import io.warp10.script.functions.math.GETEXPONENT;
import io.warp10.script.functions.math.HYPOT;
import io.warp10.script.functions.math.IEEEREMAINDER;
import io.warp10.script.functions.math.INCREMENTEXACT;
import io.warp10.script.functions.math.LOG;
import io.warp10.script.functions.math.LOG10;
import io.warp10.script.functions.math.LOG1P;
import io.warp10.script.functions.math.MAX;
import io.warp10.script.functions.math.MIN;
import io.warp10.script.functions.math.MULTIPLYEXACT;
import io.warp10.script.functions.math.NEGATEEXACT;
import io.warp10.script.functions.math.NEXTAFTER;
import io.warp10.script.functions.math.NEXTDOWN;
import io.warp10.script.functions.math.NEXTUP;
import io.warp10.script.functions.math.RANDOM;
import io.warp10.script.functions.math.RINT;
import io.warp10.script.functions.math.ROUND;
import io.warp10.script.functions.math.SCALB;
import io.warp10.script.functions.math.SIGNUM;
import io.warp10.script.functions.math.SIN;
import io.warp10.script.functions.math.SINH;
import io.warp10.script.functions.math.SQRT;
import io.warp10.script.functions.math.SUBTRACTEXACT;
import io.warp10.script.functions.math.TAN;
import io.warp10.script.functions.math.TANH;
import io.warp10.script.functions.math.TODEGREES;
import io.warp10.script.functions.math.TOINTEXACT;
import io.warp10.script.functions.math.TORADIANS;
import io.warp10.script.functions.math.ULP;
import io.warp10.script.mapper.MapperAbs;
import io.warp10.script.mapper.MapperAdd;
import io.warp10.script.mapper.MapperCeil;
import io.warp10.script.mapper.MapperDayOfMonth;
import io.warp10.script.mapper.MapperDayOfWeek;
import io.warp10.script.mapper.MapperDotProduct;
import io.warp10.script.mapper.MapperDotProductPositive;
import io.warp10.script.mapper.MapperDotProductSigmoid;
import io.warp10.script.mapper.MapperDotProductTanh;
import io.warp10.script.mapper.MapperExp;
import io.warp10.script.mapper.MapperFinite;
import io.warp10.script.mapper.MapperFloor;
import io.warp10.script.mapper.MapperGeoApproximate;
import io.warp10.script.mapper.MapperGeoClearPosition;
import io.warp10.script.mapper.MapperGeoOutside;
import io.warp10.script.mapper.MapperGeoWithin;
import io.warp10.script.mapper.MapperHourOfDay;
import io.warp10.script.mapper.MapperKernelCosine;
import io.warp10.script.mapper.MapperKernelEpanechnikov;
import io.warp10.script.mapper.MapperKernelGaussian;
import io.warp10.script.mapper.MapperKernelLogistic;
import io.warp10.script.mapper.MapperKernelQuartic;
import io.warp10.script.mapper.MapperKernelSilverman;
import io.warp10.script.mapper.MapperKernelTriangular;
import io.warp10.script.mapper.MapperKernelTricube;
import io.warp10.script.mapper.MapperKernelTriweight;
import io.warp10.script.mapper.MapperKernelUniform;
import io.warp10.script.mapper.MapperLog;
import io.warp10.script.mapper.MapperMaxX;
import io.warp10.script.mapper.MapperMinX;
import io.warp10.script.mapper.MapperMinuteOfHour;
import io.warp10.script.mapper.MapperMod;
import io.warp10.script.mapper.MapperMonthOfYear;
import io.warp10.script.mapper.MapperMul;
import io.warp10.script.mapper.MapperNPDF;
import io.warp10.script.mapper.MapperParseDouble;
import io.warp10.script.mapper.MapperPow;
import io.warp10.script.mapper.MapperProduct;
import io.warp10.script.mapper.MapperReplace;
import io.warp10.script.mapper.MapperRound;
import io.warp10.script.mapper.MapperSecondOfMinute;
import io.warp10.script.mapper.MapperSigmoid;
import io.warp10.script.mapper.MapperTanh;
import io.warp10.script.mapper.MapperTick;
import io.warp10.script.mapper.MapperToBoolean;
import io.warp10.script.mapper.MapperToDouble;
import io.warp10.script.mapper.MapperToLong;
import io.warp10.script.mapper.MapperToString;
import io.warp10.script.mapper.MapperYear;
import io.warp10.script.mapper.STRICTMAPPER;
import io.warp10.script.op.OpAND;
import io.warp10.script.op.OpAdd;
import io.warp10.script.op.OpDiv;
import io.warp10.script.op.OpEQ;
import io.warp10.script.op.OpGE;
import io.warp10.script.op.OpGT;
import io.warp10.script.op.OpLE;
import io.warp10.script.op.OpLT;
import io.warp10.script.op.OpMask;
import io.warp10.script.op.OpMul;
import io.warp10.script.op.OpNE;
import io.warp10.script.op.OpOR;
import io.warp10.script.op.OpSub;
import io.warp10.script.processing.Pencode;
import io.warp10.script.processing.color.Palpha;
import io.warp10.script.processing.color.Pbackground;
import io.warp10.script.processing.color.Pblue;
import io.warp10.script.processing.color.Pbrightness;
import io.warp10.script.processing.color.Pclear;
import io.warp10.script.processing.color.Pcolor;
import io.warp10.script.processing.color.PcolorMode;
import io.warp10.script.processing.color.Pfill;
import io.warp10.script.processing.color.Pgreen;
import io.warp10.script.processing.color.Phue;
import io.warp10.script.processing.color.PlerpColor;
import io.warp10.script.processing.color.PnoFill;
import io.warp10.script.processing.color.PnoStroke;
import io.warp10.script.processing.color.Pred;
import io.warp10.script.processing.color.Psaturation;
import io.warp10.script.processing.color.Pstroke;
import io.warp10.script.processing.image.Pblend;
import io.warp10.script.processing.image.Pcopy;
import io.warp10.script.processing.image.Pdecode;
import io.warp10.script.processing.image.Pfilter;
import io.warp10.script.processing.image.Pget;
import io.warp10.script.processing.image.Pimage;
import io.warp10.script.processing.image.PimageMode;
import io.warp10.script.processing.image.PnoTint;
import io.warp10.script.processing.image.Ppixels;
import io.warp10.script.processing.image.Pset;
import io.warp10.script.processing.image.Ptint;
import io.warp10.script.processing.image.PtoImage;
import io.warp10.script.processing.image.PupdatePixels;
import io.warp10.script.processing.math.Pconstrain;
import io.warp10.script.processing.math.Pdist;
import io.warp10.script.processing.math.Plerp;
import io.warp10.script.processing.math.Pmag;
import io.warp10.script.processing.math.Pmap;
import io.warp10.script.processing.math.Pnorm;
import io.warp10.script.processing.rendering.PGraphics;
import io.warp10.script.processing.rendering.PblendMode;
import io.warp10.script.processing.rendering.Pclip;
import io.warp10.script.processing.rendering.PnoClip;
import io.warp10.script.processing.shape.Parc;
import io.warp10.script.processing.shape.PbeginContour;
import io.warp10.script.processing.shape.PbeginShape;
import io.warp10.script.processing.shape.Pbezier;
import io.warp10.script.processing.shape.PbezierDetail;
import io.warp10.script.processing.shape.PbezierPoint;
import io.warp10.script.processing.shape.PbezierTangent;
import io.warp10.script.processing.shape.PbezierVertex;
import io.warp10.script.processing.shape.Pbox;
import io.warp10.script.processing.shape.Pcurve;
import io.warp10.script.processing.shape.PcurveDetail;
import io.warp10.script.processing.shape.PcurvePoint;
import io.warp10.script.processing.shape.PcurveTangent;
import io.warp10.script.processing.shape.PcurveTightness;
import io.warp10.script.processing.shape.PcurveVertex;
import io.warp10.script.processing.shape.Pellipse;
import io.warp10.script.processing.shape.PellipseMode;
import io.warp10.script.processing.shape.PendContour;
import io.warp10.script.processing.shape.PendShape;
import io.warp10.script.processing.shape.Pline;
import io.warp10.script.processing.shape.PloadShape;
import io.warp10.script.processing.shape.Ppoint;
import io.warp10.script.processing.shape.Pquad;
import io.warp10.script.processing.shape.PquadraticVertex;
import io.warp10.script.processing.shape.Prect;
import io.warp10.script.processing.shape.PrectMode;
import io.warp10.script.processing.shape.Pshape;
import io.warp10.script.processing.shape.PshapeMode;
import io.warp10.script.processing.shape.Psphere;
import io.warp10.script.processing.shape.PsphereDetail;
import io.warp10.script.processing.shape.PstrokeCap;
import io.warp10.script.processing.shape.PstrokeJoin;
import io.warp10.script.processing.shape.PstrokeWeight;
import io.warp10.script.processing.shape.Ptriangle;
import io.warp10.script.processing.shape.Pvertex;
import io.warp10.script.processing.structure.PpopStyle;
import io.warp10.script.processing.structure.PpushStyle;
import io.warp10.script.processing.transform.PpopMatrix;
import io.warp10.script.processing.transform.PpushMatrix;
import io.warp10.script.processing.transform.PresetMatrix;
import io.warp10.script.processing.transform.Protate;
import io.warp10.script.processing.transform.ProtateX;
import io.warp10.script.processing.transform.ProtateY;
import io.warp10.script.processing.transform.ProtateZ;
import io.warp10.script.processing.transform.Pscale;
import io.warp10.script.processing.transform.PshearX;
import io.warp10.script.processing.transform.PshearY;
import io.warp10.script.processing.transform.Ptranslate;
import io.warp10.script.processing.typography.PcreateFont;
import io.warp10.script.processing.typography.Ptext;
import io.warp10.script.processing.typography.PtextAlign;
import io.warp10.script.processing.typography.PtextAscent;
import io.warp10.script.processing.typography.PtextDescent;
import io.warp10.script.processing.typography.PtextFont;
import io.warp10.script.processing.typography.PtextLeading;
import io.warp10.script.processing.typography.PtextMode;
import io.warp10.script.processing.typography.PtextSize;
import io.warp10.script.processing.typography.PtextWidth;
import io.warp10.script.unary.ABS;
import io.warp10.script.unary.COMPLEMENT;
import io.warp10.script.unary.FROMBIN;
import io.warp10.script.unary.FROMBITS;
import io.warp10.script.unary.FROMHEX;
import io.warp10.script.unary.NOT;
import io.warp10.script.unary.REVERSEBITS;
import io.warp10.script.unary.TOBIN;
import io.warp10.script.unary.TOBITS;
import io.warp10.script.unary.TOBOOLEAN;
import io.warp10.script.unary.TODOUBLE;
import io.warp10.script.unary.TOHEX;
import io.warp10.script.unary.TOLONG;
import io.warp10.script.unary.TOSTRING;
import io.warp10.script.unary.TOTIMESTAMP;
import io.warp10.script.unary.UNIT;
import io.warp10.warp.sdk.WarpScriptExtension;
/**
* Library of functions used to manipulate Geo Time Series
* and more generally interact with a WarpScriptStack
*/
public class WarpScriptLib {
private static final Logger LOG = LoggerFactory.getLogger(WarpScriptLib.class);
private static Map<String,Object> functions = new HashMap<String, Object>();
private static Set<String> extloaded = new LinkedHashSet<String>();
/**
* Static definition of name so it can be reused outside of WarpScriptLib
*/
public static final String NULL = "NULL";
public static final String COUNTER = "COUNTER";
public static final String COUNTERSET = "COUNTERSET";
public static final String REF = "REF";
public static final String COMPILE = "COMPILE";
public static final String SAFECOMPILE = "SAFECOMPILE";
public static final String COMPILED = "COMPILED";
public static final String EVAL = "EVAL";
public static final String EVALSECURE = "EVALSECURE";
public static final String SNAPSHOT = "SNAPSHOT";
public static final String SNAPSHOTALL = "SNAPSHOTALL";
public static final String LOAD = "LOAD";
public static final String POPR = "POPR";
public static final String CPOPR = "CPOPR";
public static final String PUSHR = "PUSHR";
public static final String CLEARREGS = "CLEARREGS";
public static final String RUN = "RUN";
public static final String BOOTSTRAP = "BOOTSTRAP";
public static final String NOOP = "NOOP";
public static final String MAP_START = "{";
public static final String MAP_END = "}";
public static final String LIST_START = "[";
public static final String LIST_END = "]";
public static final String SET_START = "(";
public static final String SET_END = ")";
public static final String VECTOR_START = "[[";
public static final String VECTOR_END = "]]";
public static final String TO_VECTOR = "->V";
public static final String TO_SET = "->SET";
public static final String NEWGTS = "NEWGTS";
public static final String SWAP = "SWAP";
public static final String RELABEL = "RELABEL";
public static final String RENAME = "RENAME";
public static final String PARSESELECTOR = "PARSESELECTOR";
public static final String GEO_WKT = "GEO.WKT";
public static final String GEO_WKT_UNIFORM = "GEO.WKT.UNIFORM";
public static final String GEO_JSON = "GEO.JSON";
public static final String GEO_JSON_UNIFORM = "GEO.JSON.UNIFORM";
public static final String GEO_INTERSECTION = "GEO.INTERSECTION";
public static final String GEO_DIFFERENCE = "GEO.DIFFERENCE";
public static final String GEO_UNION = "GEO.UNION";
public static final String GEOPACK = "GEOPACK";
public static final String GEOUNPACK = "GEOUNPACK";
public static final String SECTION = "SECTION";
public static final String UNWRAP = "UNWRAP";
public static final String UNWRAPENCODER = "UNWRAPENCODER";
public static final String OPB64TO = "OPB64->";
public static final String TOOPB64 = "->OPB64";
public static final String BYTESTO = "BYTES->";
public static final String BYTESTOBITS = "BYTESTOBITS";
public static final String MARK = "MARK";
public static final String STORE = "STORE";
public static final String MAPPER_HIGHEST = "mapper.highest";
public static final String MAPPER_LOWEST = "mapper.lowest";
public static final String MAPPER_MAX = "mapper.max";
public static final String MAPPER_MIN = "mapper.min";
public static final String RSAPUBLIC = "RSAPUBLIC";
public static final String RSAPRIVATE = "RSAPRIVATE";
public static final String MSGFAIL = "MSGFAIL";
public static final String INPLACEADD = "+!";
public static final String PUT = "PUT";
public static final String SAVE = "SAVE";
public static final String RESTORE = "RESTORE";
public static final String CHRONOSTART = "CHRONOSTART";
public static final String CHRONOEND = "CHRONOEND";
public static final String TRY = "TRY";
public static final String RETHROW = "RETHROW";
static {
addNamedWarpScriptFunction(new REV("REV"));
addNamedWarpScriptFunction(new REPORT("REPORT"));
addNamedWarpScriptFunction(new MINREV("MINREV"));
addNamedWarpScriptFunction(new MANAGERONOFF("UPDATEON", WarpManager.UPDATE_DISABLED, true));
addNamedWarpScriptFunction(new MANAGERONOFF("UPDATEOFF", WarpManager.UPDATE_DISABLED, false));
addNamedWarpScriptFunction(new MANAGERONOFF("METAON", WarpManager.META_DISABLED, true));
addNamedWarpScriptFunction(new MANAGERONOFF("METAOFF", WarpManager.META_DISABLED, false));
addNamedWarpScriptFunction(new MANAGERONOFF("DELETEON", WarpManager.DELETE_DISABLED, true));
addNamedWarpScriptFunction(new MANAGERONOFF("DELETEOFF", WarpManager.DELETE_DISABLED, false));
addNamedWarpScriptFunction(new NOOP(BOOTSTRAP));
addNamedWarpScriptFunction(new RTFM("RTFM"));
addNamedWarpScriptFunction(new MAN("MAN"));
//
// Stack manipulation functions
//
addNamedWarpScriptFunction(new PIGSCHEMA("PIGSCHEMA"));
addNamedWarpScriptFunction(new MARK(MARK));
addNamedWarpScriptFunction(new CLEARTOMARK("CLEARTOMARK"));
addNamedWarpScriptFunction(new COUNTTOMARK("COUNTTOMARK"));
addNamedWarpScriptFunction(new AUTHENTICATE("AUTHENTICATE"));
addNamedWarpScriptFunction(new ISAUTHENTICATED("ISAUTHENTICATED"));
addNamedWarpScriptFunction(new STACKATTRIBUTE("STACKATTRIBUTE")); // NOT TO BE DOCUMENTED
addNamedWarpScriptFunction(new EXPORT("EXPORT"));
addNamedWarpScriptFunction(new TIMINGS("TIMINGS")); // NOT TO BE DOCUMENTED (YET)
addNamedWarpScriptFunction(new NOTIMINGS("NOTIMINGS")); // NOT TO BE DOCUMENTED (YET)
addNamedWarpScriptFunction(new ELAPSED("ELAPSED")); // NOT TO BE DOCUMENTED (YET)
addNamedWarpScriptFunction(new TIMED("TIMED"));
addNamedWarpScriptFunction(new CHRONOSTART(CHRONOSTART));
addNamedWarpScriptFunction(new CHRONOEND(CHRONOEND));
addNamedWarpScriptFunction(new CHRONOSTATS("CHRONOSTATS"));
addNamedWarpScriptFunction(new TOLIST("->LIST"));
addNamedWarpScriptFunction(new LISTTO("LIST->"));
addNamedWarpScriptFunction(new UNLIST("UNLIST"));
addNamedWarpScriptFunction(new TOSET(TO_SET));
addNamedWarpScriptFunction(new SETTO("SET->"));
addNamedWarpScriptFunction(new TOVECTOR(TO_VECTOR));
addNamedWarpScriptFunction(new VECTORTO("V->"));
addNamedWarpScriptFunction(new UNION("UNION"));
addNamedWarpScriptFunction(new INTERSECTION("INTERSECTION"));
addNamedWarpScriptFunction(new DIFFERENCE("DIFFERENCE"));
addNamedWarpScriptFunction(new TOMAP("->MAP"));
addNamedWarpScriptFunction(new MAPTO("MAP->"));
addNamedWarpScriptFunction(new UNMAP("UNMAP"));
addNamedWarpScriptFunction(new MAPID("MAPID"));
addNamedWarpScriptFunction(new TOJSON("->JSON"));
addNamedWarpScriptFunction(new JSONTO("JSON->"));
addNamedWarpScriptFunction(new TOPICKLE("->PICKLE"));
addNamedWarpScriptFunction(new PICKLETO("PICKLE->"));
addNamedWarpScriptFunction(new GET("GET"));
addNamedWarpScriptFunction(new SET("SET"));
addNamedWarpScriptFunction(new PUT(PUT));
addNamedWarpScriptFunction(new SUBMAP("SUBMAP"));
addNamedWarpScriptFunction(new SUBLIST("SUBLIST"));
addNamedWarpScriptFunction(new KEYLIST("KEYLIST"));
addNamedWarpScriptFunction(new VALUELIST("VALUELIST"));
addNamedWarpScriptFunction(new SIZE("SIZE"));
addNamedWarpScriptFunction(new SHRINK("SHRINK"));
addNamedWarpScriptFunction(new REMOVE("REMOVE"));
addNamedWarpScriptFunction(new UNIQUE("UNIQUE"));
addNamedWarpScriptFunction(new CONTAINS("CONTAINS"));
addNamedWarpScriptFunction(new CONTAINSKEY("CONTAINSKEY"));
addNamedWarpScriptFunction(new CONTAINSVALUE("CONTAINSVALUE"));
addNamedWarpScriptFunction(new REVERSE("REVERSE", true));
addNamedWarpScriptFunction(new REVERSE("CLONEREVERSE", false));
addNamedWarpScriptFunction(new DUP("DUP"));
addNamedWarpScriptFunction(new DUPN("DUPN"));
addNamedWarpScriptFunction(new SWAP(SWAP));
addNamedWarpScriptFunction(new DROP("DROP"));
addNamedWarpScriptFunction(new SAVE(SAVE));
addNamedWarpScriptFunction(new RESTORE(RESTORE));
addNamedWarpScriptFunction(new CLEAR("CLEAR"));
addNamedWarpScriptFunction(new CLEARDEFS("CLEARDEFS"));
addNamedWarpScriptFunction(new CLEARSYMBOLS("CLEARSYMBOLS"));
addNamedWarpScriptFunction(new DROPN("DROPN"));
addNamedWarpScriptFunction(new ROT("ROT"));
addNamedWarpScriptFunction(new ROLL("ROLL"));
addNamedWarpScriptFunction(new ROLLD("ROLLD"));
addNamedWarpScriptFunction(new PICK("PICK"));
addNamedWarpScriptFunction(new DEPTH("DEPTH"));
addNamedWarpScriptFunction(new MAXDEPTH("MAXDEPTH"));
addNamedWarpScriptFunction(new RESET("RESET"));
addNamedWarpScriptFunction(new MAXOPS("MAXOPS"));
addNamedWarpScriptFunction(new MAXLOOP("MAXLOOP"));
addNamedWarpScriptFunction(new MAXBUCKETS("MAXBUCKETS"));
addNamedWarpScriptFunction(new MAXGEOCELLS("MAXGEOCELLS"));
addNamedWarpScriptFunction(new MAXPIXELS("MAXPIXELS"));
addNamedWarpScriptFunction(new MAXRECURSION("MAXRECURSION"));
addNamedWarpScriptFunction(new OPS("OPS"));
addNamedWarpScriptFunction(new MAXSYMBOLS("MAXSYMBOLS"));
addNamedWarpScriptFunction(new EVAL(EVAL));
addNamedWarpScriptFunction(new NOW("NOW"));
addNamedWarpScriptFunction(new AGO("AGO"));
addNamedWarpScriptFunction(new MSTU("MSTU"));
addNamedWarpScriptFunction(new STU("STU"));
addNamedWarpScriptFunction(new APPEND("APPEND"));
addNamedWarpScriptFunction(new STORE(STORE));
addNamedWarpScriptFunction(new CSTORE("CSTORE"));
addNamedWarpScriptFunction(new LOAD(LOAD));
addNamedWarpScriptFunction(new IMPORT("IMPORT"));
addNamedWarpScriptFunction(new RUN(RUN));
addNamedWarpScriptFunction(new DEF("DEF"));
addNamedWarpScriptFunction(new UDF("UDF", false));
addNamedWarpScriptFunction(new UDF("CUDF", true));
addNamedWarpScriptFunction(new CALL("CALL"));
addNamedWarpScriptFunction(new FORGET("FORGET"));
addNamedWarpScriptFunction(new DEFINED("DEFINED"));
addNamedWarpScriptFunction(new REDEFS("REDEFS"));
addNamedWarpScriptFunction(new DEFINEDMACRO("DEFINEDMACRO"));
addNamedWarpScriptFunction(new DEFINEDMACRO("CHECKMACRO", true));
addNamedWarpScriptFunction(new NaN("NaN"));
addNamedWarpScriptFunction(new ISNaN("ISNaN"));
addNamedWarpScriptFunction(new TYPEOF("TYPEOF"));
addNamedWarpScriptFunction(new EXTLOADED("EXTLOADED"));
addNamedWarpScriptFunction(new ASSERT("ASSERT"));
addNamedWarpScriptFunction(new ASSERTMSG("ASSERTMSG"));
addNamedWarpScriptFunction(new FAIL("FAIL"));
addNamedWarpScriptFunction(new MSGFAIL(MSGFAIL));
addNamedWarpScriptFunction(new STOP("STOP"));
addNamedWarpScriptFunction(new TRY(TRY));
addNamedWarpScriptFunction(new RETHROW(RETHROW));
addNamedWarpScriptFunction(new ERROR("ERROR"));
addNamedWarpScriptFunction(new TIMEBOX("TIMEBOX"));
addNamedWarpScriptFunction(new JSONSTRICT("JSONSTRICT"));
addNamedWarpScriptFunction(new JSONLOOSE("JSONLOOSE"));
addNamedWarpScriptFunction(new DEBUGON("DEBUGON"));
addNamedWarpScriptFunction(new NDEBUGON("NDEBUGON"));
addNamedWarpScriptFunction(new DEBUGOFF("DEBUGOFF"));
addNamedWarpScriptFunction(new LINEON("LINEON"));
addNamedWarpScriptFunction(new LINEOFF("LINEOFF"));
addNamedWarpScriptFunction(new LMAP("LMAP"));
addNamedWarpScriptFunction(new NONNULL("NONNULL"));
addNamedWarpScriptFunction(new LFLATMAP("LFLATMAP"));
addNamedWarpScriptFunction(new EMPTYLIST("[]"));
addNamedWarpScriptFunction(new MARK(LIST_START));
addNamedWarpScriptFunction(new ENDLIST(LIST_END));
addNamedWarpScriptFunction(new STACKTOLIST("STACKTOLIST"));
addNamedWarpScriptFunction(new MARK(SET_START));
addNamedWarpScriptFunction(new ENDSET(SET_END));
addNamedWarpScriptFunction(new EMPTYSET("()"));
addNamedWarpScriptFunction(new MARK(VECTOR_START));
addNamedWarpScriptFunction(new ENDVECTOR(VECTOR_END));
addNamedWarpScriptFunction(new EMPTYVECTOR("[[]]"));
addNamedWarpScriptFunction(new EMPTYMAP("{}"));
addNamedWarpScriptFunction(new IMMUTABLE("IMMUTABLE"));
addNamedWarpScriptFunction(new MARK(MAP_START));
addNamedWarpScriptFunction(new ENDMAP(MAP_END));
addNamedWarpScriptFunction(new SECUREKEY("SECUREKEY"));
addNamedWarpScriptFunction(new SECURE("SECURE"));
addNamedWarpScriptFunction(new UNSECURE("UNSECURE", true));
addNamedWarpScriptFunction(new EVALSECURE(EVALSECURE));
addNamedWarpScriptFunction(new NOOP("NOOP"));
addNamedWarpScriptFunction(new DOC("DOC"));
addNamedWarpScriptFunction(new DOCMODE("DOCMODE"));
addNamedWarpScriptFunction(new INFO("INFO"));
addNamedWarpScriptFunction(new INFOMODE("INFOMODE"));
addNamedWarpScriptFunction(new SECTION(SECTION));
addNamedWarpScriptFunction(new GETSECTION("GETSECTION"));
addNamedWarpScriptFunction(new SNAPSHOT(SNAPSHOT, false, false, true, false));
addNamedWarpScriptFunction(new SNAPSHOT(SNAPSHOTALL, true, false, true, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTTOMARK", false, true, true, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTALLTOMARK", true, true, true, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPY", false, false, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYALL", true, false, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYTOMARK", false, true, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYALLTOMARK", true, true, false, false));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTN", false, false, true, true));
addNamedWarpScriptFunction(new SNAPSHOT("SNAPSHOTCOPYN", false, false, false, true));
addNamedWarpScriptFunction(new HEADER("HEADER"));
addNamedWarpScriptFunction(new ECHOON("ECHOON"));
addNamedWarpScriptFunction(new ECHOOFF("ECHOOFF"));
addNamedWarpScriptFunction(new JSONSTACK("JSONSTACK"));
addNamedWarpScriptFunction(new WSSTACK("WSSTACK"));
addNamedWarpScriptFunction(new PEEK("PEEK"));
addNamedWarpScriptFunction(new PEEKN("PEEKN"));
addNamedWarpScriptFunction(new NPEEK("NPEEK"));
addNamedWarpScriptFunction(new PSTACK("PSTACK"));
addNamedWarpScriptFunction(new TIMEON("TIMEON"));
addNamedWarpScriptFunction(new TIMEOFF("TIMEOFF"));
//
// Compilation related dummy functions
//
addNamedWarpScriptFunction(new FAIL(COMPILE, "Not supported"));
addNamedWarpScriptFunction(new NOOP(SAFECOMPILE));
addNamedWarpScriptFunction(new FAIL(COMPILED, "Not supported"));
addNamedWarpScriptFunction(new REF(REF));
addNamedWarpScriptFunction(new MACROTTL("MACROTTL"));
addNamedWarpScriptFunction(new WFON("WFON"));
addNamedWarpScriptFunction(new WFOFF("WFOFF"));
addNamedWarpScriptFunction(new SETMACROCONFIG("SETMACROCONFIG"));
addNamedWarpScriptFunction(new MACROCONFIGSECRET("MACROCONFIGSECRET"));
addNamedWarpScriptFunction(new MACROCONFIG("MACROCONFIG", false));
addNamedWarpScriptFunction(new MACROCONFIG("MACROCONFIGDEFAULT", true));
addNamedWarpScriptFunction(new MACROMAPPER("MACROMAPPER"));
addNamedWarpScriptFunction(new MACROMAPPER("MACROREDUCER"));
addNamedWarpScriptFunction(new MACROMAPPER("MACROBUCKETIZER"));
addNamedWarpScriptFunction(new MACROFILTER("MACROFILTER"));
addNamedWarpScriptFunction(new MACROFILLER("MACROFILLER"));
addNamedWarpScriptFunction(new STRICTMAPPER("STRICTMAPPER"));
addNamedWarpScriptFunction(new STRICTREDUCER("STRICTREDUCER"));
addNamedWarpScriptFunction(new PARSESELECTOR(PARSESELECTOR));
addNamedWarpScriptFunction(new TOSELECTOR("TOSELECTOR"));
addNamedWarpScriptFunction(new PARSE("PARSE"));
addNamedWarpScriptFunction(new SMARTPARSE("SMARTPARSE"));
// We do not expose DUMP, it might allocate too much memory
//addNamedWarpScriptFunction(new DUMP("DUMP"));
// Binary ops
addNamedWarpScriptFunction(new ADD("+"));
addNamedWarpScriptFunction(new INPLACEADD(INPLACEADD));
addNamedWarpScriptFunction(new SUB("-"));
addNamedWarpScriptFunction(new DIV("/"));
addNamedWarpScriptFunction(new MUL("*"));
addNamedWarpScriptFunction(new POW("**"));
addNamedWarpScriptFunction(new MOD("%"));
addNamedWarpScriptFunction(new EQ("=="));
addNamedWarpScriptFunction(new NE("!="));
addNamedWarpScriptFunction(new LT("<"));
addNamedWarpScriptFunction(new GT(">"));
addNamedWarpScriptFunction(new LE("<="));
addNamedWarpScriptFunction(new GE(">="));
addNamedWarpScriptFunction(new CondAND("&&"));
addNamedWarpScriptFunction(new CondAND("AND"));
addNamedWarpScriptFunction(new CondOR("||"));
addNamedWarpScriptFunction(new CondOR("OR"));
addNamedWarpScriptFunction(new BitwiseAND("&"));
addNamedWarpScriptFunction(new SHIFTRIGHT(">>", true));
addNamedWarpScriptFunction(new SHIFTRIGHT(">>>", false));
addNamedWarpScriptFunction(new SHIFTLEFT("<<"));
addNamedWarpScriptFunction(new BitwiseOR("|"));
addNamedWarpScriptFunction(new BitwiseXOR("^"));
addNamedWarpScriptFunction(new ALMOSTEQ("~="));
// Bitset ops
addNamedWarpScriptFunction(new BITGET("BITGET"));
addNamedWarpScriptFunction(new BITCOUNT("BITCOUNT"));
addNamedWarpScriptFunction(new BITSTOBYTES("BITSTOBYTES"));
addNamedWarpScriptFunction(new BYTESTOBITS("BYTESTOBITS"));
// Unary ops
addNamedWarpScriptFunction(new NOT("!"));
addNamedWarpScriptFunction(new COMPLEMENT("~"));
addNamedWarpScriptFunction(new REVERSEBITS("REVBITS"));
addNamedWarpScriptFunction(new NOT("NOT"));
addNamedWarpScriptFunction(new ABS("ABS"));
addNamedWarpScriptFunction(new TODOUBLE("TODOUBLE"));
addNamedWarpScriptFunction(new TOBOOLEAN("TOBOOLEAN"));
addNamedWarpScriptFunction(new TOLONG("TOLONG"));
addNamedWarpScriptFunction(new TOSTRING("TOSTRING"));
addNamedWarpScriptFunction(new TOHEX("TOHEX"));
addNamedWarpScriptFunction(new TOBIN("TOBIN"));
addNamedWarpScriptFunction(new FROMHEX("FROMHEX"));
addNamedWarpScriptFunction(new FROMBIN("FROMBIN"));
addNamedWarpScriptFunction(new TOBITS("TOBITS", false));
addNamedWarpScriptFunction(new FROMBITS("FROMBITS", false));
addNamedWarpScriptFunction(new TOLONGBYTES("->LONGBYTES"));
addNamedWarpScriptFunction(new TOBITS("->DOUBLEBITS", false));
addNamedWarpScriptFunction(new FROMBITS("DOUBLEBITS->", false));
addNamedWarpScriptFunction(new TOBITS("->FLOATBITS", true));
addNamedWarpScriptFunction(new FROMBITS("FLOATBITS->", true));
addNamedWarpScriptFunction(new TOKENINFO("TOKENINFO"));
addNamedWarpScriptFunction(new GETHOOK("GETHOOK"));
// Unit converters
addNamedWarpScriptFunction(new UNIT("w", 7 * 24 * 60 * 60 * 1000));
addNamedWarpScriptFunction(new UNIT("d", 24 * 60 * 60 * 1000));
addNamedWarpScriptFunction(new UNIT("h", 60 * 60 * 1000));
addNamedWarpScriptFunction(new UNIT("m", 60 * 1000));
addNamedWarpScriptFunction(new UNIT("s", 1000));
addNamedWarpScriptFunction(new UNIT("ms", 1));
addNamedWarpScriptFunction(new UNIT("us", 0.001));
addNamedWarpScriptFunction(new UNIT("ns", 0.000001));
addNamedWarpScriptFunction(new UNIT("ps", 0.000000001));
// Crypto functions
addNamedWarpScriptFunction(new HASH("HASH"));
addNamedWarpScriptFunction(new DIGEST("MD5", MD5Digest.class));
addNamedWarpScriptFunction(new DIGEST("SHA1", SHA1Digest.class));
addNamedWarpScriptFunction(new DIGEST("SHA256", SHA256Digest.class));
addNamedWarpScriptFunction(new HMAC("SHA256HMAC", SHA256Digest.class));
addNamedWarpScriptFunction(new HMAC("SHA1HMAC", SHA1Digest.class));
addNamedWarpScriptFunction(new AESWRAP("AESWRAP"));
addNamedWarpScriptFunction(new AESUNWRAP("AESUNWRAP"));
addNamedWarpScriptFunction(new RUNNERNONCE("RUNNERNONCE"));
addNamedWarpScriptFunction(new GZIP("GZIP"));
addNamedWarpScriptFunction(new UNGZIP("UNGZIP"));
addNamedWarpScriptFunction(new DEFLATE("DEFLATE"));
addNamedWarpScriptFunction(new INFLATE("INFLATE"));
addNamedWarpScriptFunction(new RSAGEN("RSAGEN"));
addNamedWarpScriptFunction(new RSAPUBLIC(RSAPUBLIC));
addNamedWarpScriptFunction(new RSAPRIVATE(RSAPRIVATE));
addNamedWarpScriptFunction(new RSAENCRYPT("RSAENCRYPT"));
addNamedWarpScriptFunction(new RSADECRYPT("RSADECRYPT"));
addNamedWarpScriptFunction(new RSASIGN("RSASIGN"));
addNamedWarpScriptFunction(new RSAVERIFY("RSAVERIFY"));
//
// String functions
//
addNamedWarpScriptFunction(new URLDECODE("URLDECODE"));
addNamedWarpScriptFunction(new URLENCODE("URLENCODE"));
addNamedWarpScriptFunction(new SPLIT("SPLIT"));
addNamedWarpScriptFunction(new UUID("UUID"));
addNamedWarpScriptFunction(new JOIN("JOIN"));
addNamedWarpScriptFunction(new SUBSTRING("SUBSTRING"));
addNamedWarpScriptFunction(new TOUPPER("TOUPPER"));
addNamedWarpScriptFunction(new TOLOWER("TOLOWER"));
addNamedWarpScriptFunction(new TRIM("TRIM"));
addNamedWarpScriptFunction(new B64TOHEX("B64TOHEX"));
addNamedWarpScriptFunction(new HEXTOB64("HEXTOB64"));
addNamedWarpScriptFunction(new BINTOHEX("BINTOHEX"));
addNamedWarpScriptFunction(new HEXTOBIN("HEXTOBIN"));
addNamedWarpScriptFunction(new BINTO("BIN->"));
addNamedWarpScriptFunction(new HEXTO("HEX->"));
addNamedWarpScriptFunction(new B64TO("B64->"));
addNamedWarpScriptFunction(new B64URLTO("B64URL->"));
addNamedWarpScriptFunction(new BYTESTO(BYTESTO));
addNamedWarpScriptFunction(new TOBYTES("->BYTES"));
addNamedWarpScriptFunction(new io.warp10.script.functions.TOBIN("->BIN"));
addNamedWarpScriptFunction(new io.warp10.script.functions.TOHEX("->HEX"));
addNamedWarpScriptFunction(new TOB64("->B64"));
addNamedWarpScriptFunction(new TOB64URL("->B64URL"));
addNamedWarpScriptFunction(new TOOPB64(TOOPB64));
addNamedWarpScriptFunction(new OPB64TO(OPB64TO));
addNamedWarpScriptFunction(new OPB64TOHEX("OPB64TOHEX"));
//
// Conditionals
//
addNamedWarpScriptFunction(new IFT("IFT"));
addNamedWarpScriptFunction(new IFTE("IFTE"));
addNamedWarpScriptFunction(new SWITCH("SWITCH"));
//
// Loops
//
addNamedWarpScriptFunction(new WHILE("WHILE"));
addNamedWarpScriptFunction(new UNTIL("UNTIL"));
addNamedWarpScriptFunction(new FOR("FOR"));
addNamedWarpScriptFunction(new FORSTEP("FORSTEP"));
addNamedWarpScriptFunction(new FOREACH("FOREACH"));
addNamedWarpScriptFunction(new BREAK("BREAK"));
addNamedWarpScriptFunction(new CONTINUE("CONTINUE"));
addNamedWarpScriptFunction(new EVERY("EVERY"));
addNamedWarpScriptFunction(new RANGE("RANGE"));
//
// Macro end
//
addNamedWarpScriptFunction(new RETURN("RETURN"));
addNamedWarpScriptFunction(new NRETURN("NRETURN"));
//
// GTS standalone functions
//
addNamedWarpScriptFunction(new NEWENCODER("NEWENCODER"));
addNamedWarpScriptFunction(new CHUNKENCODER("CHUNKENCODER", true));
addNamedWarpScriptFunction(new TOENCODER("->ENCODER"));
addNamedWarpScriptFunction(new ENCODERTO("ENCODER->"));
addNamedWarpScriptFunction(new TOGTS("->GTS"));
addNamedWarpScriptFunction(new OPTIMIZE("OPTIMIZE"));
addNamedWarpScriptFunction(new NEWGTS(NEWGTS));
addNamedWarpScriptFunction(new MAKEGTS("MAKEGTS"));
addNamedWarpScriptFunction(new ADDVALUE("ADDVALUE", false));
addNamedWarpScriptFunction(new ADDVALUE("SETVALUE", true));
addNamedWarpScriptFunction(new REMOVETICK("REMOVETICK"));
addNamedWarpScriptFunction(new FETCH("FETCH", false, null));
addNamedWarpScriptFunction(new FETCH("FETCHLONG", false, TYPE.LONG));
addNamedWarpScriptFunction(new FETCH("FETCHDOUBLE", false, TYPE.DOUBLE));
addNamedWarpScriptFunction(new FETCH("FETCHSTRING", false, TYPE.STRING));
addNamedWarpScriptFunction(new FETCH("FETCHBOOLEAN", false, TYPE.BOOLEAN));
addNamedWarpScriptFunction(new LIMIT("LIMIT"));
addNamedWarpScriptFunction(new MAXGTS("MAXGTS"));
addNamedWarpScriptFunction(new FIND("FIND", false));
addNamedWarpScriptFunction(new FIND("FINDSETS", true));
addNamedWarpScriptFunction(new FIND("METASET", false, true));
addNamedWarpScriptFunction(new FINDSTATS("FINDSTATS"));
addNamedWarpScriptFunction(new DEDUP("DEDUP"));
addNamedWarpScriptFunction(new ONLYBUCKETS("ONLYBUCKETS"));
addNamedWarpScriptFunction(new VALUEDEDUP("VALUEDEDUP"));
addNamedWarpScriptFunction(new CLONEEMPTY("CLONEEMPTY"));
addNamedWarpScriptFunction(new COMPACT("COMPACT"));
addNamedWarpScriptFunction(new RANGECOMPACT("RANGECOMPACT"));
addNamedWarpScriptFunction(new STANDARDIZE("STANDARDIZE"));
addNamedWarpScriptFunction(new NORMALIZE("NORMALIZE"));
addNamedWarpScriptFunction(new ISONORMALIZE("ISONORMALIZE"));
addNamedWarpScriptFunction(new ZSCORE("ZSCORE"));
addNamedWarpScriptFunction(new FILL("FILL"));
addNamedWarpScriptFunction(new FILLPREVIOUS("FILLPREVIOUS"));
addNamedWarpScriptFunction(new FILLNEXT("FILLNEXT"));
addNamedWarpScriptFunction(new FILLVALUE("FILLVALUE"));
addNamedWarpScriptFunction(new FILLTICKS("FILLTICKS"));
addNamedWarpScriptFunction(new INTERPOLATE("INTERPOLATE"));
addNamedWarpScriptFunction(new FIRSTTICK("FIRSTTICK"));
addNamedWarpScriptFunction(new LASTTICK("LASTTICK"));
addNamedWarpScriptFunction(new MERGE("MERGE"));
addNamedWarpScriptFunction(new RESETS("RESETS"));
addNamedWarpScriptFunction(new MONOTONIC("MONOTONIC"));
addNamedWarpScriptFunction(new TIMESPLIT("TIMESPLIT"));
addNamedWarpScriptFunction(new TIMECLIP("TIMECLIP"));
addNamedWarpScriptFunction(new CLIP("CLIP"));
addNamedWarpScriptFunction(new TIMEMODULO("TIMEMODULO"));
addNamedWarpScriptFunction(new CHUNK("CHUNK", true));
addNamedWarpScriptFunction(new FUSE("FUSE"));
addNamedWarpScriptFunction(new RENAME(RENAME));
addNamedWarpScriptFunction(new RELABEL(RELABEL));
addNamedWarpScriptFunction(new SETATTRIBUTES("SETATTRIBUTES"));
addNamedWarpScriptFunction(new CROP("CROP"));
addNamedWarpScriptFunction(new TIMESHIFT("TIMESHIFT"));
addNamedWarpScriptFunction(new TIMESCALE("TIMESCALE"));
addNamedWarpScriptFunction(new TICKINDEX("TICKINDEX"));
addNamedWarpScriptFunction(new FFT.Builder("FFT", true));
addNamedWarpScriptFunction(new FFT.Builder("FFTAP", false));
addNamedWarpScriptFunction(new IFFT.Builder("IFFT"));
addNamedWarpScriptFunction(new FFTWINDOW("FFTWINDOW"));
addNamedWarpScriptFunction(new FDWT("FDWT"));
addNamedWarpScriptFunction(new IDWT("IDWT"));
addNamedWarpScriptFunction(new DWTSPLIT("DWTSPLIT"));
addNamedWarpScriptFunction(new EMPTY("EMPTY"));
addNamedWarpScriptFunction(new NONEMPTY("NONEMPTY"));
addNamedWarpScriptFunction(new PARTITION("PARTITION"));
addNamedWarpScriptFunction(new PARTITION("STRICTPARTITION", true));
addNamedWarpScriptFunction(new ZIP("ZIP"));
addNamedWarpScriptFunction(new PATTERNS("PATTERNS", true));
addNamedWarpScriptFunction(new PATTERNDETECTION("PATTERNDETECTION", true));
addNamedWarpScriptFunction(new PATTERNS("ZPATTERNS", false));
addNamedWarpScriptFunction(new PATTERNDETECTION("ZPATTERNDETECTION", false));
addNamedWarpScriptFunction(new DTW("DTW", true, false));
addNamedWarpScriptFunction(new OPTDTW("OPTDTW"));
addNamedWarpScriptFunction(new DTW("ZDTW", true, true));
addNamedWarpScriptFunction(new DTW("RAWDTW", false, false));
addNamedWarpScriptFunction(new VALUEHISTOGRAM("VALUEHISTOGRAM"));
addNamedWarpScriptFunction(new PROBABILITY.Builder("PROBABILITY"));
addNamedWarpScriptFunction(new PROB("PROB"));
addNamedWarpScriptFunction(new CPROB("CPROB"));
addNamedWarpScriptFunction(new RANDPDF.Builder("RANDPDF"));
addNamedWarpScriptFunction(new SINGLEEXPONENTIALSMOOTHING("SINGLEEXPONENTIALSMOOTHING"));
addNamedWarpScriptFunction(new DOUBLEEXPONENTIALSMOOTHING("DOUBLEEXPONENTIALSMOOTHING"));
addNamedWarpScriptFunction(new LOWESS("LOWESS"));
addNamedWarpScriptFunction(new RLOWESS("RLOWESS"));
addNamedWarpScriptFunction(new STL("STL"));
addNamedWarpScriptFunction(new LTTB("LTTB", false));
addNamedWarpScriptFunction(new LTTB("TLTTB", true));
addNamedWarpScriptFunction(new LOCATIONOFFSET("LOCATIONOFFSET"));
addNamedWarpScriptFunction(new FLATTEN("FLATTEN"));
addNamedWarpScriptFunction(new RESHAPE("RESHAPE"));
addNamedWarpScriptFunction(new CHECKSHAPE("CHECKSHAPE"));
addNamedWarpScriptFunction(new SHAPE("SHAPE"));
addNamedWarpScriptFunction(new HULLSHAPE("HULLSHAPE"));
addNamedWarpScriptFunction(new CORRELATE.Builder("CORRELATE"));
addNamedWarpScriptFunction(new SORT("SORT"));
addNamedWarpScriptFunction(new SORTBY("SORTBY"));
addNamedWarpScriptFunction(new RSORT("RSORT"));
addNamedWarpScriptFunction(new LASTSORT("LASTSORT"));
addNamedWarpScriptFunction(new METASORT("METASORT"));
addNamedWarpScriptFunction(new VALUESORT("VALUESORT"));
addNamedWarpScriptFunction(new RVALUESORT("RVALUESORT"));
addNamedWarpScriptFunction(new LSORT("LSORT"));
addNamedWarpScriptFunction(new SHUFFLE("SHUFFLE"));
addNamedWarpScriptFunction(new MSORT("MSORT"));
addNamedWarpScriptFunction(new GROUPBY("GROUPBY"));
addNamedWarpScriptFunction(new FILTERBY("FILTERBY"));
addNamedWarpScriptFunction(new UPDATE("UPDATE"));
addNamedWarpScriptFunction(new META("META"));
addNamedWarpScriptFunction(new DELETE("DELETE"));
addNamedWarpScriptFunction(new WEBCALL("WEBCALL"));
addNamedWarpScriptFunction(new MATCH("MATCH"));
addNamedWarpScriptFunction(new MATCHER("MATCHER"));
addNamedWarpScriptFunction(new REPLACE("REPLACE", false));
addNamedWarpScriptFunction(new REPLACE("REPLACEALL", true));
addNamedWarpScriptFunction(new REOPTALT("REOPTALT"));
if (SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8)) {
addNamedWarpScriptFunction(new TEMPLATE("TEMPLATE"));
addNamedWarpScriptFunction(new TOTIMESTAMP("TOTIMESTAMP"));
} else {
addNamedWarpScriptFunction(new FAIL("TEMPLATE", "Requires JAVA 1.8+"));
addNamedWarpScriptFunction(new FAIL("TOTIMESTAMP", "Requires JAVA 1.8+"));
}
addNamedWarpScriptFunction(new DISCORDS("DISCORDS", true));
addNamedWarpScriptFunction(new DISCORDS("ZDISCORDS", false));
addNamedWarpScriptFunction(new INTEGRATE("INTEGRATE"));
addNamedWarpScriptFunction(new BUCKETSPAN("BUCKETSPAN"));
addNamedWarpScriptFunction(new BUCKETCOUNT("BUCKETCOUNT"));
addNamedWarpScriptFunction(new UNBUCKETIZE("UNBUCKETIZE"));
addNamedWarpScriptFunction(new LASTBUCKET("LASTBUCKET"));
addNamedWarpScriptFunction(new NAME("NAME"));
addNamedWarpScriptFunction(new LABELS("LABELS"));
addNamedWarpScriptFunction(new ATTRIBUTES("ATTRIBUTES"));
addNamedWarpScriptFunction(new LASTACTIVITY("LASTACTIVITY"));
addNamedWarpScriptFunction(new TICKS("TICKS"));
addNamedWarpScriptFunction(new LOCATIONS("LOCATIONS"));
addNamedWarpScriptFunction(new LOCSTRINGS("LOCSTRINGS"));
addNamedWarpScriptFunction(new ELEVATIONS("ELEVATIONS"));
addNamedWarpScriptFunction(new VALUES("VALUES"));
addNamedWarpScriptFunction(new VALUESPLIT("VALUESPLIT"));
addNamedWarpScriptFunction(new TICKLIST("TICKLIST"));
addNamedWarpScriptFunction(new COMMONTICKS("COMMONTICKS"));
addNamedWarpScriptFunction(new WRAP("WRAP"));
addNamedWarpScriptFunction(new WRAPRAW("WRAPRAW"));
addNamedWarpScriptFunction(new WRAPRAW("WRAPFAST", false, false));
addNamedWarpScriptFunction(new WRAP("WRAPOPT", true));
addNamedWarpScriptFunction(new WRAPRAW("WRAPRAWOPT", true));
addNamedWarpScriptFunction(new UNWRAP(UNWRAP));
addNamedWarpScriptFunction(new UNWRAP("UNWRAPEMPTY", true));
addNamedWarpScriptFunction(new UNWRAPSIZE("UNWRAPSIZE"));
addNamedWarpScriptFunction(new UNWRAPENCODER(UNWRAPENCODER));
//
// Outlier detection
//
addNamedWarpScriptFunction(new THRESHOLDTEST("THRESHOLDTEST"));
addNamedWarpScriptFunction(new ZSCORETEST("ZSCORETEST"));
addNamedWarpScriptFunction(new GRUBBSTEST("GRUBBSTEST"));
addNamedWarpScriptFunction(new ESDTEST("ESDTEST"));
addNamedWarpScriptFunction(new STLESDTEST("STLESDTEST"));
addNamedWarpScriptFunction(new HYBRIDTEST("HYBRIDTEST"));
addNamedWarpScriptFunction(new HYBRIDTEST2("HYBRIDTEST2"));
//
// Quaternion related functions
//
addNamedWarpScriptFunction(new TOQUATERNION("->Q"));
addNamedWarpScriptFunction(new QUATERNIONTO("Q->"));
addNamedWarpScriptFunction(new QCONJUGATE("QCONJUGATE"));
addNamedWarpScriptFunction(new QDIVIDE("QDIVIDE"));
addNamedWarpScriptFunction(new QMULTIPLY("QMULTIPLY"));
addNamedWarpScriptFunction(new QROTATE("QROTATE"));
addNamedWarpScriptFunction(new QROTATION("QROTATION"));
addNamedWarpScriptFunction(new ROTATIONQ("ROTATIONQ"));
addNamedWarpScriptFunction(new ATINDEX("ATINDEX"));
addNamedWarpScriptFunction(new ATTICK("ATTICK"));
addNamedWarpScriptFunction(new ATBUCKET("ATBUCKET"));
addNamedWarpScriptFunction(new CLONE("CLONE"));
addNamedWarpScriptFunction(new DURATION("DURATION"));
addNamedWarpScriptFunction(new HUMANDURATION("HUMANDURATION"));
addNamedWarpScriptFunction(new ISODURATION("ISODURATION"));
addNamedWarpScriptFunction(new ISO8601("ISO8601"));
addNamedWarpScriptFunction(new NOTBEFORE("NOTBEFORE"));
addNamedWarpScriptFunction(new NOTAFTER("NOTAFTER"));
addNamedWarpScriptFunction(new TSELEMENTS("TSELEMENTS"));
addNamedWarpScriptFunction(new TSELEMENTS("->TSELEMENTS"));
addNamedWarpScriptFunction(new FROMTSELEMENTS("TSELEMENTS->"));
addNamedWarpScriptFunction(new ADDDAYS("ADDDAYS"));
addNamedWarpScriptFunction(new ADDMONTHS("ADDMONTHS"));
addNamedWarpScriptFunction(new ADDYEARS("ADDYEARS"));
addNamedWarpScriptFunction(new QUANTIZE("QUANTIZE"));
addNamedWarpScriptFunction(new NBOUNDS("NBOUNDS"));
addNamedWarpScriptFunction(new LBOUNDS("LBOUNDS"));
//NFIRST -> Retain at most the N first values
//NLAST -> Retain at most the N last values
//
// GTS manipulation frameworks
//
addNamedWarpScriptFunction(new BUCKETIZE("BUCKETIZE"));
addNamedWarpScriptFunction(new MAP("MAP"));
addNamedWarpScriptFunction(new FILTER("FILTER", true));
addNamedWarpScriptFunction(new APPLY("APPLY", true));
addNamedWarpScriptFunction(new FILTER("PFILTER", false));
addNamedWarpScriptFunction(new APPLY("PAPPLY", false));
addNamedWarpScriptFunction(new REDUCE("REDUCE", true));
addNamedWarpScriptFunction(new REDUCE("PREDUCE", false));
addNamedWarpScriptFunction(new MaxTickSlidingWindow("max.tick.sliding.window"));
addNamedWarpScriptFunction(new MaxTimeSlidingWindow("max.time.sliding.window"));
addNamedWarpScriptFunction(new NULL(NULL));
addNamedWarpScriptFunction(new ISNULL("ISNULL"));
addNamedWarpScriptFunction(new MapperReplace.Builder("mapper.replace"));
addNamedWarpScriptFunction(new MAPPERGT("mapper.gt"));
addNamedWarpScriptFunction(new MAPPERGE("mapper.ge"));
addNamedWarpScriptFunction(new MAPPEREQ("mapper.eq"));
addNamedWarpScriptFunction(new MAPPERNE("mapper.ne"));
addNamedWarpScriptFunction(new MAPPERLE("mapper.le"));
addNamedWarpScriptFunction(new MAPPERLT("mapper.lt"));
addNamedWarpScriptFunction(new MapperAdd.Builder("mapper.add"));
addNamedWarpScriptFunction(new MapperMul.Builder("mapper.mul"));
addNamedWarpScriptFunction(new MapperPow.Builder("mapper.pow"));
try {
addNamedWarpScriptFunction(new MapperPow("mapper.sqrt", 0.5D));
} catch (WarpScriptException wse) {
throw new RuntimeException(wse);
}
addNamedWarpScriptFunction(new MapperExp.Builder("mapper.exp"));
addNamedWarpScriptFunction(new MapperLog.Builder("mapper.log"));
addNamedWarpScriptFunction(new MapperMinX.Builder("mapper.min.x"));
addNamedWarpScriptFunction(new MapperMaxX.Builder("mapper.max.x"));
addNamedWarpScriptFunction(new MapperParseDouble.Builder("mapper.parsedouble"));
addNamedWarpScriptFunction(new MapperTick.Builder("mapper.tick"));
addNamedWarpScriptFunction(new MapperYear.Builder("mapper.year"));
addNamedWarpScriptFunction(new MapperMonthOfYear.Builder("mapper.month"));
addNamedWarpScriptFunction(new MapperDayOfMonth.Builder("mapper.day"));
addNamedWarpScriptFunction(new MapperDayOfWeek.Builder("mapper.weekday"));
addNamedWarpScriptFunction(new MapperHourOfDay.Builder("mapper.hour"));
addNamedWarpScriptFunction(new MapperMinuteOfHour.Builder("mapper.minute"));
addNamedWarpScriptFunction(new MapperSecondOfMinute.Builder("mapper.second"));
addNamedWarpScriptFunction(new MapperNPDF.Builder("mapper.npdf"));
addNamedWarpScriptFunction(new MapperDotProduct.Builder("mapper.dotproduct"));
addNamedWarpScriptFunction(new MapperDotProductTanh.Builder("mapper.dotproduct.tanh"));
addNamedWarpScriptFunction(new MapperDotProductSigmoid.Builder("mapper.dotproduct.sigmoid"));
addNamedWarpScriptFunction(new MapperDotProductPositive.Builder("mapper.dotproduct.positive"));
// Kernel mappers
addNamedWarpScriptFunction(new MapperKernelCosine("mapper.kernel.cosine"));
addNamedWarpScriptFunction(new MapperKernelEpanechnikov("mapper.kernel.epanechnikov"));
addNamedWarpScriptFunction(new MapperKernelGaussian("mapper.kernel.gaussian"));
addNamedWarpScriptFunction(new MapperKernelLogistic("mapper.kernel.logistic"));
addNamedWarpScriptFunction(new MapperKernelQuartic("mapper.kernel.quartic"));
addNamedWarpScriptFunction(new MapperKernelSilverman("mapper.kernel.silverman"));
addNamedWarpScriptFunction(new MapperKernelTriangular("mapper.kernel.triangular"));
addNamedWarpScriptFunction(new MapperKernelTricube("mapper.kernel.tricube"));
addNamedWarpScriptFunction(new MapperKernelTriweight("mapper.kernel.triweight"));
addNamedWarpScriptFunction(new MapperKernelUniform("mapper.kernel.uniform"));
addNamedWarpScriptFunction(new Percentile.Builder("mapper.percentile"));
//functions.put("mapper.abscissa", new MapperSAX.Builder());
addNamedWarpScriptFunction(new FilterByClass.Builder("filter.byclass"));
addNamedWarpScriptFunction(new FilterByLabels.Builder("filter.bylabels", true, false));
addNamedWarpScriptFunction(new FilterByLabels.Builder("filter.byattr", false, true));
addNamedWarpScriptFunction(new FilterByLabels.Builder("filter.bylabelsattr", true, true));
addNamedWarpScriptFunction(new FilterByMetadata.Builder("filter.bymetadata"));
addNamedWarpScriptFunction(new FilterLastEQ.Builder("filter.last.eq"));
addNamedWarpScriptFunction(new FilterLastGE.Builder("filter.last.ge"));
addNamedWarpScriptFunction(new FilterLastGT.Builder("filter.last.gt"));
addNamedWarpScriptFunction(new FilterLastLE.Builder("filter.last.le"));
addNamedWarpScriptFunction(new FilterLastLT.Builder("filter.last.lt"));
addNamedWarpScriptFunction(new FilterLastNE.Builder("filter.last.ne"));
addNamedWarpScriptFunction(new LatencyFilter.Builder("filter.latencies"));
//
// Fillers
//
addNamedWarpScriptFunction(new FillerNext("filler.next"));
addNamedWarpScriptFunction(new FillerPrevious("filler.previous"));
addNamedWarpScriptFunction(new FillerInterpolate("filler.interpolate"));
addNamedWarpScriptFunction(new FillerTrend("filler.trend"));
//
// Geo Manipulation functions
//
addNamedWarpScriptFunction(new TOHHCODE("->HHCODE", true));
addNamedWarpScriptFunction(new TOHHCODE("->HHCODELONG", false));
addNamedWarpScriptFunction(new HHCODETO("HHCODE->"));
addNamedWarpScriptFunction(new GEOREGEXP("GEO.REGEXP"));
addNamedWarpScriptFunction(new GeoWKT(GEO_WKT, false));
addNamedWarpScriptFunction(new GeoWKT(GEO_WKT_UNIFORM, true));
addNamedWarpScriptFunction(new GeoJSON(GEO_JSON, false));
addNamedWarpScriptFunction(new GeoJSON(GEO_JSON_UNIFORM, true));
addNamedWarpScriptFunction(new GEOOPTIMIZE("GEO.OPTIMIZE"));
addNamedWarpScriptFunction(new GeoIntersection(GEO_INTERSECTION));
addNamedWarpScriptFunction(new GeoUnion(GEO_UNION));
addNamedWarpScriptFunction(new GeoSubtraction(GEO_DIFFERENCE));
addNamedWarpScriptFunction(new GEOWITHIN("GEO.WITHIN"));
addNamedWarpScriptFunction(new GEOINTERSECTS("GEO.INTERSECTS"));
addNamedWarpScriptFunction(new HAVERSINE("HAVERSINE"));
addNamedWarpScriptFunction(new GEOPACK(GEOPACK));
addNamedWarpScriptFunction(new GEOUNPACK(GEOUNPACK));
addNamedWarpScriptFunction(new MapperGeoWithin.Builder("mapper.geo.within"));
addNamedWarpScriptFunction(new MapperGeoOutside.Builder("mapper.geo.outside"));
addNamedWarpScriptFunction(new MapperGeoApproximate.Builder("mapper.geo.approximate"));
addNamedWarpScriptFunction(new COPYGEO("COPYGEO"));
addNamedWarpScriptFunction(new BBOX("BBOX"));
addNamedWarpScriptFunction(new TOGEOHASH("->GEOHASH"));
addNamedWarpScriptFunction(new GEOHASHTO("GEOHASH->"));
//
// Counters
//
addNamedWarpScriptFunction(new COUNTER(COUNTER));
addNamedWarpScriptFunction(new COUNTERVALUE("COUNTERVALUE"));
addNamedWarpScriptFunction(new COUNTERDELTA("COUNTERDELTA"));
addNamedWarpScriptFunction(new COUNTERSET(COUNTERSET));
//
// Math functions
//
addNamedWarpScriptFunction(new Pi("pi"));
addNamedWarpScriptFunction(new Pi("PI"));
addNamedWarpScriptFunction(new E("e"));
addNamedWarpScriptFunction(new E("E"));
addNamedWarpScriptFunction(new MINLONG("MINLONG"));
addNamedWarpScriptFunction(new MAXLONG("MAXLONG"));
addNamedWarpScriptFunction(new RAND("RAND"));
addNamedWarpScriptFunction(new PRNG("PRNG"));
addNamedWarpScriptFunction(new SRAND("SRAND"));
addNamedWarpScriptFunction(new NPDF.Builder("NPDF"));
addNamedWarpScriptFunction(new MUSIGMA("MUSIGMA"));
addNamedWarpScriptFunction(new KURTOSIS("KURTOSIS"));
addNamedWarpScriptFunction(new SKEWNESS("SKEWNESS"));
addNamedWarpScriptFunction(new NSUMSUMSQ("NSUMSUMSQ"));
addNamedWarpScriptFunction(new LR("LR"));
addNamedWarpScriptFunction(new MODE("MODE"));
addNamedWarpScriptFunction(new TOZ("->Z"));
addNamedWarpScriptFunction(new ZTO("Z->"));
addNamedWarpScriptFunction(new PACK("PACK"));
addNamedWarpScriptFunction(new UNPACK("UNPACK"));
//
// Linear Algebra
//
addNamedWarpScriptFunction(new TOMAT("->MAT"));
addNamedWarpScriptFunction(new MATTO("MAT->"));
addNamedWarpScriptFunction(new TR("TR"));
addNamedWarpScriptFunction(new TRANSPOSE("TRANSPOSE"));
addNamedWarpScriptFunction(new DET("DET"));
addNamedWarpScriptFunction(new INV("INV"));
addNamedWarpScriptFunction(new TOVEC("->VEC"));
addNamedWarpScriptFunction(new VECTO("VEC->"));
addNamedWarpScriptFunction(new COS("COS"));
addNamedWarpScriptFunction(new COSH("COSH"));
addNamedWarpScriptFunction(new ACOS("ACOS"));
addNamedWarpScriptFunction(new SIN("SIN"));
addNamedWarpScriptFunction(new SINH("SINH"));
addNamedWarpScriptFunction(new ASIN("ASIN"));
addNamedWarpScriptFunction(new TAN("TAN"));
addNamedWarpScriptFunction(new TANH("TANH"));
addNamedWarpScriptFunction(new ATAN("ATAN"));
addNamedWarpScriptFunction(new SIGNUM("SIGNUM"));
addNamedWarpScriptFunction(new FLOOR("FLOOR"));
addNamedWarpScriptFunction(new CEIL("CEIL"));
addNamedWarpScriptFunction(new ROUND("ROUND"));
addNamedWarpScriptFunction(new RINT("RINT"));
addNamedWarpScriptFunction(new NEXTUP("NEXTUP"));
addNamedWarpScriptFunction(new ULP("ULP"));
addNamedWarpScriptFunction(new SQRT("SQRT"));
addNamedWarpScriptFunction(new CBRT("CBRT"));
addNamedWarpScriptFunction(new EXP("EXP"));
addNamedWarpScriptFunction(new EXPM1("EXPM1"));
addNamedWarpScriptFunction(new LOG("LOG"));
addNamedWarpScriptFunction(new LOG10("LOG10"));
addNamedWarpScriptFunction(new LOG1P("LOG1P"));
addNamedWarpScriptFunction(new TORADIANS("TORADIANS"));
addNamedWarpScriptFunction(new TODEGREES("TODEGREES"));
addNamedWarpScriptFunction(new MAX("MAX"));
addNamedWarpScriptFunction(new MIN("MIN"));
addNamedWarpScriptFunction(new COPYSIGN("COPYSIGN"));
addNamedWarpScriptFunction(new HYPOT("HYPOT"));
addNamedWarpScriptFunction(new IEEEREMAINDER("IEEEREMAINDER"));
addNamedWarpScriptFunction(new NEXTAFTER("NEXTAFTER"));
addNamedWarpScriptFunction(new ATAN2("ATAN2"));
addNamedWarpScriptFunction(new FLOORDIV("FLOORDIV"));
addNamedWarpScriptFunction(new FLOORMOD("FLOORMOD"));
addNamedWarpScriptFunction(new ADDEXACT("ADDEXACT"));
addNamedWarpScriptFunction(new SUBTRACTEXACT("SUBTRACTEXACT"));
addNamedWarpScriptFunction(new MULTIPLYEXACT("MULTIPLYEXACT"));
addNamedWarpScriptFunction(new INCREMENTEXACT("INCREMENTEXACT"));
addNamedWarpScriptFunction(new DECREMENTEXACT("DECREMENTEXACT"));
addNamedWarpScriptFunction(new NEGATEEXACT("NEGATEEXACT"));
addNamedWarpScriptFunction(new TOINTEXACT("TOINTEXACT"));
addNamedWarpScriptFunction(new SCALB("SCALB"));
addNamedWarpScriptFunction(new RANDOM("RANDOM"));
addNamedWarpScriptFunction(new NEXTDOWN("NEXTDOWN"));
addNamedWarpScriptFunction(new GETEXPONENT("GETEXPONENT"));
addNamedWarpScriptFunction(new IDENT("IDENT"));
//
// Processing
//
addNamedWarpScriptFunction(new Pencode("Pencode"));
// Structure
addNamedWarpScriptFunction(new PpushStyle("PpushStyle"));
addNamedWarpScriptFunction(new PpopStyle("PpopStyle"));
// Environment
// Shape
addNamedWarpScriptFunction(new Parc("Parc"));
addNamedWarpScriptFunction(new Pellipse("Pellipse"));
addNamedWarpScriptFunction(new Ppoint("Ppoint"));
addNamedWarpScriptFunction(new Pline("Pline"));
addNamedWarpScriptFunction(new Ptriangle("Ptriangle"));
addNamedWarpScriptFunction(new Prect("Prect"));
addNamedWarpScriptFunction(new Pquad("Pquad"));
addNamedWarpScriptFunction(new Pbezier("Pbezier"));
addNamedWarpScriptFunction(new PbezierPoint("PbezierPoint"));
addNamedWarpScriptFunction(new PbezierTangent("PbezierTangent"));
addNamedWarpScriptFunction(new PbezierDetail("PbezierDetail"));
addNamedWarpScriptFunction(new Pcurve("Pcurve"));
addNamedWarpScriptFunction(new PcurvePoint("PcurvePoint"));
addNamedWarpScriptFunction(new PcurveTangent("PcurveTangent"));
addNamedWarpScriptFunction(new PcurveDetail("PcurveDetail"));
addNamedWarpScriptFunction(new PcurveTightness("PcurveTightness"));
addNamedWarpScriptFunction(new Pbox("Pbox"));
addNamedWarpScriptFunction(new Psphere("Psphere"));
addNamedWarpScriptFunction(new PsphereDetail("PsphereDetail"));
addNamedWarpScriptFunction(new PellipseMode("PellipseMode"));
addNamedWarpScriptFunction(new PrectMode("PrectMode"));
addNamedWarpScriptFunction(new PstrokeCap("PstrokeCap"));
addNamedWarpScriptFunction(new PstrokeJoin("PstrokeJoin"));
addNamedWarpScriptFunction(new PstrokeWeight("PstrokeWeight"));
addNamedWarpScriptFunction(new PbeginShape("PbeginShape"));
addNamedWarpScriptFunction(new PendShape("PendShape"));
addNamedWarpScriptFunction(new PloadShape("PloadShape"));
addNamedWarpScriptFunction(new PbeginContour("PbeginContour"));
addNamedWarpScriptFunction(new PendContour("PendContour"));
addNamedWarpScriptFunction(new Pvertex("Pvertex"));
addNamedWarpScriptFunction(new PcurveVertex("PcurveVertex"));
addNamedWarpScriptFunction(new PbezierVertex("PbezierVertex"));
addNamedWarpScriptFunction(new PquadraticVertex("PquadraticVertex"));
// TODO(hbs): support PShape (need to support PbeginShape etc applied to PShape instances)
addNamedWarpScriptFunction(new PshapeMode("PshapeMode"));
addNamedWarpScriptFunction(new Pshape("Pshape"));
// Transform
addNamedWarpScriptFunction(new PpushMatrix("PpushMatrix"));
addNamedWarpScriptFunction(new PpopMatrix("PpopMatrix"));
addNamedWarpScriptFunction(new PresetMatrix("PresetMatrix"));
addNamedWarpScriptFunction(new Protate("Protate"));
addNamedWarpScriptFunction(new ProtateX("ProtateX"));
addNamedWarpScriptFunction(new ProtateY("ProtateY"));
addNamedWarpScriptFunction(new ProtateZ("ProtateZ"));
addNamedWarpScriptFunction(new Pscale("Pscale"));
addNamedWarpScriptFunction(new PshearX("PshearX"));
addNamedWarpScriptFunction(new PshearY("PshearY"));
addNamedWarpScriptFunction(new Ptranslate("Ptranslate"));
// Color
addNamedWarpScriptFunction(new Pbackground("Pbackground"));
addNamedWarpScriptFunction(new PcolorMode("PcolorMode"));
addNamedWarpScriptFunction(new Pclear("Pclear"));
addNamedWarpScriptFunction(new Pfill("Pfill"));
addNamedWarpScriptFunction(new PnoFill("PnoFill"));
addNamedWarpScriptFunction(new Pstroke("Pstroke"));
addNamedWarpScriptFunction(new PnoStroke("PnoStroke"));
addNamedWarpScriptFunction(new Palpha("Palpha"));
addNamedWarpScriptFunction(new Pblue("Pblue"));
addNamedWarpScriptFunction(new Pbrightness("Pbrightness"));
addNamedWarpScriptFunction(new Pcolor("Pcolor"));
addNamedWarpScriptFunction(new Pgreen("Pgreen"));
addNamedWarpScriptFunction(new Phue("Phue"));
addNamedWarpScriptFunction(new PlerpColor("PlerpColor"));
addNamedWarpScriptFunction(new Pred("Pred"));
addNamedWarpScriptFunction(new Psaturation("Psaturation"));
// Image
addNamedWarpScriptFunction(new Pdecode("Pdecode"));
addNamedWarpScriptFunction(new Pimage("Pimage"));
addNamedWarpScriptFunction(new PimageMode("PimageMode"));
addNamedWarpScriptFunction(new Ptint("Ptint"));
addNamedWarpScriptFunction(new PnoTint("PnoTint"));
addNamedWarpScriptFunction(new Ppixels("Ppixels"));
addNamedWarpScriptFunction(new PupdatePixels("PupdatePixels"));
addNamedWarpScriptFunction(new PtoImage("PtoImage"));
// TODO(hbs): support texture related functions?
addNamedWarpScriptFunction(new Pblend("Pblend"));
addNamedWarpScriptFunction(new Pcopy("Pcopy"));
addNamedWarpScriptFunction(new Pget("Pget"));
addNamedWarpScriptFunction(new Pset("Pset"));
addNamedWarpScriptFunction(new Pfilter("Pfilter"));
// Rendering
addNamedWarpScriptFunction(new PblendMode("PblendMode"));
addNamedWarpScriptFunction(new Pclip("Pclip"));
addNamedWarpScriptFunction(new PnoClip("PnoClip"));
addNamedWarpScriptFunction(new PGraphics("PGraphics"));
// TODO(hbs): support shaders?
// Typography
addNamedWarpScriptFunction(new PcreateFont("PcreateFont"));
addNamedWarpScriptFunction(new Ptext("Ptext"));
addNamedWarpScriptFunction(new PtextAlign("PtextAlign"));
addNamedWarpScriptFunction(new PtextAscent("PtextAscent"));
addNamedWarpScriptFunction(new PtextDescent("PtextDescent"));
addNamedWarpScriptFunction(new PtextFont("PtextFont"));
addNamedWarpScriptFunction(new PtextLeading("PtextLeading"));
addNamedWarpScriptFunction(new PtextMode("PtextMode"));
addNamedWarpScriptFunction(new PtextSize("PtextSize"));
addNamedWarpScriptFunction(new PtextWidth("PtextWidth"));
// Math
addNamedWarpScriptFunction(new Pconstrain("Pconstrain"));
addNamedWarpScriptFunction(new Pdist("Pdist"));
addNamedWarpScriptFunction(new Plerp("Plerp"));
addNamedWarpScriptFunction(new Pmag("Pmag"));
addNamedWarpScriptFunction(new Pmap("Pmap"));
addNamedWarpScriptFunction(new Pnorm("Pnorm"));
////////////////////////////////////////////////////////////////////////////
//
// Moved from JavaLibrary
//
/////////////////////////
//
// Bucketizers
//
addNamedWarpScriptFunction(new And("bucketizer.and", false));
addNamedWarpScriptFunction(new First("bucketizer.first"));
addNamedWarpScriptFunction(new Last("bucketizer.last"));
addNamedWarpScriptFunction(new Min("bucketizer.min", true));
addNamedWarpScriptFunction(new Max("bucketizer.max", true));
addNamedWarpScriptFunction(new Mean("bucketizer.mean", false));
addNamedWarpScriptFunction(new Median("bucketizer.median"));
addNamedWarpScriptFunction(new MAD("bucketizer.mad"));
addNamedWarpScriptFunction(new Or("bucketizer.or", false));
addNamedWarpScriptFunction(new Sum("bucketizer.sum", true));
addNamedWarpScriptFunction(new Join.Builder("bucketizer.join", true, false, null));
addNamedWarpScriptFunction(new Count("bucketizer.count", false));
addNamedWarpScriptFunction(new Percentile.Builder("bucketizer.percentile"));
addNamedWarpScriptFunction(new Min("bucketizer.min.forbid-nulls", false));
addNamedWarpScriptFunction(new Max("bucketizer.max.forbid-nulls", false));
addNamedWarpScriptFunction(new Mean("bucketizer.mean.exclude-nulls", true));
addNamedWarpScriptFunction(new Sum("bucketizer.sum.forbid-nulls", false));
addNamedWarpScriptFunction(new Join.Builder("bucketizer.join.forbid-nulls", false, false, null));
addNamedWarpScriptFunction(new Count("bucketizer.count.exclude-nulls", true));
addNamedWarpScriptFunction(new Count("bucketizer.count.include-nulls", false));
addNamedWarpScriptFunction(new Count("bucketizer.count.nonnull", true));
addNamedWarpScriptFunction(new CircularMean.Builder("bucketizer.mean.circular", true));
addNamedWarpScriptFunction(new CircularMean.Builder("bucketizer.mean.circular.exclude-nulls", false));
addNamedWarpScriptFunction(new RMS("bucketizer.rms", false));
//
// Mappers
//
addNamedWarpScriptFunction(new And("mapper.and", false));
addNamedWarpScriptFunction(new Count("mapper.count", false));
addNamedWarpScriptFunction(new First("mapper.first"));
addNamedWarpScriptFunction(new Last("mapper.last"));
addNamedWarpScriptFunction(new Min(MAPPER_MIN, true));
addNamedWarpScriptFunction(new Max(MAPPER_MAX, true));
addNamedWarpScriptFunction(new Mean("mapper.mean", false));
addNamedWarpScriptFunction(new Median("mapper.median"));
addNamedWarpScriptFunction(new MAD("mapper.mad"));
addNamedWarpScriptFunction(new Or("mapper.or", false));
addNamedWarpScriptFunction(new Highest(MAPPER_HIGHEST));
addNamedWarpScriptFunction(new Lowest(MAPPER_LOWEST));
addNamedWarpScriptFunction(new Sum("mapper.sum", true));
addNamedWarpScriptFunction(new Join.Builder("mapper.join", true, false, null));
addNamedWarpScriptFunction(new Delta("mapper.delta"));
addNamedWarpScriptFunction(new Rate("mapper.rate"));
addNamedWarpScriptFunction(new HSpeed("mapper.hspeed"));
addNamedWarpScriptFunction(new HDist("mapper.hdist"));
addNamedWarpScriptFunction(new TrueCourse("mapper.truecourse"));
addNamedWarpScriptFunction(new VSpeed("mapper.vspeed"));
addNamedWarpScriptFunction(new VDist("mapper.vdist"));
addNamedWarpScriptFunction(new Variance.Builder("mapper.var", false));
addNamedWarpScriptFunction(new StandardDeviation.Builder("mapper.sd", false));
addNamedWarpScriptFunction(new MapperAbs("mapper.abs"));
addNamedWarpScriptFunction(new MapperCeil("mapper.ceil"));
addNamedWarpScriptFunction(new MapperFloor("mapper.floor"));
addNamedWarpScriptFunction(new MapperFinite("mapper.finite"));
addNamedWarpScriptFunction(new MapperRound("mapper.round"));
addNamedWarpScriptFunction(new MapperToBoolean("mapper.toboolean"));
addNamedWarpScriptFunction(new MapperToLong("mapper.tolong"));
addNamedWarpScriptFunction(new MapperToDouble("mapper.todouble"));
addNamedWarpScriptFunction(new MapperToString("mapper.tostring"));
addNamedWarpScriptFunction(new MapperTanh("mapper.tanh"));
addNamedWarpScriptFunction(new MapperSigmoid("mapper.sigmoid"));
addNamedWarpScriptFunction(new MapperProduct("mapper.product"));
addNamedWarpScriptFunction(new MapperGeoClearPosition("mapper.geo.clear"));
addNamedWarpScriptFunction(new Count("mapper.count.exclude-nulls", true));
addNamedWarpScriptFunction(new Count("mapper.count.include-nulls", false));
addNamedWarpScriptFunction(new Count("mapper.count.nonnull", true));
addNamedWarpScriptFunction(new Min("mapper.min.forbid-nulls", false));
addNamedWarpScriptFunction(new Max("mapper.max.forbid-nulls", false));
addNamedWarpScriptFunction(new Mean("mapper.mean.exclude-nulls", true));
addNamedWarpScriptFunction(new Sum("mapper.sum.forbid-nulls", false));
addNamedWarpScriptFunction(new Join.Builder("mapper.join.forbid-nulls", false, false, null));
addNamedWarpScriptFunction(new Variance.Builder("mapper.var.forbid-nulls", true));
addNamedWarpScriptFunction(new StandardDeviation.Builder("mapper.sd.forbid-nulls", true));
addNamedWarpScriptFunction(new CircularMean.Builder("mapper.mean.circular", true));
addNamedWarpScriptFunction(new CircularMean.Builder("mapper.mean.circular.exclude-nulls", false));
addNamedWarpScriptFunction(new MapperMod.Builder("mapper.mod"));
addNamedWarpScriptFunction(new RMS("mapper.rms", false));
//
// Reducers
//
addNamedWarpScriptFunction(new And("reducer.and", false));
addNamedWarpScriptFunction(new And("reducer.and.exclude-nulls", true));
addNamedWarpScriptFunction(new Min("reducer.min", true));
addNamedWarpScriptFunction(new Min("reducer.min.forbid-nulls", false));
addNamedWarpScriptFunction(new Min("reducer.min.nonnull", false));
addNamedWarpScriptFunction(new Max("reducer.max", true));
addNamedWarpScriptFunction(new Max("reducer.max.forbid-nulls", false));
addNamedWarpScriptFunction(new Max("reducer.max.nonnull", false));
addNamedWarpScriptFunction(new Mean("reducer.mean", false));
addNamedWarpScriptFunction(new Mean("reducer.mean.exclude-nulls", true));
addNamedWarpScriptFunction(new Median("reducer.median"));
addNamedWarpScriptFunction(new MAD("reducer.mad"));
addNamedWarpScriptFunction(new Or("reducer.or", false));
addNamedWarpScriptFunction(new Or("reducer.or.exclude-nulls", true));
addNamedWarpScriptFunction(new Sum("reducer.sum", true));
addNamedWarpScriptFunction(new Sum("reducer.sum.forbid-nulls", false));
addNamedWarpScriptFunction(new Sum("reducer.sum.nonnull", false));
addNamedWarpScriptFunction(new Join.Builder("reducer.join", true, false, null));
addNamedWarpScriptFunction(new Join.Builder("reducer.join.forbid-nulls", false, false, null));
addNamedWarpScriptFunction(new Join.Builder("reducer.join.nonnull", false, false, null));
addNamedWarpScriptFunction(new Join.Builder("reducer.join.urlencoded", false, true, ""));
addNamedWarpScriptFunction(new Variance.Builder("reducer.var", false));
addNamedWarpScriptFunction(new Variance.Builder("reducer.var.forbid-nulls", false));
addNamedWarpScriptFunction(new StandardDeviation.Builder("reducer.sd", false));
addNamedWarpScriptFunction(new StandardDeviation.Builder("reducer.sd.forbid-nulls", false));
addNamedWarpScriptFunction(new Argminmax.Builder("reducer.argmin", true));
addNamedWarpScriptFunction(new Argminmax.Builder("reducer.argmax", false));
addNamedWarpScriptFunction(new MapperProduct("reducer.product"));
addNamedWarpScriptFunction(new Count("reducer.count", false));
addNamedWarpScriptFunction(new Count("reducer.count.include-nulls", false));
addNamedWarpScriptFunction(new Count("reducer.count.exclude-nulls", true));
addNamedWarpScriptFunction(new Count("reducer.count.nonnull", true));
addNamedWarpScriptFunction(new ShannonEntropy("reducer.shannonentropy.0", false));
addNamedWarpScriptFunction(new ShannonEntropy("reducer.shannonentropy.1", true));
addNamedWarpScriptFunction(new Percentile.Builder("reducer.percentile"));
addNamedWarpScriptFunction(new CircularMean.Builder("reducer.mean.circular", true));
addNamedWarpScriptFunction(new CircularMean.Builder("reducer.mean.circular.exclude-nulls", false));
addNamedWarpScriptFunction(new RMS("reducer.rms", false));
addNamedWarpScriptFunction(new RMS("reducer.rms.exclude-nulls", true));
//
// Filters
//
//
// N-ary ops
//
addNamedWarpScriptFunction(new OpAdd("op.add", true));
addNamedWarpScriptFunction(new OpAdd("op.add.ignore-nulls", false));
addNamedWarpScriptFunction(new OpSub("op.sub"));
addNamedWarpScriptFunction(new OpMul("op.mul", true));
addNamedWarpScriptFunction(new OpMul("op.mul.ignore-nulls", false));
addNamedWarpScriptFunction(new OpDiv("op.div"));
addNamedWarpScriptFunction(new OpMask("op.mask", false));
addNamedWarpScriptFunction(new OpMask("op.negmask", true));
addNamedWarpScriptFunction(new OpNE("op.ne"));
addNamedWarpScriptFunction(new OpEQ("op.eq"));
addNamedWarpScriptFunction(new OpLT("op.lt"));
addNamedWarpScriptFunction(new OpGT("op.gt"));
addNamedWarpScriptFunction(new OpLE("op.le"));
addNamedWarpScriptFunction(new OpGE("op.ge"));
addNamedWarpScriptFunction(new OpAND("op.and.ignore-nulls", false));
addNamedWarpScriptFunction(new OpAND("op.and", true));
addNamedWarpScriptFunction(new OpOR("op.or.ignore-nulls", false));
addNamedWarpScriptFunction(new OpOR("op.or", true));
/////////////////////////
int nregs = Integer.parseInt(WarpConfig.getProperty(Configuration.CONFIG_WARPSCRIPT_REGISTERS, String.valueOf(WarpScriptStack.DEFAULT_REGISTERS)));
addNamedWarpScriptFunction(new CLEARREGS(CLEARREGS));
addNamedWarpScriptFunction(new VARS("VARS"));
addNamedWarpScriptFunction(new ASREGS("ASREGS"));
for (int i = 0; i < nregs; i++) {
addNamedWarpScriptFunction(new POPR(POPR + i, i));
addNamedWarpScriptFunction(new POPR(CPOPR + i, i, true));
addNamedWarpScriptFunction(new PUSHR(PUSHR + i, i));
}
}
public static void addNamedWarpScriptFunction(NamedWarpScriptFunction namedFunction) {
functions.put(namedFunction.getName(), namedFunction);
}
public static Object getFunction(String name) {
return functions.get(name);
}
public static void registerExtensions() {
Properties props = WarpConfig.getProperties();
if (null == props) {
return;
}
//
// Extract the list of extensions
//
Set<String> ext = new LinkedHashSet<String>();
if (props.containsKey(Configuration.CONFIG_WARPSCRIPT_EXTENSIONS)) {
String[] extensions = props.getProperty(Configuration.CONFIG_WARPSCRIPT_EXTENSIONS).split(",");
for (String extension: extensions) {
ext.add(extension.trim());
}
}
for (Object key: props.keySet()) {
if (!key.toString().startsWith(Configuration.CONFIG_WARPSCRIPT_EXTENSION_PREFIX)) {
continue;
}
ext.add(props.get(key).toString().trim());
}
// Sort the extensions
List<String> sortedext = new ArrayList<String>(ext);
sortedext.sort(null);
List<String> failedExt = new ArrayList<String>();
//
// Determine the possible jar from which WarpScriptLib was loaded
//
String wsljar = null;
URL wslurl = WarpScriptLib.class.getResource('/' + WarpScriptLib.class.getCanonicalName().replace('.', '/') + ".class");
if (null != wslurl && "jar".equals(wslurl.getProtocol())) {
wsljar = wslurl.toString().replaceAll("!/.*", "").replaceAll("jar:file:", "");
}
for (String extension: sortedext) {
// If the extension name contains '#', remove everything up to the last '#', this was used as a sorting prefix
if (extension.contains("#")) {
extension = extension.replaceAll("^.*#", "");
}
try {
//
// Locate the class using the current class loader
//
URL url = WarpScriptLib.class.getResource('/' + extension.replace('.', '/') + ".class");
if (null == url) {
LOG.error("Unable to load extension '" + extension + "', make sure it is in the class path.");
failedExt.add(extension);
continue;
}
Class cls = null;
//
// If the class was located in a jar, load it using a specific class loader
// so we can have fat jars with specific deps, unless the jar is the same as
// the one from which WarpScriptLib was loaded, in which case we use the same
// class loader.
//
if ("jar".equals(url.getProtocol())) {
String jarfile = url.toString().replaceAll("!/.*", "").replaceAll("jar:file:", "");
ClassLoader cl = WarpScriptLib.class.getClassLoader();
// If the jar differs from that from which WarpScriptLib was loaded, create a dedicated class loader
if (!jarfile.equals(wsljar) && !"true".equals(props.getProperty(Configuration.CONFIG_WARPSCRIPT_DEFAULTCL_PREFIX + extension))) {
cl = new WarpClassLoader(jarfile, WarpScriptLib.class.getClassLoader());
}
cls = Class.forName(extension, true, cl);
} else {
cls = Class.forName(extension, true, WarpScriptLib.class.getClassLoader());
}
//Class cls = Class.forName(extension);
WarpScriptExtension wse = (WarpScriptExtension) cls.newInstance();
wse.register();
String namespace = props.getProperty(Configuration.CONFIG_WARPSCRIPT_NAMESPACE_PREFIX + wse.getClass().getName(), "").trim();
if (null != namespace && !"".equals(namespace)) {
if (namespace.contains("%")) {
namespace = URLDecoder.decode(namespace, "UTF-8");
}
LOG.info("LOADED extension '" + extension + "'" + " under namespace '" + namespace + "'.");
} else {
LOG.info("LOADED extension '" + extension + "'");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (!failedExt.isEmpty()) {
StringBuilder sb = new StringBuilder();
sb.append("The following WarpScript extensions could not be loaded, aborting:");
for (String extension: failedExt) {
sb.append(" '");
sb.append(extension);
sb.append("'");
}
LOG.error(sb.toString());
throw new RuntimeException(sb.toString());
}
}
public static void register(WarpScriptExtension extension) {
String namespace = WarpConfig.getProperty(Configuration.CONFIG_WARPSCRIPT_NAMESPACE_PREFIX + extension.getClass().getName(), "").trim();
if (namespace.contains("%")) {
try {
namespace = URLDecoder.decode(namespace, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
register(namespace, extension);
}
public static void register(String namespace, WarpScriptExtension extension) {
extloaded.add(extension.getClass().getCanonicalName());
Map<String,Object> extfuncs = extension.getFunctions();
if (null == extfuncs) {
return;
}
for (Entry<String,Object> entry: extfuncs.entrySet()) {
if (null == entry.getValue()) {
functions.remove(namespace + entry.getKey());
} else {
functions.put(namespace + entry.getKey(), entry.getValue());
}
}
}
public static boolean extloaded(String name) {
return extloaded.contains(name);
}
public static List<String> extensions() {
return new ArrayList<String>(extloaded);
}
/**
* Check whether or not an object is castable to a macro
* @param o
* @return
*/
public static boolean isMacro(Object o) {
if (null == o) {
return false;
}
return o instanceof Macro;
}
public static ArrayList getFunctionNames() {
List<Object> list = new ArrayList<Object>();
list.addAll(functions.keySet());
return (ArrayList)list;
}
}
| add UPDATE to lib
| warp10/src/main/java/io/warp10/script/WarpScriptLib.java | add UPDATE to lib | <ide><path>arp10/src/main/java/io/warp10/script/WarpScriptLib.java
<ide> addNamedWarpScriptFunction(new LOCATIONOFFSET("LOCATIONOFFSET"));
<ide> addNamedWarpScriptFunction(new FLATTEN("FLATTEN"));
<ide> addNamedWarpScriptFunction(new RESHAPE("RESHAPE"));
<add> addNamedWarpScriptFunction(new PERMUTE("PERMUTE"));
<ide> addNamedWarpScriptFunction(new CHECKSHAPE("CHECKSHAPE"));
<ide> addNamedWarpScriptFunction(new SHAPE("SHAPE"));
<ide> addNamedWarpScriptFunction(new HULLSHAPE("HULLSHAPE")); |
|
JavaScript | mit | 44f2c26307f1c8eaf6627d284872d8830d171250 | 0 | arpetti/LEDITA,arpetti/LEDITA | var async = require('async');
var studentsService = require('./StudentsService');
var activityCreateDao = require('../dao/ActivityCreateDao');
var composesService = require('./ComposesService');
var technologyService = require('./TechnologyService');
var resourceService = require('./ResourceService');
var messages = require('../validate/ValidationMessages');
var logger = require('../util/LogWrapper');
var createActivityObj = function(studentsId, activityData) {
return {
students_id : studentsId,
name : activityData.actName,
dur_min : activityData.dur_min,
dur_hh : activityData.dur_h,
dur_dd : activityData.dur_d,
dur_mon : activityData.dur_mon,
pract_descr : activityData.pract_descr,
edu_descr : activityData.edu_descr,
modality : activityData.modality
};
};
module.exports = {
hasResources: function(activityData) {
return activityData.resources && activityData.resources.length > 0;
},
// cb(err, {activity_id : activityId, composes_id : composesId}, message)
createActivity: function(ldId, activityData, cb) {
logger.log().info('ActivityCreateService: ' + JSON.stringify(activityData));
// Sample Data:
// {
// "actName":"my activity name", name
// "modality":"1", modality
// "dur_mon":1, dur_mon
// "dur_d":2, dur_dd
// "dur_h":3, dur_hh
// "dur_min":4, dur_min
// "org":"1", --> ref: students_type.type
// "group_number":5, --> insert: students.group_number
// "people_per_group":6, --> insert: students.people_per_group
// "technologies":["Whiteboard","touch screen"], --> get activity.id after insert, pass to TechnologyService
// "pract_descr":"long description", pract_descr
// "edu_descr":"pedagogical long description", edu_descr
// "resources":[
// {"name":"res1","type":"restype1","descr":"res descr 1","link":"http://res.1"},
// {"name":"res2","type":"restype2","descr":"res 2 description","link":"http://res.2"}
// ]
// }
async.waterfall([
// Step 1: Insert STUDENTS
function(callback){
studentsService.insertStudents(activityData.org, activityData.group_number, activityData.people_per_group, function(err, studentsId, message) {
if(err) {
callback(new Error(message));
} else {
callback(null, studentsId);
}
});
},
// Step 2: Insert ACTIVITY
function(studentsId, callback) {
var activityObj = createActivityObj(studentsId, activityData)
activityCreateDao.insertActivity(activityObj, function(err, activityId) {
if(err) {
logger.log().error('Activity Create Service error inserting activity', err);
callback(new Error(messages.ACTIVITY_INSERT_FAIL));
} else {
callback(null, activityId, studentsId);
}
});
},
// Step 3: Insert COMPOSES
function(activityId, studentsId, callback) {
composesService.addActivity(ldId, activityId, function(err, composesId, message) {
if(err) {
callback(new Error(message));
} else {
var successInfo = {
activity_id : activityId,
students_id : studentsId,
composes_id : composesId
};
callback(null, activityId, successInfo);
}
});
},
// Step 4: Insert or Connect Technologies
function(activityId, successInfo, callback) {
technologyService.insertSupports(activityId, activityData.technologies, function() {
callback(null, activityId, successInfo);
})
},
// Step 5: Add Resources
function(activityId, successInfo, callback) {
if(module.exports.hasResources(activityData)) {
resourceService.addResources(activityId, activityData.resources, function() {
callback(null, successInfo);
});
}
}
], function (err, successInfo) {
if(err) {
logger.log().error('Activity NOT created.', err);
cb(err, null, err.message);
} else {
logger.log().info('Activity successfully created: ' + JSON.stringify(successInfo));
cb(null, successInfo, null);
}
});
}
}; | server/service/ActivityCreateService.js | var async = require('async');
var studentsService = require('./StudentsService');
var activityCreateDao = require('../dao/ActivityCreateDao');
var composesService = require('./ComposesService');
var technologyService = require('./TechnologyService');
var resourceService = require('./Resourceservice');
var messages = require('../validate/ValidationMessages');
var logger = require('../util/LogWrapper');
var createActivityObj = function(studentsId, activityData) {
return {
students_id : studentsId,
name : activityData.actName,
dur_min : activityData.dur_min,
dur_hh : activityData.dur_h,
dur_dd : activityData.dur_d,
dur_mon : activityData.dur_mon,
pract_descr : activityData.pract_descr,
edu_descr : activityData.edu_descr,
modality : activityData.modality
};
};
module.exports = {
hasResources: function(activityData) {
return activityData.resources && activityData.resources.length > 0;
},
// cb(err, {activity_id : activityId, composes_id : composesId}, message)
createActivity: function(ldId, activityData, cb) {
logger.log().info('ActivityCreateService: ' + JSON.stringify(activityData));
// Sample Data:
// {
// "actName":"my activity name", name
// "modality":"1", modality
// "dur_mon":1, dur_mon
// "dur_d":2, dur_dd
// "dur_h":3, dur_hh
// "dur_min":4, dur_min
// "org":"1", --> ref: students_type.type
// "group_number":5, --> insert: students.group_number
// "people_per_group":6, --> insert: students.people_per_group
// "technologies":["Whiteboard","touch screen"], --> get activity.id after insert, pass to TechnologyService
// "pract_descr":"long description", pract_descr
// "edu_descr":"pedagogical long description", edu_descr
// "resources":[
// {"name":"res1","type":"restype1","descr":"res descr 1","link":"http://res.1"},
// {"name":"res2","type":"restype2","descr":"res 2 description","link":"http://res.2"}
// ]
// }
async.waterfall([
// Step 1: Insert STUDENTS
function(callback){
studentsService.insertStudents(activityData.org, activityData.group_number, activityData.people_per_group, function(err, studentsId, message) {
if(err) {
callback(new Error(message));
} else {
callback(null, studentsId);
}
});
},
// Step 2: Insert ACTIVITY
function(studentsId, callback) {
var activityObj = createActivityObj(studentsId, activityData)
activityCreateDao.insertActivity(activityObj, function(err, activityId) {
if(err) {
logger.log().error('Activity Create Service error inserting activity', err);
callback(new Error(messages.ACTIVITY_INSERT_FAIL));
} else {
callback(null, activityId, studentsId);
}
});
},
// Step 3: Insert COMPOSES
function(activityId, studentsId, callback) {
composesService.addActivity(ldId, activityId, function(err, composesId, message) {
if(err) {
callback(new Error(message));
} else {
var successInfo = {
activity_id : activityId,
students_id : studentsId,
composes_id : composesId
};
callback(null, activityId, successInfo);
}
});
},
// Step 4: Insert or Connect Technologies
function(activityId, successInfo, callback) {
technologyService.insertSupports(activityId, activityData.technologies, function() {
callback(null, activityId, successInfo);
})
},
// Step 5: Add Resources
function(activityId, successInfo, callback) {
if(module.exports.hasResources(activityData)) {
resourceService.addResources(activityId, activityData.resources, function() {
callback(null, successInfo);
});
}
}
], function (err, successInfo) {
if(err) {
cb(err, null, err.message);
} else {
logger.log().info('Activity successfully created: ' + JSON.stringify(successInfo));
cb(null, successInfo, null);
}
});
}
}; | fix build - case sensitive issue on resource service
| server/service/ActivityCreateService.js | fix build - case sensitive issue on resource service | <ide><path>erver/service/ActivityCreateService.js
<ide> var activityCreateDao = require('../dao/ActivityCreateDao');
<ide> var composesService = require('./ComposesService');
<ide> var technologyService = require('./TechnologyService');
<del>var resourceService = require('./Resourceservice');
<add>var resourceService = require('./ResourceService');
<ide> var messages = require('../validate/ValidationMessages');
<ide> var logger = require('../util/LogWrapper');
<ide>
<ide>
<ide> ], function (err, successInfo) {
<ide> if(err) {
<add> logger.log().error('Activity NOT created.', err);
<ide> cb(err, null, err.message);
<ide> } else {
<ide> logger.log().info('Activity successfully created: ' + JSON.stringify(successInfo)); |
|
Java | apache-2.0 | e3630178b8eb854a6d54b513972ef8413e3b9596 | 0 | dusenberrymw/systemml,gweidner/incubator-systemml,dhutchis/systemml,dusenberrymw/systemml,sandeep-n/incubator-systemml,akchinSTC/systemml,asurve/incubator-systemml,dhutchis/systemml,niketanpansare/systemml,dhutchis/systemml,deroneriksson/incubator-systemml,dhutchis/systemml,dusenberrymw/systemml,deroneriksson/systemml,Wenpei/incubator-systemml,Myasuka/systemml,Myasuka/systemml,gweidner/systemml,iyounus/incubator-systemml,dusenberrymw/systemml,nakul02/systemml,gweidner/incubator-systemml,deroneriksson/systemml,apache/incubator-systemml,asurve/incubator-systemml,niketanpansare/incubator-systemml,deroneriksson/systemml,apache/incubator-systemml,dusenberrymw/systemml,niketanpansare/incubator-systemml,asurve/systemml,akchinSTC/systemml,dusenberrymw/incubator-systemml,dusenberrymw/incubator-systemml,deroneriksson/systemml,dusenberrymw/systemml,sandeep-n/incubator-systemml,asurve/systemml,Myasuka/systemml,deroneriksson/incubator-systemml,akchinSTC/systemml,Wenpei/incubator-systemml,Wenpei/incubator-systemml,akchinSTC/systemml,fschueler/incubator-systemml,dusenberrymw/incubator-systemml,Myasuka/systemml,fschueler/incubator-systemml,nakul02/incubator-systemml,nakul02/incubator-systemml,nakul02/incubator-systemml,fschueler/incubator-systemml,gweidner/systemml,nakul02/systemml,nakul02/systemml,apache/incubator-systemml,deroneriksson/incubator-systemml,dusenberrymw/incubator-systemml,niketanpansare/systemml,deroneriksson/incubator-systemml,asurve/arvind-sysml2,nakul02/systemml,gweidner/systemml,iyounus/incubator-systemml,asurve/systemml,nakul02/systemml,deroneriksson/incubator-systemml,asurve/incubator-systemml,Wenpei/incubator-systemml,niketanpansare/systemml,akchinSTC/systemml,sandeep-n/incubator-systemml,gweidner/incubator-systemml,niketanpansare/incubator-systemml,niketanpansare/systemml,asurve/incubator-systemml,gweidner/systemml,dusenberrymw/incubator-systemml,apache/incubator-systemml,gweidner/incubator-systemml,niketanpansare/incubator-systemml,gweidner/incubator-systemml,asurve/systemml,apache/incubator-systemml,gweidner/systemml,asurve/arvind-sysml2,iyounus/incubator-systemml,dusenberrymw/incubator-systemml,asurve/arvind-sysml2,iyounus/incubator-systemml,niketanpansare/systemml,nakul02/systemml,asurve/arvind-sysml2,Myasuka/systemml,nakul02/incubator-systemml,fschueler/incubator-systemml,nakul02/incubator-systemml,asurve/incubator-systemml,deroneriksson/incubator-systemml,dhutchis/systemml,deroneriksson/systemml,asurve/systemml,asurve/incubator-systemml,asurve/arvind-sysml2,apache/incubator-systemml,asurve/systemml,gweidner/incubator-systemml,akchinSTC/systemml,iyounus/incubator-systemml,Myasuka/systemml,iyounus/incubator-systemml,nakul02/incubator-systemml,niketanpansare/systemml,asurve/arvind-sysml2,sandeep-n/incubator-systemml,deroneriksson/systemml,dhutchis/systemml,gweidner/systemml | /**
* IBM Confidential
* OCO Source Materials
* (C) Copyright IBM Corp. 2010, 2014
* The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office.
*/
package com.ibm.bi.dml.runtime.matrix.io;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.math.random.Well1024a;
import com.ibm.bi.dml.lops.MMTSJ.MMTSJType;
import com.ibm.bi.dml.lops.PartialAggregate.CorrectionLocationType;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException;
import com.ibm.bi.dml.runtime.functionobjects.And;
import com.ibm.bi.dml.runtime.functionobjects.Builtin;
import com.ibm.bi.dml.runtime.functionobjects.CM;
import com.ibm.bi.dml.runtime.functionobjects.CTable;
import com.ibm.bi.dml.runtime.functionobjects.KahanPlus;
import com.ibm.bi.dml.runtime.functionobjects.MaxIndex;
import com.ibm.bi.dml.runtime.functionobjects.Minus;
import com.ibm.bi.dml.runtime.functionobjects.Multiply;
import com.ibm.bi.dml.runtime.functionobjects.Plus;
import com.ibm.bi.dml.runtime.functionobjects.ReduceAll;
import com.ibm.bi.dml.runtime.functionobjects.SwapIndex;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.CM_COV_Object;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.KahanObject;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.ScalarObject;
import com.ibm.bi.dml.runtime.instructions.MRInstructions.RangeBasedReIndexInstruction.IndexRange;
import com.ibm.bi.dml.runtime.matrix.mapred.IndexedMatrixValue;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateBinaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateOperator;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateUnaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.BinaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.CMOperator;
import com.ibm.bi.dml.runtime.matrix.operators.COVOperator;
import com.ibm.bi.dml.runtime.matrix.operators.Operator;
import com.ibm.bi.dml.runtime.matrix.operators.ReorgOperator;
import com.ibm.bi.dml.runtime.matrix.operators.ScalarOperator;
import com.ibm.bi.dml.runtime.matrix.operators.UnaryOperator;
import com.ibm.bi.dml.runtime.util.NormalPRNGenerator;
import com.ibm.bi.dml.runtime.util.PRNGenerator;
import com.ibm.bi.dml.runtime.util.UniformPRNGenerator;
import com.ibm.bi.dml.runtime.util.UtilFunctions;
public class MatrixBlockDSM extends MatrixValue
{
@SuppressWarnings("unused")
private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2014\n" +
"US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.";
//sparsity nnz threshold, based on practical experiments on space consumption and performance
public static final double SPARCITY_TURN_POINT = 0.4;
//sparsity column threshold, based on initial capacity of sparse representation
public static final int SKINNY_MATRIX_TURN_POINT = 4;
//sparsity threshold for ultra-sparse matrix operations (40nnz in a 1kx1k block)
public static final double ULTRA_SPARSITY_TURN_POINT = 0.00004;
public enum BlockType{
EMPTY_BLOCK,
ULTRA_SPARSE_BLOCK, //ultra sparse representation, in-mem same as sparse
SPARSE_BLOCK, //sparse representation, see sparseRows
DENSE_BLOCK, //dense representation, see denseBlock
}
//matrix meta data
protected int rlen = -1;
protected int clen = -1;
protected boolean sparse = true;
protected int nonZeros = 0;
//matrix data (sparse or dense)
protected double[] denseBlock = null;
protected SparseRow[] sparseRows = null;
//sparse-block-specific attributes (allocation only)
protected int estimatedNNzsPerRow = -1;
//ctable-specific attributes
protected int maxrow = -1;
protected int maxcolumn = -1;
//grpaggregate-specific attributes
protected int numGroups = -1;
////////
// Matrix Constructors
//
public MatrixBlockDSM()
{
rlen = 0;
clen = 0;
sparse = true;
nonZeros = 0;
maxrow = 0;
maxcolumn = 0;
}
public MatrixBlockDSM(int rl, int cl, boolean sp)
{
rlen = rl;
clen = cl;
sparse = sp;
nonZeros = 0;
maxrow = 0;
maxcolumn = 0;
}
public MatrixBlockDSM(int rl, int cl, boolean sp, int estnnzs)
{
this(rl, cl, sp);
estimatedNNzsPerRow=(int)Math.ceil((double)estnnzs/(double)rl);
}
public MatrixBlockDSM(MatrixBlockDSM that)
{
this.copy(that);
}
////////
// Initialization methods
// (reset, init, allocate, etc)
public void reset()
{
reset(-rlen);
}
public void reset(int estnnzs)
{
estimatedNNzsPerRow=(int)Math.ceil((double)estnnzs/(double)rlen);
if(sparse)
{
resetSparse();
}
else
{
if(denseBlock!=null)
{
if(denseBlock.length<rlen*clen)
denseBlock=null;
else
Arrays.fill(denseBlock, 0, rlen*clen, 0);
}
}
nonZeros=0;
//operation-specific attributes
maxrow = rlen;
maxcolumn = clen;
numGroups = -1;
}
public void reset(int rl, int cl) {
rlen=rl;
clen=cl;
nonZeros=0;
reset();
}
public void reset(int rl, int cl, int estnnzs) {
rlen=rl;
clen=cl;
nonZeros=0;
reset(estnnzs);
}
public void reset(int rl, int cl, boolean sp)
{
sparse=sp;
reset(rl, cl);
}
public void reset(int rl, int cl, boolean sp, int estnnzs)
{
sparse=sp;
reset(rl, cl, estnnzs);
}
public void resetSparse()
{
if(sparseRows!=null)
{
for(int i=0; i<Math.min(rlen, sparseRows.length); i++)
if(sparseRows[i]!=null)
sparseRows[i].reset(estimatedNNzsPerRow, clen);
}
}
public void resetDenseWithValue(int rl, int cl, double v)
{
estimatedNNzsPerRow=-1;
rlen=rl;
clen=cl;
sparse=false;
if(v==0)
{
reset();
return;
}
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
denseBlock=new double[limit];
Arrays.fill(denseBlock, 0, limit, v);
nonZeros=limit;
}
/**
* NOTE: This method is designed only for dense representation.
*
* @param arr
* @param r
* @param c
* @throws DMLRuntimeException
*/
public void init(double[][] arr, int r, int c)
throws DMLRuntimeException
{
//input checks
if ( sparse )
throw new DMLRuntimeException("MatrixBlockDSM.init() can be invoked only on matrices with dense representation.");
if( r*c > rlen*clen )
throw new DMLRuntimeException("MatrixBlockDSM.init() invoked with too large dimensions ("+r+","+c+") vs ("+rlen+","+clen+")");
//allocate or resize dense block
allocateDenseBlock();
//copy and compute nnz
for(int i=0, ix=0; i < r; i++, ix+=clen)
System.arraycopy(arr[i], 0, denseBlock, ix, arr[i].length);
recomputeNonZeros();
maxrow = r;
maxcolumn = c;
}
/**
* NOTE: This method is designed only for dense representation.
*
* @param arr
* @param r
* @param c
* @throws DMLRuntimeException
*/
public void init(double[] arr, int r, int c)
throws DMLRuntimeException
{
//input checks
if ( sparse )
throw new DMLRuntimeException("MatrixBlockDSM.init() can be invoked only on matrices with dense representation.");
if( r*c > rlen*clen )
throw new DMLRuntimeException("MatrixBlockDSM.init() invoked with too large dimensions ("+r+","+c+") vs ("+rlen+","+clen+")");
//allocate or resize dense block
allocateDenseBlock();
//copy and compute nnz
System.arraycopy(arr, 0, denseBlock, 0, arr.length);
recomputeNonZeros();
maxrow = r;
maxcolumn = c;
}
/**
*
*/
public void allocateDenseBlock()
{
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length < limit )
denseBlock=new double[limit];
nonZeros = 0;
}
/**
*
* @param r
*/
public void adjustSparseRows(int r)
{
if(sparseRows==null)
sparseRows=new SparseRow[rlen];
else if(sparseRows.length<=r)
{
SparseRow[] oldSparseRows=sparseRows;
sparseRows=new SparseRow[rlen];
for(int i=0; i<Math.min(oldSparseRows.length, rlen); i++) {
sparseRows[i]=oldSparseRows[i];
}
}
}
/**
* This should be called only in the read and write functions for CP
* This function should be called before calling any setValueDenseUnsafe()
*
* @param rl
* @param cl
*/
public void allocateDenseBlockUnsafe(int rl, int cl)
{
sparse=false;
rlen=rl;
clen=cl;
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
{
denseBlock=new double[limit];
}else
Arrays.fill(denseBlock, 0, limit, 0);
}
/**
* This should be called only in the read and write functions for CP
* This function should be called before calling any setValueSparseUnsafe() or appendValueSparseUnsafe()
* @param rl
* @param cl
* @param estimatedmNNzs
*/
@Deprecated
public void allocateSparseRowsUnsafe(int rl, int cl, int estimatedmNNzs)
{
sparse=true;
rlen=rl;
clen=cl;
int nnzsPerRow=(int) Math.ceil((double)estimatedmNNzs/(double)rl);
if(sparseRows!=null)
{
if(sparseRows.length>=rlen)
{
for(int i=0; i<rlen; i++)
{
if(sparseRows[i]==null)
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
else
sparseRows[i].reset(nnzsPerRow, cl);
}
}else
{
SparseRow[] temp=sparseRows;
sparseRows=new SparseRow[rlen];
int i=0;
for(; i<temp.length; i++)
{
if(temp[i]!=null)
{
sparseRows[i]=temp[i];
sparseRows[i].reset(nnzsPerRow, cl);
}else
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
}
for(; i<rlen; i++)
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
}
}else
{
sparseRows=new SparseRow[rlen];
for(int i=0; i<rlen; i++)
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
}
}
/**
* Allows to cleanup all previously allocated sparserows or denseblocks.
* This is for example required in reading a matrix with many empty blocks
* via distributed cache into in-memory list of blocks - not cleaning blocks
* from non-empty blocks would significantly increase the total memory consumption.
*
*/
public void cleanupBlock( boolean dense, boolean sparse )
{
if(dense)
denseBlock = null;
if(sparse)
sparseRows = null;
}
////////
// Metadata information
public int getNumRows()
{
return rlen;
}
/**
* NOTE: setNumRows() and setNumColumns() are used only in tertiaryInstruction (for contingency tables)
*
* @param _r
*/
public void setNumRows(int r)
{
rlen = r;
}
public int getNumColumns()
{
return clen;
}
public void setNumColumns(int c)
{
clen = c;
}
public int getNonZeros()
{
return nonZeros;
}
/**
* Returns the current representation (true for sparse).
*/
public boolean isInSparseFormat()
{
return sparse;
}
/**
*
* @return
*/
public boolean isUltraSparse()
{
double sp = ((double)nonZeros/rlen)/clen;
//check for sparse representation in order to account for vectors in dense
return sparse && sp<ULTRA_SPARSITY_TURN_POINT && nonZeros<40;
}
/**
* Returns the exact representation once it is written or
* exam sparsity is called.
*
* @return
*/
public boolean isExactInSparseFormat()
{
long lrlen = (long) rlen;
long lclen = (long) clen;
long lnonZeros = (long) nonZeros;
//ensure exact size estimates for write
if( lnonZeros<=0 )
//if( sparse || lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT )
{
recomputeNonZeros();
lnonZeros = (long) nonZeros;
}
return (lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT && lclen>SKINNY_MATRIX_TURN_POINT);
}
/**
*
* @param rlen
* @param clen
* @param nonZeros
* @return
*/
public static boolean isExactInSparseFormat(long rlen, long clen, long nonZeros)
{
return (nonZeros<(rlen*clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT);
}
public boolean isVector()
{
return (rlen == 1 || clen == 1);
}
/**
* Return the maximum row encountered WITHIN the current block
*
*/
public int getMaxRow()
{
if (!sparse)
return getNumRows();
else
return maxrow;
}
public void setMaxRow(int r)
{
maxrow = r;
}
/**
* Return the maximum column encountered WITHIN the current block
*
*/
public int getMaxColumn()
{
if (!sparse)
return getNumColumns();
else
return maxcolumn;
}
public void setMaxColumn(int c)
{
maxcolumn = c;
}
@Override
public boolean isEmpty()
{
return isEmptyBlock(false);
}
public boolean isEmptyBlock()
{
return isEmptyBlock(true);
}
public boolean isEmptyBlock(boolean safe)
{
boolean ret = false;
if( sparse && sparseRows==null )
ret = true;
else if( !sparse && denseBlock==null )
ret = true;
if( nonZeros==0 )
{
//prevent under-estimation
if(safe)
recomputeNonZeros();
ret = (nonZeros==0);
}
return ret;
}
////////
// Data handling
public double[] getDenseArray()
{
if(sparse)
return null;
return denseBlock;
}
public SparseRow[] getSparseRows()
{
if(!sparse)
return null;
return sparseRows;
}
public SparseCellIterator getSparseCellIterator()
{
if(!sparse)
throw new RuntimeException("getSparseCellInterator should not be called for dense format");
return new SparseCellIterator(rlen, sparseRows);
}
@Override
public void getCellValues(Collection<Double> ret)
{
int limit=rlen*clen;
if(sparse)
{
if(sparseRows==null)
{
for(int i=0; i<limit; i++)
ret.add(0.0);
}else
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] container=sparseRows[r].getValueContainer();
for(int j=0; j<sparseRows[r].size(); j++)
ret.add(container[j]);
}
int zeros=limit-ret.size();
for(int i=0; i<zeros; i++)
ret.add(0.0);
}
}else
{
if(denseBlock==null)
{
for(int i=0; i<limit; i++)
ret.add(0.0);
}else
{
for(int i=0; i<limit; i++)
ret.add(denseBlock[i]);
}
}
}
@Override
public void getCellValues(Map<Double, Integer> ret)
{
int limit=rlen*clen;
if(sparse)
{
if(sparseRows==null)
{
ret.put(0.0, limit);
}else
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] container=sparseRows[r].getValueContainer();
for(int j=0; j<sparseRows[r].size(); j++)
{
Double v=container[j];
Integer old=ret.get(v);
if(old!=null)
ret.put(v, old+1);
else
ret.put(v, 1);
}
}
int zeros=limit-ret.size();
Integer old=ret.get(0.0);
if(old!=null)
ret.put(0.0, old+zeros);
else
ret.put(0.0, zeros);
}
}else
{
if(denseBlock==null)
{
ret.put(0.0, limit);
}else
{
for(int i=0; i<limit; i++)
{
double v=denseBlock[i];
Integer old=ret.get(v);
if(old!=null)
ret.put(v, old+1);
else
ret.put(v, 1);
}
}
}
}
@Override
public double getValue(int r, int c)
{
if(r>rlen || c > clen)
throw new RuntimeException("indexes ("+r+","+c+") out of range ("+rlen+","+clen+")");
if(sparse)
{
if(sparseRows==null || sparseRows.length<=r || sparseRows[r]==null)
return 0;
return sparseRows[r].get(c);
}else
{
if(denseBlock==null)
return 0;
return denseBlock[r*clen+c];
}
}
@Override
public void setValue(int r, int c, double v)
{
if(r>rlen || c > clen)
throw new RuntimeException("indexes ("+r+","+c+") out of range ("+rlen+","+clen+")");
if(sparse)
{
if( (sparseRows==null || sparseRows.length<=r || sparseRows[r]==null) && v==0.0)
return;
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
if(sparseRows[r].set(c, v))
nonZeros++;
}else
{
if(denseBlock==null && v==0.0)
return;
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
{
denseBlock=new double[limit];
//Arrays.fill(denseBlock, 0, limit, 0);
}
int index=r*clen+c;
if(denseBlock[index]==0)
nonZeros++;
denseBlock[index]=v;
if(v==0)
nonZeros--;
}
}
@Override
public void setValue(CellIndex index, double v)
{
setValue(index.row, index.column, v);
}
@Override
/**
* If (r,c) \in Block, add v to existing cell
* If not, add a new cell with index (r,c)
*/
public void addValue(int r, int c, double v) {
if(sparse)
{
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
double curV=sparseRows[r].get(c);
if(curV==0)
nonZeros++;
curV+=v;
if(curV==0)
nonZeros--;
else
sparseRows[r].set(c, curV);
}
else
{
int limit=rlen*clen;
if(denseBlock==null)
{
denseBlock=new double[limit];
Arrays.fill(denseBlock, 0, limit, 0);
}
int index=r*clen+c;
if(denseBlock[index]==0)
nonZeros++;
denseBlock[index]+=v;
if(denseBlock[index]==0)
nonZeros--;
}
}
public double quickGetValue(int r, int c)
{
if(sparse)
{
if(sparseRows==null || sparseRows.length<=r || sparseRows[r]==null)
return 0;
return sparseRows[r].get(c);
}
else
{
if(denseBlock==null)
return 0;
return denseBlock[r*clen+c];
}
}
public void quickSetValue(int r, int c, double v)
{
if(sparse)
{
if( (sparseRows==null || sparseRows.length<=r || sparseRows[r]==null) && v==0.0)
return;
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
if(sparseRows[r].set(c, v))
nonZeros++;
}
else
{
if(denseBlock==null && v==0.0)
return;
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
{
denseBlock=new double[limit];
//Arrays.fill(denseBlock, 0, limit, 0);
}
int index=r*clen+c;
if(denseBlock[index]==0)
nonZeros++;
denseBlock[index]=v;
if(v==0)
nonZeros--;
}
}
public double getValueDenseUnsafe(int r, int c)
{
if(denseBlock==null)
return 0;
return denseBlock[r*clen+c];
}
/**
* This can be only called when you know you have properly allocated spaces for a dense representation
* and r and c are in the the range of the dimension
* Note: this function won't keep track of the nozeros
*/
public void setValueDenseUnsafe(int r, int c, double v)
{
denseBlock[r*clen+c]=v;
}
public double getValueSparseUnsafe(int r, int c)
{
if(sparseRows==null || sparseRows.length<=r || sparseRows[r]==null)
return 0;
return sparseRows[r].get(c);
}
/**
* This can be only called when you know you have properly allocated spaces for a sparse representation
* and r and c are in the the range of the dimension
* Note: this function won't keep track of the nozeros
*/
public void setValueSparseUnsafe(int r, int c, double v)
{
sparseRows[r].set(c, v);
}
/**
* Append value is only used when values are appended at the end of each row for the sparse representation
* This can only be called, when the caller knows the access pattern of the block
* @param r
* @param c
* @param v
*/
public void appendValue(int r, int c, double v)
{
if(v==0) return;
if(!sparse)
quickSetValue(r, c, v);
else
{
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
/*else {
if (sparseRows[r].capacity()==0) {
System.out.println(" ... !null: " + sparseRows[r].size() + ", " + sparseRows[r].capacity() + ", " + sparseRows[r].getValueContainer().length + ", " + sparseRows[r].estimatedNzs + ", " + sparseRows[r].maxNzs);
}
}*/
sparseRows[r].append(c, v);
nonZeros++;
}
}
/**
* This can be only called when you know you have properly allocated spaces for a sparse representation
* and r and c are in the the range of the dimension
* Note: this function won't keep track of the nozeros
* This can only be called, when the caller knows the access pattern of the block
*/
public void appendValueSparseUnsafe(int r, int c, double v)
{
sparseRows[r].append(c, v);
}
public void appendRow(int r, SparseRow values)
{
if(values==null)
return;
if(sparse)
{
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(values);
else
sparseRows[r].copy(values);
nonZeros+=values.size();
}else
{
int[] cols=values.getIndexContainer();
double[] vals=values.getValueContainer();
for(int i=0; i<values.size(); i++)
quickSetValue(r, cols[i], vals[i]);
}
}
/**
*
* @param that
* @param rowoffset
* @param coloffset
*/
public void appendToSparse( MatrixBlockDSM that, int rowoffset, int coloffset )
{
if( that==null || that.isEmptyBlock(false) )
return; //nothing to append
//init sparse rows if necessary
//adjustSparseRows(rlen-1);
if( that.sparse ) //SPARSE <- SPARSE
{
for( int i=0; i<that.rlen; i++ )
{
SparseRow brow = that.sparseRows[i];
if( brow!=null && brow.size()>0 )
{
int aix = rowoffset+i;
int len = brow.size();
int[] ix = brow.getIndexContainer();
double[] val = brow.getValueContainer();
if( sparseRows[aix]==null )
sparseRows[aix] = new SparseRow(estimatedNNzsPerRow,clen);
for( int j=0; j<len; j++ )
sparseRows[aix].append(coloffset+ix[j], val[j]);
}
}
}
else //SPARSE <- DENSE
{
for( int i=0; i<that.rlen; i++ )
{
int aix = rowoffset+i;
for( int j=0, bix=i*that.clen; j<that.clen; j++ )
{
double val = that.denseBlock[bix+j];
if( val != 0 )
{
if( sparseRows[aix]==null )//create sparserow only if required
sparseRows[aix] = new SparseRow(estimatedNNzsPerRow,clen);
sparseRows[aix].append(coloffset+j, val);
}
}
}
}
}
/**
*
*/
public void sortSparseRows()
{
if( !sparse || sparseRows==null )
return;
for( SparseRow arow : sparseRows )
if( arow!=null && arow.size()>1 )
arow.sort();
}
/**
* Wrapper method for reduceall-min of a matrix.
*
* @return
* @throws DMLRuntimeException
*/
public double min()
throws DMLRuntimeException
{
//construct operator
AggregateOperator aop = new AggregateOperator(Double.MAX_VALUE, Builtin.getBuiltinFnObject("min"));
AggregateUnaryOperator auop = new AggregateUnaryOperator( aop, ReduceAll.getReduceAllFnObject());
//execute operation
MatrixBlockDSM out = new MatrixBlockDSM(1, 1, false);
MatrixAggLib.aggregateUnaryMatrix(this, out, auop);
return out.quickGetValue(0, 0);
}
/**
* Wrapper method for reduceall-max of a matrix.
*
* @return
* @throws DMLRuntimeException
*/
public double max()
throws DMLRuntimeException
{
//construct operator
AggregateOperator aop = new AggregateOperator(-Double.MAX_VALUE, Builtin.getBuiltinFnObject("max"));
AggregateUnaryOperator auop = new AggregateUnaryOperator( aop, ReduceAll.getReduceAllFnObject());
//execute operation
MatrixBlockDSM out = new MatrixBlockDSM(1, 1, false);
MatrixAggLib.aggregateUnaryMatrix(this, out, auop);
return out.quickGetValue(0, 0);
}
////////
// basic block handling functions
public void examSparsity()
throws DMLRuntimeException
{
double sp = ((double)nonZeros/rlen)/clen;
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(sparse)
{
if(sp>=SPARCITY_TURN_POINT || clen<=SKINNY_MATRIX_TURN_POINT) {
//System.out.println("Calling sparseToDense(): nz=" + nonZeros + ", rlen=" + rlen + ", clen=" + clen + ", sparsity = " + sp + ", spturn=" + SPARCITY_TURN_POINT );
sparseToDense();
}
}
else
{
if(sp<SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT) {
//System.out.println("Calling denseToSparse(): nz=" + nonZeros + ", rlen=" + rlen + ", clen=" + clen + ", sparsity = " + sp + ", spturn=" + SPARCITY_TURN_POINT );
denseToSparse();
}
}
}
private void denseToSparse()
{
//LOG.info("**** denseToSparse: "+this.getNumRows()+"x"+this.getNumColumns()+" nonZeros: "+this.nonZeros);
sparse=true;
adjustSparseRows(rlen-1);
reset();
if(denseBlock==null)
return;
int index=0;
for(int r=0; r<rlen; r++)
{
for(int c=0; c<clen; c++)
{
if(denseBlock[index]!=0)
{
if(sparseRows[r]==null) //create sparse row only if required
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[r].append(c, denseBlock[index]);
nonZeros++;
}
index++;
}
}
//cleanup dense block
denseBlock = null;
}
private void sparseToDense()
throws DMLRuntimeException
{
//LOG.info("**** sparseToDense: "+this.getNumRows()+"x"+this.getNumColumns()+" nonZeros: "+this.nonZeros);
sparse=false;
int limit=rlen*clen;
if ( limit < 0 ) {
throw new DMLRuntimeException("Unexpected error in sparseToDense().. limit < 0: " + rlen + ", " + clen + ", " + limit);
}
allocateDenseBlock();
Arrays.fill(denseBlock, 0, limit, 0);
nonZeros=0;
if(sparseRows==null)
return;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
if(values[i]==0) continue;
denseBlock[r*clen+cols[i]]=values[i];
nonZeros++;
}
}
//cleanup sparse rows
sparseRows = null;
}
public void recomputeNonZeros()
{
nonZeros=0;
if( sparse && sparseRows!=null )
{
int limit = Math.min(rlen, sparseRows.length);
for(int i=0; i<limit; i++)
if(sparseRows[i]!=null)
nonZeros += sparseRows[i].size();
}
else if( !sparse && denseBlock!=null )
{
int limit=rlen*clen;
for(int i=0; i<limit; i++)
{
//HotSpot JVM bug causes crash in presence of NaNs
//nonZeros += (denseBlock[i]!=0) ? 1 : 0;
if( denseBlock[i]!=0 )
nonZeros++;
}
}
}
private long recomputeNonZeros(int rl, int ru, int cl, int cu)
{
long nnz = 0;
if(sparse)
{
if(sparseRows!=null)
{
int rlimit = Math.min( ru+1, Math.min(rlen, sparseRows.length) );
if( cl==0 && cu==clen-1 ) //specific case: all cols
{
for(int i=rl; i<rlimit; i++)
if(sparseRows[i]!=null && sparseRows[i].size()>0)
nnz+=sparseRows[i].size();
}
else if( cl==cu ) //specific case: one column
{
for(int i=rl; i<rlimit; i++)
if(sparseRows[i]!=null && sparseRows[i].size()>0)
nnz += (sparseRows[i].get(cl)!=0) ? 1 : 0;
}
else //general case
{
int astart,aend;
for(int i=rl; i<rlimit; i++)
if(sparseRows[i]!=null && sparseRows[i].size()>0)
{
SparseRow arow = sparseRows[i];
astart = arow.searchIndexesFirstGTE(cl);
aend = arow.searchIndexesFirstGTE(cu);
nnz += (astart!=-1) ? (aend-astart+1) : 0;
}
}
}
}else
{
if(denseBlock!=null)
{
for( int i=rl, ix=rl*clen; i<=ru; i++, ix+=clen )
for( int j=cl; j<=cu; j++ )
{
//HotSpot JVM bug causes crash in presence of NaNs
//nnz += (denseBlock[ix+j]!=0) ? 1 : 0;
if( denseBlock[ix+j]!=0 )
nnz++;
}
}
}
return nnz;
}
public void copy(MatrixValue thatValue)
{
MatrixBlockDSM that;
try {
that = checkType(thatValue);
} catch (DMLUnsupportedOperationException e) {
throw new RuntimeException(e);
}
if( this == that ) //prevent data loss (e.g., on sparse-dense conversion)
throw new RuntimeException( "Copy must not overwrite itself!" );
this.rlen=that.rlen;
this.clen=that.clen;
this.sparse=checkRealSparsity(that);
estimatedNNzsPerRow=(int)Math.ceil((double)thatValue.getNonZeros()/(double)rlen);
if(this.sparse && that.sparse)
copySparseToSparse(that);
else if(this.sparse && !that.sparse)
copyDenseToSparse(that);
else if(!this.sparse && that.sparse)
copySparseToDense(that);
else
copyDenseToDense(that);
}
public void copy(MatrixValue thatValue, boolean sp) {
MatrixBlockDSM that;
try {
that = checkType(thatValue);
} catch (DMLUnsupportedOperationException e) {
throw new RuntimeException(e);
}
if( this == that ) //prevent data loss (e.g., on sparse-dense conversion)
throw new RuntimeException( "Copy must not overwrite itself!" );
this.rlen=that.rlen;
this.clen=that.clen;
this.sparse=sp;
estimatedNNzsPerRow=(int)Math.ceil((double)thatValue.getNonZeros()/(double)rlen);
if(this.sparse && that.sparse)
copySparseToSparse(that);
else if(this.sparse && !that.sparse)
copyDenseToSparse(that);
else if(!this.sparse && that.sparse)
copySparseToDense(that);
else
copyDenseToDense(that);
}
private void copySparseToSparse(MatrixBlockDSM that)
{
this.nonZeros=that.nonZeros;
if(that.sparseRows==null)
{
resetSparse();
return;
}
adjustSparseRows(Math.min(that.rlen, that.sparseRows.length)-1);
for(int i=0; i<Math.min(that.sparseRows.length, rlen); i++)
{
if(that.sparseRows[i]!=null)
{
if(sparseRows[i]==null)
sparseRows[i]=new SparseRow(that.sparseRows[i]);
else
sparseRows[i].copy(that.sparseRows[i]);
}else if(this.sparseRows[i]!=null)
this.sparseRows[i].reset(estimatedNNzsPerRow, clen);
}
}
private void copyDenseToDense(MatrixBlockDSM that)
{
this.nonZeros=that.nonZeros;
if(that.denseBlock==null)
{
if(denseBlock!=null)
Arrays.fill(denseBlock, 0);
return;
}
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
denseBlock=new double[limit];
System.arraycopy(that.denseBlock, 0, this.denseBlock, 0, limit);
}
private void copySparseToDense(MatrixBlockDSM that)
{
this.nonZeros=that.nonZeros;
if(that.sparseRows==null)
{
if(denseBlock!=null)
Arrays.fill(denseBlock, 0);
return;
}
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
denseBlock=new double[limit];
else
Arrays.fill(denseBlock, 0, limit, 0);
int start=0;
for(int r=0; r<Math.min(that.sparseRows.length, rlen); r++, start+=clen)
{
if(that.sparseRows[r]==null) continue;
double[] values=that.sparseRows[r].getValueContainer();
int[] cols=that.sparseRows[r].getIndexContainer();
for(int i=0; i<that.sparseRows[r].size(); i++)
{
denseBlock[start+cols[i]]=values[i];
}
}
}
private void copyDenseToSparse(MatrixBlockDSM that)
{
nonZeros = that.nonZeros;
if(that.denseBlock==null)
{
resetSparse();
return;
}
adjustSparseRows(rlen-1);
for(int i=0, ix=0; i<rlen; i++)
{
if( sparseRows[i]!=null )
sparseRows[i].reset(estimatedNNzsPerRow, clen);
for(int j=0; j<clen; j++)
{
double val = that.denseBlock[ix++];
if( val != 0 )
{
if(sparseRows[i]==null) //create sparse row only if required
sparseRows[i]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[i].append(j, val);
}
}
}
}
/**
* In-place copy of matrix src into the index range of the existing current matrix.
* Note that removal of existing nnz in the index range and nnz maintenance is
* only done if 'awareDestNZ=true',
*
* @param rl
* @param ru
* @param cl
* @param cu
* @param src
* @param awareDestNZ
* true, forces (1) to remove existing non-zeros in the index range of the
* destination if not present in src and (2) to internally maintain nnz
* false, assume empty index range in destination and do not maintain nnz
* (the invoker is responsible to recompute nnz after all copies are done)
*/
public void copy(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ )
{
if(sparse && src.sparse)
copySparseToSparse(rl, ru, cl, cu, src, awareDestNZ);
else if(sparse && !src.sparse)
copyDenseToSparse(rl, ru, cl, cu, src, awareDestNZ);
else if(!sparse && src.sparse)
copySparseToDense(rl, ru, cl, cu, src, awareDestNZ);
else
copyDenseToDense(rl, ru, cl, cu, src, awareDestNZ);
}
private void copySparseToSparse(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.sparseRows==null)
{
if( awareDestNZ && sparseRows != null )
copyEmptyToSparse(rl, ru, cl, cu, true);
return;
}
if(sparseRows==null)
sparseRows=new SparseRow[rlen];
else if( awareDestNZ )
{
copyEmptyToSparse(rl, ru, cl, cu, true);
//explicit clear if awareDestNZ because more efficient since
//src will have multiple columns and only few overwriting values
}
//copy values
int alen;
int[] aix;
double[] avals;
for( int i=0; i<src.rlen; i++ )
{
SparseRow arow = src.sparseRows[i];
if( arow != null && arow.size()>0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
if( sparseRows[rl+i] == null || sparseRows[rl+i].size()==0 )
{
sparseRows[rl+i] = new SparseRow(estimatedNNzsPerRow, clen);
SparseRow brow = sparseRows[rl+i];
for( int j=0; j<alen; j++ )
brow.append(cl+aix[j], avals[j]);
if( awareDestNZ )
nonZeros += brow.size();
}
else if( awareDestNZ ) //general case (w/ awareness NNZ)
{
SparseRow brow = sparseRows[rl+i];
int lnnz = brow.size();
if( cl==cu && cl==aix[0] )
{
if (avals[0]==0)
brow.deleteIndex(cl);
else
brow.set(cl, avals[0] );
}
else
{
brow.deleteIndexRange(cl, cu);
for( int j=0; j<alen; j++ )
brow.set(cl+aix[j], avals[j]);
}
nonZeros += (brow.size() - lnnz);
}
else //general case (w/o awareness NNZ)
{
SparseRow brow = sparseRows[rl+i];
//brow.set(cl, arow);
for( int j=0; j<alen; j++ )
brow.set(cl+aix[j], avals[j]);
}
}
}
}
private void copySparseToDense(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.sparseRows==null)
{
if( awareDestNZ && denseBlock != null ) {
nonZeros -= (int)recomputeNonZeros(rl, ru, cl, cu);
copyEmptyToDense(rl, ru, cl, cu);
}
return;
}
if(denseBlock==null)
allocateDenseBlock();
else if( awareDestNZ )
{
nonZeros -= (int)recomputeNonZeros(rl, ru, cl, cu);
copyEmptyToDense(rl, ru, cl, cu);
}
//copy values
int alen;
int[] aix;
double[] avals;
for( int i=0, ix=rl*clen; i<src.rlen; i++, ix+=clen )
{
SparseRow arow = src.sparseRows[i];
if( arow != null && arow.size()>0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
for( int j=0; j<alen; j++ )
denseBlock[ix+cl+aix[j]] = avals[j];
if(awareDestNZ)
nonZeros += alen;
}
}
}
private void copyDenseToSparse(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.denseBlock==null)
{
if( awareDestNZ && sparseRows != null )
copyEmptyToSparse(rl, ru, cl, cu, true);
return;
}
if(sparseRows==null)
sparseRows=new SparseRow[rlen];
//no need to clear for awareDestNZ since overwritten
//copy values
double val;
for( int i=0, ix=0; i<src.rlen; i++, ix+=src.clen )
{
int rix = rl + i;
if( sparseRows[rix]==null || sparseRows[rix].size()==0 )
{
for( int j=0; j<src.clen; j++ )
if( (val = src.denseBlock[ix+j]) != 0 )
{
if( sparseRows[rix]==null )
sparseRows[rix] = new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[rix].append(cl+j, val);
}
if( awareDestNZ && sparseRows[rix]!=null )
nonZeros += sparseRows[rix].size();
}
else if( awareDestNZ ) //general case (w/ awareness NNZ)
{
SparseRow brow = sparseRows[rix];
int lnnz = brow.size();
if( cl==cu )
{
if ((val = src.denseBlock[ix])==0)
brow.deleteIndex(cl);
else
brow.set(cl, val);
}
else
{
brow.deleteIndexRange(cl, cu);
for( int j=0; j<src.clen; j++ )
if( (val = src.denseBlock[ix+j]) != 0 )
brow.set(cl+j, val);
}
nonZeros += (brow.size() - lnnz);
}
else //general case (w/o awareness NNZ)
{
SparseRow brow = sparseRows[rix];
for( int j=0; j<src.clen; j++ )
if( (val = src.denseBlock[ix+j]) != 0 )
brow.set(cl+j, val);
}
}
}
private void copyDenseToDense(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.denseBlock==null)
{
if( awareDestNZ && denseBlock != null ) {
nonZeros -= (int)recomputeNonZeros(rl, ru, cl, cu);
copyEmptyToDense(rl, ru, cl, cu);
}
return;
}
if(denseBlock==null)
allocateDenseBlock();
//no need to clear for awareDestNZ since overwritten
if( awareDestNZ )
nonZeros = nonZeros - (int)recomputeNonZeros(rl, ru, cl, cu) + src.nonZeros;
//copy values
int rowLen = cu-cl+1;
if(clen == src.clen) //optimization for equal width
System.arraycopy(src.denseBlock, 0, denseBlock, rl*clen+cl, src.rlen*src.clen);
else
for( int i=0, ix1=0, ix2=rl*clen+cl; i<src.rlen; i++, ix1+=src.clen, ix2+=clen )
System.arraycopy(src.denseBlock, ix1, denseBlock, ix2, rowLen);
}
public void copyRowArrayToDense(int destRow, double[] src, int sourceStart)
{
//handle empty dest
if(denseBlock==null)
allocateDenseBlock();
//no need to clear for awareDestNZ since overwritten
System.arraycopy(src, sourceStart, denseBlock, destRow*clen, clen);
}
private void copyEmptyToSparse(int rl, int ru, int cl, int cu, boolean updateNNZ )
{
if( cl==cu ) //specific case: column vector
{
if( updateNNZ )
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
{
int lnnz = sparseRows[i].size();
sparseRows[i].deleteIndex(cl);
nonZeros += (sparseRows[i].size()-lnnz);
}
}
else
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
sparseRows[i].deleteIndex(cl);
}
}
else
{
if( updateNNZ )
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
{
int lnnz = sparseRows[i].size();
sparseRows[i].deleteIndexRange(cl, cu);
nonZeros += (sparseRows[i].size()-lnnz);
}
}
else
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
sparseRows[i].deleteIndexRange(cl, cu);
}
}
}
private void copyEmptyToDense(int rl, int ru, int cl, int cu)
{
int rowLen = cu-cl+1;
if(clen == rowLen) //optimization for equal width
Arrays.fill(denseBlock, rl*clen+cl, ru*clen+cu+1, 0);
else
for( int i=rl, ix2=rl*clen+cl; i<=ru; i++, ix2+=clen )
Arrays.fill(denseBlock, ix2, ix2+rowLen, 0);
}
////////
// Input/Output functions
@Override
public void readFields(DataInput in)
throws IOException
{
rlen = in.readInt();
clen = in.readInt();
byte bformat = in.readByte();
if( bformat<0 || bformat>=BlockType.values().length )
throw new IOException("invalid format: '"+bformat+"' (need to be 0-"+BlockType.values().length+".");
BlockType format=BlockType.values()[bformat];
switch(format)
{
case ULTRA_SPARSE_BLOCK:
sparse = true;
cleanupBlock(true, true); //clean all
readUltraSparseBlock(in);
break;
case SPARSE_BLOCK:
sparse = true;
cleanupBlock(true, false); //reuse sparse
readSparseBlock(in);
break;
case DENSE_BLOCK:
sparse = false;
cleanupBlock(false, true); //reuse dense
readDenseBlock(in);
break;
case EMPTY_BLOCK:
sparse = true;
cleanupBlock(true, true); //clean all
nonZeros = 0;
break;
}
}
private void readDenseBlock(DataInput in) throws IOException {
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length < limit )
denseBlock=new double[limit];
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=in.readDouble();
if(denseBlock[i]!=0)
nonZeros++;
}
}
private void readSparseBlock(DataInput in) throws IOException {
adjustSparseRows(rlen-1);
nonZeros=0;
for(int r=0; r<rlen; r++)
{
int nr=in.readInt();
nonZeros+=nr;
if(nr==0)
{
if(sparseRows[r]!=null)
sparseRows[r].reset(estimatedNNzsPerRow, clen);
continue;
}
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(nr);
else
sparseRows[r].reset(nr, clen);
for(int j=0; j<nr; j++)
sparseRows[r].append(in.readInt(), in.readDouble());
}
}
private void readUltraSparseBlock(DataInput in) throws IOException
{
adjustSparseRows(rlen-1); //adjust to size
resetSparse(); //reset all sparse rows
//at least 1 nonZero, otherwise empty block
nonZeros = in.readInt();
for(int i=0; i<nonZeros; i++)
{
int r = in.readInt();
int c = in.readInt();
double val = in.readDouble();
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(1,clen);
sparseRows[r].append(c, val);
}
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(rlen);
out.writeInt(clen);
if(sparse)
{
if(sparseRows==null || nonZeros==0) //MB or cond
writeEmptyBlock(out);
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
writeSparseToUltraSparse(out); //MB new write
//if it should be dense, then write to the dense format
else if(nonZeros>=((long)rlen)*((long)clen)*SPARCITY_TURN_POINT || clen<=SKINNY_MATRIX_TURN_POINT)
writeSparseToDense(out);
else
writeSparseBlock(out);
}else
{
if(denseBlock==null || nonZeros==0) //MB or cond
writeEmptyBlock(out);
//if it should be sparse
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
writeDenseToUltraSparse(out);
else if(nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT)
writeDenseToSparse(out);
else
writeDenseBlock(out);
}
}
private void writeEmptyBlock(DataOutput out) throws IOException
{
//empty blocks do not need to materialize row information
out.writeByte( BlockType.EMPTY_BLOCK.ordinal() );
}
private void writeDenseBlock(DataOutput out) throws IOException
{
out.writeByte( BlockType.DENSE_BLOCK.ordinal() );
int limit=rlen*clen;
if( out instanceof MatrixBlockDSMDataOutput ) //fast serialize
((MatrixBlockDSMDataOutput)out).writeDoubleArray(limit, denseBlock);
else //general case (if fast serialize not supported)
for(int i=0; i<limit; i++)
out.writeDouble(denseBlock[i]);
}
private void writeSparseBlock(DataOutput out) throws IOException
{
out.writeByte( BlockType.SPARSE_BLOCK.ordinal() );
if( out instanceof MatrixBlockDSMDataOutput ) //fast serialize
((MatrixBlockDSMDataOutput)out).writeSparseRows(rlen, sparseRows);
else //general case (if fast serialize not supported)
{
int r=0;
for(;r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null)
out.writeInt(0);
else
{
int nr=sparseRows[r].size();
out.writeInt(nr);
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int j=0; j<nr; j++)
{
out.writeInt(cols[j]);
out.writeDouble(values[j]);
}
}
}
for(;r<rlen; r++)
out.writeInt(0);
}
}
private void writeSparseToUltraSparse(DataOutput out) throws IOException
{
out.writeByte( BlockType.ULTRA_SPARSE_BLOCK.ordinal() );
out.writeInt(nonZeros);
for(int r=0;r<Math.min(rlen, sparseRows.length); r++)
if(sparseRows[r]!=null && sparseRows[r].size()>0 )
{
int alen = sparseRows[r].size();
int[] aix = sparseRows[r].getIndexContainer();
double[] avals = sparseRows[r].getValueContainer();
for(int j=0; j<alen; j++)
{
out.writeInt(r);
out.writeInt(aix[j]);
out.writeDouble(avals[j]);
}
}
}
private void writeSparseToDense(DataOutput out)
throws IOException
{
//write block type 'dense'
out.writeByte( BlockType.DENSE_BLOCK.ordinal() );
//write data (from sparse to dense)
if( sparseRows==null ) //empty block
for( int i=0; i<rlen*clen; i++ )
out.writeDouble(0);
else //existing sparse block
{
for( int i=0; i<rlen; i++ )
{
if( i<sparseRows.length && sparseRows[i]!=null && sparseRows[i].size()>0 )
{
SparseRow arow = sparseRows[i];
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
//foreach non-zero value, fill with 0s if required
for( int j=0, j2=0; j2<alen; j++, j2++ ) {
for( ; j<aix[j2]; j++ )
out.writeDouble( 0 );
out.writeDouble( avals[j2] );
}
//remaining 0 values in row
for( int j=aix[alen-1]+1; j<clen; j++)
out.writeDouble( 0 );
}
else //empty row
for( int j=0; j<clen; j++ )
out.writeDouble( 0 );
}
}
/* old version with binary search for each cell
out.writeByte( BlockType.DENSE_BLOCK.ordinal() );
for(int i=0; i<rlen; i++)
for(int j=0; j<clen; j++)
out.writeDouble(quickGetValue(i, j));
*/
}
private void writeDenseToUltraSparse(DataOutput out) throws IOException
{
out.writeByte( BlockType.ULTRA_SPARSE_BLOCK.ordinal() );
out.writeInt(nonZeros);
for(int r=0, ix=0; r<rlen; r++)
for(int c=0; c<clen; c++, ix++)
if( denseBlock[ix]!=0 )
{
out.writeInt(r);
out.writeInt(c);
out.writeDouble(denseBlock[ix]);
}
}
private void writeDenseToSparse(DataOutput out)
throws IOException
{
out.writeByte( BlockType.SPARSE_BLOCK.ordinal() );
int start=0;
for(int r=0; r<rlen; r++)
{
//count nonzeros
int nr=0;
for(int i=start; i<start+clen; i++)
if(denseBlock[i]!=0.0)
nr++;
out.writeInt(nr);
for(int c=0; c<clen; c++)
{
if(denseBlock[start]!=0.0)
{
out.writeInt(c);
out.writeDouble(denseBlock[start]);
}
start++;
}
}
}
/**
* NOTE: The used estimates must be kept consistent with the respective write functions.
*
* @return
*/
public long getExactSizeOnDisk()
{
long lrlen = (long) rlen;
long lclen = (long) clen;
long lnonZeros = (long) nonZeros;
//ensure exact size estimates for write
if( lnonZeros<=0 )
//if( sparse || lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT )
{
recomputeNonZeros();
lnonZeros = (long) nonZeros;
}
//get exact size estimate (see write for the corresponding meaning)
if(sparse)
{
if(sparseRows==null || nonZeros==0)
return 9; //empty block
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
return 4 + nonZeros*16 + 9; //ultra sparse block
else if(lnonZeros>=(lrlen*lclen)*SPARCITY_TURN_POINT || lclen<=SKINNY_MATRIX_TURN_POINT)
return lrlen*lclen*8 + 9; //dense block
else
return lrlen*4 + lnonZeros*12 + 9; //sparse block
}else
{
if(denseBlock==null || nonZeros==0)
return 9; //empty block
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
return 4 + nonZeros*16 + 9; //ultra sparse block
else if(lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT && lclen>SKINNY_MATRIX_TURN_POINT)
return lrlen*4 + lnonZeros*12 + 9; //sparse block
else
return lrlen*lclen*8 + 9; //dense block
}
}
////////
// Estimates size and sparsity
public static long estimateSize(long nrows, long ncols, double sparsity)
{
long size=44;//the basic variables and references sizes
//determine sparse/dense representation
boolean sparse=true;
if(ncols<=SKINNY_MATRIX_TURN_POINT)
sparse=false;
else
sparse= sparsity < SPARCITY_TURN_POINT;
//estimate memory consumption for sparse/dense
if(sparse)
{
//NOTES:
// * Each sparse row has a fixed overhead of 8B (reference) + 32B (object) +
// 12B (3 int members), 32B (overhead int array), 32B (overhead double array),
// * Each non-zero value requires 12B for the column-index/value pair.
// * Overheads for arrays, objects, and references refer to 64bit JVMs
// * If nnz < than rows we have only also empty rows.
//account for sparsity and initial capacity
long cnnz = Math.max(SparseRow.initialCapacity, (long)Math.ceil(sparsity*ncols));
long rlen = Math.min(nrows, (long) Math.ceil(sparsity*nrows*ncols));
size += rlen * ( 116 + 12 * cnnz ); //sparse row
size += (nrows-rlen) * 8; //empty rows
//OLD ESTIMATE:
//int len = Math.max(SparseRow.initialCapacity, (int)Math.ceil(sparsity*ncols));
//size += nrows * (28 + 12 * len );
}
else
{
size += nrows*ncols*8;
}
return size;
}
/**
*
* @param lrlen
* @param lclen
* @param lnonZeros
* @param sparse
* @return
*/
public static long estimateSizeOnDisk( long lrlen, long lclen, long lnonZeros, boolean sparse )
{
if(sparse)
{
return lrlen*4 + lnonZeros*12 + 9;
}
else
{
return lrlen*lclen*8 + 9;
}
}
public static SparsityEstimate estimateSparsityOnAggBinary(MatrixBlockDSM m1, MatrixBlockDSM m2, AggregateBinaryOperator op)
{
//NOTE: since MatrixMultLib always uses a dense intermediate output
//with subsequent check for sparsity, we should always return a dense estimate.
//Once, we support more aggregate binary operations, we need to change this.
return new SparsityEstimate(false, m1.getNumRows()*m2.getNumRows());
/*
SparsityEstimate est=new SparsityEstimate();
double m=m2.getNumColumns();
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if ( !op.sparseSafe || m <=SKINNY_MATRIX_TURN_POINT)
{
est.sparse=false;
}
else
{
double n=m1.getNumRows();
double k=m1.getNumColumns();
double nz1=m1.getNonZeros();
double nz2=m2.getNonZeros();
double pq=nz1*nz2/n/k/k/m;
double estimated= 1-Math.pow(1-pq, k);
est.sparse=(estimated < SPARCITY_TURN_POINT);
est.estimatedNonZeros=(int)(estimated*n*m);
}
return est;
*/
}
private static SparsityEstimate estimateSparsityOnBinary(MatrixBlockDSM m1, MatrixBlockDSM m2, BinaryOperator op)
{
SparsityEstimate est=new SparsityEstimate();
double m=m1.getNumColumns();
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(!op.sparseSafe || m<=SKINNY_MATRIX_TURN_POINT)
{
est.sparse=false;
return est;
}
double n=m1.getNumRows();
double nz1=m1.getNonZeros();
double nz2=m2.getNonZeros();
double estimated=0;
if(op.fn instanceof And || op.fn instanceof Multiply)//p*q
{
estimated=nz1/n/m*nz2/n/m;
}else //1-(1-p)*(1-q)
{
estimated=1-(1-nz1/n/m)*(1-nz2/n/m);
}
est.sparse= (estimated<SPARCITY_TURN_POINT);
est.estimatedNonZeros=(int)(estimated*n*m);
return est;
}
private boolean estimateSparsityOnSlice(int selectRlen, int selectClen, int finalRlen, int finalClen)
{
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(finalClen<=SKINNY_MATRIX_TURN_POINT)
return false;
else
return((double)nonZeros/(double)rlen/(double)clen*(double)selectRlen*(double)selectClen/(double)finalRlen/(double)finalClen<SPARCITY_TURN_POINT);
}
private boolean estimateSparsityOnLeftIndexing(long rlenm1, long clenm1, int nnzm1, int nnzm2)
{
boolean ret = (clenm1>SKINNY_MATRIX_TURN_POINT);
long ennz = Math.min(rlenm1*clenm1, nnzm1+nnzm2);
return (ret && (((double)ennz)/rlenm1/clenm1) < SPARCITY_TURN_POINT);
}
private boolean estimateSparsityOnGroupedAgg( long rlen, long groups )
{
boolean ret = (groups>SKINNY_MATRIX_TURN_POINT);
return (ret && (((double)rlen)/groups) < SPARCITY_TURN_POINT);
}
////////
// Core block operations (called from instructions)
public MatrixValue scalarOperations(ScalarOperator op, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM ret = checkType(result);
// estimate the sparsity structure of result matrix
boolean sp = this.sparse; // by default, we guess result.sparsity=input.sparsity
if (!op.sparseSafe)
sp = false; // if the operation is not sparse safe, then result will be in dense format
if( ret==null )
ret = new MatrixBlockDSM(rlen, clen, sp, this.nonZeros);
else
ret.reset(rlen, clen, sp, this.nonZeros);
ret.copy(this, sp);
if(op.sparseSafe)
ret.sparseScalarOperationsInPlace(op);
else
ret.denseScalarOperationsInPlace(op);
return ret;
}
public void scalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(op.sparseSafe)
this.sparseScalarOperationsInPlace(op);
else
this.denseScalarOperationsInPlace(op);
}
/**
* Note: only apply to non zero cells
*
* @param op
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
private void sparseScalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(sparse)
{
if(sparseRows==null)
return;
nonZeros=0;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] values=sparseRows[r].getValueContainer();
int[] cols=sparseRows[r].getIndexContainer();
int pos=0;
for(int i=0; i<sparseRows[r].size(); i++)
{
double v=op.executeScalar(values[i]);
if(v!=0)
{
values[pos]=v;
cols[pos]=cols[i];
pos++;
nonZeros++;
}
}
sparseRows[r].truncate(pos);
}
}else
{
//early abort possible since sparsesafe
if(denseBlock==null)
return;
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.executeScalar(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
private void denseScalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if( sparse ) //SPARSE MATRIX
{
double v;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
v=op.executeScalar(quickGetValue(r, c));
quickSetValue(r, c, v);
}
}
else //DENSE MATRIX
{
//early abort not possible because not sparsesafe (e.g., A+7)
if(denseBlock==null)
allocateDenseBlock();
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.executeScalar(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
public MatrixValue unaryOperations(UnaryOperator op, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
checkType(result);
// estimate the sparsity structure of result matrix
boolean sp = this.sparse; // by default, we guess result.sparsity=input.sparsity
if (!op.sparseSafe)
sp = false; // if the operation is not sparse safe, then result will be in dense format
if(result==null)
result=new MatrixBlockDSM(rlen, clen, sp, this.nonZeros);
result.copy(this);
//core execution
((MatrixBlockDSM)result).unaryOperationsInPlace(op);
return result;
}
public void unaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(op.sparseSafe)
sparseUnaryOperationsInPlace(op);
else
denseUnaryOperationsInPlace(op);
}
/**
* only apply to non zero cells
*
* @param op
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
private void sparseUnaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(sparse)
{
if(sparseRows==null)
return;
nonZeros=0;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] values=sparseRows[r].getValueContainer();
int[] cols=sparseRows[r].getIndexContainer();
int pos=0;
for(int i=0; i<sparseRows[r].size(); i++)
{
double v=op.fn.execute(values[i]);
if(v!=0)
{
values[pos]=v;
cols[pos]=cols[i];
pos++;
nonZeros++;
}
}
sparseRows[r].truncate(pos);
}
}
else
{
//early abort possible since sparsesafe
if(denseBlock==null)
return;
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.fn.execute(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
private void denseUnaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if( sparse ) //SPARSE MATRIX
{
double v;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
v=op.fn.execute(quickGetValue(r, c));
quickSetValue(r, c, v);
}
}
else//DENSE MATRIX
{
//early abort not possible because not sparsesafe
if(denseBlock==null)
allocateDenseBlock();
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.fn.execute(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
public MatrixValue binaryOperations(BinaryOperator op, MatrixValue thatValue, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that=checkType(thatValue);
checkType(result);
if(this.rlen!=that.rlen || this.clen!=that.clen)
throw new RuntimeException("block sizes are not matched for binary " +
"cell operations: "+this.rlen+"*"+this.clen+" vs "+ that.rlen+"*"
+that.clen);
MatrixBlockDSM tmp = null;
if(op.sparseSafe)
tmp = sparseBinaryHelp(op, that, (MatrixBlockDSM)result);
else
tmp = denseBinaryHelp(op, that, (MatrixBlockDSM)result);
return tmp;
}
private MatrixBlockDSM sparseBinaryHelp(BinaryOperator op, MatrixBlockDSM that, MatrixBlockDSM result)
throws DMLRuntimeException
{
//+, -, (*)
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(result==null)
result=new MatrixBlockDSM(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
else
result.reset(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
if(this.sparse && that.sparse)
{
//special case, if both matrices are all 0s, just return
if(this.sparseRows==null && that.sparseRows==null)
return result;
if(result.sparse)
result.adjustSparseRows(result.rlen-1);
if(this.sparseRows!=null)
this.adjustSparseRows(rlen-1);
if(that.sparseRows!=null)
that.adjustSparseRows(that.rlen-1);
if(this.sparseRows!=null && that.sparseRows!=null)
{
for(int r=0; r<rlen; r++)
{
if(this.sparseRows[r]==null && that.sparseRows[r]==null)
continue;
if(result.sparse)
{
int estimateSize=0;
if(this.sparseRows[r]!=null)
estimateSize+=this.sparseRows[r].size();
if(that.sparseRows[r]!=null)
estimateSize+=that.sparseRows[r].size();
estimateSize=Math.min(clen, estimateSize);
if(result.sparseRows[r]==null)
result.sparseRows[r]=new SparseRow(estimateSize, result.clen);
else if(result.sparseRows[r].capacity()<estimateSize)
result.sparseRows[r].recap(estimateSize);
}
if(this.sparseRows[r]!=null && that.sparseRows[r]!=null)
{
mergeForSparseBinary(op, this.sparseRows[r].getValueContainer(),
this.sparseRows[r].getIndexContainer(), this.sparseRows[r].size(),
that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), r, result);
}else if(this.sparseRows[r]==null)
{
appendRightForSparseBinary(op, that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), 0, r, result);
}else
{
appendLeftForSparseBinary(op, this.sparseRows[r].getValueContainer(),
this.sparseRows[r].getIndexContainer(), this.sparseRows[r].size(), 0, r, result);
}
}
}else if(this.sparseRows==null)
{
for(int r=0; r<rlen; r++)
{
if(that.sparseRows[r]==null)
continue;
if(result.sparse)
{
if(result.sparseRows[r]==null)
result.sparseRows[r]=new SparseRow(that.sparseRows[r].size(), result.clen);
else if(result.sparseRows[r].capacity()<that.sparseRows[r].size())
result.sparseRows[r].recap(that.sparseRows[r].size());
}
appendRightForSparseBinary(op, that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), 0, r, result);
}
}else
{
for(int r=0; r<rlen; r++)
{
if(this.sparseRows[r]==null)
continue;
if(result.sparse)
{
if(result.sparseRows[r]==null)
result.sparseRows[r]=new SparseRow(this.sparseRows[r].size(), result.clen);
else if(result.sparseRows[r].capacity()<this.sparseRows[r].size())
result.sparseRows[r].recap(this.sparseRows[r].size());
}
appendLeftForSparseBinary(op, this.sparseRows[r].getValueContainer(),
this.sparseRows[r].getIndexContainer(), this.sparseRows[r].size(), 0, r, result);
}
}
}
else if( !result.sparse && (this.sparse || that.sparse) &&
(op.fn instanceof Plus || op.fn instanceof Minus ||
(op.fn instanceof Multiply && !that.sparse )))
{
//specific case in order to prevent binary search on sparse inputs (see quickget and quickset)
result.allocateDenseBlock();
int m = result.rlen;
int n = result.clen;
double[] c = result.denseBlock;
//1) process left input: assignment
int alen;
int[] aix;
double[] avals;
if( this.sparse ) //SPARSE left
{
Arrays.fill(result.denseBlock, 0, result.denseBlock.length, 0);
if( this.sparseRows != null )
{
for( int i=0, ix=0; i<m; i++, ix+=n ) {
SparseRow arow = this.sparseRows[i];
if( arow != null && arow.size() > 0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
for(int k = 0; k < alen; k++)
c[ix+aix[k]] = avals[k];
}
}
}
}
else //DENSE left
{
if( this.denseBlock!=null )
System.arraycopy(this.denseBlock, 0, c, 0, m*n);
else
Arrays.fill(result.denseBlock, 0, result.denseBlock.length, 0);
}
//2) process right input: op.fn (+,-,*), * only if dense
if( that.sparse ) //SPARSE right
{
if(that.sparseRows!=null)
{
for( int i=0, ix=0; i<m; i++, ix+=n ) {
SparseRow arow = that.sparseRows[i];
if( arow != null && arow.size() > 0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
for(int k = 0; k < alen; k++)
c[ix+aix[k]] = op.fn.execute(c[ix+aix[k]], avals[k]);
}
}
}
}
else //DENSE right
{
if( that.denseBlock!=null )
for( int i=0; i<m*n; i++ )
c[i] = op.fn.execute(c[i], that.denseBlock[i]);
else if(op.fn instanceof Multiply)
Arrays.fill(result.denseBlock, 0, result.denseBlock.length, 0);
}
//3) recompute nnz
result.recomputeNonZeros();
}
else if( !result.sparse && !this.sparse && !that.sparse && this.denseBlock!=null && that.denseBlock!=null )
{
result.allocateDenseBlock();
int m = result.rlen;
int n = result.clen;
double[] c = result.denseBlock;
//int nnz = 0;
for( int i=0; i<m*n; i++ )
{
c[i] = op.fn.execute(this.denseBlock[i], that.denseBlock[i]);
//HotSpot JVM bug causes crash in presence of NaNs
//nnz += (c[i]!=0)? 1 : 0;
if( c[i] != 0 )
result.nonZeros++;
}
//result.nonZeros = nnz;
}
else //generic case
{
double thisvalue, thatvalue, resultvalue;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
thisvalue=this.quickGetValue(r, c);
thatvalue=that.quickGetValue(r, c);
if(thisvalue==0 && thatvalue==0)
continue;
resultvalue=op.fn.execute(thisvalue, thatvalue);
result.appendValue(r, c, resultvalue);
}
}
return result;
}
private MatrixBlockDSM denseBinaryHelp(BinaryOperator op, MatrixBlockDSM that, MatrixBlockDSM result)
throws DMLRuntimeException
{
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(result==null)
result=new MatrixBlockDSM(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
else
result.reset(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
double v = op.fn.execute(this.quickGetValue(r, c), that.quickGetValue(r, c));
result.appendValue(r, c, v);
}
return result;
}
/*
* like a merge sort
*/
private static void mergeForSparseBinary(BinaryOperator op, double[] values1, int[] cols1, int size1,
double[] values2, int[] cols2, int size2, int resultRow, MatrixBlockDSM result)
throws DMLRuntimeException
{
int p1=0, p2=0, column;
double v;
//merge
while(p1<size1 && p2< size2)
{
if(cols1[p1]<cols2[p2])
{
v=op.fn.execute(values1[p1], 0);
column=cols1[p1];
p1++;
}else if(cols1[p1]==cols2[p2])
{
v=op.fn.execute(values1[p1], values2[p2]);
column=cols1[p1];
p1++;
p2++;
}else
{
v=op.fn.execute(0, values2[p2]);
column=cols2[p2];
p2++;
}
result.appendValue(resultRow, column, v);
}
//add left over
appendLeftForSparseBinary(op, values1, cols1, size1, p1, resultRow, result);
appendRightForSparseBinary(op, values2, cols2, size2, p2, resultRow, result);
}
private static void appendLeftForSparseBinary(BinaryOperator op, double[] values1, int[] cols1, int size1,
int pos, int resultRow, MatrixBlockDSM result)
throws DMLRuntimeException
{
for(int j=pos; j<size1; j++)
{
double v = op.fn.execute(values1[j], 0);
result.appendValue(resultRow, cols1[j], v);
}
}
private static void appendRightForSparseBinary(BinaryOperator op, double[] values2, int[] cols2, int size2,
int pos, int resultRow, MatrixBlockDSM result) throws DMLRuntimeException
{
for( int j=pos; j<size2; j++ )
{
double v = op.fn.execute(0, values2[j]);
result.appendValue(resultRow, cols2[j], v);
}
}
public void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction,
MatrixValue newWithCorrection)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//assert(aggOp.correctionExists);
MatrixBlockDSM cor=checkType(correction);
MatrixBlockDSM newWithCor=checkType(newWithCorrection);
KahanObject buffer=new KahanObject(0, 0);
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW)
{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=cor.quickGetValue(0, c);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c),
newWithCor.quickGetValue(r+1, c));
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(0, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
{
if(aggOp.increOp.fn instanceof Builtin
&& ((Builtin)(aggOp.increOp.fn)).bFunc == Builtin.BuiltinFunctionCode.MAXINDEX ){
for(int r=0; r<rlen; r++){
double currMaxValue = cor.quickGetValue(r, 0);
long newMaxIndex = (long)newWithCor.quickGetValue(r, 0);
double newMaxValue = newWithCor.quickGetValue(r, 1);
double update = aggOp.increOp.fn.execute(newMaxValue, currMaxValue);
if(update == 1){
quickSetValue(r, 0, newMaxIndex);
cor.quickSetValue(r, 0, newMaxValue);
}
}
}else{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=cor.quickGetValue(r, 0);;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c), newWithCor.quickGetValue(r, c+1));
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, 0, buffer._correction);
}
}
}
else if(aggOp.correctionLocation==CorrectionLocationType.NONE)
{
//e.g., ak+ kahan plus as used in sum, mapmult, mmcj and tsmm
if(aggOp.increOp.fn instanceof KahanPlus)
{
MatrixAggLib.aggregateBinaryMatrix(newWithCor, this, cor);
}
else
{
if( newWithCor.isInSparseFormat() && aggOp.sparseSafe ) //SPARSE
{
SparseRow[] bRows = newWithCor.getSparseRows();
if( bRows==null ) //early abort on empty block
return;
for( int r=0; r<Math.min(rlen, bRows.length); r++ )
{
SparseRow brow = bRows[r];
if( brow != null && brow.size() > 0 )
{
int blen = brow.size();
int[] bix = brow.getIndexContainer();
double[] bvals = brow.getValueContainer();
for( int j=0; j<blen; j++)
{
int c = bix[j];
buffer._sum = this.quickGetValue(r, c);
buffer._correction = cor.quickGetValue(r, c);
buffer = (KahanObject) aggOp.increOp.fn.execute(buffer, bvals[j]);
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, c, buffer._correction);
}
}
}
}
else //DENSE or SPARSE (!sparsesafe)
{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=cor.quickGetValue(r, c);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c));
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, c, buffer._correction);
}
}
//change representation if required
//(note since ak+ on blocks is currently only applied in MR, hence no need to account for this in mem estimates)
examSparsity();
}
}
else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOROWS)
{
double n, n2, mu2;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=cor.quickGetValue(0, c);
buffer._correction=cor.quickGetValue(1, c);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r+1, c);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(0, c, n);
cor.quickSetValue(1, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS)
{
double n, n2, mu2;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=cor.quickGetValue(r, 0);
buffer._correction=cor.quickGetValue(r, 1);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r, c+1);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, 0, n);
cor.quickSetValue(r, 1, buffer._correction);
}
}
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
}
public void incrementalAggregate(AggregateOperator aggOp, MatrixValue newWithCorrection)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//assert(aggOp.correctionExists);
MatrixBlockDSM newWithCor=checkType(newWithCorrection);
KahanObject buffer=new KahanObject(0, 0);
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW)
{
for(int r=0; r<rlen-1; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=this.quickGetValue(r+1, c);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c),
newWithCor.quickGetValue(r+1, c));
quickSetValue(r, c, buffer._sum);
quickSetValue(r+1, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
{
if(aggOp.increOp.fn instanceof Builtin
&& ((Builtin)(aggOp.increOp.fn)).bFunc == Builtin.BuiltinFunctionCode.MAXINDEX ){
for(int r = 0; r < rlen; r++){
double currMaxValue = quickGetValue(r, 1);
long newMaxIndex = (long)newWithCor.quickGetValue(r, 0);
double newMaxValue = newWithCor.quickGetValue(r, 1);
double update = aggOp.increOp.fn.execute(newMaxValue, currMaxValue);
if(update == 1){
quickSetValue(r, 0, newMaxIndex);
quickSetValue(r, 1, newMaxValue);
}
}
}else{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen-1; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=this.quickGetValue(r, c+1);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c), newWithCor.quickGetValue(r, c+1));
quickSetValue(r, c, buffer._sum);
quickSetValue(r, c+1, buffer._correction);
}
}
}/*else if(aggOp.correctionLocation==0)
{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
//buffer._sum=this.getValue(r, c);
//buffer._correction=0;
//buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.getValue(r, c));
setValue(r, c, this.getValue(r, c)+newWithCor.getValue(r, c));
}
}*/else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOROWS)
{
double n, n2, mu2;
for(int r=0; r<rlen-2; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=this.quickGetValue(r+1, c);
buffer._correction=this.quickGetValue(r+2, c);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r+1, c);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
quickSetValue(r+1, c, n);
quickSetValue(r+2, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS)
{
double n, n2, mu2;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen-2; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=this.quickGetValue(r, c+1);
buffer._correction=this.quickGetValue(r, c+2);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r, c+1);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
quickSetValue(r, c+1, n);
quickSetValue(r, c+2, buffer._correction);
}
}
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
}
@Override
public MatrixValue reorgOperations(ReorgOperator op, MatrixValue ret, int startRow, int startColumn, int length)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if (!(op.fn.equals(SwapIndex.getSwapIndexFnObject()) || op.fn.equals(MaxIndex.getMaxIndexFnObject())))
throw new DMLRuntimeException("the current reorgOperations cannot support: "+op.fn.getClass()+".");
MatrixBlockDSM result=checkType(ret);
CellIndex tempCellIndex = new CellIndex(-1,-1);
boolean reducedDim=op.fn.computeDimension(rlen, clen, tempCellIndex);
boolean sps;
if(reducedDim)
sps = false;
else if(op.fn.equals(MaxIndex.getMaxIndexFnObject()))
sps = true;
else
sps = checkRealSparsity(this, true);
if(result==null)
result=new MatrixBlockDSM(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
else
result.reset(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
if( MatrixReorgLib.isSupportedReorgOperator(op) )
{
//SPECIAL case (operators with special performance requirements,
//or size-dependent special behavior)
MatrixReorgLib.reorg(this, result, op);
}
else
{
//GENERIC case (any reorg operator)
CellIndex temp = new CellIndex(0, 0);
if(sparse)
{
if(sparseRows!=null)
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
tempCellIndex.set(r, cols[i]);
op.fn.execute(tempCellIndex, temp);
result.appendValue(temp.row, temp.column, values[i]);
}
}
}
}
else
{
if( denseBlock != null )
{
if( result.isInSparseFormat() ) //SPARSE<-DENSE
{
double[] a = denseBlock;
for( int i=0, aix=0; i<rlen; i++ )
for( int j=0; j<clen; j++, aix++ )
{
temp.set(i, j);
op.fn.execute(temp, temp);
result.appendValue(temp.row, temp.column, a[aix]);
}
}
else //DENSE<-DENSE
{
result.allocateDenseBlock();
Arrays.fill(result.denseBlock, 0);
double[] a = denseBlock;
double[] c = result.denseBlock;
int n = result.clen;
for( int i=0, aix=0; i<rlen; i++ )
for( int j=0; j<clen; j++, aix++ )
{
temp.set(i, j);
op.fn.execute(temp, temp);
c[temp.row*n+temp.column] = a[aix];
}
result.nonZeros = nonZeros;
}
}
}
}
return result;
}
/**
*
* @param that
* @param ret
* @return
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
public MatrixBlockDSM appendOperations( MatrixBlockDSM that, MatrixBlockDSM ret )
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM result = checkType( ret );
final int m = rlen;
final int n = clen+that.clen;
final int nnz = nonZeros+that.nonZeros;
boolean sp = checkRealSparsity(m, n, nnz);
//init result matrix
if( result == null )
result = new MatrixBlockDSM(m, n, sp, nnz);
else
result.reset(m, n, sp, nnz);
//core append operation
//copy left and right input into output
if( !result.sparse ) //DENSE
{
result.copy(0, m-1, 0, clen-1, this, false);
result.copy(0, m-1, clen, n-1, that, false);
}
else //SPARSE
{
result.adjustSparseRows(rlen-1);
result.appendToSparse(this, 0, 0);
result.appendToSparse(that, 0, clen);
}
result.nonZeros = nnz;
return result;
}
/**
*
* @param op
* @param ret
* @param startRow
* @param startColumn
* @param length
* @return
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
@Deprecated
public MatrixValue appendOperations(ReorgOperator op, MatrixValue ret, int startRow, int startColumn, int length)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM result=checkType(ret);
CellIndex tempCellIndex = new CellIndex(-1,-1);
boolean reducedDim=op.fn.computeDimension(rlen, clen, tempCellIndex);
boolean sps;
if(reducedDim)
sps=false;
else
sps=checkRealSparsity(this);
if(result==null)
result=new MatrixBlockDSM(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
else if(result.getNumRows()==0 && result.getNumColumns()==0)
result.reset(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
CellIndex temp = new CellIndex(0, 0);
if(sparse)
{
if(sparseRows!=null)
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
tempCellIndex.set(r, cols[i]);
op.fn.execute(tempCellIndex, temp);
result.appendValue(temp.row, temp.column, values[i]);
}
}
}
}else
{
if(denseBlock!=null)
{
int limit=rlen*clen;
int r,c;
for(int i=0; i<limit; i++)
{
r=i/clen;
c=i%clen;
temp.set(r, c);
op.fn.execute(temp, temp);
result.appendValue(temp.row, temp.column, denseBlock[i]);
}
}
}
return result;
}
/**
*
* @param out
* @param tstype
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue transposeSelfMatrixMultOperations( MatrixBlockDSM out, MMTSJType tstype )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//check for transpose type
if( !(tstype == MMTSJType.LEFT || tstype == MMTSJType.RIGHT) )
throw new DMLRuntimeException("Invalid MMTSJ type '"+tstype+"'.");
//compute matrix mult
boolean leftTranspose = ( tstype == MMTSJType.LEFT );
MatrixMultLib.matrixMultTransposeSelf(this, out, leftTranspose);
return out;
}
/**
* Method to perform leftIndexing operation for a given lower and upper bounds in row and column dimensions.
* Updated matrix is returned as the output.
*
* Operations to be performed:
* 1) result=this;
* 2) result[rowLower:rowUpper, colLower:colUpper] = rhsMatrix;
*
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue leftIndexingOperations(MatrixValue rhsMatrix, long rowLower, long rowUpper,
long colLower, long colUpper, MatrixValue ret, boolean inplace)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
// Check the validity of bounds
if ( rowLower < 1 || rowLower > getNumRows() || rowUpper < rowLower || rowUpper > getNumRows()
|| colLower < 1 || colUpper > getNumColumns() || colUpper < colLower || colUpper > getNumColumns() ) {
throw new DMLRuntimeException("Invalid values for matrix indexing: " +
"["+rowLower+":"+rowUpper+"," + colLower+":"+colUpper+"] " +
"must be within matrix dimensions ["+getNumRows()+","+getNumColumns()+"].");
}
if ( (rowUpper-rowLower+1) < rhsMatrix.getNumRows() || (colUpper-colLower+1) < rhsMatrix.getNumColumns()) {
throw new DMLRuntimeException("Invalid values for matrix indexing: " +
"dimensions of the source matrix ["+rhsMatrix.getNumRows()+"x" + rhsMatrix.getNumColumns() + "] " +
"do not match the shape of the matrix specified by indices [" +
rowLower +":" + rowUpper + ", " + colLower + ":" + colUpper + "].");
}
MatrixBlockDSM result=checkType(ret);
boolean sp = estimateSparsityOnLeftIndexing(rlen, clen, nonZeros, rhsMatrix.getNonZeros());
if( !inplace ) //general case
{
if(result==null)
result=new MatrixBlockDSM(rlen, clen, sp);
else
result.reset(rlen, clen, sp);
result.copy(this, sp);
}
else //update in-place
result = this;
//NOTE conceptually we could directly use a zeroout and copy(..., false) but
// since this was factors slower, we still use a full copy and subsequently
// copy(..., true) - however, this can be changed in the future once we
// improved the performance of zeroout.
//result = (MatrixBlockDSM) zeroOutOperations(result, new IndexRange(rowLower,rowUpper, colLower, colUpper ), false);
int rl = (int)rowLower-1;
int ru = (int)rowUpper-1;
int cl = (int)colLower-1;
int cu = (int)colUpper-1;
MatrixBlockDSM src = (MatrixBlockDSM)rhsMatrix;
if(rl==ru && cl==cu) //specific case: cell update
{
//copy single value and update nnz
result.quickSetValue(rl, cl, src.quickGetValue(0, 0));
}
else //general case
{
//copy submatrix into result
result.copy(rl, ru, cl, cu, src, true);
}
return result;
}
/**
* Explicitly allow left indexing for scalars.
*
* * Operations to be performed:
* 1) result=this;
* 2) result[row,column] = scalar.getDoubleValue();
*
* @param scalar
* @param row
* @param col
* @param ret
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue leftIndexingOperations(ScalarObject scalar, long row, long col, MatrixValue ret, boolean inplace)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
MatrixBlockDSM result=checkType(ret);
if( !inplace ) //general case
{
if(result==null)
result=new MatrixBlockDSM(this);
else
result.copy(this);
}
else //update in-place
result = this;
int rl = (int)row-1;
int cl = (int)col-1;
result.quickSetValue(rl, cl, scalar.getDoubleValue());
return result;
}
/**
* Method to perform rangeReIndex operation for a given lower and upper bounds in row and column dimensions.
* Extracted submatrix is returned as "result".
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue sliceOperations(long rowLower, long rowUpper, long colLower, long colUpper, MatrixValue ret)
throws DMLRuntimeException, DMLUnsupportedOperationException {
// check the validity of bounds
if ( rowLower < 1 || rowLower > getNumRows() || rowUpper < rowLower || rowUpper > getNumRows()
|| colLower < 1 || colUpper > getNumColumns() || colUpper < colLower || colUpper > getNumColumns() ) {
throw new DMLRuntimeException("Invalid values for matrix indexing: " +
"["+rowLower+":"+rowUpper+"," + colLower+":"+colUpper+"] " +
"must be within matrix dimensions ["+getNumRows()+","+getNumColumns()+"]");
}
int rl = (int)rowLower-1;
int ru = (int)rowUpper-1;
int cl = (int)colLower-1;
int cu = (int)colUpper-1;
//System.out.println(" -- performing slide on [" + getNumRows() + "x" + getNumColumns() + "] with ["+rl+":"+ru+","+cl+":"+cu+"].");
// Output matrix will have the same sparsity as that of the input matrix.
// (assuming a uniform distribution of non-zeros in the input)
boolean result_sparsity = this.sparse && ((cu-cl+1)>SKINNY_MATRIX_TURN_POINT);
MatrixBlockDSM result=checkType(ret);
int estnnzs=(int) ((double)this.nonZeros/rlen/clen*(ru-rl+1)*(cu-cl+1));
if(result==null)
result=new MatrixBlockDSM(ru-rl+1, cu-cl+1, result_sparsity, estnnzs);
else
result.reset(ru-rl+1, cu-cl+1, result_sparsity, estnnzs);
// actual slice operation
if( rowLower==1 && rowUpper==rlen && colLower==1 && colUpper==clen ) {
// copy if entire matrix required
result.copy( this );
}
else //general case
{
//core slicing operation (nnz maintained internally)
if (sparse)
sliceSparse(rl, ru, cl, cu, result);
else
sliceDense(rl, ru, cl, cu, result);
}
return result;
}
/**
*
* @param rl
* @param ru
* @param cl
* @param cu
* @param dest
*/
private void sliceSparse(int rl, int ru, int cl, int cu, MatrixBlockDSM dest)
{
if ( sparseRows == null )
return;
if( cl==cu ) //specific case: column vector (always dense)
{
dest.allocateDenseBlock();
double val;
for( int i=rl, ix=0; i<=ru; i++, ix++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
if( (val = sparseRows[i].get(cl)) != 0 )
{
dest.denseBlock[ix] = val;
dest.nonZeros++;
}
}
else //general case (sparse and dense)
{
for(int i=rl; i <= ru; i++)
if(sparseRows[i] != null && sparseRows[i].size()>0)
{
SparseRow arow = sparseRows[i];
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
int astart = (cl>0)?arow.searchIndexesFirstGTE(cl):0;
if( astart != -1 )
for( int j=astart; j<alen && aix[j] <= cu; j++ )
dest.appendValue(i-rl, aix[j]-cl, avals[j]);
}
}
}
/**
*
* @param rl
* @param ru
* @param cl
* @param cu
* @param dest
*/
private void sliceDense(int rl, int ru, int cl, int cu, MatrixBlockDSM dest)
{
if( denseBlock == null )
return;
dest.allocateDenseBlock();
if( cl==cu ) //specific case: column vector
{
if( clen==1 ) //vector -> vector
System.arraycopy(denseBlock, rl, dest.denseBlock, 0, ru-rl+1);
else //matrix -> vector
for( int i=rl*clen+cl, ix=0; i<=ru*clen+cu; i+=clen, ix++ )
dest.denseBlock[ix] = denseBlock[i];
}
else //general case (dense)
{
for(int i = rl, ix1 = rl*clen+cl, ix2=0; i <= ru; i++, ix1+=clen, ix2+=dest.clen)
System.arraycopy(denseBlock, ix1, dest.denseBlock, ix2, dest.clen);
}
dest.recomputeNonZeros();
}
public void sliceOperations(ArrayList<IndexedMatrixValue> outlist, IndexRange range, int rowCut, int colCut,
int normalBlockRowFactor, int normalBlockColFactor, int boundaryRlen, int boundaryClen)
{
MatrixBlockDSM topleft=null, topright=null, bottomleft=null, bottomright=null;
Iterator<IndexedMatrixValue> p=outlist.iterator();
int blockRowFactor=normalBlockRowFactor, blockColFactor=normalBlockColFactor;
if(rowCut>range.rowEnd)
blockRowFactor=boundaryRlen;
if(colCut>range.colEnd)
blockColFactor=boundaryClen;
int minrowcut=(int)Math.min(rowCut,range.rowEnd);
int mincolcut=(int)Math.min(colCut, range.colEnd);
int maxrowcut=(int)Math.max(rowCut, range.rowStart);
int maxcolcut=(int)Math.max(colCut, range.colStart);
if(range.rowStart<rowCut && range.colStart<colCut)
{
topleft=(MatrixBlockDSM) p.next().getValue();
//topleft.reset(blockRowFactor, blockColFactor,
// checkSparcityOnSlide(rowCut-(int)range.rowStart, colCut-(int)range.colStart, blockRowFactor, blockColFactor));
topleft.reset(blockRowFactor, blockColFactor,
estimateSparsityOnSlice(minrowcut-(int)range.rowStart, mincolcut-(int)range.colStart, blockRowFactor, blockColFactor));
}
if(range.rowStart<rowCut && range.colEnd>=colCut)
{
topright=(MatrixBlockDSM) p.next().getValue();
topright.reset(blockRowFactor, boundaryClen,
estimateSparsityOnSlice(minrowcut-(int)range.rowStart, (int)range.colEnd-maxcolcut+1, blockRowFactor, boundaryClen));
}
if(range.rowEnd>=rowCut && range.colStart<colCut)
{
bottomleft=(MatrixBlockDSM) p.next().getValue();
bottomleft.reset(boundaryRlen, blockColFactor,
estimateSparsityOnSlice((int)range.rowEnd-maxrowcut+1, mincolcut-(int)range.colStart, boundaryRlen, blockColFactor));
}
if(range.rowEnd>=rowCut && range.colEnd>=colCut)
{
bottomright=(MatrixBlockDSM) p.next().getValue();
bottomright.reset(boundaryRlen, boundaryClen,
estimateSparsityOnSlice((int)range.rowEnd-maxrowcut+1, (int)range.colEnd-maxcolcut+1, boundaryRlen, boundaryClen));
//System.out.println("bottomright size: "+bottomright.rlen+" X "+bottomright.clen);
}
if(sparse)
{
if(sparseRows!=null)
{
int r=(int)range.rowStart;
for(; r<Math.min(Math.min(rowCut, sparseRows.length), range.rowEnd+1); r++)
sliceHelp(r, range, colCut, topleft, topright, normalBlockRowFactor-rowCut, normalBlockRowFactor, normalBlockColFactor);
for(; r<=Math.min(range.rowEnd, sparseRows.length-1); r++)
sliceHelp(r, range, colCut, bottomleft, bottomright, -rowCut, normalBlockRowFactor, normalBlockColFactor);
//System.out.println("in: \n"+this);
//System.out.println("outlist: \n"+outlist);
}
}else
{
if(denseBlock!=null)
{
int i=((int)range.rowStart)*clen;
int r=(int) range.rowStart;
for(; r<Math.min(rowCut, range.rowEnd+1); r++)
{
int c=(int) range.colStart;
for(; c<Math.min(colCut, range.colEnd+1); c++)
topleft.appendValue(r+normalBlockRowFactor-rowCut, c+normalBlockColFactor-colCut, denseBlock[i+c]);
for(; c<=range.colEnd; c++)
topright.appendValue(r+normalBlockRowFactor-rowCut, c-colCut, denseBlock[i+c]);
i+=clen;
}
for(; r<=range.rowEnd; r++)
{
int c=(int) range.colStart;
for(; c<Math.min(colCut, range.colEnd+1); c++)
bottomleft.appendValue(r-rowCut, c+normalBlockColFactor-colCut, denseBlock[i+c]);
for(; c<=range.colEnd; c++)
bottomright.appendValue(r-rowCut, c-colCut, denseBlock[i+c]);
i+=clen;
}
}
}
}
private void sliceHelp(int r, IndexRange range, int colCut, MatrixBlockDSM left, MatrixBlockDSM right, int rowOffset, int normalBlockRowFactor, int normalBlockColFactor)
{
// if(left==null || right==null)
// throw new RuntimeException("left = "+left+", and right = "+right);
if(sparseRows[r]==null) return;
//System.out.println("row "+r+"\t"+sparseRows[r]);
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
int start=sparseRows[r].searchIndexesFirstGTE((int)range.colStart);
//System.out.println("start: "+start);
if(start<0) return;
int end=sparseRows[r].searchIndexesFirstLTE((int)range.colEnd);
//System.out.println("end: "+end);
if(end<0 || start>end) return;
for(int i=start; i<=end; i++)
{
if(cols[i]<colCut)
left.appendValue(r+rowOffset, cols[i]+normalBlockColFactor-colCut, values[i]);
else
right.appendValue(r+rowOffset, cols[i]-colCut, values[i]);
// System.out.println("set "+r+", "+cols[i]+": "+values[i]);
}
}
@Override
//This the append operations for MR side
//nextNCol is the number columns for the block right of block v2
public void appendOperations(MatrixValue v2,
ArrayList<IndexedMatrixValue> outlist, int blockRowFactor,
int blockColFactor, boolean m2IsLast, int nextNCol)
throws DMLUnsupportedOperationException, DMLRuntimeException {
MatrixBlockDSM m2=(MatrixBlockDSM)v2;
//System.out.println("second matrix: \n"+m2);
Iterator<IndexedMatrixValue> p=outlist.iterator();
if(this.clen==blockColFactor)
{
MatrixBlockDSM first=(MatrixBlockDSM) p.next().getValue();
first.copy(this);
MatrixBlockDSM second=(MatrixBlockDSM) p.next().getValue();
second.copy(m2);
}else
{
int ncol=Math.min(clen+m2.getNumColumns(), blockColFactor);
int part=ncol-clen;
MatrixBlockDSM first=(MatrixBlockDSM) p.next().getValue();
first.reset(rlen, ncol, this.nonZeros+m2.getNonZeros()*part/m2.getNumColumns());
//copy the first matrix
if(this.sparse)
{
if(this.sparseRows!=null)
{
for(int i=0; i<Math.min(rlen, this.sparseRows.length); i++)
{
if(this.sparseRows[i]!=null)
first.appendRow(i, this.sparseRows[i]);
}
}
}else if(this.denseBlock!=null)
{
int sindx=0;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
first.appendValue(r, c, this.denseBlock[sindx]);
sindx++;
}
}
MatrixBlockDSM second=null;
if(part<m2.clen)
{
second=(MatrixBlockDSM) p.next().getValue();
if(m2IsLast)
second.reset(m2.rlen, m2.clen-part, m2.sparse);
else
second.reset(m2.rlen, Math.min(m2.clen-part+nextNCol, blockColFactor), m2.sparse);
}
//copy the second
if(m2.sparse)
{
if(m2.sparseRows!=null)
{
for(int i=0; i<Math.min(m2.rlen, m2.sparseRows.length); i++)
{
if(m2.sparseRows[i]!=null)
{
int[] indexContainer=m2.sparseRows[i].getIndexContainer();
double[] valueContainer=m2.sparseRows[i].getValueContainer();
for(int j=0; j<m2.sparseRows[i].size(); j++)
{
if(indexContainer[j]<part)
first.appendValue(i, clen+indexContainer[j], valueContainer[j]);
else
second.appendValue(i, indexContainer[j]-part, valueContainer[j]);
}
}
}
}
}else if(m2.denseBlock!=null)
{
int sindx=0;
for(int r=0; r<m2.rlen; r++)
{
int c=0;
for(; c<part; c++)
{
first.appendValue(r, clen+c, m2.denseBlock[sindx+c]);
// System.out.println("access "+(sindx+c));
// System.out.println("add first ("+r+", "+(clen+c)+"), "+m2.denseBlock[sindx+c]);
}
for(; c<m2.clen; c++)
{
second.appendValue(r, c-part, m2.denseBlock[sindx+c]);
// System.out.println("access "+(sindx+c));
// System.out.println("add second ("+r+", "+(c-part)+"), "+m2.denseBlock[sindx+c]);
}
sindx+=m2.clen;
}
}
}
}
public MatrixValue zeroOutOperations(MatrixValue result, IndexRange range, boolean complementary)
throws DMLUnsupportedOperationException, DMLRuntimeException {
checkType(result);
boolean sps;
double currentSparsity=(double)nonZeros/(double)rlen/(double)clen;
double estimatedSps=currentSparsity*(double)(range.rowEnd-range.rowStart+1)
*(double)(range.colEnd-range.colStart+1)/(double)rlen/(double)clen;
if(!complementary)
estimatedSps=currentSparsity-estimatedSps;
if(estimatedSps< SPARCITY_TURN_POINT)
sps=true;
else sps=false;
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(clen<=SKINNY_MATRIX_TURN_POINT)
sps=false;
if(result==null)
result=new MatrixBlockDSM(rlen, clen, sps, (int)(estimatedSps*rlen*clen));
else
result.reset(rlen, clen, sps, (int)(estimatedSps*rlen*clen));
if(sparse)
{
if(sparseRows!=null)
{
if(!complementary)//if zero out
{
for(int r=0; r<Math.min((int)range.rowStart, sparseRows.length); r++)
((MatrixBlockDSM) result).appendRow(r, sparseRows[r]);
for(int r=Math.min((int)range.rowEnd+1, sparseRows.length); r<Math.min(rlen, sparseRows.length); r++)
((MatrixBlockDSM) result).appendRow(r, sparseRows[r]);
}
for(int r=(int)range.rowStart; r<=Math.min(range.rowEnd, sparseRows.length-1); r++)
{
if(sparseRows[r]==null) continue;
//System.out.println("row "+r+"\t"+sparseRows[r]);
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
if(complementary)//if selection
{
int start=sparseRows[r].searchIndexesFirstGTE((int)range.colStart);
//System.out.println("start: "+start);
if(start<0) continue;
int end=sparseRows[r].searchIndexesFirstGT((int)range.colEnd);
//System.out.println("end: "+end);
if(end<0 || start>end) continue;
for(int i=start; i<end; i++)
{
((MatrixBlockDSM) result).appendValue(r, cols[i], values[i]);
// System.out.println("set "+r+", "+cols[i]+": "+values[i]);
}
}else
{
int start=sparseRows[r].searchIndexesFirstGTE((int)range.colStart);
//System.out.println("start: "+start);
if(start<0) start=sparseRows[r].size();
int end=sparseRows[r].searchIndexesFirstGT((int)range.colEnd);
//System.out.println("end: "+end);
if(end<0) end=sparseRows[r].size();
/* if(r==999)
{
System.out.println("----------------------");
System.out.println("range: "+range);
System.out.println("row: "+sparseRows[r]);
System.out.println("start: "+start);
System.out.println("end: "+end);
}
*/
for(int i=0; i<start; i++)
{
((MatrixBlockDSM) result).appendValue(r, cols[i], values[i]);
// if(r==999) System.out.println("append ("+r+", "+cols[i]+"): "+values[i]);
}
for(int i=end; i<sparseRows[r].size(); i++)
{
((MatrixBlockDSM) result).appendValue(r, cols[i], values[i]);
// if(r==999) System.out.println("append ("+r+", "+cols[i]+"): "+values[i]);
}
}
}
}
}else
{
if(denseBlock!=null)
{
if(complementary)//if selection
{
int offset=((int)range.rowStart)*clen;
for(int r=(int) range.rowStart; r<=range.rowEnd; r++)
{
for(int c=(int) range.colStart; c<=range.colEnd; c++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset+c]);
offset+=clen;
}
}else
{
int offset=0;
int r=0;
for(; r<(int)range.rowStart; r++)
for(int c=0; c<clen; c++, offset++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset]);
for(; r<=(int)range.rowEnd; r++)
{
for(int c=0; c<(int)range.colStart; c++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset+c]);
for(int c=(int)range.colEnd+1; c<clen; c++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset+c]);
offset+=clen;
}
for(; r<rlen; r++)
for(int c=0; c<clen; c++, offset++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset]);
}
}
}
//System.out.println("zeroout in:\n"+this);
//System.out.println("zeroout result:\n"+result);
return result;
}
//This function is not really used
/* public void zeroOutOperationsInPlace(IndexRange range, boolean complementary)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//do not change the format of the block
if(sparse)
{
if(sparseRows==null) return;
if(complementary)//if selection, need to remove unwanted rows
{
for(int r=0; r<Math.min((int)range.rowStart, sparseRows.length); r++)
if(sparseRows[r]!=null)
{
nonZeros-=sparseRows[r].size();
sparseRows[r].reset();
}
for(int r=Math.min((int)range.rowEnd+1, sparseRows.length-1); r<Math.min(rlen, sparseRows.length); r++)
if(sparseRows[r]!=null)
{
nonZeros-=sparseRows[r].size();
sparseRows[r].reset();
}
}
for(int r=(int)range.rowStart; r<=Math.min(range.rowEnd, sparseRows.length-1); r++)
{
if(sparseRows[r]==null) continue;
int oldsize=sparseRows[r].size();
if(complementary)//if selection
sparseRows[r].deleteIndexComplementaryRange((int)range.colStart, (int)range.rowEnd);
else //if zeroout
sparseRows[r].deleteIndexRange((int)range.colStart, (int)range.rowEnd);
nonZeros-=(oldsize-sparseRows[r].size());
}
}else
{
if(denseBlock==null) return;
int start=(int)range.rowStart*clen;
if(complementary)//if selection, need to remove unwanted rows
{
nonZeros=0;
Arrays.fill(denseBlock, 0, start, 0);
Arrays.fill(denseBlock, ((int)range.rowEnd+1)*clen, rlen*clen, 0);
for(int r=(int) range.rowStart; r<=range.rowEnd; r++)
{
Arrays.fill(denseBlock, start, start+(int) range.colStart, 0);
Arrays.fill(denseBlock, start+(int)range.colEnd+1, start+clen, 0);
for(int c=(int) range.colStart; c<=range.colEnd; c++)
if(denseBlock[start+c]!=0)
nonZeros++;
start+=clen;
}
}else
{
for(int r=(int) range.rowStart; r<=range.rowEnd; r++)
{
for(int c=(int) range.colStart; c<=range.colEnd; c++)
if(denseBlock[start+c]!=0)
nonZeros--;
Arrays.fill(denseBlock, start+(int) range.colStart, start+(int)range.colEnd+1, 0);
start+=clen;
}
}
}
}*/
public MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
return aggregateUnaryOperations(op, result,
blockingFactorRow, blockingFactorCol, indexesIn, false);
}
public MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn, boolean inCP)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
CellIndex tempCellIndex = new CellIndex(-1,-1);
op.indexFn.computeDimension(rlen, clen, tempCellIndex);
if(op.aggOp.correctionExists)
{
switch(op.aggOp.correctionLocation)
{
case LASTROW: tempCellIndex.row++; break;
case LASTCOLUMN: tempCellIndex.column++; break;
case LASTTWOROWS: tempCellIndex.row+=2; break;
case LASTTWOCOLUMNS: tempCellIndex.column+=2; break;
default:
throw new DMLRuntimeException("unrecognized correctionLocation: "+op.aggOp.correctionLocation);
}
}
if(result==null)
result=new MatrixBlockDSM(tempCellIndex.row, tempCellIndex.column, false);
else
result.reset(tempCellIndex.row, tempCellIndex.column, false);
MatrixBlockDSM ret = (MatrixBlockDSM) result;
if( MatrixAggLib.isSupportedUnaryAggregateOperator(op) ) {
MatrixAggLib.aggregateUnaryMatrix(this, ret, op);
MatrixAggLib.recomputeIndexes(ret, op, blockingFactorRow, blockingFactorCol, indexesIn);
}
else if(op.sparseSafe)
sparseAggregateUnaryHelp(op, ret, blockingFactorRow, blockingFactorCol, indexesIn);
else
denseAggregateUnaryHelp(op, ret, blockingFactorRow, blockingFactorCol, indexesIn);
if(op.aggOp.correctionExists && inCP)
((MatrixBlockDSM)result).dropLastRowsOrColums(op.aggOp.correctionLocation);
return ret;
}
private void sparseAggregateUnaryHelp(AggregateUnaryOperator op, MatrixBlockDSM result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn) throws DMLRuntimeException
{
//initialize result
if(op.aggOp.initialValue!=0)
result.resetDenseWithValue(result.rlen, result.clen, op.aggOp.initialValue);
CellIndex tempCellIndex = new CellIndex(-1,-1);
KahanObject buffer=new KahanObject(0,0);
int r = 0, c = 0;
if(sparse)
{
if(sparseRows!=null)
{
for(r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
tempCellIndex.set(r, cols[i]);
op.indexFn.execute(tempCellIndex, tempCellIndex);
incrementalAggregateUnaryHelp(op.aggOp, result, tempCellIndex.row, tempCellIndex.column, values[i], buffer);
}
}
}
}
else
{
if(denseBlock!=null)
{
int limit=rlen*clen;
for(int i=0; i<limit; i++)
{
r=i/clen;
c=i%clen;
tempCellIndex.set(r, c);
op.indexFn.execute(tempCellIndex, tempCellIndex);
incrementalAggregateUnaryHelp(op.aggOp, result, tempCellIndex.row, tempCellIndex.column, denseBlock[i], buffer);
}
}
}
}
private void denseAggregateUnaryHelp(AggregateUnaryOperator op, MatrixBlockDSM result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn) throws DMLRuntimeException
{
//initialize
if(op.aggOp.initialValue!=0)
result.resetDenseWithValue(result.rlen, result.clen, op.aggOp.initialValue);
CellIndex tempCellIndex = new CellIndex(-1,-1);
KahanObject buffer=new KahanObject(0,0);
for(int i=0; i<rlen; i++)
for(int j=0; j<clen; j++)
{
tempCellIndex.set(i, j);
op.indexFn.execute(tempCellIndex, tempCellIndex);
if(op.aggOp.correctionExists
&& op.aggOp.correctionLocation == CorrectionLocationType.LASTCOLUMN
&& op.aggOp.increOp.fn instanceof Builtin
&& ((Builtin)(op.aggOp.increOp.fn)).bFunc == Builtin.BuiltinFunctionCode.MAXINDEX ){
double currMaxValue = result.quickGetValue(i, 1);
long newMaxIndex = UtilFunctions.cellIndexCalculation(indexesIn.getColumnIndex(), blockingFactorCol, j);
double newMaxValue = quickGetValue(i, j);
double update = op.aggOp.increOp.fn.execute(newMaxValue, currMaxValue);
//System.out.println("currV="+currMaxValue+",newV="+newMaxValue+",newIX="+newMaxIndex+",update="+update);
if(update == 1){
result.quickSetValue(i, 0, newMaxIndex);
result.quickSetValue(i, 1, newMaxValue);
}
}else
incrementalAggregateUnaryHelp(op.aggOp, result, tempCellIndex.row, tempCellIndex.column, quickGetValue(i,j), buffer);
}
}
private void incrementalAggregateUnaryHelp(AggregateOperator aggOp, MatrixBlockDSM result, int row, int column,
double newvalue, KahanObject buffer) throws DMLRuntimeException
{
if(aggOp.correctionExists)
{
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW || aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
{
int corRow=row, corCol=column;
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW)//extra row
corRow++;
else if(aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
corCol++;
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
buffer._sum=result.quickGetValue(row, column);
buffer._correction=result.quickGetValue(corRow, corCol);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newvalue);
result.quickSetValue(row, column, buffer._sum);
result.quickSetValue(corRow, corCol, buffer._correction);
}else if(aggOp.correctionLocation==CorrectionLocationType.NONE)
{
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
}else// for mean
{
int corRow=row, corCol=column;
int countRow=row, countCol=column;
if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOROWS)
{
countRow++;
corRow+=2;
}
else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS)
{
countCol++;
corCol+=2;
}
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
buffer._sum=result.quickGetValue(row, column);
buffer._correction=result.quickGetValue(corRow, corCol);
double count=result.quickGetValue(countRow, countCol)+1.0;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newvalue, count);
result.quickSetValue(row, column, buffer._sum);
result.quickSetValue(corRow, corCol, buffer._correction);
result.quickSetValue(countRow, countCol, count);
}
}else
{
newvalue=aggOp.increOp.fn.execute(result.quickGetValue(row, column), newvalue);
result.quickSetValue(row, column, newvalue);
}
}
/**
*
* @param correctionLocation
*/
private void dropLastRowsOrColums(CorrectionLocationType correctionLocation)
{
//do nothing
if( correctionLocation==CorrectionLocationType.NONE
|| correctionLocation==CorrectionLocationType.INVALID )
{
return;
}
//determine number of rows/cols to be removed
int step = ( correctionLocation==CorrectionLocationType.LASTTWOROWS
|| correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS) ? 2 : 1;
//e.g., colSums, colMeans, colMaxs, colMeans
if( correctionLocation==CorrectionLocationType.LASTROW
|| correctionLocation==CorrectionLocationType.LASTTWOROWS )
{
if( sparse ) //SPARSE
{
if(sparseRows!=null)
for(int i=1; i<=step; i++)
if(sparseRows[rlen-i]!=null)
this.nonZeros-=sparseRows[rlen-i].size();
}
else //DENSE
{
if(denseBlock!=null)
for(int i=(rlen-step)*clen; i<rlen*clen; i++)
if(denseBlock[i]!=0)
this.nonZeros--;
}
//just need to shrink the dimension, the deleted rows won't be accessed
rlen -= step;
}
//e.g., rowSums, rowsMeans, rowsMaxs, rowsMeans
if( correctionLocation==CorrectionLocationType.LASTCOLUMN
|| correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS )
{
if(sparse) //SPARSE
{
if(sparseRows!=null)
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
if(sparseRows[r]!=null)
{
int newSize=sparseRows[r].searchIndexesFirstGTE(clen-step);
if(newSize>=0)
{
this.nonZeros-=sparseRows[r].size()-newSize;
sparseRows[r].truncate(newSize);
}
}
}
}
else //DENSE
{
if(this.denseBlock!=null)
{
//the first row doesn't need to be copied
int targetIndex=clen-step;
int sourceOffset=clen;
this.nonZeros=0;
for(int i=0; i<targetIndex; i++)
if(denseBlock[i]!=0)
this.nonZeros++;
//start from the 2nd row
for(int r=1; r<rlen; r++)
{
for(int c=0; c<clen-step; c++)
{
if((denseBlock[targetIndex]=denseBlock[sourceOffset+c])!=0)
this.nonZeros++;
targetIndex++;
}
sourceOffset+=clen;
}
}
}
clen -= step;
}
}
public CM_COV_Object cmOperations(CMOperator op)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1) {
throw new DMLRuntimeException("Central Moment can not be computed on ["
+ this.getNumRows() + "," + this.getNumColumns() + "] matrix.");
}
CM_COV_Object cmobj = new CM_COV_Object();
int nzcount = 0;
if(sparse && sparseRows!=null) //SPARSE
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
//int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
op.fn.execute(cmobj, values[i]);
nzcount++;
}
}
// account for zeros in the vector
op.fn.execute(cmobj, 0.0, this.getNumRows()-nzcount);
}
else if(denseBlock!=null) //DENSE
{
//always vector (see check above)
for(int i=0; i<rlen; i++)
op.fn.execute(cmobj, denseBlock[i]);
}
return cmobj;
}
public CM_COV_Object cmOperations(CMOperator op, MatrixBlockDSM weights)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1 || weights.getNumColumns() != 1) {
throw new DMLRuntimeException("Central Moment can be computed only on 1-dimensional column matrices.");
}
if ( this.getNumRows() != weights.getNumRows() || this.getNumColumns() != weights.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching dimensions between input and weight matrices - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ weights.getNumRows() + "," + weights.getNumColumns() +"]");
}
CM_COV_Object cmobj = new CM_COV_Object();
if (sparse && sparseRows!=null) //SPARSE
{
for(int i=0; i < rlen; i++)
op.fn.execute(cmobj, this.quickGetValue(i,0), weights.quickGetValue(i,0));
/*
int zerocount = 0, zerorows=0, nzrows=0;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
// This matrix has only a single column
if(sparseRows[r]==null) {
zerocount += weights.getValue(r,0);
zerorows++;
}
//int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
//x = sparseRows[r].size();
if ( sparseRows[r].size() == 0 )
zerorows++;
for(int i=0; i<sparseRows[r].size(); i++) {
//op.fn.execute(cmobj, values[i], weights.getValue(r,0));
nzrows++;
}
}
System.out.println("--> total="+this.getNumRows() + ", nzrows=" + nzrows + ", zerorows="+zerorows+"... zerocount="+zerocount);
// account for zeros in the vector
//op.fn.execute(cmobj, 0.0, zerocount);
*/ }
else if(denseBlock!=null) //DENSE
{
//always vectors (see check above)
if( !weights.sparse )
{
//both dense vectors (default case)
if(weights.denseBlock!=null)
for( int i=0; i<rlen; i++ )
op.fn.execute(cmobj, denseBlock[i], weights.denseBlock[i]);
}
else
{
for(int i=0; i<rlen; i++)
op.fn.execute(cmobj, denseBlock[i], weights.quickGetValue(i,0) );
}
}
return cmobj;
}
public CM_COV_Object covOperations(COVOperator op, MatrixBlockDSM that)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1 || that.getNumColumns() != 1 ) {
throw new DMLRuntimeException("Covariance can be computed only on 1-dimensional column matrices.");
}
if ( this.getNumRows() != that.getNumRows() || this.getNumColumns() != that.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching input matrix dimensions - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ that.getNumRows() + "," + that.getNumColumns() +"]");
}
CM_COV_Object covobj = new CM_COV_Object();
if(sparse && sparseRows!=null) //SPARSE
{
for(int i=0; i < rlen; i++ )
op.fn.execute(covobj, this.quickGetValue(i,0), that.quickGetValue(i,0));
}
else if(denseBlock!=null) //DENSE
{
//always vectors (see check above)
if( !that.sparse )
{
//both dense vectors (default case)
if(that.denseBlock!=null)
for( int i=0; i<rlen; i++ )
op.fn.execute(covobj, denseBlock[i], that.denseBlock[i]);
}
else
{
for(int i=0; i<rlen; i++)
op.fn.execute(covobj, denseBlock[i], that.quickGetValue(i,0));
}
}
return covobj;
}
public CM_COV_Object covOperations(COVOperator op, MatrixBlockDSM that, MatrixBlockDSM weights)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1 || that.getNumColumns() != 1 || weights.getNumColumns() != 1) {
throw new DMLRuntimeException("Covariance can be computed only on 1-dimensional column matrices.");
}
if ( this.getNumRows() != that.getNumRows() || this.getNumColumns() != that.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching input matrix dimensions - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ that.getNumRows() + "," + that.getNumColumns() +"]");
}
if ( this.getNumRows() != weights.getNumRows() || this.getNumColumns() != weights.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching dimensions between input and weight matrices - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ weights.getNumRows() + "," + weights.getNumColumns() +"]");
}
CM_COV_Object covobj = new CM_COV_Object();
if(sparse && sparseRows!=null) //SPARSE
{
for(int i=0; i < rlen; i++ )
op.fn.execute(covobj, this.quickGetValue(i,0), that.quickGetValue(i,0), weights.quickGetValue(i,0));
}
else if(denseBlock!=null) //DENSE
{
//always vectors (see check above)
if( !that.sparse && !weights.sparse )
{
//all dense vectors (default case)
if(that.denseBlock!=null)
for( int i=0; i<rlen; i++ )
op.fn.execute(covobj, denseBlock[i], that.denseBlock[i], weights.denseBlock[i]);
}
else
{
for(int i=0; i<rlen; i++)
op.fn.execute(covobj, denseBlock[i], that.quickGetValue(i,0), weights.quickGetValue(i,0));
}
}
return covobj;
}
public MatrixValue sortOperations(MatrixValue weights, MatrixValue result) throws DMLRuntimeException, DMLUnsupportedOperationException {
boolean wtflag = (weights!=null);
MatrixBlockDSM wts= (weights == null ? null : checkType(weights));
checkType(result);
if ( getNumColumns() != 1 ) {
throw new DMLRuntimeException("Invalid input dimensions (" + getNumRows() + "x" + getNumColumns() + ") to sort operation.");
}
if ( wts != null && wts.getNumColumns() != 1 ) {
throw new DMLRuntimeException("Invalid weight dimensions (" + wts.getNumRows() + "x" + wts.getNumColumns() + ") to sort operation.");
}
// Copy the input elements into a temporary array for sorting
// #rows in temp matrix = 1 + #nnz in the input ( 1 is for the "zero" value)
int dim1 = 1+this.getNonZeros();
// First column is data and second column is weights
double[][] tdw = new double[dim1][2];
double d, w, zero_wt=0;
if ( wtflag ) {
for ( int r=0, ind=1; r < getNumRows(); r++ ) {
d = quickGetValue(r,0);
w = wts.quickGetValue(r,0);
if ( d != 0 ) {
tdw[ind][0] = d;
tdw[ind][1] = w;
ind++;
}
else
zero_wt += w;
}
tdw[0][0] = 0.0;
tdw[0][1] = zero_wt;
}
else {
tdw[0][0] = 0.0;
tdw[0][1] = getNumRows() - getNonZeros(); // number of zeros in the input data
int ind = 1;
if(sparse) {
if(sparseRows!=null) {
for(int r=0; r<Math.min(rlen, sparseRows.length); r++) {
if(sparseRows[r]==null) continue;
//int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++) {
tdw[ind][0] = values[i];
tdw[ind][1] = 1;
ind++;
}
}
}
}
else {
if(denseBlock!=null) {
int limit=rlen*clen;
for(int i=0; i<limit; i++) {
// copy only non-zero values
if ( denseBlock[i] != 0.0 ) {
tdw[ind][0] = denseBlock[i];
tdw[ind][1] = 1;
ind++;
}
}
}
}
}
// Sort td and tw based on values inside td (ascending sort)
Arrays.sort(tdw, new Comparator<double[]>(){
@Override
public int compare(double[] arg0, double[] arg1) {
return (arg0[0] < arg1[0] ? -1 : (arg0[0] == arg1[0] ? 0 : 1));
}}
);
// Copy the output from sort into "result"
// result is always dense (currently)
if(result==null)
result=new MatrixBlockDSM(dim1, 2, false);
else
result.reset(dim1, 2, false);
((MatrixBlockDSM) result).init(tdw, dim1, 2);
return result;
}
/**
* Computes the weighted interQuartileMean.
* The matrix block ("this" pointer) has two columns, in which the first column
* refers to the data and second column denotes corresponding weights.
*
* @return InterQuartileMean
* @throws DMLRuntimeException
*/
public double interQuartileMean() throws DMLRuntimeException {
double sum_wt = sumWeightForQuantile();
int fromPos = (int) Math.ceil(0.25*sum_wt);
int toPos = (int) Math.ceil(0.75*sum_wt);
int selectRange = toPos-fromPos; // range: (fromPos,toPos]
if ( selectRange == 0 )
return 0.0;
int index, count=0;
// The first row (0^th row) has value 0.
// If it has a non-zero weight i.e., input data has zero values
// then "index" must start from 0, otherwise we skip the first row
// and start with the next value in the data, which is in the 1st row.
if ( quickGetValue(0,1) > 0 )
index = 0;
else
index = 1;
// keep scanning the weights, until we hit the required position <code>fromPos</code>
while ( count < fromPos ) {
count += quickGetValue(index,1);
++index;
}
double runningSum;
double val;
int wt, selectedCount;
runningSum = (count-fromPos) * quickGetValue(index-1, 0);
selectedCount = (count-fromPos);
while(count <= toPos ) {
val = quickGetValue(index,0);
wt = (int) quickGetValue(index,1);
runningSum += (val * Math.min(wt, selectRange-selectedCount));
selectedCount += Math.min(wt, selectRange-selectedCount);
count += wt;
++index;
}
//System.out.println(fromPos + ", " + toPos + ": " + count + ", "+ runningSum + ", " + selectedCount);
return runningSum/selectedCount;
}
public MatrixValue pickValues(MatrixValue quantiles, MatrixValue ret)
throws DMLUnsupportedOperationException, DMLRuntimeException {
MatrixBlockDSM qs=checkType(quantiles);
if ( qs.clen != 1 ) {
throw new DMLRuntimeException("Multiple quantiles can only be computed on a 1D matrix");
}
MatrixBlockDSM output = checkType(ret);
if(output==null)
output=new MatrixBlockDSM(qs.rlen, qs.clen, false); // resulting matrix is mostly likely be dense
else
output.reset(qs.rlen, qs.clen, false);
for ( int i=0; i < qs.rlen; i++ ) {
output.quickSetValue(i, 0, this.pickValue(qs.quickGetValue(i,0)) );
}
return output;
}
public double pickValue(double quantile)
throws DMLRuntimeException
{
double sum_wt = sumWeightForQuantile();
int pos = (int) Math.ceil(quantile*sum_wt);
int t = 0, i=-1;
do {
i++;
t += quickGetValue(i,1);
} while(t<pos && i < getNumRows());
return quickGetValue(i,0);
}
/**
* In a given two column matrix, the second column denotes weights.
* This function computes the total weight
*
* @return
* @throws DMLRuntimeException
*/
private double sumWeightForQuantile()
throws DMLRuntimeException
{
double sum_wt = 0;
for (int i=0; i < getNumRows(); i++ )
sum_wt += quickGetValue(i, 1);
if ( (int)sum_wt != sum_wt ) {
throw new DMLRuntimeException("Unexpected error while computing quantile -- weights must be integers.");
}
return sum_wt;
}
public MatrixValue aggregateBinaryOperations(MatrixValue m1Value, MatrixValue m2Value,
MatrixValue result, AggregateBinaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM m1=checkType(m1Value);
MatrixBlockDSM m2=checkType(m2Value);
checkType(result);
if(m1.clen!=m2.rlen)
throw new RuntimeException("dimensions do not match for matrix multiplication ("+m1.clen+"!="+m2.rlen+")");
int rl=m1.rlen;
int cl=m2.clen;
SparsityEstimate sp=estimateSparsityOnAggBinary(m1, m2, op);
if(result==null)
result=new MatrixBlockDSM(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
else
result.reset(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
if(op.sparseSafe)
sparseAggregateBinaryHelp(m1, m2, (MatrixBlockDSM)result, op);
else
aggBinSparseUnsafe(m1, m2, (MatrixBlockDSM)result, op);
return result;
}
public MatrixValue aggregateBinaryOperations(MatrixIndexes m1Index, MatrixValue m1Value, MatrixIndexes m2Index, MatrixValue m2Value,
MatrixValue result, AggregateBinaryOperator op, boolean partialMult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM m1=checkType(m1Value);
MatrixBlockDSM m2=checkType(m2Value);
checkType(result);
if ( partialMult ) {
// check if matrix block's row-column range falls within the whole vector's row-column range
}
else if(m1.clen!=m2.rlen)
throw new RuntimeException("dimensions do not match for matrix multiplication ("+m1.clen+"!="+m2.rlen+")");
int rl, cl;
SparsityEstimate sp;
if ( partialMult ) {
// TODO: avoid this code!!
rl = m1.rlen;
cl = 1;
sp = new SparsityEstimate(false,m1.rlen);
}
else {
rl=m1.rlen;
cl=m2.clen;
sp = estimateSparsityOnAggBinary(m1, m2, op);
}
if(result==null)
result=new MatrixBlockDSM(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
else
result.reset(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
if(op.sparseSafe)
sparseAggregateBinaryHelp(m1Index, m1, m2Index, m2, (MatrixBlockDSM)result, op, partialMult);
else
aggBinSparseUnsafe(m1, m2, (MatrixBlockDSM)result, op);
return result;
}
private static void sparseAggregateBinaryHelp(MatrixIndexes m1Index, MatrixBlockDSM m1, MatrixIndexes m2Index, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op, boolean partialMult) throws DMLRuntimeException
{
//matrix multiplication
if(op.binaryFn instanceof Multiply && op.aggOp.increOp.fn instanceof Plus && !partialMult)
{
MatrixMultLib.matrixMult(m1, m2, result);
}
else
{
if(!m1.sparse && m2 != null && !m2.sparse )
aggBinDenseDense(m1, m2, result, op);
else if(m1.sparse && m2 != null && m2.sparse)
aggBinSparseSparse(m1, m2, result, op);
else if(m1.sparse)
aggBinSparseDense(m1Index, m1, m2Index, m2, result, op, partialMult);
else
aggBinDenseSparse(m1, m2, result, op);
}
}
private static void sparseAggregateBinaryHelp(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op) throws DMLRuntimeException
{
if(op.binaryFn instanceof Multiply && op.aggOp.increOp.fn instanceof Plus )
{
MatrixMultLib.matrixMult(m1, m2, result);
}
else
{
if(!m1.sparse && !m2.sparse)
aggBinDenseDense(m1, m2, result, op);
else if(m1.sparse && m2.sparse)
aggBinSparseSparse(m1, m2, result, op);
else if(m1.sparse)
aggBinSparseDense(m1, m2, result, op);
else
aggBinDenseSparse(m1, m2, result, op);
}
}
/**
* to perform aggregateBinary when both matrices are dense
*/
private static void aggBinDenseDense(MatrixBlockDSM m1, MatrixBlockDSM m2, MatrixBlockDSM result, AggregateBinaryOperator op) throws DMLRuntimeException
{
int j, l, i, aIndex, bIndex;
double temp;
double v;
double[] a = m1.getDenseArray();
double[] b = m2.getDenseArray();
if(a==null || b==null)
return;
for(l = 0; l < m1.clen; l++)
{
aIndex = l;
//cIndex = 0;
for(i = 0; i < m1.rlen; i++)
{
// aIndex = l + i * m1clen
temp = a[aIndex];
bIndex = l * m1.rlen;
for(j = 0; j < m2.clen; j++)
{
// cIndex = i * m1.rlen + j
// bIndex = l * m1.rlen + j
v = op.aggOp.increOp.fn.execute(result.quickGetValue(i, j), op.binaryFn.execute(temp, b[bIndex]));
result.quickSetValue(i, j, v);
//cIndex++;
bIndex++;
}
aIndex += m1.clen;
}
}
}
/*
* to perform aggregateBinary when the first matrix is dense and the second is sparse
*/
private static void aggBinDenseSparse(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op)
throws DMLRuntimeException
{
if(m2.sparseRows==null)
return;
for(int k=0; k<Math.min(m2.rlen, m2.sparseRows.length); k++)
{
if(m2.sparseRows[k]==null) continue;
int[] cols=m2.sparseRows[k].getIndexContainer();
double[] values=m2.sparseRows[k].getValueContainer();
for(int p=0; p<m2.sparseRows[k].size(); p++)
{
int j=cols[p];
for(int i=0; i<m1.rlen; i++)
{
double old=result.quickGetValue(i, j);
double aik=m1.quickGetValue(i, k);
double addValue=op.binaryFn.execute(aik, values[p]);
double newvalue=op.aggOp.increOp.fn.execute(old, addValue);
result.quickSetValue(i, j, newvalue);
}
}
}
}
private static void aggBinSparseDense(MatrixIndexes m1Index,
MatrixBlockDSM m1, MatrixIndexes m2Index, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op,
boolean partialMult) throws DMLRuntimeException {
if (m1.sparseRows == null)
return;
//System.out.println("#*#*#**# in special aggBinSparseDense ... ");
int end_l, incrA = 0, incrB = 0;
// l varies from 0..end_l, where the upper bound end_l is determined by
// the Matrix Input (not the vector input)
if (partialMult == false) {
// both A and B are matrices
end_l = m1.clen;
} else {
if (m2.isVector()) {
// A is a matrix and B is a vector
incrB = (int) UtilFunctions.cellIndexCalculation(m1Index
.getColumnIndex(), 1000, 0) - 1; // matrixB.l goes from
// incr+start_l to
// incr+end_l
end_l = incrB + m1.clen;
} else if (m1.isVector()) {
// A is a vector and B is a matrix
incrA = (int) UtilFunctions.cellIndexCalculation(m2Index
.getRowIndex(), 1000, 0) - 1; // matrixA.l goes from
// incr+start_l to
// incr+end_l
end_l = incrA + m2.rlen;
} else
throw new RuntimeException(
"Unexpected case in matrixMult w/ partialMult");
}
/*System.out.println("m1: [" + m1.rlen + "," + m1.clen + "] m2: ["
+ m2.rlen + "," + m2.clen + "] incrA: " + incrA + " incrB: "
+ incrB + ", end_l " + end_l);*/
for (int i = 0; i < Math.min(m1.rlen, m1.sparseRows.length); i++) {
if (m1.sparseRows[i] == null)
continue;
int[] cols = m1.sparseRows[i].getIndexContainer();
double[] values = m1.sparseRows[i].getValueContainer();
for (int j = 0; j < m2.clen; j++) {
double aij = 0;
/*int p = 0;
if (partialMult) {
// this code is executed when m1 is a vector and m2 is a
// matrix
while (m1.isVector() && cols[p] < incrA)
p++;
}*/
// when m1 and m2 are matrices : incrA=0 & end_l=m1.clen (#cols
// in whole m1)
// when m1 is matrix & m2 is vector: incrA=0 &
// end_l=m1.sparseRows[i].size()
// when m1 is vector & m2 is matrix: incrA=based on
// m2Index.rowIndex & end_l=incrA+m2.rlen (#rows in m2's block)
for (int p = incrA; p < m1.sparseRows[i].size()
&& cols[p] < end_l; p++) {
int k = cols[p];
double addValue = op.binaryFn.execute(values[p], m2
.quickGetValue(k + incrB, j));
aij = op.aggOp.increOp.fn.execute(aij, addValue);
}
result.appendValue(i, j, aij);
}
}
}
/*
* to perform aggregateBinary when the first matrix is sparse and the second is dense
*/
private static void aggBinSparseDense(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op)
throws DMLRuntimeException
{
if(m1.sparseRows==null)
return;
for(int i=0; i<Math.min(m1.rlen, m1.sparseRows.length); i++)
{
if(m1.sparseRows[i]==null) continue;
int[] cols=m1.sparseRows[i].getIndexContainer();
double[] values=m1.sparseRows[i].getValueContainer();
for(int j=0; j<m2.clen; j++)
{
double aij=0;
for(int p=0; p<m1.sparseRows[i].size(); p++)
{
int k=cols[p];
double addValue=op.binaryFn.execute(values[p], m2.quickGetValue(k, j));
aij=op.aggOp.increOp.fn.execute(aij, addValue);
}
result.appendValue(i, j, aij);
}
}
}
/*
* to perform aggregateBinary when both matrices are sparse
*/
private static void aggBinSparseSparse(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op)
throws DMLRuntimeException
{
if(m1.sparseRows==null || m2.sparseRows==null)
return;
//double[] cache=null;
TreeMap<Integer, Double> cache=null;
if(result.isInSparseFormat())
{
//cache=new double[m2.getNumColumns()];
cache=new TreeMap<Integer, Double>();
}
for(int i=0; i<Math.min(m1.rlen, m1.sparseRows.length); i++)
{
if(m1.sparseRows[i]==null) continue;
int[] cols1=m1.sparseRows[i].getIndexContainer();
double[] values1=m1.sparseRows[i].getValueContainer();
for(int p=0; p<m1.sparseRows[i].size(); p++)
{
int k=cols1[p];
if(m2.sparseRows[k]==null) continue;
int[] cols2=m2.sparseRows[k].getIndexContainer();
double[] values2=m2.sparseRows[k].getValueContainer();
for(int q=0; q<m2.sparseRows[k].size(); q++)
{
int j=cols2[q];
double addValue=op.binaryFn.execute(values1[p], values2[q]);
if(result.isInSparseFormat())
{
//cache[j]=op.aggOp.increOp.fn.execute(cache[j], addValue);
Double old=cache.get(j);
if(old==null)
old=0.0;
cache.put(j, op.aggOp.increOp.fn.execute(old, addValue));
}else
{
double old=result.quickGetValue(i, j);
double newvalue=op.aggOp.increOp.fn.execute(old, addValue);
result.quickSetValue(i, j, newvalue);
}
}
}
if(result.isInSparseFormat())
{
/*for(int j=0; j<cache.length; j++)
{
if(cache[j]!=0)
{
result.appendValue(i, j, cache[j]);
cache[j]=0;
}
}*/
for(Entry<Integer, Double> e: cache.entrySet())
{
result.appendValue(i, e.getKey(), e.getValue());
}
cache.clear();
}
}
}
private static void aggBinSparseUnsafe(MatrixBlockDSM m1, MatrixBlockDSM m2, MatrixBlockDSM result,
AggregateBinaryOperator op) throws DMLRuntimeException
{
for(int i=0; i<m1.rlen; i++)
for(int j=0; j<m2.clen; j++)
{
double aggValue=op.aggOp.initialValue;
for(int k=0; k<m1.clen; k++)
{
double aik=m1.quickGetValue(i, k);
double bkj=m2.quickGetValue(k, j);
double addValue=op.binaryFn.execute(aik, bkj);
aggValue=op.aggOp.increOp.fn.execute(aggValue, addValue);
}
result.appendValue(i, j, aggValue);
}
}
/**
* Invocation from CP instructions. The aggregate is computed on the groups object
* against target and weights.
*
* Notes:
* * The computed number of groups is reused for multiple invocations with different target.
* * This implementation supports that the target is passed as column or row vector,
* in case of row vectors we also use sparse-safe implementations for sparse safe
* aggregation operators.
*
* @param tgt
* @param wghts
* @param ret
* @param op
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue groupedAggOperations(MatrixValue tgt, MatrixValue wghts, MatrixValue ret, Operator op)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//setup input matrices
// this <- groups
MatrixBlockDSM target = checkType(tgt);
MatrixBlockDSM weights = checkType(wghts);
//check valid dimensions
if( this.getNumColumns() != 1 || (weights!=null && weights.getNumColumns()!=1) )
throw new DMLRuntimeException("groupedAggregate can only operate on 1-dimensional column matrices for groups and weights.");
if( target.getNumColumns() != 1 && op instanceof CMOperator )
throw new DMLRuntimeException("groupedAggregate can only operate on 1-dimensional column matrices for target (for this aggregation function).");
if( target.getNumColumns() != 1 && target.getNumRows()!=1 )
throw new DMLRuntimeException("groupedAggregate can only operate on 1-dimensional column or row matrix for target.");
if( this.getNumRows() != Math.max(target.getNumRows(),target.getNumColumns()) || (weights != null && this.getNumRows() != weights.getNumRows()) )
throw new DMLRuntimeException("groupedAggregate can only operate on matrices with equal dimensions.");
// Determine the number of groups
if( numGroups <= 0 ) //reuse if available
{
double min = this.min();
double max = this.max();
if ( min <= 0 )
throw new DMLRuntimeException("Invalid value (" + min + ") encountered in 'groups' while computing groupedAggregate");
if ( max <= 0 )
throw new DMLRuntimeException("Invalid value (" + max + ") encountered in 'groups' while computing groupedAggregate.");
numGroups = (int) max;
}
// Allocate result matrix
MatrixBlockDSM result = checkType(ret);
boolean result_sparsity = estimateSparsityOnGroupedAgg(rlen, numGroups);
if(result==null)
result=new MatrixBlockDSM(numGroups, 1, result_sparsity);
else
result.reset(numGroups, 1, result_sparsity);
// Compute the result
double w = 1; // default weight
//CM operator for count, mean, variance
//note: current support only for column vectors
if(op instanceof CMOperator) {
// initialize required objects for storing the result of CM operations
CM cmFn = CM.getCMFnObject(((CMOperator) op).getAggOpType());
CM_COV_Object[] cmValues = new CM_COV_Object[numGroups];
for ( int i=0; i < numGroups; i++ )
cmValues[i] = new CM_COV_Object();
for ( int i=0; i < this.getNumRows(); i++ ) {
int g = (int) this.quickGetValue(i, 0);
double d = target.quickGetValue(i,0);
if ( weights != null )
w = weights.quickGetValue(i,0);
// cmValues is 0-indexed, whereas range of values for g = [1,numGroups]
cmFn.execute(cmValues[g-1], d, w);
}
// extract the required value from each CM_COV_Object
for ( int i=0; i < numGroups; i++ )
// result is 0-indexed, so is cmValues
result.quickSetValue(i, 0, cmValues[i].getRequiredResult(op));
}
//Aggregate operator for sum (via kahan sum)
//note: support for row/column vectors and dense/sparse
else if( op instanceof AggregateOperator )
{
//the only aggregate operator that is supported here is sum,
//furthermore, we always use KahanPlus and hence aggop.correctionExists is true
AggregateOperator aggop = (AggregateOperator) op;
//default case for aggregate(sum)
groupedAggregateKahanPlus(target, weights, result, aggop);
}
else
throw new DMLRuntimeException("Invalid operator (" + op + ") encountered while processing groupedAggregate.");
return result;
}
/**
* This is a specific implementation for aggregate(fn="sum"), where we use KahanPlus for numerical
* stability. In contrast to other functions of aggregate, this implementation supports row and column
* vectors for target and exploits sparse representations since KahanPlus is sparse-safe.
*
* @param target
* @param weights
* @param op
* @throws DMLRuntimeException
*/
private void groupedAggregateKahanPlus( MatrixBlockDSM target, MatrixBlockDSM weights, MatrixBlockDSM result, AggregateOperator aggop ) throws DMLRuntimeException
{
boolean rowVector = target.getNumColumns()>1;
double w = 1; //default weight
//skip empty blocks (sparse-safe operation)
if( target.isEmptyBlock(false) )
return;
//init group buffers
KahanObject[] buffer = new KahanObject[numGroups];
for(int i=0; i < numGroups; i++ )
buffer[i] = new KahanObject(aggop.initialValue, 0);
if( rowVector ) //target is rowvector
{
if( target.sparse ) //SPARSE target
{
if( target.sparseRows[0]!=null )
{
int len = target.sparseRows[0].size();
int[] aix = target.sparseRows[0].getIndexContainer();
double[] avals = target.sparseRows[0].getValueContainer();
for( int j=0; j<len; j++ ) //for each nnz
{
int g = (int) this.quickGetValue(aix[j], 0);
if ( weights != null )
w = weights.quickGetValue(aix[j],0);
aggop.increOp.fn.execute(buffer[g-1], avals[j]*w);
}
}
}
else //DENSE target
{
for ( int i=0; i < target.getNumColumns(); i++ ) {
double d = target.denseBlock[ i ];
if( d != 0 ) //sparse-safe
{
int g = (int) this.quickGetValue(i, 0);
if ( weights != null )
w = weights.quickGetValue(i,0);
// buffer is 0-indexed, whereas range of values for g = [1,numGroups]
aggop.increOp.fn.execute(buffer[g-1], d*w);
}
}
}
}
else //column vector (always dense, but works for sparse as well)
{
for ( int i=0; i < this.getNumRows(); i++ )
{
double d = target.quickGetValue(i,0);
if( d != 0 ) //sparse-safe
{
int g = (int) this.quickGetValue(i, 0);
if ( weights != null )
w = weights.quickGetValue(i,0);
// buffer is 0-indexed, whereas range of values for g = [1,numGroups]
aggop.increOp.fn.execute(buffer[g-1], d*w);
}
}
}
// extract the results from group buffers
for ( int i=0; i < numGroups; i++ )
result.quickSetValue(i, 0, buffer[i]._sum);
}
public MatrixValue removeEmptyOperations( MatrixValue ret, boolean rows )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//check for empty inputs
if( nonZeros==0 ) {
ret.reset(0, 0, false);
return ret;
}
MatrixBlockDSM result = checkType(ret);
if( rows )
return removeEmptyRows(result);
else //cols
return removeEmptyColumns(result);
}
/**
*
* @param ret
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
private MatrixBlockDSM removeEmptyRows(MatrixBlockDSM ret)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//scan block and determine empty rows
int rlen2 = 0;
boolean[] flags = new boolean[ rlen ];
if( sparse )
{
for ( int i=0; i < sparseRows.length; i++ ) {
if ( sparseRows[i] != null && sparseRows[i].size() > 0 )
{
flags[i] = false;
rlen2++;
}
else
flags[i] = true;
}
}
else
{
for(int i=0; i<rlen; i++) {
flags[i] = true;
int index = i*clen;
for(int j=0; j<clen; j++)
if( denseBlock[index++] != 0 )
{
flags[i] = false;
rlen2++;
break; //early abort for current row
}
}
}
//reset result and copy rows
ret.reset(rlen2, clen, sparse);
int rindex = 0;
for( int i=0; i<rlen; i++ )
if( !flags[i] )
{
//copy row to result
if(sparse)
{
ret.appendRow(rindex, sparseRows[i]);
}
else
{
if( ret.denseBlock==null )
ret.denseBlock = new double[ rlen2*clen ];
int index1 = i*clen;
int index2 = rindex*clen;
for(int j=0; j<clen; j++)
{
if( denseBlock[index1] != 0 )
{
ret.denseBlock[index2] = denseBlock[index1];
ret.nonZeros++;
}
index1++;
index2++;
}
}
rindex++;
}
//check sparsity
ret.examSparsity();
return ret;
}
/**
*
* @param ret
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
private MatrixBlockDSM removeEmptyColumns(MatrixBlockDSM ret)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//scan block and determine empty cols
int clen2 = 0;
boolean[] flags = new boolean[ clen ];
for(int j=0; j<clen; j++) {
flags[j] = true;
for(int i=0; i<rlen; i++) {
double value = quickGetValue(i, j);
if( value != 0 )
{
flags[j] = false;
clen2++;
break; //early abort for current col
}
}
}
//reset result and copy rows
ret.reset(rlen, clen2, sparse);
int cindex = 0;
for( int j=0; j<clen; j++ )
if( !flags[j] )
{
//copy col to result
for( int i=0; i<rlen; i++ )
{
double value = quickGetValue(i, j);
if( value != 0 )
ret.quickSetValue(i, cindex, value);
}
cindex++;
}
//check sparsity
ret.examSparsity();
return ret;
}
@Override
public MatrixValue replaceOperations(MatrixValue result, double pattern, double replacement)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM ret = checkType(result);
examSparsity(); //ensure its in the right format
ret.reset(rlen, clen, sparse);
if( nonZeros == 0 && pattern != 0 )
return ret; //early abort
boolean NaNpattern = Double.isNaN(pattern);
if( sparse ) //SPARSE
{
if( pattern !=0d ) //SPARSE <- SPARSE (sparse-safe)
{
ret.adjustSparseRows(ret.rlen-1);
SparseRow[] a = sparseRows;
SparseRow[] c = ret.sparseRows;
for( int i=0; i<rlen; i++ )
{
SparseRow arow = a[ i ];
if( arow!=null && arow.size()>0 )
{
SparseRow crow = new SparseRow(arow.size());
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
for( int j=0; j<alen; j++ )
{
double val = avals[j];
if( val== pattern || (NaNpattern && Double.isNaN(val)) )
crow.append(aix[j], replacement);
else
crow.append(aix[j], val);
}
c[ i ] = crow;
}
}
}
else //DENSE <- SPARSE
{
ret.sparse = false;
ret.allocateDenseBlock();
SparseRow[] a = sparseRows;
double[] c = ret.denseBlock;
//initialize with replacement (since all 0 values, see SPARSITY_TURN_POINT)
Arrays.fill(c, replacement);
//overwrite with existing values (via scatter)
if( a != null ) //check for empty matrix
for( int i=0, cix=0; i<rlen; i++, cix+=clen )
{
SparseRow arow = a[ i ];
if( arow!=null && arow.size()>0 )
{
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
for( int j=0; j<alen; j++ )
if( avals[ j ] != 0 )
c[ cix+aix[j] ] = avals[ j ];
}
}
}
}
else //DENSE <- DENSE
{
int mn = ret.rlen * ret.clen;
ret.allocateDenseBlock();
double[] a = denseBlock;
double[] c = ret.denseBlock;
for( int i=0; i<mn; i++ )
{
double val = a[i];
if( val== pattern || (NaNpattern && Double.isNaN(val)) )
c[i] = replacement;
else
c[i] = a[i];
}
}
ret.recomputeNonZeros();
ret.examSparsity();
return ret;
}
/**
* D = ctable(A,v2,W)
* this <- A; scalarThat <- v2; that2 <- W; result <- D
*
* (i1,j1,v1) from input1 (this)
* (v2) from sclar_input2 (scalarThat)
* (i3,j3,w) from input3 (that2)
*/
@Override
public void tertiaryOperations(Operator op, double scalarThat,
MatrixValue that2Val, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that2 = checkType(that2Val);
CTable ctable = CTable.getCTableFnObject();
double v2 = scalarThat;
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
double w = that2.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
/**
* D = ctable(A,v2,w)
* this <- A; scalar_that <- v2; scalar_that2 <- w; result <- D
*
* (i1,j1,v1) from input1 (this)
* (v2) from sclar_input2 (scalarThat)
* (w) from scalar_input3 (scalarThat2)
*/
@Override
public void tertiaryOperations(Operator op, double scalarThat,
double scalarThat2, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
CTable ctable = CTable.getCTableFnObject();
double v2 = scalarThat;
double w = scalarThat2;
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
/**
* Specific ctable case of ctable(seq(...),X), where X is the only
* matrix input. The 'left' input parameter specifies if the seq appeared
* on the left, otherwise it appeared on the right.
*
*/
@Override
public void tertiaryOperations(Operator op, MatrixIndexes ix1, double scalarThat,
boolean left, int brlen, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
CTable ctable = CTable.getCTableFnObject();
double w = scalarThat;
int offset = (int) ((ix1.getRowIndex()-1)*brlen);
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
if( left )
ctable.execute(offset+i+1, v1, w, ctableResult);
else
ctable.execute(v1, offset+i+1, w, ctableResult);
}
}
/**
* D = ctable(A,B,w)
* this <- A; that <- B; scalar_that2 <- w; result <- D
*
* (i1,j1,v1) from input1 (this)
* (i1,j1,v2) from input2 (that)
* (w) from scalar_input3 (scalarThat2)
*/
@Override
public void tertiaryOperations(Operator op, MatrixValue thatVal,
double scalarThat2, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that = checkType(thatVal);
CTable ctable = CTable.getCTableFnObject();
double w = scalarThat2;
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
double v2 = that.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
/**
* D = ctable(A,B,W)
* this <- A; that <- B; that2 <- W; result <- D
*
* (i1,j1,v1) from input1 (this)
* (i1,j1,v2) from input2 (that)
* (i1,j1,w) from input3 (that2)
*/
public void tertiaryOperations(Operator op, MatrixValue thatVal, MatrixValue that2Val, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that = checkType(thatVal);
MatrixBlockDSM that2 = checkType(that2Val);
CTable ctable = CTable.getCTableFnObject();
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
double v2 = that.quickGetValue(i, j);
double w = that2.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
public void binaryOperationsInPlace(BinaryOperator op, MatrixValue thatValue)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that=checkType(thatValue);
if(this.rlen!=that.rlen || this.clen!=that.clen)
throw new RuntimeException("block sizes are not matched for binary " +
"cell operations: "+this.rlen+"*"+this.clen+" vs "+ that.rlen+"*"
+that.clen);
// System.out.println("-- this:\n"+this);
// System.out.println("-- that:\n"+that);
if(op.sparseSafe)
sparseBinaryInPlaceHelp(op, that);
else
denseBinaryInPlaceHelp(op, that);
// System.out.println("-- this (result):\n"+this);
}
private void sparseBinaryInPlaceHelp(BinaryOperator op, MatrixBlockDSM that) throws DMLRuntimeException
{
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(resultSparse.sparse && !this.sparse)
denseToSparse();
else if(!resultSparse.sparse && this.sparse)
sparseToDense();
if(this.sparse && that.sparse)
{
//special case, if both matrices are all 0s, just return
if(this.sparseRows==null && that.sparseRows==null)
return;
if(this.sparseRows!=null)
adjustSparseRows(rlen-1);
if(that.sparseRows!=null)
that.adjustSparseRows(rlen-1);
if(this.sparseRows!=null && that.sparseRows!=null)
{
for(int r=0; r<rlen; r++)
{
if(this.sparseRows[r]==null && that.sparseRows[r]==null)
continue;
if(that.sparseRows[r]==null)
{
double[] values=this.sparseRows[r].getValueContainer();
for(int i=0; i<this.sparseRows[r].size(); i++)
values[i]=op.fn.execute(values[i], 0);
}else
{
int estimateSize=0;
if(this.sparseRows[r]!=null)
estimateSize+=this.sparseRows[r].size();
if(that.sparseRows[r]!=null)
estimateSize+=that.sparseRows[r].size();
estimateSize=Math.min(clen, estimateSize);
//temp
SparseRow thisRow=this.sparseRows[r];
this.sparseRows[r]=new SparseRow(estimateSize, clen);
if(thisRow!=null)
{
nonZeros-=thisRow.size();
mergeForSparseBinary(op, thisRow.getValueContainer(),
thisRow.getIndexContainer(), thisRow.size(),
that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), r, this);
}else
{
appendRightForSparseBinary(op, that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), 0, r, this);
}
}
}
}
else if(this.sparseRows==null)
{
this.sparseRows=new SparseRow[rlen];
for(int r=0; r<rlen; r++)
{
SparseRow brow = that.sparseRows[r];
if( brow!=null && brow.size()>0 )
{
this.sparseRows[r] = new SparseRow( brow.size(), clen );
appendRightForSparseBinary(op, brow.getValueContainer(), brow.getIndexContainer(), brow.size(), 0, r, this);
}
}
}
else //that.sparseRows==null
{
for(int r=0; r<rlen; r++)
{
SparseRow arow = this.sparseRows[r];
if( arow!=null && arow.size()>0 )
appendLeftForSparseBinary(op, arow.getValueContainer(), arow.getIndexContainer(), arow.size(), 0, r, this);
}
}
}else
{
double thisvalue, thatvalue, resultvalue;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
thisvalue=this.quickGetValue(r, c);
thatvalue=that.quickGetValue(r, c);
resultvalue=op.fn.execute(thisvalue, thatvalue);
this.quickSetValue(r, c, resultvalue);
}
}
}
private void denseBinaryInPlaceHelp(BinaryOperator op, MatrixBlockDSM that) throws DMLRuntimeException
{
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(resultSparse.sparse && !this.sparse)
denseToSparse();
else if(!resultSparse.sparse && this.sparse)
sparseToDense();
double v;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
v=op.fn.execute(this.quickGetValue(r, c), that.quickGetValue(r, c));
quickSetValue(r, c, v);
}
}
////////////////////////////////////////////////////////////////////////////////
/* public MatrixBlockDSM getRandomDenseMatrix_normal(int rows, int cols, long seed)
{
Random random=new Random(seed);
this.allocateDenseBlock();
RandNPair pair = new RandNPair();
int index = 0;
while ( index < rows*cols ) {
pair.compute(random);
this.denseBlock[index++] = pair.getFirst();
if ( index < rows*cols )
this.denseBlock[index++] = pair.getSecond();
}
this.updateNonZeros();
return this;
}
public MatrixBlockDSM getRandomSparseMatrix_normal(int rows, int cols, double sparsity, long seed)
{
double val;
Random random = new Random(System.currentTimeMillis());
RandN rn = new RandN(seed);
this.sparseRows=new SparseRow[rows];
for(int i=0; i<rows; i++)
{
this.sparseRows[i]=new SparseRow();
for(int j=0; j<cols; j++)
{
if(random.nextDouble()>sparsity)
continue;
val = rn.nextDouble();
this.sparseRows[i].append(j, val );
}
}
this.updateNonZeros();
return this;
}
*/
////////
// Data Generation Methods
// (rand, sequence)
/**
* Function to generate a matrix of random numbers. This is invoked from maptasks of
* DataGen MR job. The parameter <code>seed</code> denotes the block-level seed.
*
* @param pdf
* @param rows
* @param cols
* @param rowsInBlock
* @param colsInBlock
* @param sparsity
* @param min
* @param max
* @param seed
* @return
* @throws DMLRuntimeException
*/
public MatrixBlockDSM getRandomMatrix(String pdf, int rows, int cols, int rowsInBlock, int colsInBlock, double sparsity, double min, double max, long seed) throws DMLRuntimeException
{
return getRandomMatrix(pdf, rows, cols, rowsInBlock, colsInBlock, sparsity, min, max, null, seed);
}
/**
* Function to generate a matrix of random numbers. This is invoked both
* from CP as well as from MR. In case of CP, it generates an entire matrix
* block-by-block. A <code>bigrand</code> is passed so that block-level
* seeds are generated internally. In case of MR, it generates a single
* block for given block-level seed <code>bSeed</code>.
*
* When pdf="uniform", cell values are drawn from uniform distribution in
* range <code>[min,max]</code>.
*
* When pdf="normal", cell values are drawn from standard normal
* distribution N(0,1). The range of generated values will always be
* (-Inf,+Inf).
*
* @param rows
* @param cols
* @param rowsInBlock
* @param colsInBlock
* @param sparsity
* @param min
* @param max
* @param bigrand
* @param bSeed
* @return
* @throws DMLRuntimeException
*/
public MatrixBlockDSM getRandomMatrix(String pdf, int rows, int cols, int rowsInBlock, int colsInBlock, double sparsity, double min, double max, Well1024a bigrand, long bSeed) throws DMLRuntimeException
{
// Setup Pseudo Random Number Generator for cell values based on 'pdf'.
PRNGenerator valuePRNG = null;
if ( pdf.equalsIgnoreCase("uniform"))
valuePRNG = new UniformPRNGenerator();
else if ( pdf.equalsIgnoreCase("normal"))
valuePRNG = new NormalPRNGenerator();
else
throw new DMLRuntimeException("Unsupported distribution function for Rand: " + pdf);
/*
* Setup min and max for distributions other than "uniform". Min and Max
* are set up in such a way that the usual logic of
* (max-min)*prng.nextDouble() is still valid. This is done primarily to
* share the same code across different distributions.
*/
if ( pdf.equalsIgnoreCase("normal") ) {
min=0;
max=1;
}
// Determine the sparsity of output matrix
sparse = (sparsity < SPARCITY_TURN_POINT);
if(cols<=SKINNY_MATRIX_TURN_POINT) {
sparse=false;
}
this.reset(rows, cols, sparse);
// Special case shortcuts for efficiency
if ( pdf.equalsIgnoreCase("uniform")) {
//specific cases for efficiency
if ( min == 0.0 && max == 0.0 ) { //all zeros
// nothing to do here
return this;
}
else if( !sparse && sparsity==1.0d && min == max ) //equal values
{
allocateDenseBlock();
Arrays.fill(denseBlock, 0, rlen*clen, min);
nonZeros = rlen*clen;
return this;
}
}
// Allocate memory
if ( sparse ) {
sparseRows = new SparseRow[rows];
//note: individual sparse rows are allocated on demand,
//for consistentcy with memory estimates and prevent OOMs.
}
else {
this.allocateDenseBlock();
}
double range = max - min;
int nrb = (int) Math.ceil((double)rows/rowsInBlock);
int ncb = (int) Math.ceil((double)cols/colsInBlock);
int blockrows, blockcols, rowoffset, coloffset;
int blocknnz;
// loop throught row-block indices
for(int rbi=0; rbi < nrb; rbi++) {
blockrows = (rbi == nrb-1 ? (rows-rbi*rowsInBlock) : rowsInBlock);
rowoffset = rbi*rowsInBlock;
// loop throught column-block indices
for(int cbj=0; cbj < ncb; cbj++) {
blockcols = (cbj == ncb-1 ? (cols-cbj*colsInBlock) : colsInBlock);
coloffset = cbj*colsInBlock;
// Generate a block (rbi,cbj)
// select the appropriate block-level seed
long seed = -1;
if ( bigrand == null ) {
// case of MR: simply use the passed-in value
seed = bSeed;
}
else {
// case of CP: generate a block-level seed from matrix-level Well1024a seed
seed = bigrand.nextLong();
}
// Initialize the PRNGenerator for cell values
valuePRNG.init(seed);
// Initialize the PRNGenerator for determining cells that contain a non-zero value
// Note that, "pdf" parameter applies only to cell values and the individual cells
// are always selected uniformly at random.
UniformPRNGenerator nnzPRNG = new UniformPRNGenerator(seed);
// block-level sparsity, which may differ from overall sparsity in the matrix.
boolean localSparse = sparse && !(blockcols<=SKINNY_MATRIX_TURN_POINT);
if ( localSparse ) {
blocknnz = (int) Math.ceil((blockrows*sparsity)*blockcols);
for(int ind=0; ind<blocknnz; ind++) {
int i = nnzPRNG.nextInt(blockrows);
int j = nnzPRNG.nextInt(blockcols);
double v = nnzPRNG.nextDouble();
if( sparseRows[rowoffset+i]==null )
sparseRows[rowoffset+i]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[rowoffset+i].set(coloffset+j, v);
}
}
else {
if (sparsity == 1.0) {
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0, index = ((ii+rowoffset)*cols)+coloffset; jj < blockcols; jj++, index++) {
double val = min + (range * valuePRNG.nextDouble());
this.denseBlock[index] = val;
}
}
}
else {
if ( sparse ) {
/* This case evaluated only when this function is invoked from CP.
* In this case:
* sparse=true -> entire matrix is in sparse format and hence denseBlock=null
* localSparse=true -> local block is dense, and hence on MR side a denseBlock will be allocated
* i.e., we need to generate data in a dense-style but set values in sparseRows
*
*/
// In this case, entire matrix is in sparse format but the current block is dense
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0; jj < blockcols; jj++) {
if(nnzPRNG.nextDouble() <= sparsity) {
double val = min + (range * valuePRNG.nextDouble());
if( sparseRows[ii+rowoffset]==null )
sparseRows[ii+rowoffset]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[ii+rowoffset].set(jj+coloffset, val);
}
}
}
}
else {
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0, index = ((ii+rowoffset)*cols)+coloffset; jj < blockcols; jj++, index++) {
if(nnzPRNG.nextDouble() <= sparsity) {
double val = min + (range * valuePRNG.nextDouble());
this.denseBlock[index] = val;
}
}
}
}
}
} // sparse or dense
} // cbj
} // rbi
recomputeNonZeros();
return this;
}
/**
* Method to generate a sequence according to the given parameters. The
* generated sequence is always in dense format.
*
* Both end points specified <code>from</code> and <code>to</code> must be
* included in the generated sequence i.e., [from,to] both inclusive. Note
* that, <code>to</code> is included only if (to-from) is perfectly
* divisible by <code>incr</code>.
*
* For example, seq(0,1,0.5) generates (0.0 0.5 1.0)
* whereas seq(0,1,0.6) generates (0.0 0.6) but not (0.0 0.6 1.0)
*
* @param from
* @param to
* @param incr
* @return
* @throws DMLRuntimeException
*/
public MatrixBlockDSM getSequence(double from, double to, double incr) throws DMLRuntimeException {
boolean neg = (from > to);
if (neg != (incr < 0))
throw new DMLRuntimeException("Wrong sign for the increment in a call to seq()");
//System.out.println(System.nanoTime() + ": begin of seq()");
int rows = 1 + (int)Math.floor((to-from)/incr);
int cols = 1;
sparse = false; // sequence matrix is always dense
this.reset(rows, cols, sparse);
this.allocateDenseBlock();
//System.out.println(System.nanoTime() + ": MatrixBlockDSM.seq(): seq("+from+","+to+","+incr+") rows = " + rows);
this.denseBlock[0] = from;
for(int i=1; i < rows; i++) {
from += incr;
this.denseBlock[i] = from;
}
recomputeNonZeros();
//System.out.println(System.nanoTime() + ": end of seq()");
return this;
}
////////
// Misc methods
private static MatrixBlockDSM checkType(MatrixValue block) throws DMLUnsupportedOperationException
{
if( block!=null && !(block instanceof MatrixBlockDSM))
throw new DMLUnsupportedOperationException("the Matrix Value is not MatrixBlockDSM!");
return (MatrixBlockDSM) block;
}
private static boolean checkRealSparsity(long rlen, long clen, long nnz)
{
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if( clen<=SKINNY_MATRIX_TURN_POINT )
return false;
else
return (((double)nnz)/rlen/clen < SPARCITY_TURN_POINT);
}
private static boolean checkRealSparsity(MatrixBlockDSM m)
{
return checkRealSparsity( m, false );
}
private static boolean checkRealSparsity(MatrixBlockDSM m, boolean transpose)
{
int lrlen = (transpose) ? m.clen : m.rlen;
int lclen = (transpose) ? m.rlen : m.clen;
int lnnz = m.getNonZeros();
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(lclen<=SKINNY_MATRIX_TURN_POINT)
return false;
else
return (((double)lnnz)/lrlen/lclen < SPARCITY_TURN_POINT);
}
public void print()
{
System.out.println("sparse = "+sparse);
if(!sparse)
System.out.println("nonzeros = "+nonZeros);
for(int i=0; i<rlen; i++)
{
for(int j=0; j<clen; j++)
{
System.out.print(quickGetValue(i, j)+"\t");
}
System.out.println();
}
}
@Override
public int compareTo(Object arg0)
{
// don't compare blocks
return 0;
}
@Override
public String toString()
{
String ret="sparse? = "+sparse+"\n" ;
ret+="nonzeros = "+nonZeros+"\n";
ret+="size: "+rlen+" X "+clen+"\n";
boolean toprint=false;
if(!toprint)
return "sparse? = "+sparse+"\nnonzeros = "+nonZeros+"\nsize: "+rlen+" X "+clen+"\n";
if(sparse)
{
int len=0;
if(sparseRows!=null)
len=Math.min(rlen, sparseRows.length);
int i=0;
for(; i<len; i++)
{
ret+="row +"+i+": "+sparseRows[i]+"\n";
if(sparseRows[i]!=null)
{
for(int j=0; j<sparseRows[i].size(); j++)
if(sparseRows[i].getValueContainer()[j]!=0.0)
toprint=true;
}
}
for(; i<rlen; i++)
{
ret+="row +"+i+": null\n";
}
}else
{
if(denseBlock!=null)
{
int start=0;
for(int i=0; i<rlen; i++)
{
for(int j=0; j<clen; j++)
{
ret+=this.denseBlock[start+j]+"\t";
if(this.denseBlock[start+j]!=0.0)
toprint=true;
}
ret+="\n";
start+=clen;
}
}
}
return ret;
}
///////////////////////////
// Helper classes
public static class SparsityEstimate
{
public int estimatedNonZeros=0;
public boolean sparse=false;
public SparsityEstimate(boolean sps, int nnzs)
{
sparse=sps;
estimatedNonZeros=nnzs;
}
public SparsityEstimate(){}
}
public static class IJV
{
public int i=-1;
public int j=-1;
public double v=0;
public IJV()
{}
public IJV(int i, int j, double v)
{
set(i, j, v);
}
public void set(int i, int j, double v)
{
this.i=i;
this.j=j;
this.v=v;
}
public String toString()
{
return "("+i+", "+j+"): "+v;
}
}
public static class SparseCellIterator implements Iterator<IJV>
{
private int rlen=0;
private SparseRow[] sparseRows=null;
private int curRow=-1;
private int curColIndex=-1;
private int[] colIndexes=null;
private double[] values=null;
private boolean nothingLeft=false;
private IJV retijv=new IJV();
public SparseCellIterator(int nrows, SparseRow[] mtx)
{
rlen=nrows;
sparseRows=mtx;
curRow=0;
if(sparseRows==null)
nothingLeft=true;
else
findNextNonZeroRow();
}
private void findNextNonZeroRow() {
while(curRow<Math.min(rlen, sparseRows.length) && (sparseRows[curRow]==null || sparseRows[curRow].size()==0))
curRow++;
if(curRow>=Math.min(rlen, sparseRows.length))
nothingLeft=true;
else
{
curColIndex=0;
colIndexes=sparseRows[curRow].getIndexContainer();
values=sparseRows[curRow].getValueContainer();
}
}
@Override
public boolean hasNext() {
if(nothingLeft)
return false;
else
return true;
}
@Override
public IJV next() {
retijv.set(curRow, colIndexes[curColIndex], values[curColIndex]);
curColIndex++;
if(curColIndex>=sparseRows[curRow].size())
{
curRow++;
findNextNonZeroRow();
}
return retijv;
}
@Override
public void remove() {
throw new RuntimeException("SparseCellIterator.remove should not be called!");
}
}
}
| SystemML/SystemML/DML/src/main/java/com/ibm/bi/dml/runtime/matrix/io/MatrixBlockDSM.java | /**
* IBM Confidential
* OCO Source Materials
* (C) Copyright IBM Corp. 2010, 2014
* The source code for this program is not published or otherwise divested of its trade secrets, irrespective of what has been deposited with the U.S. Copyright Office.
*/
package com.ibm.bi.dml.runtime.matrix.io;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.commons.math.random.Well1024a;
import com.ibm.bi.dml.lops.MMTSJ.MMTSJType;
import com.ibm.bi.dml.lops.PartialAggregate.CorrectionLocationType;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.DMLUnsupportedOperationException;
import com.ibm.bi.dml.runtime.functionobjects.And;
import com.ibm.bi.dml.runtime.functionobjects.Builtin;
import com.ibm.bi.dml.runtime.functionobjects.CM;
import com.ibm.bi.dml.runtime.functionobjects.CTable;
import com.ibm.bi.dml.runtime.functionobjects.KahanPlus;
import com.ibm.bi.dml.runtime.functionobjects.MaxIndex;
import com.ibm.bi.dml.runtime.functionobjects.Minus;
import com.ibm.bi.dml.runtime.functionobjects.Multiply;
import com.ibm.bi.dml.runtime.functionobjects.Plus;
import com.ibm.bi.dml.runtime.functionobjects.ReduceAll;
import com.ibm.bi.dml.runtime.functionobjects.SwapIndex;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.CM_COV_Object;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.KahanObject;
import com.ibm.bi.dml.runtime.instructions.CPInstructions.ScalarObject;
import com.ibm.bi.dml.runtime.instructions.MRInstructions.RangeBasedReIndexInstruction.IndexRange;
import com.ibm.bi.dml.runtime.matrix.mapred.IndexedMatrixValue;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateBinaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateOperator;
import com.ibm.bi.dml.runtime.matrix.operators.AggregateUnaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.BinaryOperator;
import com.ibm.bi.dml.runtime.matrix.operators.CMOperator;
import com.ibm.bi.dml.runtime.matrix.operators.COVOperator;
import com.ibm.bi.dml.runtime.matrix.operators.Operator;
import com.ibm.bi.dml.runtime.matrix.operators.ReorgOperator;
import com.ibm.bi.dml.runtime.matrix.operators.ScalarOperator;
import com.ibm.bi.dml.runtime.matrix.operators.UnaryOperator;
import com.ibm.bi.dml.runtime.util.NormalPRNGenerator;
import com.ibm.bi.dml.runtime.util.PRNGenerator;
import com.ibm.bi.dml.runtime.util.UniformPRNGenerator;
import com.ibm.bi.dml.runtime.util.UtilFunctions;
public class MatrixBlockDSM extends MatrixValue
{
@SuppressWarnings("unused")
private static final String _COPYRIGHT = "Licensed Materials - Property of IBM\n(C) Copyright IBM Corp. 2010, 2014\n" +
"US Government Users Restricted Rights - Use, duplication disclosure restricted by GSA ADP Schedule Contract with IBM Corp.";
//sparsity nnz threshold, based on practical experiments on space consumption and performance
public static final double SPARCITY_TURN_POINT = 0.4;
//sparsity column threshold, based on initial capacity of sparse representation
public static final int SKINNY_MATRIX_TURN_POINT = 4;
//sparsity threshold for ultra-sparse matrix operations (40nnz in a 1kx1k block)
public static final double ULTRA_SPARSITY_TURN_POINT = 0.00004;
public enum BlockType{
EMPTY_BLOCK,
ULTRA_SPARSE_BLOCK, //ultra sparse representation, in-mem same as sparse
SPARSE_BLOCK, //sparse representation, see sparseRows
DENSE_BLOCK, //dense representation, see denseBlock
}
//matrix meta data
protected int rlen = -1;
protected int clen = -1;
protected boolean sparse = true;
protected int nonZeros = 0;
//matrix data (sparse or dense)
protected double[] denseBlock = null;
protected SparseRow[] sparseRows = null;
//sparse-block-specific attributes (allocation only)
protected int estimatedNNzsPerRow = -1;
//ctable-specific attributes
protected int maxrow = -1;
protected int maxcolumn = -1;
//grpaggregate-specific attributes
protected int numGroups = -1;
////////
// Matrix Constructors
//
public MatrixBlockDSM()
{
rlen = 0;
clen = 0;
sparse = true;
nonZeros = 0;
maxrow = 0;
maxcolumn = 0;
}
public MatrixBlockDSM(int rl, int cl, boolean sp)
{
rlen = rl;
clen = cl;
sparse = sp;
nonZeros = 0;
maxrow = 0;
maxcolumn = 0;
}
public MatrixBlockDSM(int rl, int cl, boolean sp, int estnnzs)
{
this(rl, cl, sp);
estimatedNNzsPerRow=(int)Math.ceil((double)estnnzs/(double)rl);
}
public MatrixBlockDSM(MatrixBlockDSM that)
{
this.copy(that);
}
////////
// Initialization methods
// (reset, init, allocate, etc)
public void reset()
{
reset(-rlen);
}
public void reset(int estnnzs)
{
estimatedNNzsPerRow=(int)Math.ceil((double)estnnzs/(double)rlen);
if(sparse)
{
resetSparse();
}
else
{
if(denseBlock!=null)
{
if(denseBlock.length<rlen*clen)
denseBlock=null;
else
Arrays.fill(denseBlock, 0, rlen*clen, 0);
}
}
nonZeros=0;
//operation-specific attributes
maxrow = rlen;
maxcolumn = clen;
numGroups = -1;
}
public void reset(int rl, int cl) {
rlen=rl;
clen=cl;
nonZeros=0;
reset();
}
public void reset(int rl, int cl, int estnnzs) {
rlen=rl;
clen=cl;
nonZeros=0;
reset(estnnzs);
}
public void reset(int rl, int cl, boolean sp)
{
sparse=sp;
reset(rl, cl);
}
public void reset(int rl, int cl, boolean sp, int estnnzs)
{
sparse=sp;
reset(rl, cl, estnnzs);
}
public void resetSparse()
{
if(sparseRows!=null)
{
for(int i=0; i<Math.min(rlen, sparseRows.length); i++)
if(sparseRows[i]!=null)
sparseRows[i].reset(estimatedNNzsPerRow, clen);
}
}
public void resetDenseWithValue(int rl, int cl, double v)
{
estimatedNNzsPerRow=-1;
rlen=rl;
clen=cl;
sparse=false;
if(v==0)
{
reset();
return;
}
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
denseBlock=new double[limit];
Arrays.fill(denseBlock, 0, limit, v);
nonZeros=limit;
}
/**
* NOTE: This method is designed only for dense representation.
*
* @param arr
* @param r
* @param c
* @throws DMLRuntimeException
*/
public void init(double[][] arr, int r, int c)
throws DMLRuntimeException
{
//input checks
if ( sparse )
throw new DMLRuntimeException("MatrixBlockDSM.init() can be invoked only on matrices with dense representation.");
if( r*c > rlen*clen )
throw new DMLRuntimeException("MatrixBlockDSM.init() invoked with too large dimensions ("+r+","+c+") vs ("+rlen+","+clen+")");
//allocate or resize dense block
allocateDenseBlock();
//copy and compute nnz
for(int i=0, ix=0; i < r; i++, ix+=clen)
System.arraycopy(arr[i], 0, denseBlock, ix, arr[i].length);
recomputeNonZeros();
maxrow = r;
maxcolumn = c;
}
/**
* NOTE: This method is designed only for dense representation.
*
* @param arr
* @param r
* @param c
* @throws DMLRuntimeException
*/
public void init(double[] arr, int r, int c)
throws DMLRuntimeException
{
//input checks
if ( sparse )
throw new DMLRuntimeException("MatrixBlockDSM.init() can be invoked only on matrices with dense representation.");
if( r*c > rlen*clen )
throw new DMLRuntimeException("MatrixBlockDSM.init() invoked with too large dimensions ("+r+","+c+") vs ("+rlen+","+clen+")");
//allocate or resize dense block
allocateDenseBlock();
//copy and compute nnz
System.arraycopy(arr, 0, denseBlock, 0, arr.length);
recomputeNonZeros();
maxrow = r;
maxcolumn = c;
}
/**
*
*/
public void allocateDenseBlock()
{
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length < limit )
denseBlock=new double[limit];
nonZeros = 0;
}
/**
*
* @param r
*/
public void adjustSparseRows(int r)
{
if(sparseRows==null)
sparseRows=new SparseRow[rlen];
else if(sparseRows.length<=r)
{
SparseRow[] oldSparseRows=sparseRows;
sparseRows=new SparseRow[rlen];
for(int i=0; i<Math.min(oldSparseRows.length, rlen); i++) {
sparseRows[i]=oldSparseRows[i];
}
}
}
/**
* This should be called only in the read and write functions for CP
* This function should be called before calling any setValueDenseUnsafe()
*
* @param rl
* @param cl
*/
public void allocateDenseBlockUnsafe(int rl, int cl)
{
sparse=false;
rlen=rl;
clen=cl;
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
{
denseBlock=new double[limit];
}else
Arrays.fill(denseBlock, 0, limit, 0);
}
/**
* This should be called only in the read and write functions for CP
* This function should be called before calling any setValueSparseUnsafe() or appendValueSparseUnsafe()
* @param rl
* @param cl
* @param estimatedmNNzs
*/
@Deprecated
public void allocateSparseRowsUnsafe(int rl, int cl, int estimatedmNNzs)
{
sparse=true;
rlen=rl;
clen=cl;
int nnzsPerRow=(int) Math.ceil((double)estimatedmNNzs/(double)rl);
if(sparseRows!=null)
{
if(sparseRows.length>=rlen)
{
for(int i=0; i<rlen; i++)
{
if(sparseRows[i]==null)
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
else
sparseRows[i].reset(nnzsPerRow, cl);
}
}else
{
SparseRow[] temp=sparseRows;
sparseRows=new SparseRow[rlen];
int i=0;
for(; i<temp.length; i++)
{
if(temp[i]!=null)
{
sparseRows[i]=temp[i];
sparseRows[i].reset(nnzsPerRow, cl);
}else
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
}
for(; i<rlen; i++)
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
}
}else
{
sparseRows=new SparseRow[rlen];
for(int i=0; i<rlen; i++)
sparseRows[i]=new SparseRow(nnzsPerRow, cl);
}
}
/**
* Allows to cleanup all previously allocated sparserows or denseblocks.
* This is for example required in reading a matrix with many empty blocks
* via distributed cache into in-memory list of blocks - not cleaning blocks
* from non-empty blocks would significantly increase the total memory consumption.
*
*/
public void cleanupBlock( boolean dense, boolean sparse )
{
if(dense)
denseBlock = null;
if(sparse)
sparseRows = null;
}
////////
// Metadata information
public int getNumRows()
{
return rlen;
}
/**
* NOTE: setNumRows() and setNumColumns() are used only in tertiaryInstruction (for contingency tables)
*
* @param _r
*/
public void setNumRows(int r)
{
rlen = r;
}
public int getNumColumns()
{
return clen;
}
public void setNumColumns(int c)
{
clen = c;
}
public int getNonZeros()
{
return nonZeros;
}
/**
* Returns the current representation (true for sparse).
*/
public boolean isInSparseFormat()
{
return sparse;
}
/**
*
* @return
*/
public boolean isUltraSparse()
{
double sp = ((double)nonZeros/rlen)/clen;
//check for sparse representation in order to account for vectors in dense
return sparse && sp<ULTRA_SPARSITY_TURN_POINT && nonZeros<40;
}
/**
* Returns the exact representation once it is written or
* exam sparsity is called.
*
* @return
*/
public boolean isExactInSparseFormat()
{
long lrlen = (long) rlen;
long lclen = (long) clen;
long lnonZeros = (long) nonZeros;
//ensure exact size estimates for write
if( lnonZeros<=0 )
//if( sparse || lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT )
{
recomputeNonZeros();
lnonZeros = (long) nonZeros;
}
return (lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT && lclen>SKINNY_MATRIX_TURN_POINT);
}
/**
*
* @param rlen
* @param clen
* @param nonZeros
* @return
*/
public static boolean isExactInSparseFormat(long rlen, long clen, long nonZeros)
{
return (nonZeros<(rlen*clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT);
}
public boolean isVector()
{
return (rlen == 1 || clen == 1);
}
/**
* Return the maximum row encountered WITHIN the current block
*
*/
public int getMaxRow()
{
if (!sparse)
return getNumRows();
else
return maxrow;
}
public void setMaxRow(int r)
{
maxrow = r;
}
/**
* Return the maximum column encountered WITHIN the current block
*
*/
public int getMaxColumn()
{
if (!sparse)
return getNumColumns();
else
return maxcolumn;
}
public void setMaxColumn(int c)
{
maxcolumn = c;
}
@Override
public boolean isEmpty()
{
return isEmptyBlock(false);
}
public boolean isEmptyBlock()
{
return isEmptyBlock(true);
}
public boolean isEmptyBlock(boolean safe)
{
boolean ret = false;
if( sparse && sparseRows==null )
ret = true;
else if( !sparse && denseBlock==null )
ret = true;
if( nonZeros==0 )
{
//prevent under-estimation
if(safe)
recomputeNonZeros();
ret = (nonZeros==0);
}
return ret;
}
////////
// Data handling
public double[] getDenseArray()
{
if(sparse)
return null;
return denseBlock;
}
public SparseRow[] getSparseRows()
{
if(!sparse)
return null;
return sparseRows;
}
public SparseCellIterator getSparseCellIterator()
{
if(!sparse)
throw new RuntimeException("getSparseCellInterator should not be called for dense format");
return new SparseCellIterator(rlen, sparseRows);
}
@Override
public void getCellValues(Collection<Double> ret)
{
int limit=rlen*clen;
if(sparse)
{
if(sparseRows==null)
{
for(int i=0; i<limit; i++)
ret.add(0.0);
}else
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] container=sparseRows[r].getValueContainer();
for(int j=0; j<sparseRows[r].size(); j++)
ret.add(container[j]);
}
int zeros=limit-ret.size();
for(int i=0; i<zeros; i++)
ret.add(0.0);
}
}else
{
if(denseBlock==null)
{
for(int i=0; i<limit; i++)
ret.add(0.0);
}else
{
for(int i=0; i<limit; i++)
ret.add(denseBlock[i]);
}
}
}
@Override
public void getCellValues(Map<Double, Integer> ret)
{
int limit=rlen*clen;
if(sparse)
{
if(sparseRows==null)
{
ret.put(0.0, limit);
}else
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] container=sparseRows[r].getValueContainer();
for(int j=0; j<sparseRows[r].size(); j++)
{
Double v=container[j];
Integer old=ret.get(v);
if(old!=null)
ret.put(v, old+1);
else
ret.put(v, 1);
}
}
int zeros=limit-ret.size();
Integer old=ret.get(0.0);
if(old!=null)
ret.put(0.0, old+zeros);
else
ret.put(0.0, zeros);
}
}else
{
if(denseBlock==null)
{
ret.put(0.0, limit);
}else
{
for(int i=0; i<limit; i++)
{
double v=denseBlock[i];
Integer old=ret.get(v);
if(old!=null)
ret.put(v, old+1);
else
ret.put(v, 1);
}
}
}
}
@Override
public double getValue(int r, int c)
{
if(r>rlen || c > clen)
throw new RuntimeException("indexes ("+r+","+c+") out of range ("+rlen+","+clen+")");
if(sparse)
{
if(sparseRows==null || sparseRows.length<=r || sparseRows[r]==null)
return 0;
return sparseRows[r].get(c);
}else
{
if(denseBlock==null)
return 0;
return denseBlock[r*clen+c];
}
}
@Override
public void setValue(int r, int c, double v)
{
if(r>rlen || c > clen)
throw new RuntimeException("indexes ("+r+","+c+") out of range ("+rlen+","+clen+")");
if(sparse)
{
if( (sparseRows==null || sparseRows.length<=r || sparseRows[r]==null) && v==0.0)
return;
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
if(sparseRows[r].set(c, v))
nonZeros++;
}else
{
if(denseBlock==null && v==0.0)
return;
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
{
denseBlock=new double[limit];
//Arrays.fill(denseBlock, 0, limit, 0);
}
int index=r*clen+c;
if(denseBlock[index]==0)
nonZeros++;
denseBlock[index]=v;
if(v==0)
nonZeros--;
}
}
@Override
public void setValue(CellIndex index, double v)
{
setValue(index.row, index.column, v);
}
@Override
/**
* If (r,c) \in Block, add v to existing cell
* If not, add a new cell with index (r,c)
*/
public void addValue(int r, int c, double v) {
if(sparse)
{
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
double curV=sparseRows[r].get(c);
if(curV==0)
nonZeros++;
curV+=v;
if(curV==0)
nonZeros--;
else
sparseRows[r].set(c, curV);
}
else
{
int limit=rlen*clen;
if(denseBlock==null)
{
denseBlock=new double[limit];
Arrays.fill(denseBlock, 0, limit, 0);
}
int index=r*clen+c;
if(denseBlock[index]==0)
nonZeros++;
denseBlock[index]+=v;
if(denseBlock[index]==0)
nonZeros--;
}
}
public double quickGetValue(int r, int c)
{
if(sparse)
{
if(sparseRows==null || sparseRows.length<=r || sparseRows[r]==null)
return 0;
return sparseRows[r].get(c);
}
else
{
if(denseBlock==null)
return 0;
return denseBlock[r*clen+c];
}
}
public void quickSetValue(int r, int c, double v)
{
if(sparse)
{
if( (sparseRows==null || sparseRows.length<=r || sparseRows[r]==null) && v==0.0)
return;
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
if(sparseRows[r].set(c, v))
nonZeros++;
}
else
{
if(denseBlock==null && v==0.0)
return;
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
{
denseBlock=new double[limit];
//Arrays.fill(denseBlock, 0, limit, 0);
}
int index=r*clen+c;
if(denseBlock[index]==0)
nonZeros++;
denseBlock[index]=v;
if(v==0)
nonZeros--;
}
}
public double getValueDenseUnsafe(int r, int c)
{
if(denseBlock==null)
return 0;
return denseBlock[r*clen+c];
}
/**
* This can be only called when you know you have properly allocated spaces for a dense representation
* and r and c are in the the range of the dimension
* Note: this function won't keep track of the nozeros
*/
public void setValueDenseUnsafe(int r, int c, double v)
{
denseBlock[r*clen+c]=v;
}
public double getValueSparseUnsafe(int r, int c)
{
if(sparseRows==null || sparseRows.length<=r || sparseRows[r]==null)
return 0;
return sparseRows[r].get(c);
}
/**
* This can be only called when you know you have properly allocated spaces for a sparse representation
* and r and c are in the the range of the dimension
* Note: this function won't keep track of the nozeros
*/
public void setValueSparseUnsafe(int r, int c, double v)
{
sparseRows[r].set(c, v);
}
/**
* Append value is only used when values are appended at the end of each row for the sparse representation
* This can only be called, when the caller knows the access pattern of the block
* @param r
* @param c
* @param v
*/
public void appendValue(int r, int c, double v)
{
if(v==0) return;
if(!sparse)
quickSetValue(r, c, v);
else
{
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
/*else {
if (sparseRows[r].capacity()==0) {
System.out.println(" ... !null: " + sparseRows[r].size() + ", " + sparseRows[r].capacity() + ", " + sparseRows[r].getValueContainer().length + ", " + sparseRows[r].estimatedNzs + ", " + sparseRows[r].maxNzs);
}
}*/
sparseRows[r].append(c, v);
nonZeros++;
}
}
/**
* This can be only called when you know you have properly allocated spaces for a sparse representation
* and r and c are in the the range of the dimension
* Note: this function won't keep track of the nozeros
* This can only be called, when the caller knows the access pattern of the block
*/
public void appendValueSparseUnsafe(int r, int c, double v)
{
sparseRows[r].append(c, v);
}
public void appendRow(int r, SparseRow values)
{
if(values==null)
return;
if(sparse)
{
adjustSparseRows(r);
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(values);
else
sparseRows[r].copy(values);
nonZeros+=values.size();
}else
{
int[] cols=values.getIndexContainer();
double[] vals=values.getValueContainer();
for(int i=0; i<values.size(); i++)
quickSetValue(r, cols[i], vals[i]);
}
}
/**
*
* @param that
* @param rowoffset
* @param coloffset
*/
public void appendToSparse( MatrixBlockDSM that, int rowoffset, int coloffset )
{
if( that==null || that.isEmptyBlock(false) )
return; //nothing to append
//init sparse rows if necessary
//adjustSparseRows(rlen-1);
if( that.sparse ) //SPARSE <- SPARSE
{
for( int i=0; i<that.rlen; i++ )
{
SparseRow brow = that.sparseRows[i];
if( brow!=null && brow.size()>0 )
{
int aix = rowoffset+i;
int len = brow.size();
int[] ix = brow.getIndexContainer();
double[] val = brow.getValueContainer();
if( sparseRows[aix]==null )
sparseRows[aix] = new SparseRow(estimatedNNzsPerRow,clen);
for( int j=0; j<len; j++ )
sparseRows[aix].append(coloffset+ix[j], val[j]);
}
}
}
else //SPARSE <- DENSE
{
for( int i=0; i<that.rlen; i++ )
{
int aix = rowoffset+i;
for( int j=0, bix=i*that.clen; j<that.clen; j++ )
{
double val = that.denseBlock[bix+j];
if( val != 0 )
{
if( sparseRows[aix]==null )//create sparserow only if required
sparseRows[aix] = new SparseRow(estimatedNNzsPerRow,clen);
sparseRows[aix].append(coloffset+j, val);
}
}
}
}
}
/**
*
*/
public void sortSparseRows()
{
if( !sparse || sparseRows==null )
return;
for( SparseRow arow : sparseRows )
if( arow!=null && arow.size()>1 )
arow.sort();
}
/**
* Wrapper method for reduceall-min of a matrix.
*
* @return
* @throws DMLRuntimeException
*/
public double min()
throws DMLRuntimeException
{
//construct operator
AggregateOperator aop = new AggregateOperator(Double.MAX_VALUE, Builtin.getBuiltinFnObject("min"));
AggregateUnaryOperator auop = new AggregateUnaryOperator( aop, ReduceAll.getReduceAllFnObject());
//execute operation
MatrixBlockDSM out = new MatrixBlockDSM(1, 1, false);
MatrixAggLib.aggregateUnaryMatrix(this, out, auop);
return out.quickGetValue(0, 0);
}
/**
* Wrapper method for reduceall-max of a matrix.
*
* @return
* @throws DMLRuntimeException
*/
public double max()
throws DMLRuntimeException
{
//construct operator
AggregateOperator aop = new AggregateOperator(-Double.MAX_VALUE, Builtin.getBuiltinFnObject("max"));
AggregateUnaryOperator auop = new AggregateUnaryOperator( aop, ReduceAll.getReduceAllFnObject());
//execute operation
MatrixBlockDSM out = new MatrixBlockDSM(1, 1, false);
MatrixAggLib.aggregateUnaryMatrix(this, out, auop);
return out.quickGetValue(0, 0);
}
////////
// basic block handling functions
public void examSparsity()
throws DMLRuntimeException
{
double sp = ((double)nonZeros/rlen)/clen;
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(sparse)
{
if(sp>=SPARCITY_TURN_POINT || clen<=SKINNY_MATRIX_TURN_POINT) {
//System.out.println("Calling sparseToDense(): nz=" + nonZeros + ", rlen=" + rlen + ", clen=" + clen + ", sparsity = " + sp + ", spturn=" + SPARCITY_TURN_POINT );
sparseToDense();
}
}
else
{
if(sp<SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT) {
//System.out.println("Calling denseToSparse(): nz=" + nonZeros + ", rlen=" + rlen + ", clen=" + clen + ", sparsity = " + sp + ", spturn=" + SPARCITY_TURN_POINT );
denseToSparse();
}
}
}
private void denseToSparse()
{
//LOG.info("**** denseToSparse: "+this.getNumRows()+"x"+this.getNumColumns()+" nonZeros: "+this.nonZeros);
sparse=true;
adjustSparseRows(rlen-1);
reset();
if(denseBlock==null)
return;
int index=0;
for(int r=0; r<rlen; r++)
{
for(int c=0; c<clen; c++)
{
if(denseBlock[index]!=0)
{
if(sparseRows[r]==null) //create sparse row only if required
sparseRows[r]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[r].append(c, denseBlock[index]);
nonZeros++;
}
index++;
}
}
//cleanup dense block
denseBlock = null;
}
private void sparseToDense()
throws DMLRuntimeException
{
//LOG.info("**** sparseToDense: "+this.getNumRows()+"x"+this.getNumColumns()+" nonZeros: "+this.nonZeros);
sparse=false;
int limit=rlen*clen;
if ( limit < 0 ) {
throw new DMLRuntimeException("Unexpected error in sparseToDense().. limit < 0: " + rlen + ", " + clen + ", " + limit);
}
allocateDenseBlock();
Arrays.fill(denseBlock, 0, limit, 0);
nonZeros=0;
if(sparseRows==null)
return;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
if(values[i]==0) continue;
denseBlock[r*clen+cols[i]]=values[i];
nonZeros++;
}
}
//cleanup sparse rows
sparseRows = null;
}
public void recomputeNonZeros()
{
nonZeros=0;
if( sparse && sparseRows!=null )
{
int limit = Math.min(rlen, sparseRows.length);
for(int i=0; i<limit; i++)
if(sparseRows[i]!=null)
nonZeros += sparseRows[i].size();
}
else if( !sparse && denseBlock!=null )
{
int limit=rlen*clen;
for(int i=0; i<limit; i++)
{
//HotSpot JVM bug causes crash in presence of NaNs
//nonZeros += (denseBlock[i]!=0) ? 1 : 0;
if( denseBlock[i]!=0 )
nonZeros++;
}
}
}
private long recomputeNonZeros(int rl, int ru, int cl, int cu)
{
long nnz = 0;
if(sparse)
{
if(sparseRows!=null)
{
int rlimit = Math.min( ru+1, Math.min(rlen, sparseRows.length) );
if( cl==0 && cu==clen-1 ) //specific case: all cols
{
for(int i=rl; i<rlimit; i++)
if(sparseRows[i]!=null && sparseRows[i].size()>0)
nnz+=sparseRows[i].size();
}
else if( cl==cu ) //specific case: one column
{
for(int i=rl; i<rlimit; i++)
if(sparseRows[i]!=null && sparseRows[i].size()>0)
nnz += (sparseRows[i].get(cl)!=0) ? 1 : 0;
}
else //general case
{
int astart,aend;
for(int i=rl; i<rlimit; i++)
if(sparseRows[i]!=null && sparseRows[i].size()>0)
{
SparseRow arow = sparseRows[i];
astart = arow.searchIndexesFirstGTE(cl);
aend = arow.searchIndexesFirstGTE(cu);
nnz += (astart!=-1) ? (aend-astart+1) : 0;
}
}
}
}else
{
if(denseBlock!=null)
{
for( int i=rl, ix=rl*clen; i<=ru; i++, ix+=clen )
for( int j=cl; j<=cu; j++ )
{
//HotSpot JVM bug causes crash in presence of NaNs
//nnz += (denseBlock[ix+j]!=0) ? 1 : 0;
if( denseBlock[ix+j]!=0 )
nnz++;
}
}
}
return nnz;
}
public void copy(MatrixValue thatValue)
{
MatrixBlockDSM that;
try {
that = checkType(thatValue);
} catch (DMLUnsupportedOperationException e) {
throw new RuntimeException(e);
}
if( this == that ) //prevent data loss (e.g., on sparse-dense conversion)
throw new RuntimeException( "Copy must not overwrite itself!" );
this.rlen=that.rlen;
this.clen=that.clen;
this.sparse=checkRealSparsity(that);
estimatedNNzsPerRow=(int)Math.ceil((double)thatValue.getNonZeros()/(double)rlen);
if(this.sparse && that.sparse)
copySparseToSparse(that);
else if(this.sparse && !that.sparse)
copyDenseToSparse(that);
else if(!this.sparse && that.sparse)
copySparseToDense(that);
else
copyDenseToDense(that);
}
public void copy(MatrixValue thatValue, boolean sp) {
MatrixBlockDSM that;
try {
that = checkType(thatValue);
} catch (DMLUnsupportedOperationException e) {
throw new RuntimeException(e);
}
if( this == that ) //prevent data loss (e.g., on sparse-dense conversion)
throw new RuntimeException( "Copy must not overwrite itself!" );
this.rlen=that.rlen;
this.clen=that.clen;
this.sparse=sp;
estimatedNNzsPerRow=(int)Math.ceil((double)thatValue.getNonZeros()/(double)rlen);
if(this.sparse && that.sparse)
copySparseToSparse(that);
else if(this.sparse && !that.sparse)
copyDenseToSparse(that);
else if(!this.sparse && that.sparse)
copySparseToDense(that);
else
copyDenseToDense(that);
}
private void copySparseToSparse(MatrixBlockDSM that)
{
this.nonZeros=that.nonZeros;
if(that.sparseRows==null)
{
resetSparse();
return;
}
adjustSparseRows(Math.min(that.rlen, that.sparseRows.length)-1);
for(int i=0; i<Math.min(that.sparseRows.length, rlen); i++)
{
if(that.sparseRows[i]!=null)
{
if(sparseRows[i]==null)
sparseRows[i]=new SparseRow(that.sparseRows[i]);
else
sparseRows[i].copy(that.sparseRows[i]);
}else if(this.sparseRows[i]!=null)
this.sparseRows[i].reset(estimatedNNzsPerRow, clen);
}
}
private void copyDenseToDense(MatrixBlockDSM that)
{
this.nonZeros=that.nonZeros;
if(that.denseBlock==null)
{
if(denseBlock!=null)
Arrays.fill(denseBlock, 0);
return;
}
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
denseBlock=new double[limit];
System.arraycopy(that.denseBlock, 0, this.denseBlock, 0, limit);
}
private void copySparseToDense(MatrixBlockDSM that)
{
this.nonZeros=that.nonZeros;
if(that.sparseRows==null)
{
if(denseBlock!=null)
Arrays.fill(denseBlock, 0);
return;
}
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length<limit)
denseBlock=new double[limit];
else
Arrays.fill(denseBlock, 0, limit, 0);
int start=0;
for(int r=0; r<Math.min(that.sparseRows.length, rlen); r++, start+=clen)
{
if(that.sparseRows[r]==null) continue;
double[] values=that.sparseRows[r].getValueContainer();
int[] cols=that.sparseRows[r].getIndexContainer();
for(int i=0; i<that.sparseRows[r].size(); i++)
{
denseBlock[start+cols[i]]=values[i];
}
}
}
private void copyDenseToSparse(MatrixBlockDSM that)
{
nonZeros = that.nonZeros;
if(that.denseBlock==null)
{
resetSparse();
return;
}
adjustSparseRows(rlen-1);
for(int i=0, ix=0; i<rlen; i++)
{
if( sparseRows[i]!=null )
sparseRows[i].reset(estimatedNNzsPerRow, clen);
for(int j=0; j<clen; j++)
{
double val = that.denseBlock[ix++];
if( val != 0 )
{
if(sparseRows[i]==null) //create sparse row only if required
sparseRows[i]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[i].append(j, val);
}
}
}
}
/**
* In-place copy of matrix src into the index range of the existing current matrix.
* Note that removal of existing nnz in the index range and nnz maintenance is
* only done if 'awareDestNZ=true',
*
* @param rl
* @param ru
* @param cl
* @param cu
* @param src
* @param awareDestNZ
* true, forces (1) to remove existing non-zeros in the index range of the
* destination if not present in src and (2) to internally maintain nnz
* false, assume empty index range in destination and do not maintain nnz
* (the invoker is responsible to recompute nnz after all copies are done)
*/
public void copy(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ )
{
if(sparse && src.sparse)
copySparseToSparse(rl, ru, cl, cu, src, awareDestNZ);
else if(sparse && !src.sparse)
copyDenseToSparse(rl, ru, cl, cu, src, awareDestNZ);
else if(!sparse && src.sparse)
copySparseToDense(rl, ru, cl, cu, src, awareDestNZ);
else
copyDenseToDense(rl, ru, cl, cu, src, awareDestNZ);
}
private void copySparseToSparse(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.sparseRows==null)
{
if( awareDestNZ && sparseRows != null )
copyEmptyToSparse(rl, ru, cl, cu, true);
return;
}
if(sparseRows==null)
sparseRows=new SparseRow[rlen];
else if( awareDestNZ )
{
copyEmptyToSparse(rl, ru, cl, cu, true);
//explicit clear if awareDestNZ because more efficient since
//src will have multiple columns and only few overwriting values
}
//copy values
int alen;
int[] aix;
double[] avals;
for( int i=0; i<src.rlen; i++ )
{
SparseRow arow = src.sparseRows[i];
if( arow != null && arow.size()>0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
if( sparseRows[rl+i] == null || sparseRows[rl+i].size()==0 )
{
sparseRows[rl+i] = new SparseRow(estimatedNNzsPerRow, clen);
SparseRow brow = sparseRows[rl+i];
for( int j=0; j<alen; j++ )
brow.append(cl+aix[j], avals[j]);
if( awareDestNZ )
nonZeros += brow.size();
}
else if( awareDestNZ ) //general case (w/ awareness NNZ)
{
SparseRow brow = sparseRows[rl+i];
int lnnz = brow.size();
if( cl==cu && cl==aix[0] )
{
if (avals[0]==0)
brow.deleteIndex(cl);
else
brow.set(cl, avals[0] );
}
else
{
brow.deleteIndexRange(cl, cu);
for( int j=0; j<alen; j++ )
brow.set(cl+aix[j], avals[j]);
}
nonZeros += (brow.size() - lnnz);
}
else //general case (w/o awareness NNZ)
{
SparseRow brow = sparseRows[rl+i];
//brow.set(cl, arow);
for( int j=0; j<alen; j++ )
brow.set(cl+aix[j], avals[j]);
}
}
}
}
private void copySparseToDense(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.sparseRows==null)
{
if( awareDestNZ && denseBlock != null ) {
nonZeros -= (int)recomputeNonZeros(rl, ru, cl, cu);
copyEmptyToDense(rl, ru, cl, cu);
}
return;
}
if(denseBlock==null)
allocateDenseBlock();
else if( awareDestNZ )
{
nonZeros -= (int)recomputeNonZeros(rl, ru, cl, cu);
copyEmptyToDense(rl, ru, cl, cu);
}
//copy values
int alen;
int[] aix;
double[] avals;
for( int i=0, ix=rl*clen; i<src.rlen; i++, ix+=clen )
{
SparseRow arow = src.sparseRows[i];
if( arow != null && arow.size()>0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
for( int j=0; j<alen; j++ )
denseBlock[ix+cl+aix[j]] = avals[j];
if(awareDestNZ)
nonZeros += alen;
}
}
}
private void copyDenseToSparse(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.denseBlock==null)
{
if( awareDestNZ && sparseRows != null )
copyEmptyToSparse(rl, ru, cl, cu, true);
return;
}
if(sparseRows==null)
sparseRows=new SparseRow[rlen];
//no need to clear for awareDestNZ since overwritten
//copy values
double val;
for( int i=0, ix=0; i<src.rlen; i++, ix+=src.clen )
{
int rix = rl + i;
if( sparseRows[rix]==null || sparseRows[rix].size()==0 )
{
for( int j=0; j<src.clen; j++ )
if( (val = src.denseBlock[ix+j]) != 0 )
{
if( sparseRows[rix]==null )
sparseRows[rix] = new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[rix].append(cl+j, val);
}
if( awareDestNZ && sparseRows[rix]!=null )
nonZeros += sparseRows[rix].size();
}
else if( awareDestNZ ) //general case (w/ awareness NNZ)
{
SparseRow brow = sparseRows[rix];
int lnnz = brow.size();
if( cl==cu )
{
if ((val = src.denseBlock[ix])==0)
brow.deleteIndex(cl);
else
brow.set(cl, val);
}
else
{
brow.deleteIndexRange(cl, cu);
for( int j=0; j<src.clen; j++ )
if( (val = src.denseBlock[ix+j]) != 0 )
brow.set(cl+j, val);
}
nonZeros += (brow.size() - lnnz);
}
else //general case (w/o awareness NNZ)
{
SparseRow brow = sparseRows[rix];
for( int j=0; j<src.clen; j++ )
if( (val = src.denseBlock[ix+j]) != 0 )
brow.set(cl+j, val);
}
}
}
private void copyDenseToDense(int rl, int ru, int cl, int cu, MatrixBlockDSM src, boolean awareDestNZ)
{
//handle empty src and dest
if(src.denseBlock==null)
{
if( awareDestNZ && denseBlock != null ) {
nonZeros -= (int)recomputeNonZeros(rl, ru, cl, cu);
copyEmptyToDense(rl, ru, cl, cu);
}
return;
}
if(denseBlock==null)
allocateDenseBlock();
//no need to clear for awareDestNZ since overwritten
if( awareDestNZ )
nonZeros = nonZeros - (int)recomputeNonZeros(rl, ru, cl, cu) + src.nonZeros;
//copy values
int rowLen = cu-cl+1;
if(clen == src.clen) //optimization for equal width
System.arraycopy(src.denseBlock, 0, denseBlock, rl*clen+cl, src.rlen*src.clen);
else
for( int i=0, ix1=0, ix2=rl*clen+cl; i<src.rlen; i++, ix1+=src.clen, ix2+=clen )
System.arraycopy(src.denseBlock, ix1, denseBlock, ix2, rowLen);
}
public void copyRowArrayToDense(int destRow, double[] src, int sourceStart)
{
//handle empty dest
if(denseBlock==null)
allocateDenseBlock();
//no need to clear for awareDestNZ since overwritten
System.arraycopy(src, sourceStart, denseBlock, destRow*clen, clen);
}
private void copyEmptyToSparse(int rl, int ru, int cl, int cu, boolean updateNNZ )
{
if( cl==cu ) //specific case: column vector
{
if( updateNNZ )
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
{
int lnnz = sparseRows[i].size();
sparseRows[i].deleteIndex(cl);
nonZeros += (sparseRows[i].size()-lnnz);
}
}
else
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
sparseRows[i].deleteIndex(cl);
}
}
else
{
if( updateNNZ )
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
{
int lnnz = sparseRows[i].size();
sparseRows[i].deleteIndexRange(cl, cu);
nonZeros += (sparseRows[i].size()-lnnz);
}
}
else
{
for( int i=rl; i<=ru; i++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
sparseRows[i].deleteIndexRange(cl, cu);
}
}
}
private void copyEmptyToDense(int rl, int ru, int cl, int cu)
{
int rowLen = cu-cl+1;
if(clen == rowLen) //optimization for equal width
Arrays.fill(denseBlock, rl*clen+cl, ru*clen+cu+1, 0);
else
for( int i=rl, ix2=rl*clen+cl; i<=ru; i++, ix2+=clen )
Arrays.fill(denseBlock, ix2, ix2+rowLen, 0);
}
////////
// Input/Output functions
@Override
public void readFields(DataInput in)
throws IOException
{
rlen = in.readInt();
clen = in.readInt();
byte bformat = in.readByte();
if( bformat<0 || bformat>=BlockType.values().length )
throw new IOException("invalid format: '"+bformat+"' (need to be 0-"+BlockType.values().length+".");
BlockType format=BlockType.values()[bformat];
switch(format)
{
case ULTRA_SPARSE_BLOCK:
sparse = true;
cleanupBlock(true, true); //clean all
readUltraSparseBlock(in);
break;
case SPARSE_BLOCK:
sparse = true;
cleanupBlock(true, false); //reuse sparse
readSparseBlock(in);
break;
case DENSE_BLOCK:
sparse = false;
cleanupBlock(false, true); //reuse dense
readDenseBlock(in);
break;
case EMPTY_BLOCK:
sparse = true;
cleanupBlock(true, true); //clean all
nonZeros = 0;
break;
}
}
private void readDenseBlock(DataInput in) throws IOException {
int limit=rlen*clen;
if(denseBlock==null || denseBlock.length < limit )
denseBlock=new double[limit];
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=in.readDouble();
if(denseBlock[i]!=0)
nonZeros++;
}
}
private void readSparseBlock(DataInput in) throws IOException {
adjustSparseRows(rlen-1);
nonZeros=0;
for(int r=0; r<rlen; r++)
{
int nr=in.readInt();
nonZeros+=nr;
if(nr==0)
{
if(sparseRows[r]!=null)
sparseRows[r].reset(estimatedNNzsPerRow, clen);
continue;
}
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(nr);
else
sparseRows[r].reset(nr, clen);
for(int j=0; j<nr; j++)
sparseRows[r].append(in.readInt(), in.readDouble());
}
}
private void readUltraSparseBlock(DataInput in) throws IOException
{
adjustSparseRows(rlen-1); //adjust to size
resetSparse(); //reset all sparse rows
//at least 1 nonZero, otherwise empty block
nonZeros = in.readInt();
for(int i=0; i<nonZeros; i++)
{
int r = in.readInt();
int c = in.readInt();
double val = in.readDouble();
if(sparseRows[r]==null)
sparseRows[r]=new SparseRow(1,clen);
sparseRows[r].append(c, val);
}
}
@Override
public void write(DataOutput out) throws IOException {
out.writeInt(rlen);
out.writeInt(clen);
if(sparse)
{
if(sparseRows==null || nonZeros==0) //MB or cond
writeEmptyBlock(out);
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
writeSparseToUltraSparse(out); //MB new write
//if it should be dense, then write to the dense format
else if(nonZeros>=((long)rlen)*((long)clen)*SPARCITY_TURN_POINT || clen<=SKINNY_MATRIX_TURN_POINT)
writeSparseToDense(out);
else
writeSparseBlock(out);
}else
{
if(denseBlock==null || nonZeros==0) //MB or cond
writeEmptyBlock(out);
//if it should be sparse
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
writeDenseToUltraSparse(out);
else if(nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT)
writeDenseToSparse(out);
else
writeDenseBlock(out);
}
}
private void writeEmptyBlock(DataOutput out) throws IOException
{
//empty blocks do not need to materialize row information
out.writeByte( BlockType.EMPTY_BLOCK.ordinal() );
}
private void writeDenseBlock(DataOutput out) throws IOException
{
out.writeByte( BlockType.DENSE_BLOCK.ordinal() );
int limit=rlen*clen;
if( out instanceof MatrixBlockDSMDataOutput ) //fast serialize
((MatrixBlockDSMDataOutput)out).writeDoubleArray(limit, denseBlock);
else //general case (if fast serialize not supported)
for(int i=0; i<limit; i++)
out.writeDouble(denseBlock[i]);
}
private void writeSparseBlock(DataOutput out) throws IOException
{
out.writeByte( BlockType.SPARSE_BLOCK.ordinal() );
if( out instanceof MatrixBlockDSMDataOutput ) //fast serialize
((MatrixBlockDSMDataOutput)out).writeSparseRows(rlen, sparseRows);
else //general case (if fast serialize not supported)
{
int r=0;
for(;r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null)
out.writeInt(0);
else
{
int nr=sparseRows[r].size();
out.writeInt(nr);
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int j=0; j<nr; j++)
{
out.writeInt(cols[j]);
out.writeDouble(values[j]);
}
}
}
for(;r<rlen; r++)
out.writeInt(0);
}
}
private void writeSparseToUltraSparse(DataOutput out) throws IOException
{
out.writeByte( BlockType.ULTRA_SPARSE_BLOCK.ordinal() );
out.writeInt(nonZeros);
for(int r=0;r<Math.min(rlen, sparseRows.length); r++)
if(sparseRows[r]!=null && sparseRows[r].size()>0 )
{
int alen = sparseRows[r].size();
int[] aix = sparseRows[r].getIndexContainer();
double[] avals = sparseRows[r].getValueContainer();
for(int j=0; j<alen; j++)
{
out.writeInt(r);
out.writeInt(aix[j]);
out.writeDouble(avals[j]);
}
}
}
private void writeSparseToDense(DataOutput out)
throws IOException
{
//write block type 'dense'
out.writeByte( BlockType.DENSE_BLOCK.ordinal() );
//write data (from sparse to dense)
if( sparseRows==null ) //empty block
for( int i=0; i<rlen*clen; i++ )
out.writeDouble(0);
else //existing sparse block
{
for( int i=0; i<rlen; i++ )
{
if( i<sparseRows.length && sparseRows[i]!=null && sparseRows[i].size()>0 )
{
SparseRow arow = sparseRows[i];
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
//foreach non-zero value, fill with 0s if required
for( int j=0, j2=0; j2<alen; j++, j2++ ) {
for( ; j<aix[j2]; j++ )
out.writeDouble( 0 );
out.writeDouble( avals[j2] );
}
//remaining 0 values in row
for( int j=aix[alen-1]+1; j<clen; j++)
out.writeDouble( 0 );
}
else //empty row
for( int j=0; j<clen; j++ )
out.writeDouble( 0 );
}
}
/* old version with binary search for each cell
out.writeByte( BlockType.DENSE_BLOCK.ordinal() );
for(int i=0; i<rlen; i++)
for(int j=0; j<clen; j++)
out.writeDouble(quickGetValue(i, j));
*/
}
private void writeDenseToUltraSparse(DataOutput out) throws IOException
{
out.writeByte( BlockType.ULTRA_SPARSE_BLOCK.ordinal() );
out.writeInt(nonZeros);
for(int r=0, ix=0; r<rlen; r++)
for(int c=0; c<clen; c++, ix++)
if( denseBlock[ix]!=0 )
{
out.writeInt(r);
out.writeInt(c);
out.writeDouble(denseBlock[ix]);
}
}
private void writeDenseToSparse(DataOutput out)
throws IOException
{
out.writeByte( BlockType.SPARSE_BLOCK.ordinal() );
int start=0;
for(int r=0; r<rlen; r++)
{
//count nonzeros
int nr=0;
for(int i=start; i<start+clen; i++)
if(denseBlock[i]!=0.0)
nr++;
out.writeInt(nr);
for(int c=0; c<clen; c++)
{
if(denseBlock[start]!=0.0)
{
out.writeInt(c);
out.writeDouble(denseBlock[start]);
}
start++;
}
}
}
/**
* NOTE: The used estimates must be kept consistent with the respective write functions.
*
* @return
*/
public long getExactSizeOnDisk()
{
long lrlen = (long) rlen;
long lclen = (long) clen;
long lnonZeros = (long) nonZeros;
//ensure exact size estimates for write
if( lnonZeros<=0 )
//if( sparse || lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT )
{
recomputeNonZeros();
lnonZeros = (long) nonZeros;
}
//get exact size estimate (see write for the corresponding meaning)
if(sparse)
{
if(sparseRows==null || nonZeros==0)
return 9; //empty block
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
return 4 + nonZeros*16 + 9; //ultra sparse block
else if(lnonZeros>=(lrlen*lclen)*SPARCITY_TURN_POINT || lclen<=SKINNY_MATRIX_TURN_POINT)
return lrlen*lclen*8 + 9; //dense block
else
return lrlen*4 + lnonZeros*12 + 9; //sparse block
}else
{
if(denseBlock==null || nonZeros==0)
return 9; //empty block
else if( nonZeros<rlen && nonZeros<((long)rlen)*((long)clen)*SPARCITY_TURN_POINT && clen>SKINNY_MATRIX_TURN_POINT )
return 4 + nonZeros*16 + 9; //ultra sparse block
else if(lnonZeros<(lrlen*lclen)*SPARCITY_TURN_POINT && lclen>SKINNY_MATRIX_TURN_POINT)
return lrlen*4 + lnonZeros*12 + 9; //sparse block
else
return lrlen*lclen*8 + 9; //dense block
}
}
////////
// Estimates size and sparsity
public static long estimateSize(long nrows, long ncols, double sparsity)
{
long size=44;//the basic variables and references sizes
//determine sparse/dense representation
boolean sparse=true;
if(ncols<=SKINNY_MATRIX_TURN_POINT)
sparse=false;
else
sparse= sparsity < SPARCITY_TURN_POINT;
//estimate memory consumption for sparse/dense
if(sparse)
{
//NOTES:
// * Each sparse row has a fixed overhead of 8B (reference) + 32B (object) +
// 12B (3 int members), 32B (overhead int array), 32B (overhead double array),
// * Each non-zero value requires 12B for the column-index/value pair.
// * Overheads for arrays, objects, and references refer to 64bit JVMs
// * If nnz < than rows we have only also empty rows.
//account for sparsity and initial capacity
long cnnz = Math.max(SparseRow.initialCapacity, (long)Math.ceil(sparsity*ncols));
long rlen = Math.min(nrows, (long) Math.ceil(sparsity*nrows*ncols));
size += rlen * ( 116 + 12 * cnnz ); //sparse row
size += (nrows-rlen) * 8; //empty rows
//OLD ESTIMATE:
//int len = Math.max(SparseRow.initialCapacity, (int)Math.ceil(sparsity*ncols));
//size += nrows * (28 + 12 * len );
}
else
{
size += nrows*ncols*8;
}
return size;
}
/**
*
* @param lrlen
* @param lclen
* @param lnonZeros
* @param sparse
* @return
*/
public static long estimateSizeOnDisk( long lrlen, long lclen, long lnonZeros, boolean sparse )
{
if(sparse)
{
return lrlen*4 + lnonZeros*12 + 9;
}
else
{
return lrlen*lclen*8 + 9;
}
}
public static SparsityEstimate estimateSparsityOnAggBinary(MatrixBlockDSM m1, MatrixBlockDSM m2, AggregateBinaryOperator op)
{
//NOTE: since MatrixMultLib always uses a dense intermediate output
//with subsequent check for sparsity, we should always return a dense estimate.
//Once, we support more aggregate binary operations, we need to change this.
return new SparsityEstimate(false, m1.getNumRows()*m2.getNumRows());
/*
SparsityEstimate est=new SparsityEstimate();
double m=m2.getNumColumns();
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if ( !op.sparseSafe || m <=SKINNY_MATRIX_TURN_POINT)
{
est.sparse=false;
}
else
{
double n=m1.getNumRows();
double k=m1.getNumColumns();
double nz1=m1.getNonZeros();
double nz2=m2.getNonZeros();
double pq=nz1*nz2/n/k/k/m;
double estimated= 1-Math.pow(1-pq, k);
est.sparse=(estimated < SPARCITY_TURN_POINT);
est.estimatedNonZeros=(int)(estimated*n*m);
}
return est;
*/
}
private static SparsityEstimate estimateSparsityOnBinary(MatrixBlockDSM m1, MatrixBlockDSM m2, BinaryOperator op)
{
SparsityEstimate est=new SparsityEstimate();
double m=m1.getNumColumns();
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(!op.sparseSafe || m<=SKINNY_MATRIX_TURN_POINT)
{
est.sparse=false;
return est;
}
double n=m1.getNumRows();
double nz1=m1.getNonZeros();
double nz2=m2.getNonZeros();
double estimated=0;
if(op.fn instanceof And || op.fn instanceof Multiply)//p*q
{
estimated=nz1/n/m*nz2/n/m;
}else //1-(1-p)*(1-q)
{
estimated=1-(1-nz1/n/m)*(1-nz2/n/m);
}
est.sparse= (estimated<SPARCITY_TURN_POINT);
est.estimatedNonZeros=(int)(estimated*n*m);
return est;
}
private boolean estimateSparsityOnSlice(int selectRlen, int selectClen, int finalRlen, int finalClen)
{
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(finalClen<=SKINNY_MATRIX_TURN_POINT)
return false;
else
return((double)nonZeros/(double)rlen/(double)clen*(double)selectRlen*(double)selectClen/(double)finalRlen/(double)finalClen<SPARCITY_TURN_POINT);
}
private boolean estimateSparsityOnLeftIndexing(long rlenm1, long clenm1, int nnzm1, int nnzm2)
{
boolean ret = (clenm1>SKINNY_MATRIX_TURN_POINT);
long ennz = Math.min(rlenm1*clenm1, nnzm1+nnzm2);
return (ret && (((double)ennz)/rlenm1/clenm1) < SPARCITY_TURN_POINT);
}
////////
// Core block operations (called from instructions)
public MatrixValue scalarOperations(ScalarOperator op, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM ret = checkType(result);
// estimate the sparsity structure of result matrix
boolean sp = this.sparse; // by default, we guess result.sparsity=input.sparsity
if (!op.sparseSafe)
sp = false; // if the operation is not sparse safe, then result will be in dense format
if( ret==null )
ret = new MatrixBlockDSM(rlen, clen, sp, this.nonZeros);
else
ret.reset(rlen, clen, sp, this.nonZeros);
ret.copy(this, sp);
if(op.sparseSafe)
ret.sparseScalarOperationsInPlace(op);
else
ret.denseScalarOperationsInPlace(op);
return ret;
}
public void scalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(op.sparseSafe)
this.sparseScalarOperationsInPlace(op);
else
this.denseScalarOperationsInPlace(op);
}
/**
* Note: only apply to non zero cells
*
* @param op
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
private void sparseScalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(sparse)
{
if(sparseRows==null)
return;
nonZeros=0;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] values=sparseRows[r].getValueContainer();
int[] cols=sparseRows[r].getIndexContainer();
int pos=0;
for(int i=0; i<sparseRows[r].size(); i++)
{
double v=op.executeScalar(values[i]);
if(v!=0)
{
values[pos]=v;
cols[pos]=cols[i];
pos++;
nonZeros++;
}
}
sparseRows[r].truncate(pos);
}
}else
{
//early abort possible since sparsesafe
if(denseBlock==null)
return;
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.executeScalar(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
private void denseScalarOperationsInPlace(ScalarOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if( sparse ) //SPARSE MATRIX
{
double v;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
v=op.executeScalar(quickGetValue(r, c));
quickSetValue(r, c, v);
}
}
else //DENSE MATRIX
{
//early abort not possible because not sparsesafe (e.g., A+7)
if(denseBlock==null)
allocateDenseBlock();
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.executeScalar(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
public MatrixValue unaryOperations(UnaryOperator op, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
checkType(result);
// estimate the sparsity structure of result matrix
boolean sp = this.sparse; // by default, we guess result.sparsity=input.sparsity
if (!op.sparseSafe)
sp = false; // if the operation is not sparse safe, then result will be in dense format
if(result==null)
result=new MatrixBlockDSM(rlen, clen, sp, this.nonZeros);
result.copy(this);
//core execution
((MatrixBlockDSM)result).unaryOperationsInPlace(op);
return result;
}
public void unaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(op.sparseSafe)
sparseUnaryOperationsInPlace(op);
else
denseUnaryOperationsInPlace(op);
}
/**
* only apply to non zero cells
*
* @param op
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
private void sparseUnaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if(sparse)
{
if(sparseRows==null)
return;
nonZeros=0;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
double[] values=sparseRows[r].getValueContainer();
int[] cols=sparseRows[r].getIndexContainer();
int pos=0;
for(int i=0; i<sparseRows[r].size(); i++)
{
double v=op.fn.execute(values[i]);
if(v!=0)
{
values[pos]=v;
cols[pos]=cols[i];
pos++;
nonZeros++;
}
}
sparseRows[r].truncate(pos);
}
}
else
{
//early abort possible since sparsesafe
if(denseBlock==null)
return;
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.fn.execute(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
private void denseUnaryOperationsInPlace(UnaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if( sparse ) //SPARSE MATRIX
{
double v;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
v=op.fn.execute(quickGetValue(r, c));
quickSetValue(r, c, v);
}
}
else//DENSE MATRIX
{
//early abort not possible because not sparsesafe
if(denseBlock==null)
allocateDenseBlock();
int limit=rlen*clen;
nonZeros=0;
for(int i=0; i<limit; i++)
{
denseBlock[i]=op.fn.execute(denseBlock[i]);
if(denseBlock[i]!=0)
nonZeros++;
}
}
}
public MatrixValue binaryOperations(BinaryOperator op, MatrixValue thatValue, MatrixValue result)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that=checkType(thatValue);
checkType(result);
if(this.rlen!=that.rlen || this.clen!=that.clen)
throw new RuntimeException("block sizes are not matched for binary " +
"cell operations: "+this.rlen+"*"+this.clen+" vs "+ that.rlen+"*"
+that.clen);
MatrixBlockDSM tmp = null;
if(op.sparseSafe)
tmp = sparseBinaryHelp(op, that, (MatrixBlockDSM)result);
else
tmp = denseBinaryHelp(op, that, (MatrixBlockDSM)result);
return tmp;
}
private MatrixBlockDSM sparseBinaryHelp(BinaryOperator op, MatrixBlockDSM that, MatrixBlockDSM result)
throws DMLRuntimeException
{
//+, -, (*)
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(result==null)
result=new MatrixBlockDSM(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
else
result.reset(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
if(this.sparse && that.sparse)
{
//special case, if both matrices are all 0s, just return
if(this.sparseRows==null && that.sparseRows==null)
return result;
if(result.sparse)
result.adjustSparseRows(result.rlen-1);
if(this.sparseRows!=null)
this.adjustSparseRows(rlen-1);
if(that.sparseRows!=null)
that.adjustSparseRows(that.rlen-1);
if(this.sparseRows!=null && that.sparseRows!=null)
{
for(int r=0; r<rlen; r++)
{
if(this.sparseRows[r]==null && that.sparseRows[r]==null)
continue;
if(result.sparse)
{
int estimateSize=0;
if(this.sparseRows[r]!=null)
estimateSize+=this.sparseRows[r].size();
if(that.sparseRows[r]!=null)
estimateSize+=that.sparseRows[r].size();
estimateSize=Math.min(clen, estimateSize);
if(result.sparseRows[r]==null)
result.sparseRows[r]=new SparseRow(estimateSize, result.clen);
else if(result.sparseRows[r].capacity()<estimateSize)
result.sparseRows[r].recap(estimateSize);
}
if(this.sparseRows[r]!=null && that.sparseRows[r]!=null)
{
mergeForSparseBinary(op, this.sparseRows[r].getValueContainer(),
this.sparseRows[r].getIndexContainer(), this.sparseRows[r].size(),
that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), r, result);
}else if(this.sparseRows[r]==null)
{
appendRightForSparseBinary(op, that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), 0, r, result);
}else
{
appendLeftForSparseBinary(op, this.sparseRows[r].getValueContainer(),
this.sparseRows[r].getIndexContainer(), this.sparseRows[r].size(), 0, r, result);
}
}
}else if(this.sparseRows==null)
{
for(int r=0; r<rlen; r++)
{
if(that.sparseRows[r]==null)
continue;
if(result.sparse)
{
if(result.sparseRows[r]==null)
result.sparseRows[r]=new SparseRow(that.sparseRows[r].size(), result.clen);
else if(result.sparseRows[r].capacity()<that.sparseRows[r].size())
result.sparseRows[r].recap(that.sparseRows[r].size());
}
appendRightForSparseBinary(op, that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), 0, r, result);
}
}else
{
for(int r=0; r<rlen; r++)
{
if(this.sparseRows[r]==null)
continue;
if(result.sparse)
{
if(result.sparseRows[r]==null)
result.sparseRows[r]=new SparseRow(this.sparseRows[r].size(), result.clen);
else if(result.sparseRows[r].capacity()<this.sparseRows[r].size())
result.sparseRows[r].recap(this.sparseRows[r].size());
}
appendLeftForSparseBinary(op, this.sparseRows[r].getValueContainer(),
this.sparseRows[r].getIndexContainer(), this.sparseRows[r].size(), 0, r, result);
}
}
}
else if( !result.sparse && (this.sparse || that.sparse) &&
(op.fn instanceof Plus || op.fn instanceof Minus ||
(op.fn instanceof Multiply && !that.sparse )))
{
//specific case in order to prevent binary search on sparse inputs (see quickget and quickset)
result.allocateDenseBlock();
int m = result.rlen;
int n = result.clen;
double[] c = result.denseBlock;
//1) process left input: assignment
int alen;
int[] aix;
double[] avals;
if( this.sparse ) //SPARSE left
{
Arrays.fill(result.denseBlock, 0, result.denseBlock.length, 0);
if( this.sparseRows != null )
{
for( int i=0, ix=0; i<m; i++, ix+=n ) {
SparseRow arow = this.sparseRows[i];
if( arow != null && arow.size() > 0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
for(int k = 0; k < alen; k++)
c[ix+aix[k]] = avals[k];
}
}
}
}
else //DENSE left
{
if( this.denseBlock!=null )
System.arraycopy(this.denseBlock, 0, c, 0, m*n);
else
Arrays.fill(result.denseBlock, 0, result.denseBlock.length, 0);
}
//2) process right input: op.fn (+,-,*), * only if dense
if( that.sparse ) //SPARSE right
{
if(that.sparseRows!=null)
{
for( int i=0, ix=0; i<m; i++, ix+=n ) {
SparseRow arow = that.sparseRows[i];
if( arow != null && arow.size() > 0 )
{
alen = arow.size();
aix = arow.getIndexContainer();
avals = arow.getValueContainer();
for(int k = 0; k < alen; k++)
c[ix+aix[k]] = op.fn.execute(c[ix+aix[k]], avals[k]);
}
}
}
}
else //DENSE right
{
if( that.denseBlock!=null )
for( int i=0; i<m*n; i++ )
c[i] = op.fn.execute(c[i], that.denseBlock[i]);
else if(op.fn instanceof Multiply)
Arrays.fill(result.denseBlock, 0, result.denseBlock.length, 0);
}
//3) recompute nnz
result.recomputeNonZeros();
}
else if( !result.sparse && !this.sparse && !that.sparse && this.denseBlock!=null && that.denseBlock!=null )
{
result.allocateDenseBlock();
int m = result.rlen;
int n = result.clen;
double[] c = result.denseBlock;
//int nnz = 0;
for( int i=0; i<m*n; i++ )
{
c[i] = op.fn.execute(this.denseBlock[i], that.denseBlock[i]);
//HotSpot JVM bug causes crash in presence of NaNs
//nnz += (c[i]!=0)? 1 : 0;
if( c[i] != 0 )
result.nonZeros++;
}
//result.nonZeros = nnz;
}
else //generic case
{
double thisvalue, thatvalue, resultvalue;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
thisvalue=this.quickGetValue(r, c);
thatvalue=that.quickGetValue(r, c);
if(thisvalue==0 && thatvalue==0)
continue;
resultvalue=op.fn.execute(thisvalue, thatvalue);
result.appendValue(r, c, resultvalue);
}
}
return result;
}
private MatrixBlockDSM denseBinaryHelp(BinaryOperator op, MatrixBlockDSM that, MatrixBlockDSM result)
throws DMLRuntimeException
{
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(result==null)
result=new MatrixBlockDSM(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
else
result.reset(rlen, clen, resultSparse.sparse, resultSparse.estimatedNonZeros);
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
double v = op.fn.execute(this.quickGetValue(r, c), that.quickGetValue(r, c));
result.appendValue(r, c, v);
}
return result;
}
/*
* like a merge sort
*/
private static void mergeForSparseBinary(BinaryOperator op, double[] values1, int[] cols1, int size1,
double[] values2, int[] cols2, int size2, int resultRow, MatrixBlockDSM result)
throws DMLRuntimeException
{
int p1=0, p2=0, column;
double v;
//merge
while(p1<size1 && p2< size2)
{
if(cols1[p1]<cols2[p2])
{
v=op.fn.execute(values1[p1], 0);
column=cols1[p1];
p1++;
}else if(cols1[p1]==cols2[p2])
{
v=op.fn.execute(values1[p1], values2[p2]);
column=cols1[p1];
p1++;
p2++;
}else
{
v=op.fn.execute(0, values2[p2]);
column=cols2[p2];
p2++;
}
result.appendValue(resultRow, column, v);
}
//add left over
appendLeftForSparseBinary(op, values1, cols1, size1, p1, resultRow, result);
appendRightForSparseBinary(op, values2, cols2, size2, p2, resultRow, result);
}
private static void appendLeftForSparseBinary(BinaryOperator op, double[] values1, int[] cols1, int size1,
int pos, int resultRow, MatrixBlockDSM result)
throws DMLRuntimeException
{
for(int j=pos; j<size1; j++)
{
double v = op.fn.execute(values1[j], 0);
result.appendValue(resultRow, cols1[j], v);
}
}
private static void appendRightForSparseBinary(BinaryOperator op, double[] values2, int[] cols2, int size2,
int pos, int resultRow, MatrixBlockDSM result) throws DMLRuntimeException
{
for( int j=pos; j<size2; j++ )
{
double v = op.fn.execute(0, values2[j]);
result.appendValue(resultRow, cols2[j], v);
}
}
public void incrementalAggregate(AggregateOperator aggOp, MatrixValue correction,
MatrixValue newWithCorrection)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//assert(aggOp.correctionExists);
MatrixBlockDSM cor=checkType(correction);
MatrixBlockDSM newWithCor=checkType(newWithCorrection);
KahanObject buffer=new KahanObject(0, 0);
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW)
{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=cor.quickGetValue(0, c);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c),
newWithCor.quickGetValue(r+1, c));
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(0, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
{
if(aggOp.increOp.fn instanceof Builtin
&& ((Builtin)(aggOp.increOp.fn)).bFunc == Builtin.BuiltinFunctionCode.MAXINDEX ){
for(int r=0; r<rlen; r++){
double currMaxValue = cor.quickGetValue(r, 0);
long newMaxIndex = (long)newWithCor.quickGetValue(r, 0);
double newMaxValue = newWithCor.quickGetValue(r, 1);
double update = aggOp.increOp.fn.execute(newMaxValue, currMaxValue);
if(update == 1){
quickSetValue(r, 0, newMaxIndex);
cor.quickSetValue(r, 0, newMaxValue);
}
}
}else{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=cor.quickGetValue(r, 0);;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c), newWithCor.quickGetValue(r, c+1));
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, 0, buffer._correction);
}
}
}
else if(aggOp.correctionLocation==CorrectionLocationType.NONE)
{
//e.g., ak+ kahan plus as used in sum, mapmult, mmcj and tsmm
if(aggOp.increOp.fn instanceof KahanPlus)
{
MatrixAggLib.aggregateBinaryMatrix(newWithCor, this, cor);
}
else
{
if( newWithCor.isInSparseFormat() && aggOp.sparseSafe ) //SPARSE
{
SparseRow[] bRows = newWithCor.getSparseRows();
if( bRows==null ) //early abort on empty block
return;
for( int r=0; r<Math.min(rlen, bRows.length); r++ )
{
SparseRow brow = bRows[r];
if( brow != null && brow.size() > 0 )
{
int blen = brow.size();
int[] bix = brow.getIndexContainer();
double[] bvals = brow.getValueContainer();
for( int j=0; j<blen; j++)
{
int c = bix[j];
buffer._sum = this.quickGetValue(r, c);
buffer._correction = cor.quickGetValue(r, c);
buffer = (KahanObject) aggOp.increOp.fn.execute(buffer, bvals[j]);
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, c, buffer._correction);
}
}
}
}
else //DENSE or SPARSE (!sparsesafe)
{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=cor.quickGetValue(r, c);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c));
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, c, buffer._correction);
}
}
//change representation if required
//(note since ak+ on blocks is currently only applied in MR, hence no need to account for this in mem estimates)
examSparsity();
}
}
else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOROWS)
{
double n, n2, mu2;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=cor.quickGetValue(0, c);
buffer._correction=cor.quickGetValue(1, c);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r+1, c);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(0, c, n);
cor.quickSetValue(1, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS)
{
double n, n2, mu2;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=cor.quickGetValue(r, 0);
buffer._correction=cor.quickGetValue(r, 1);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r, c+1);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
cor.quickSetValue(r, 0, n);
cor.quickSetValue(r, 1, buffer._correction);
}
}
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
}
public void incrementalAggregate(AggregateOperator aggOp, MatrixValue newWithCorrection)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//assert(aggOp.correctionExists);
MatrixBlockDSM newWithCor=checkType(newWithCorrection);
KahanObject buffer=new KahanObject(0, 0);
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW)
{
for(int r=0; r<rlen-1; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=this.quickGetValue(r+1, c);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c),
newWithCor.quickGetValue(r+1, c));
quickSetValue(r, c, buffer._sum);
quickSetValue(r+1, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
{
if(aggOp.increOp.fn instanceof Builtin
&& ((Builtin)(aggOp.increOp.fn)).bFunc == Builtin.BuiltinFunctionCode.MAXINDEX ){
for(int r = 0; r < rlen; r++){
double currMaxValue = quickGetValue(r, 1);
long newMaxIndex = (long)newWithCor.quickGetValue(r, 0);
double newMaxValue = newWithCor.quickGetValue(r, 1);
double update = aggOp.increOp.fn.execute(newMaxValue, currMaxValue);
if(update == 1){
quickSetValue(r, 0, newMaxIndex);
quickSetValue(r, 1, newMaxValue);
}
}
}else{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen-1; c++)
{
buffer._sum=this.quickGetValue(r, c);
buffer._correction=this.quickGetValue(r, c+1);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.quickGetValue(r, c), newWithCor.quickGetValue(r, c+1));
quickSetValue(r, c, buffer._sum);
quickSetValue(r, c+1, buffer._correction);
}
}
}/*else if(aggOp.correctionLocation==0)
{
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
//buffer._sum=this.getValue(r, c);
//buffer._correction=0;
//buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newWithCor.getValue(r, c));
setValue(r, c, this.getValue(r, c)+newWithCor.getValue(r, c));
}
}*/else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOROWS)
{
double n, n2, mu2;
for(int r=0; r<rlen-2; r++)
for(int c=0; c<clen; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=this.quickGetValue(r+1, c);
buffer._correction=this.quickGetValue(r+2, c);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r+1, c);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
quickSetValue(r+1, c, n);
quickSetValue(r+2, c, buffer._correction);
}
}else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS)
{
double n, n2, mu2;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen-2; c++)
{
buffer._sum=this.quickGetValue(r, c);
n=this.quickGetValue(r, c+1);
buffer._correction=this.quickGetValue(r, c+2);
mu2=newWithCor.quickGetValue(r, c);
n2=newWithCor.quickGetValue(r, c+1);
n=n+n2;
double toadd=(mu2-buffer._sum)*n2/n;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, toadd);
quickSetValue(r, c, buffer._sum);
quickSetValue(r, c+1, n);
quickSetValue(r, c+2, buffer._correction);
}
}
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
}
@Override
public MatrixValue reorgOperations(ReorgOperator op, MatrixValue ret, int startRow, int startColumn, int length)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
if (!(op.fn.equals(SwapIndex.getSwapIndexFnObject()) || op.fn.equals(MaxIndex.getMaxIndexFnObject())))
throw new DMLRuntimeException("the current reorgOperations cannot support: "+op.fn.getClass()+".");
MatrixBlockDSM result=checkType(ret);
CellIndex tempCellIndex = new CellIndex(-1,-1);
boolean reducedDim=op.fn.computeDimension(rlen, clen, tempCellIndex);
boolean sps;
if(reducedDim)
sps = false;
else if(op.fn.equals(MaxIndex.getMaxIndexFnObject()))
sps = true;
else
sps = checkRealSparsity(this, true);
if(result==null)
result=new MatrixBlockDSM(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
else
result.reset(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
if( MatrixReorgLib.isSupportedReorgOperator(op) )
{
//SPECIAL case (operators with special performance requirements,
//or size-dependent special behavior)
MatrixReorgLib.reorg(this, result, op);
}
else
{
//GENERIC case (any reorg operator)
CellIndex temp = new CellIndex(0, 0);
if(sparse)
{
if(sparseRows!=null)
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
tempCellIndex.set(r, cols[i]);
op.fn.execute(tempCellIndex, temp);
result.appendValue(temp.row, temp.column, values[i]);
}
}
}
}
else
{
if( denseBlock != null )
{
if( result.isInSparseFormat() ) //SPARSE<-DENSE
{
double[] a = denseBlock;
for( int i=0, aix=0; i<rlen; i++ )
for( int j=0; j<clen; j++, aix++ )
{
temp.set(i, j);
op.fn.execute(temp, temp);
result.appendValue(temp.row, temp.column, a[aix]);
}
}
else //DENSE<-DENSE
{
result.allocateDenseBlock();
Arrays.fill(result.denseBlock, 0);
double[] a = denseBlock;
double[] c = result.denseBlock;
int n = result.clen;
for( int i=0, aix=0; i<rlen; i++ )
for( int j=0; j<clen; j++, aix++ )
{
temp.set(i, j);
op.fn.execute(temp, temp);
c[temp.row*n+temp.column] = a[aix];
}
result.nonZeros = nonZeros;
}
}
}
}
return result;
}
/**
*
* @param that
* @param ret
* @return
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
public MatrixBlockDSM appendOperations( MatrixBlockDSM that, MatrixBlockDSM ret )
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM result = checkType( ret );
final int m = rlen;
final int n = clen+that.clen;
final int nnz = nonZeros+that.nonZeros;
boolean sp = checkRealSparsity(m, n, nnz);
//init result matrix
if( result == null )
result = new MatrixBlockDSM(m, n, sp, nnz);
else
result.reset(m, n, sp, nnz);
//core append operation
//copy left and right input into output
if( !result.sparse ) //DENSE
{
result.copy(0, m-1, 0, clen-1, this, false);
result.copy(0, m-1, clen, n-1, that, false);
}
else //SPARSE
{
result.adjustSparseRows(rlen-1);
result.appendToSparse(this, 0, 0);
result.appendToSparse(that, 0, clen);
}
result.nonZeros = nnz;
return result;
}
/**
*
* @param op
* @param ret
* @param startRow
* @param startColumn
* @param length
* @return
* @throws DMLUnsupportedOperationException
* @throws DMLRuntimeException
*/
@Deprecated
public MatrixValue appendOperations(ReorgOperator op, MatrixValue ret, int startRow, int startColumn, int length)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM result=checkType(ret);
CellIndex tempCellIndex = new CellIndex(-1,-1);
boolean reducedDim=op.fn.computeDimension(rlen, clen, tempCellIndex);
boolean sps;
if(reducedDim)
sps=false;
else
sps=checkRealSparsity(this);
if(result==null)
result=new MatrixBlockDSM(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
else if(result.getNumRows()==0 && result.getNumColumns()==0)
result.reset(tempCellIndex.row, tempCellIndex.column, sps, this.nonZeros);
CellIndex temp = new CellIndex(0, 0);
if(sparse)
{
if(sparseRows!=null)
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
tempCellIndex.set(r, cols[i]);
op.fn.execute(tempCellIndex, temp);
result.appendValue(temp.row, temp.column, values[i]);
}
}
}
}else
{
if(denseBlock!=null)
{
int limit=rlen*clen;
int r,c;
for(int i=0; i<limit; i++)
{
r=i/clen;
c=i%clen;
temp.set(r, c);
op.fn.execute(temp, temp);
result.appendValue(temp.row, temp.column, denseBlock[i]);
}
}
}
return result;
}
/**
*
* @param out
* @param tstype
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue transposeSelfMatrixMultOperations( MatrixBlockDSM out, MMTSJType tstype )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//check for transpose type
if( !(tstype == MMTSJType.LEFT || tstype == MMTSJType.RIGHT) )
throw new DMLRuntimeException("Invalid MMTSJ type '"+tstype+"'.");
//compute matrix mult
boolean leftTranspose = ( tstype == MMTSJType.LEFT );
MatrixMultLib.matrixMultTransposeSelf(this, out, leftTranspose);
return out;
}
/**
* Method to perform leftIndexing operation for a given lower and upper bounds in row and column dimensions.
* Updated matrix is returned as the output.
*
* Operations to be performed:
* 1) result=this;
* 2) result[rowLower:rowUpper, colLower:colUpper] = rhsMatrix;
*
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue leftIndexingOperations(MatrixValue rhsMatrix, long rowLower, long rowUpper,
long colLower, long colUpper, MatrixValue ret, boolean inplace)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
// Check the validity of bounds
if ( rowLower < 1 || rowLower > getNumRows() || rowUpper < rowLower || rowUpper > getNumRows()
|| colLower < 1 || colUpper > getNumColumns() || colUpper < colLower || colUpper > getNumColumns() ) {
throw new DMLRuntimeException("Invalid values for matrix indexing: " +
"["+rowLower+":"+rowUpper+"," + colLower+":"+colUpper+"] " +
"must be within matrix dimensions ["+getNumRows()+","+getNumColumns()+"].");
}
if ( (rowUpper-rowLower+1) < rhsMatrix.getNumRows() || (colUpper-colLower+1) < rhsMatrix.getNumColumns()) {
throw new DMLRuntimeException("Invalid values for matrix indexing: " +
"dimensions of the source matrix ["+rhsMatrix.getNumRows()+"x" + rhsMatrix.getNumColumns() + "] " +
"do not match the shape of the matrix specified by indices [" +
rowLower +":" + rowUpper + ", " + colLower + ":" + colUpper + "].");
}
MatrixBlockDSM result=checkType(ret);
boolean sp = estimateSparsityOnLeftIndexing(rlen, clen, nonZeros, rhsMatrix.getNonZeros());
if( !inplace ) //general case
{
if(result==null)
result=new MatrixBlockDSM(rlen, clen, sp);
else
result.reset(rlen, clen, sp);
result.copy(this, sp);
}
else //update in-place
result = this;
//NOTE conceptually we could directly use a zeroout and copy(..., false) but
// since this was factors slower, we still use a full copy and subsequently
// copy(..., true) - however, this can be changed in the future once we
// improved the performance of zeroout.
//result = (MatrixBlockDSM) zeroOutOperations(result, new IndexRange(rowLower,rowUpper, colLower, colUpper ), false);
int rl = (int)rowLower-1;
int ru = (int)rowUpper-1;
int cl = (int)colLower-1;
int cu = (int)colUpper-1;
MatrixBlockDSM src = (MatrixBlockDSM)rhsMatrix;
if(rl==ru && cl==cu) //specific case: cell update
{
//copy single value and update nnz
result.quickSetValue(rl, cl, src.quickGetValue(0, 0));
}
else //general case
{
//copy submatrix into result
result.copy(rl, ru, cl, cu, src, true);
}
return result;
}
/**
* Explicitly allow left indexing for scalars.
*
* * Operations to be performed:
* 1) result=this;
* 2) result[row,column] = scalar.getDoubleValue();
*
* @param scalar
* @param row
* @param col
* @param ret
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue leftIndexingOperations(ScalarObject scalar, long row, long col, MatrixValue ret, boolean inplace)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
MatrixBlockDSM result=checkType(ret);
if( !inplace ) //general case
{
if(result==null)
result=new MatrixBlockDSM(this);
else
result.copy(this);
}
else //update in-place
result = this;
int rl = (int)row-1;
int cl = (int)col-1;
result.quickSetValue(rl, cl, scalar.getDoubleValue());
return result;
}
/**
* Method to perform rangeReIndex operation for a given lower and upper bounds in row and column dimensions.
* Extracted submatrix is returned as "result".
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue sliceOperations(long rowLower, long rowUpper, long colLower, long colUpper, MatrixValue ret)
throws DMLRuntimeException, DMLUnsupportedOperationException {
// check the validity of bounds
if ( rowLower < 1 || rowLower > getNumRows() || rowUpper < rowLower || rowUpper > getNumRows()
|| colLower < 1 || colUpper > getNumColumns() || colUpper < colLower || colUpper > getNumColumns() ) {
throw new DMLRuntimeException("Invalid values for matrix indexing: " +
"["+rowLower+":"+rowUpper+"," + colLower+":"+colUpper+"] " +
"must be within matrix dimensions ["+getNumRows()+","+getNumColumns()+"]");
}
int rl = (int)rowLower-1;
int ru = (int)rowUpper-1;
int cl = (int)colLower-1;
int cu = (int)colUpper-1;
//System.out.println(" -- performing slide on [" + getNumRows() + "x" + getNumColumns() + "] with ["+rl+":"+ru+","+cl+":"+cu+"].");
// Output matrix will have the same sparsity as that of the input matrix.
// (assuming a uniform distribution of non-zeros in the input)
boolean result_sparsity = this.sparse && ((cu-cl+1)>SKINNY_MATRIX_TURN_POINT);
MatrixBlockDSM result=checkType(ret);
int estnnzs=(int) ((double)this.nonZeros/rlen/clen*(ru-rl+1)*(cu-cl+1));
if(result==null)
result=new MatrixBlockDSM(ru-rl+1, cu-cl+1, result_sparsity, estnnzs);
else
result.reset(ru-rl+1, cu-cl+1, result_sparsity, estnnzs);
// actual slice operation
if( rowLower==1 && rowUpper==rlen && colLower==1 && colUpper==clen ) {
// copy if entire matrix required
result.copy( this );
}
else //general case
{
//core slicing operation (nnz maintained internally)
if (sparse)
sliceSparse(rl, ru, cl, cu, result);
else
sliceDense(rl, ru, cl, cu, result);
}
return result;
}
/**
*
* @param rl
* @param ru
* @param cl
* @param cu
* @param dest
*/
private void sliceSparse(int rl, int ru, int cl, int cu, MatrixBlockDSM dest)
{
if ( sparseRows == null )
return;
if( cl==cu ) //specific case: column vector (always dense)
{
dest.allocateDenseBlock();
double val;
for( int i=rl, ix=0; i<=ru; i++, ix++ )
if( sparseRows[i] != null && sparseRows[i].size()>0 )
if( (val = sparseRows[i].get(cl)) != 0 )
{
dest.denseBlock[ix] = val;
dest.nonZeros++;
}
}
else //general case (sparse and dense)
{
for(int i=rl; i <= ru; i++)
if(sparseRows[i] != null && sparseRows[i].size()>0)
{
SparseRow arow = sparseRows[i];
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
int astart = (cl>0)?arow.searchIndexesFirstGTE(cl):0;
if( astart != -1 )
for( int j=astart; j<alen && aix[j] <= cu; j++ )
dest.appendValue(i-rl, aix[j]-cl, avals[j]);
}
}
}
/**
*
* @param rl
* @param ru
* @param cl
* @param cu
* @param dest
*/
private void sliceDense(int rl, int ru, int cl, int cu, MatrixBlockDSM dest)
{
if( denseBlock == null )
return;
dest.allocateDenseBlock();
if( cl==cu ) //specific case: column vector
{
if( clen==1 ) //vector -> vector
System.arraycopy(denseBlock, rl, dest.denseBlock, 0, ru-rl+1);
else //matrix -> vector
for( int i=rl*clen+cl, ix=0; i<=ru*clen+cu; i+=clen, ix++ )
dest.denseBlock[ix] = denseBlock[i];
}
else //general case (dense)
{
for(int i = rl, ix1 = rl*clen+cl, ix2=0; i <= ru; i++, ix1+=clen, ix2+=dest.clen)
System.arraycopy(denseBlock, ix1, dest.denseBlock, ix2, dest.clen);
}
dest.recomputeNonZeros();
}
public void sliceOperations(ArrayList<IndexedMatrixValue> outlist, IndexRange range, int rowCut, int colCut,
int normalBlockRowFactor, int normalBlockColFactor, int boundaryRlen, int boundaryClen)
{
MatrixBlockDSM topleft=null, topright=null, bottomleft=null, bottomright=null;
Iterator<IndexedMatrixValue> p=outlist.iterator();
int blockRowFactor=normalBlockRowFactor, blockColFactor=normalBlockColFactor;
if(rowCut>range.rowEnd)
blockRowFactor=boundaryRlen;
if(colCut>range.colEnd)
blockColFactor=boundaryClen;
int minrowcut=(int)Math.min(rowCut,range.rowEnd);
int mincolcut=(int)Math.min(colCut, range.colEnd);
int maxrowcut=(int)Math.max(rowCut, range.rowStart);
int maxcolcut=(int)Math.max(colCut, range.colStart);
if(range.rowStart<rowCut && range.colStart<colCut)
{
topleft=(MatrixBlockDSM) p.next().getValue();
//topleft.reset(blockRowFactor, blockColFactor,
// checkSparcityOnSlide(rowCut-(int)range.rowStart, colCut-(int)range.colStart, blockRowFactor, blockColFactor));
topleft.reset(blockRowFactor, blockColFactor,
estimateSparsityOnSlice(minrowcut-(int)range.rowStart, mincolcut-(int)range.colStart, blockRowFactor, blockColFactor));
}
if(range.rowStart<rowCut && range.colEnd>=colCut)
{
topright=(MatrixBlockDSM) p.next().getValue();
topright.reset(blockRowFactor, boundaryClen,
estimateSparsityOnSlice(minrowcut-(int)range.rowStart, (int)range.colEnd-maxcolcut+1, blockRowFactor, boundaryClen));
}
if(range.rowEnd>=rowCut && range.colStart<colCut)
{
bottomleft=(MatrixBlockDSM) p.next().getValue();
bottomleft.reset(boundaryRlen, blockColFactor,
estimateSparsityOnSlice((int)range.rowEnd-maxrowcut+1, mincolcut-(int)range.colStart, boundaryRlen, blockColFactor));
}
if(range.rowEnd>=rowCut && range.colEnd>=colCut)
{
bottomright=(MatrixBlockDSM) p.next().getValue();
bottomright.reset(boundaryRlen, boundaryClen,
estimateSparsityOnSlice((int)range.rowEnd-maxrowcut+1, (int)range.colEnd-maxcolcut+1, boundaryRlen, boundaryClen));
//System.out.println("bottomright size: "+bottomright.rlen+" X "+bottomright.clen);
}
if(sparse)
{
if(sparseRows!=null)
{
int r=(int)range.rowStart;
for(; r<Math.min(Math.min(rowCut, sparseRows.length), range.rowEnd+1); r++)
sliceHelp(r, range, colCut, topleft, topright, normalBlockRowFactor-rowCut, normalBlockRowFactor, normalBlockColFactor);
for(; r<=Math.min(range.rowEnd, sparseRows.length-1); r++)
sliceHelp(r, range, colCut, bottomleft, bottomright, -rowCut, normalBlockRowFactor, normalBlockColFactor);
//System.out.println("in: \n"+this);
//System.out.println("outlist: \n"+outlist);
}
}else
{
if(denseBlock!=null)
{
int i=((int)range.rowStart)*clen;
int r=(int) range.rowStart;
for(; r<Math.min(rowCut, range.rowEnd+1); r++)
{
int c=(int) range.colStart;
for(; c<Math.min(colCut, range.colEnd+1); c++)
topleft.appendValue(r+normalBlockRowFactor-rowCut, c+normalBlockColFactor-colCut, denseBlock[i+c]);
for(; c<=range.colEnd; c++)
topright.appendValue(r+normalBlockRowFactor-rowCut, c-colCut, denseBlock[i+c]);
i+=clen;
}
for(; r<=range.rowEnd; r++)
{
int c=(int) range.colStart;
for(; c<Math.min(colCut, range.colEnd+1); c++)
bottomleft.appendValue(r-rowCut, c+normalBlockColFactor-colCut, denseBlock[i+c]);
for(; c<=range.colEnd; c++)
bottomright.appendValue(r-rowCut, c-colCut, denseBlock[i+c]);
i+=clen;
}
}
}
}
private void sliceHelp(int r, IndexRange range, int colCut, MatrixBlockDSM left, MatrixBlockDSM right, int rowOffset, int normalBlockRowFactor, int normalBlockColFactor)
{
// if(left==null || right==null)
// throw new RuntimeException("left = "+left+", and right = "+right);
if(sparseRows[r]==null) return;
//System.out.println("row "+r+"\t"+sparseRows[r]);
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
int start=sparseRows[r].searchIndexesFirstGTE((int)range.colStart);
//System.out.println("start: "+start);
if(start<0) return;
int end=sparseRows[r].searchIndexesFirstLTE((int)range.colEnd);
//System.out.println("end: "+end);
if(end<0 || start>end) return;
for(int i=start; i<=end; i++)
{
if(cols[i]<colCut)
left.appendValue(r+rowOffset, cols[i]+normalBlockColFactor-colCut, values[i]);
else
right.appendValue(r+rowOffset, cols[i]-colCut, values[i]);
// System.out.println("set "+r+", "+cols[i]+": "+values[i]);
}
}
@Override
//This the append operations for MR side
//nextNCol is the number columns for the block right of block v2
public void appendOperations(MatrixValue v2,
ArrayList<IndexedMatrixValue> outlist, int blockRowFactor,
int blockColFactor, boolean m2IsLast, int nextNCol)
throws DMLUnsupportedOperationException, DMLRuntimeException {
MatrixBlockDSM m2=(MatrixBlockDSM)v2;
//System.out.println("second matrix: \n"+m2);
Iterator<IndexedMatrixValue> p=outlist.iterator();
if(this.clen==blockColFactor)
{
MatrixBlockDSM first=(MatrixBlockDSM) p.next().getValue();
first.copy(this);
MatrixBlockDSM second=(MatrixBlockDSM) p.next().getValue();
second.copy(m2);
}else
{
int ncol=Math.min(clen+m2.getNumColumns(), blockColFactor);
int part=ncol-clen;
MatrixBlockDSM first=(MatrixBlockDSM) p.next().getValue();
first.reset(rlen, ncol, this.nonZeros+m2.getNonZeros()*part/m2.getNumColumns());
//copy the first matrix
if(this.sparse)
{
if(this.sparseRows!=null)
{
for(int i=0; i<Math.min(rlen, this.sparseRows.length); i++)
{
if(this.sparseRows[i]!=null)
first.appendRow(i, this.sparseRows[i]);
}
}
}else if(this.denseBlock!=null)
{
int sindx=0;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
first.appendValue(r, c, this.denseBlock[sindx]);
sindx++;
}
}
MatrixBlockDSM second=null;
if(part<m2.clen)
{
second=(MatrixBlockDSM) p.next().getValue();
if(m2IsLast)
second.reset(m2.rlen, m2.clen-part, m2.sparse);
else
second.reset(m2.rlen, Math.min(m2.clen-part+nextNCol, blockColFactor), m2.sparse);
}
//copy the second
if(m2.sparse)
{
if(m2.sparseRows!=null)
{
for(int i=0; i<Math.min(m2.rlen, m2.sparseRows.length); i++)
{
if(m2.sparseRows[i]!=null)
{
int[] indexContainer=m2.sparseRows[i].getIndexContainer();
double[] valueContainer=m2.sparseRows[i].getValueContainer();
for(int j=0; j<m2.sparseRows[i].size(); j++)
{
if(indexContainer[j]<part)
first.appendValue(i, clen+indexContainer[j], valueContainer[j]);
else
second.appendValue(i, indexContainer[j]-part, valueContainer[j]);
}
}
}
}
}else if(m2.denseBlock!=null)
{
int sindx=0;
for(int r=0; r<m2.rlen; r++)
{
int c=0;
for(; c<part; c++)
{
first.appendValue(r, clen+c, m2.denseBlock[sindx+c]);
// System.out.println("access "+(sindx+c));
// System.out.println("add first ("+r+", "+(clen+c)+"), "+m2.denseBlock[sindx+c]);
}
for(; c<m2.clen; c++)
{
second.appendValue(r, c-part, m2.denseBlock[sindx+c]);
// System.out.println("access "+(sindx+c));
// System.out.println("add second ("+r+", "+(c-part)+"), "+m2.denseBlock[sindx+c]);
}
sindx+=m2.clen;
}
}
}
}
public MatrixValue zeroOutOperations(MatrixValue result, IndexRange range, boolean complementary)
throws DMLUnsupportedOperationException, DMLRuntimeException {
checkType(result);
boolean sps;
double currentSparsity=(double)nonZeros/(double)rlen/(double)clen;
double estimatedSps=currentSparsity*(double)(range.rowEnd-range.rowStart+1)
*(double)(range.colEnd-range.colStart+1)/(double)rlen/(double)clen;
if(!complementary)
estimatedSps=currentSparsity-estimatedSps;
if(estimatedSps< SPARCITY_TURN_POINT)
sps=true;
else sps=false;
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(clen<=SKINNY_MATRIX_TURN_POINT)
sps=false;
if(result==null)
result=new MatrixBlockDSM(rlen, clen, sps, (int)(estimatedSps*rlen*clen));
else
result.reset(rlen, clen, sps, (int)(estimatedSps*rlen*clen));
if(sparse)
{
if(sparseRows!=null)
{
if(!complementary)//if zero out
{
for(int r=0; r<Math.min((int)range.rowStart, sparseRows.length); r++)
((MatrixBlockDSM) result).appendRow(r, sparseRows[r]);
for(int r=Math.min((int)range.rowEnd+1, sparseRows.length); r<Math.min(rlen, sparseRows.length); r++)
((MatrixBlockDSM) result).appendRow(r, sparseRows[r]);
}
for(int r=(int)range.rowStart; r<=Math.min(range.rowEnd, sparseRows.length-1); r++)
{
if(sparseRows[r]==null) continue;
//System.out.println("row "+r+"\t"+sparseRows[r]);
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
if(complementary)//if selection
{
int start=sparseRows[r].searchIndexesFirstGTE((int)range.colStart);
//System.out.println("start: "+start);
if(start<0) continue;
int end=sparseRows[r].searchIndexesFirstGT((int)range.colEnd);
//System.out.println("end: "+end);
if(end<0 || start>end) continue;
for(int i=start; i<end; i++)
{
((MatrixBlockDSM) result).appendValue(r, cols[i], values[i]);
// System.out.println("set "+r+", "+cols[i]+": "+values[i]);
}
}else
{
int start=sparseRows[r].searchIndexesFirstGTE((int)range.colStart);
//System.out.println("start: "+start);
if(start<0) start=sparseRows[r].size();
int end=sparseRows[r].searchIndexesFirstGT((int)range.colEnd);
//System.out.println("end: "+end);
if(end<0) end=sparseRows[r].size();
/* if(r==999)
{
System.out.println("----------------------");
System.out.println("range: "+range);
System.out.println("row: "+sparseRows[r]);
System.out.println("start: "+start);
System.out.println("end: "+end);
}
*/
for(int i=0; i<start; i++)
{
((MatrixBlockDSM) result).appendValue(r, cols[i], values[i]);
// if(r==999) System.out.println("append ("+r+", "+cols[i]+"): "+values[i]);
}
for(int i=end; i<sparseRows[r].size(); i++)
{
((MatrixBlockDSM) result).appendValue(r, cols[i], values[i]);
// if(r==999) System.out.println("append ("+r+", "+cols[i]+"): "+values[i]);
}
}
}
}
}else
{
if(denseBlock!=null)
{
if(complementary)//if selection
{
int offset=((int)range.rowStart)*clen;
for(int r=(int) range.rowStart; r<=range.rowEnd; r++)
{
for(int c=(int) range.colStart; c<=range.colEnd; c++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset+c]);
offset+=clen;
}
}else
{
int offset=0;
int r=0;
for(; r<(int)range.rowStart; r++)
for(int c=0; c<clen; c++, offset++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset]);
for(; r<=(int)range.rowEnd; r++)
{
for(int c=0; c<(int)range.colStart; c++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset+c]);
for(int c=(int)range.colEnd+1; c<clen; c++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset+c]);
offset+=clen;
}
for(; r<rlen; r++)
for(int c=0; c<clen; c++, offset++)
((MatrixBlockDSM) result).appendValue(r, c, denseBlock[offset]);
}
}
}
//System.out.println("zeroout in:\n"+this);
//System.out.println("zeroout result:\n"+result);
return result;
}
//This function is not really used
/* public void zeroOutOperationsInPlace(IndexRange range, boolean complementary)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
//do not change the format of the block
if(sparse)
{
if(sparseRows==null) return;
if(complementary)//if selection, need to remove unwanted rows
{
for(int r=0; r<Math.min((int)range.rowStart, sparseRows.length); r++)
if(sparseRows[r]!=null)
{
nonZeros-=sparseRows[r].size();
sparseRows[r].reset();
}
for(int r=Math.min((int)range.rowEnd+1, sparseRows.length-1); r<Math.min(rlen, sparseRows.length); r++)
if(sparseRows[r]!=null)
{
nonZeros-=sparseRows[r].size();
sparseRows[r].reset();
}
}
for(int r=(int)range.rowStart; r<=Math.min(range.rowEnd, sparseRows.length-1); r++)
{
if(sparseRows[r]==null) continue;
int oldsize=sparseRows[r].size();
if(complementary)//if selection
sparseRows[r].deleteIndexComplementaryRange((int)range.colStart, (int)range.rowEnd);
else //if zeroout
sparseRows[r].deleteIndexRange((int)range.colStart, (int)range.rowEnd);
nonZeros-=(oldsize-sparseRows[r].size());
}
}else
{
if(denseBlock==null) return;
int start=(int)range.rowStart*clen;
if(complementary)//if selection, need to remove unwanted rows
{
nonZeros=0;
Arrays.fill(denseBlock, 0, start, 0);
Arrays.fill(denseBlock, ((int)range.rowEnd+1)*clen, rlen*clen, 0);
for(int r=(int) range.rowStart; r<=range.rowEnd; r++)
{
Arrays.fill(denseBlock, start, start+(int) range.colStart, 0);
Arrays.fill(denseBlock, start+(int)range.colEnd+1, start+clen, 0);
for(int c=(int) range.colStart; c<=range.colEnd; c++)
if(denseBlock[start+c]!=0)
nonZeros++;
start+=clen;
}
}else
{
for(int r=(int) range.rowStart; r<=range.rowEnd; r++)
{
for(int c=(int) range.colStart; c<=range.colEnd; c++)
if(denseBlock[start+c]!=0)
nonZeros--;
Arrays.fill(denseBlock, start+(int) range.colStart, start+(int)range.colEnd+1, 0);
start+=clen;
}
}
}
}*/
public MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
return aggregateUnaryOperations(op, result,
blockingFactorRow, blockingFactorCol, indexesIn, false);
}
public MatrixValue aggregateUnaryOperations(AggregateUnaryOperator op, MatrixValue result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn, boolean inCP)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
CellIndex tempCellIndex = new CellIndex(-1,-1);
op.indexFn.computeDimension(rlen, clen, tempCellIndex);
if(op.aggOp.correctionExists)
{
switch(op.aggOp.correctionLocation)
{
case LASTROW: tempCellIndex.row++; break;
case LASTCOLUMN: tempCellIndex.column++; break;
case LASTTWOROWS: tempCellIndex.row+=2; break;
case LASTTWOCOLUMNS: tempCellIndex.column+=2; break;
default:
throw new DMLRuntimeException("unrecognized correctionLocation: "+op.aggOp.correctionLocation);
}
}
if(result==null)
result=new MatrixBlockDSM(tempCellIndex.row, tempCellIndex.column, false);
else
result.reset(tempCellIndex.row, tempCellIndex.column, false);
MatrixBlockDSM ret = (MatrixBlockDSM) result;
if( MatrixAggLib.isSupportedUnaryAggregateOperator(op) ) {
MatrixAggLib.aggregateUnaryMatrix(this, ret, op);
MatrixAggLib.recomputeIndexes(ret, op, blockingFactorRow, blockingFactorCol, indexesIn);
}
else if(op.sparseSafe)
sparseAggregateUnaryHelp(op, ret, blockingFactorRow, blockingFactorCol, indexesIn);
else
denseAggregateUnaryHelp(op, ret, blockingFactorRow, blockingFactorCol, indexesIn);
if(op.aggOp.correctionExists && inCP)
((MatrixBlockDSM)result).dropLastRowsOrColums(op.aggOp.correctionLocation);
return ret;
}
private void sparseAggregateUnaryHelp(AggregateUnaryOperator op, MatrixBlockDSM result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn) throws DMLRuntimeException
{
//initialize result
if(op.aggOp.initialValue!=0)
result.resetDenseWithValue(result.rlen, result.clen, op.aggOp.initialValue);
CellIndex tempCellIndex = new CellIndex(-1,-1);
KahanObject buffer=new KahanObject(0,0);
int r = 0, c = 0;
if(sparse)
{
if(sparseRows!=null)
{
for(r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
tempCellIndex.set(r, cols[i]);
op.indexFn.execute(tempCellIndex, tempCellIndex);
incrementalAggregateUnaryHelp(op.aggOp, result, tempCellIndex.row, tempCellIndex.column, values[i], buffer);
}
}
}
}
else
{
if(denseBlock!=null)
{
int limit=rlen*clen;
for(int i=0; i<limit; i++)
{
r=i/clen;
c=i%clen;
tempCellIndex.set(r, c);
op.indexFn.execute(tempCellIndex, tempCellIndex);
incrementalAggregateUnaryHelp(op.aggOp, result, tempCellIndex.row, tempCellIndex.column, denseBlock[i], buffer);
}
}
}
}
private void denseAggregateUnaryHelp(AggregateUnaryOperator op, MatrixBlockDSM result,
int blockingFactorRow, int blockingFactorCol, MatrixIndexes indexesIn) throws DMLRuntimeException
{
//initialize
if(op.aggOp.initialValue!=0)
result.resetDenseWithValue(result.rlen, result.clen, op.aggOp.initialValue);
CellIndex tempCellIndex = new CellIndex(-1,-1);
KahanObject buffer=new KahanObject(0,0);
for(int i=0; i<rlen; i++)
for(int j=0; j<clen; j++)
{
tempCellIndex.set(i, j);
op.indexFn.execute(tempCellIndex, tempCellIndex);
if(op.aggOp.correctionExists
&& op.aggOp.correctionLocation == CorrectionLocationType.LASTCOLUMN
&& op.aggOp.increOp.fn instanceof Builtin
&& ((Builtin)(op.aggOp.increOp.fn)).bFunc == Builtin.BuiltinFunctionCode.MAXINDEX ){
double currMaxValue = result.quickGetValue(i, 1);
long newMaxIndex = UtilFunctions.cellIndexCalculation(indexesIn.getColumnIndex(), blockingFactorCol, j);
double newMaxValue = quickGetValue(i, j);
double update = op.aggOp.increOp.fn.execute(newMaxValue, currMaxValue);
//System.out.println("currV="+currMaxValue+",newV="+newMaxValue+",newIX="+newMaxIndex+",update="+update);
if(update == 1){
result.quickSetValue(i, 0, newMaxIndex);
result.quickSetValue(i, 1, newMaxValue);
}
}else
incrementalAggregateUnaryHelp(op.aggOp, result, tempCellIndex.row, tempCellIndex.column, quickGetValue(i,j), buffer);
}
}
private void incrementalAggregateUnaryHelp(AggregateOperator aggOp, MatrixBlockDSM result, int row, int column,
double newvalue, KahanObject buffer) throws DMLRuntimeException
{
if(aggOp.correctionExists)
{
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW || aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
{
int corRow=row, corCol=column;
if(aggOp.correctionLocation==CorrectionLocationType.LASTROW)//extra row
corRow++;
else if(aggOp.correctionLocation==CorrectionLocationType.LASTCOLUMN)
corCol++;
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
buffer._sum=result.quickGetValue(row, column);
buffer._correction=result.quickGetValue(corRow, corCol);
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newvalue);
result.quickSetValue(row, column, buffer._sum);
result.quickSetValue(corRow, corCol, buffer._correction);
}else if(aggOp.correctionLocation==CorrectionLocationType.NONE)
{
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
}else// for mean
{
int corRow=row, corCol=column;
int countRow=row, countCol=column;
if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOROWS)
{
countRow++;
corRow+=2;
}
else if(aggOp.correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS)
{
countCol++;
corCol+=2;
}
else
throw new DMLRuntimeException("unrecognized correctionLocation: "+aggOp.correctionLocation);
buffer._sum=result.quickGetValue(row, column);
buffer._correction=result.quickGetValue(corRow, corCol);
double count=result.quickGetValue(countRow, countCol)+1.0;
buffer=(KahanObject) aggOp.increOp.fn.execute(buffer, newvalue, count);
result.quickSetValue(row, column, buffer._sum);
result.quickSetValue(corRow, corCol, buffer._correction);
result.quickSetValue(countRow, countCol, count);
}
}else
{
newvalue=aggOp.increOp.fn.execute(result.quickGetValue(row, column), newvalue);
result.quickSetValue(row, column, newvalue);
}
}
/**
*
* @param correctionLocation
*/
private void dropLastRowsOrColums(CorrectionLocationType correctionLocation)
{
//do nothing
if( correctionLocation==CorrectionLocationType.NONE
|| correctionLocation==CorrectionLocationType.INVALID )
{
return;
}
//determine number of rows/cols to be removed
int step = ( correctionLocation==CorrectionLocationType.LASTTWOROWS
|| correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS) ? 2 : 1;
//e.g., colSums, colMeans, colMaxs, colMeans
if( correctionLocation==CorrectionLocationType.LASTROW
|| correctionLocation==CorrectionLocationType.LASTTWOROWS )
{
if( sparse ) //SPARSE
{
if(sparseRows!=null)
for(int i=1; i<=step; i++)
if(sparseRows[rlen-i]!=null)
this.nonZeros-=sparseRows[rlen-i].size();
}
else //DENSE
{
if(denseBlock!=null)
for(int i=(rlen-step)*clen; i<rlen*clen; i++)
if(denseBlock[i]!=0)
this.nonZeros--;
}
//just need to shrink the dimension, the deleted rows won't be accessed
rlen -= step;
}
//e.g., rowSums, rowsMeans, rowsMaxs, rowsMeans
if( correctionLocation==CorrectionLocationType.LASTCOLUMN
|| correctionLocation==CorrectionLocationType.LASTTWOCOLUMNS )
{
if(sparse) //SPARSE
{
if(sparseRows!=null)
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
if(sparseRows[r]!=null)
{
int newSize=sparseRows[r].searchIndexesFirstGTE(clen-step);
if(newSize>=0)
{
this.nonZeros-=sparseRows[r].size()-newSize;
sparseRows[r].truncate(newSize);
}
}
}
}
else //DENSE
{
if(this.denseBlock!=null)
{
//the first row doesn't need to be copied
int targetIndex=clen-step;
int sourceOffset=clen;
this.nonZeros=0;
for(int i=0; i<targetIndex; i++)
if(denseBlock[i]!=0)
this.nonZeros++;
//start from the 2nd row
for(int r=1; r<rlen; r++)
{
for(int c=0; c<clen-step; c++)
{
if((denseBlock[targetIndex]=denseBlock[sourceOffset+c])!=0)
this.nonZeros++;
targetIndex++;
}
sourceOffset+=clen;
}
}
}
clen -= step;
}
}
public CM_COV_Object cmOperations(CMOperator op)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1) {
throw new DMLRuntimeException("Central Moment can not be computed on ["
+ this.getNumRows() + "," + this.getNumColumns() + "] matrix.");
}
CM_COV_Object cmobj = new CM_COV_Object();
int nzcount = 0;
if(sparse && sparseRows!=null) //SPARSE
{
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
if(sparseRows[r]==null) continue;
//int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++)
{
op.fn.execute(cmobj, values[i]);
nzcount++;
}
}
// account for zeros in the vector
op.fn.execute(cmobj, 0.0, this.getNumRows()-nzcount);
}
else if(denseBlock!=null) //DENSE
{
//always vector (see check above)
for(int i=0; i<rlen; i++)
op.fn.execute(cmobj, denseBlock[i]);
}
return cmobj;
}
public CM_COV_Object cmOperations(CMOperator op, MatrixBlockDSM weights)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1 || weights.getNumColumns() != 1) {
throw new DMLRuntimeException("Central Moment can be computed only on 1-dimensional column matrices.");
}
if ( this.getNumRows() != weights.getNumRows() || this.getNumColumns() != weights.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching dimensions between input and weight matrices - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ weights.getNumRows() + "," + weights.getNumColumns() +"]");
}
CM_COV_Object cmobj = new CM_COV_Object();
if (sparse && sparseRows!=null) //SPARSE
{
for(int i=0; i < rlen; i++)
op.fn.execute(cmobj, this.quickGetValue(i,0), weights.quickGetValue(i,0));
/*
int zerocount = 0, zerorows=0, nzrows=0;
for(int r=0; r<Math.min(rlen, sparseRows.length); r++)
{
// This matrix has only a single column
if(sparseRows[r]==null) {
zerocount += weights.getValue(r,0);
zerorows++;
}
//int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
//x = sparseRows[r].size();
if ( sparseRows[r].size() == 0 )
zerorows++;
for(int i=0; i<sparseRows[r].size(); i++) {
//op.fn.execute(cmobj, values[i], weights.getValue(r,0));
nzrows++;
}
}
System.out.println("--> total="+this.getNumRows() + ", nzrows=" + nzrows + ", zerorows="+zerorows+"... zerocount="+zerocount);
// account for zeros in the vector
//op.fn.execute(cmobj, 0.0, zerocount);
*/ }
else if(denseBlock!=null) //DENSE
{
//always vectors (see check above)
if( !weights.sparse )
{
//both dense vectors (default case)
if(weights.denseBlock!=null)
for( int i=0; i<rlen; i++ )
op.fn.execute(cmobj, denseBlock[i], weights.denseBlock[i]);
}
else
{
for(int i=0; i<rlen; i++)
op.fn.execute(cmobj, denseBlock[i], weights.quickGetValue(i,0) );
}
}
return cmobj;
}
public CM_COV_Object covOperations(COVOperator op, MatrixBlockDSM that)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1 || that.getNumColumns() != 1 ) {
throw new DMLRuntimeException("Covariance can be computed only on 1-dimensional column matrices.");
}
if ( this.getNumRows() != that.getNumRows() || this.getNumColumns() != that.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching input matrix dimensions - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ that.getNumRows() + "," + that.getNumColumns() +"]");
}
CM_COV_Object covobj = new CM_COV_Object();
if(sparse && sparseRows!=null) //SPARSE
{
for(int i=0; i < rlen; i++ )
op.fn.execute(covobj, this.quickGetValue(i,0), that.quickGetValue(i,0));
}
else if(denseBlock!=null) //DENSE
{
//always vectors (see check above)
if( !that.sparse )
{
//both dense vectors (default case)
if(that.denseBlock!=null)
for( int i=0; i<rlen; i++ )
op.fn.execute(covobj, denseBlock[i], that.denseBlock[i]);
}
else
{
for(int i=0; i<rlen; i++)
op.fn.execute(covobj, denseBlock[i], that.quickGetValue(i,0));
}
}
return covobj;
}
public CM_COV_Object covOperations(COVOperator op, MatrixBlockDSM that, MatrixBlockDSM weights)
throws DMLRuntimeException
{
/* this._data must be a 1 dimensional vector */
if ( this.getNumColumns() != 1 || that.getNumColumns() != 1 || weights.getNumColumns() != 1) {
throw new DMLRuntimeException("Covariance can be computed only on 1-dimensional column matrices.");
}
if ( this.getNumRows() != that.getNumRows() || this.getNumColumns() != that.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching input matrix dimensions - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ that.getNumRows() + "," + that.getNumColumns() +"]");
}
if ( this.getNumRows() != weights.getNumRows() || this.getNumColumns() != weights.getNumColumns()) {
throw new DMLRuntimeException("Covariance: Mismatching dimensions between input and weight matrices - " +
"["+this.getNumRows()+","+this.getNumColumns() +"] != ["
+ weights.getNumRows() + "," + weights.getNumColumns() +"]");
}
CM_COV_Object covobj = new CM_COV_Object();
if(sparse && sparseRows!=null) //SPARSE
{
for(int i=0; i < rlen; i++ )
op.fn.execute(covobj, this.quickGetValue(i,0), that.quickGetValue(i,0), weights.quickGetValue(i,0));
}
else if(denseBlock!=null) //DENSE
{
//always vectors (see check above)
if( !that.sparse && !weights.sparse )
{
//all dense vectors (default case)
if(that.denseBlock!=null)
for( int i=0; i<rlen; i++ )
op.fn.execute(covobj, denseBlock[i], that.denseBlock[i], weights.denseBlock[i]);
}
else
{
for(int i=0; i<rlen; i++)
op.fn.execute(covobj, denseBlock[i], that.quickGetValue(i,0), weights.quickGetValue(i,0));
}
}
return covobj;
}
public MatrixValue sortOperations(MatrixValue weights, MatrixValue result) throws DMLRuntimeException, DMLUnsupportedOperationException {
boolean wtflag = (weights!=null);
MatrixBlockDSM wts= (weights == null ? null : checkType(weights));
checkType(result);
if ( getNumColumns() != 1 ) {
throw new DMLRuntimeException("Invalid input dimensions (" + getNumRows() + "x" + getNumColumns() + ") to sort operation.");
}
if ( wts != null && wts.getNumColumns() != 1 ) {
throw new DMLRuntimeException("Invalid weight dimensions (" + wts.getNumRows() + "x" + wts.getNumColumns() + ") to sort operation.");
}
// Copy the input elements into a temporary array for sorting
// #rows in temp matrix = 1 + #nnz in the input ( 1 is for the "zero" value)
int dim1 = 1+this.getNonZeros();
// First column is data and second column is weights
double[][] tdw = new double[dim1][2];
double d, w, zero_wt=0;
if ( wtflag ) {
for ( int r=0, ind=1; r < getNumRows(); r++ ) {
d = quickGetValue(r,0);
w = wts.quickGetValue(r,0);
if ( d != 0 ) {
tdw[ind][0] = d;
tdw[ind][1] = w;
ind++;
}
else
zero_wt += w;
}
tdw[0][0] = 0.0;
tdw[0][1] = zero_wt;
}
else {
tdw[0][0] = 0.0;
tdw[0][1] = getNumRows() - getNonZeros(); // number of zeros in the input data
int ind = 1;
if(sparse) {
if(sparseRows!=null) {
for(int r=0; r<Math.min(rlen, sparseRows.length); r++) {
if(sparseRows[r]==null) continue;
//int[] cols=sparseRows[r].getIndexContainer();
double[] values=sparseRows[r].getValueContainer();
for(int i=0; i<sparseRows[r].size(); i++) {
tdw[ind][0] = values[i];
tdw[ind][1] = 1;
ind++;
}
}
}
}
else {
if(denseBlock!=null) {
int limit=rlen*clen;
for(int i=0; i<limit; i++) {
// copy only non-zero values
if ( denseBlock[i] != 0.0 ) {
tdw[ind][0] = denseBlock[i];
tdw[ind][1] = 1;
ind++;
}
}
}
}
}
// Sort td and tw based on values inside td (ascending sort)
Arrays.sort(tdw, new Comparator<double[]>(){
@Override
public int compare(double[] arg0, double[] arg1) {
return (arg0[0] < arg1[0] ? -1 : (arg0[0] == arg1[0] ? 0 : 1));
}}
);
// Copy the output from sort into "result"
// result is always dense (currently)
if(result==null)
result=new MatrixBlockDSM(dim1, 2, false);
else
result.reset(dim1, 2, false);
((MatrixBlockDSM) result).init(tdw, dim1, 2);
return result;
}
/**
* Computes the weighted interQuartileMean.
* The matrix block ("this" pointer) has two columns, in which the first column
* refers to the data and second column denotes corresponding weights.
*
* @return InterQuartileMean
* @throws DMLRuntimeException
*/
public double interQuartileMean() throws DMLRuntimeException {
double sum_wt = sumWeightForQuantile();
int fromPos = (int) Math.ceil(0.25*sum_wt);
int toPos = (int) Math.ceil(0.75*sum_wt);
int selectRange = toPos-fromPos; // range: (fromPos,toPos]
if ( selectRange == 0 )
return 0.0;
int index, count=0;
// The first row (0^th row) has value 0.
// If it has a non-zero weight i.e., input data has zero values
// then "index" must start from 0, otherwise we skip the first row
// and start with the next value in the data, which is in the 1st row.
if ( quickGetValue(0,1) > 0 )
index = 0;
else
index = 1;
// keep scanning the weights, until we hit the required position <code>fromPos</code>
while ( count < fromPos ) {
count += quickGetValue(index,1);
++index;
}
double runningSum;
double val;
int wt, selectedCount;
runningSum = (count-fromPos) * quickGetValue(index-1, 0);
selectedCount = (count-fromPos);
while(count <= toPos ) {
val = quickGetValue(index,0);
wt = (int) quickGetValue(index,1);
runningSum += (val * Math.min(wt, selectRange-selectedCount));
selectedCount += Math.min(wt, selectRange-selectedCount);
count += wt;
++index;
}
//System.out.println(fromPos + ", " + toPos + ": " + count + ", "+ runningSum + ", " + selectedCount);
return runningSum/selectedCount;
}
public MatrixValue pickValues(MatrixValue quantiles, MatrixValue ret)
throws DMLUnsupportedOperationException, DMLRuntimeException {
MatrixBlockDSM qs=checkType(quantiles);
if ( qs.clen != 1 ) {
throw new DMLRuntimeException("Multiple quantiles can only be computed on a 1D matrix");
}
MatrixBlockDSM output = checkType(ret);
if(output==null)
output=new MatrixBlockDSM(qs.rlen, qs.clen, false); // resulting matrix is mostly likely be dense
else
output.reset(qs.rlen, qs.clen, false);
for ( int i=0; i < qs.rlen; i++ ) {
output.quickSetValue(i, 0, this.pickValue(qs.quickGetValue(i,0)) );
}
return output;
}
public double pickValue(double quantile)
throws DMLRuntimeException
{
double sum_wt = sumWeightForQuantile();
int pos = (int) Math.ceil(quantile*sum_wt);
int t = 0, i=-1;
do {
i++;
t += quickGetValue(i,1);
} while(t<pos && i < getNumRows());
return quickGetValue(i,0);
}
/**
* In a given two column matrix, the second column denotes weights.
* This function computes the total weight
*
* @return
* @throws DMLRuntimeException
*/
private double sumWeightForQuantile()
throws DMLRuntimeException
{
double sum_wt = 0;
for (int i=0; i < getNumRows(); i++ )
sum_wt += quickGetValue(i, 1);
if ( (int)sum_wt != sum_wt ) {
throw new DMLRuntimeException("Unexpected error while computing quantile -- weights must be integers.");
}
return sum_wt;
}
public MatrixValue aggregateBinaryOperations(MatrixValue m1Value, MatrixValue m2Value,
MatrixValue result, AggregateBinaryOperator op)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM m1=checkType(m1Value);
MatrixBlockDSM m2=checkType(m2Value);
checkType(result);
if(m1.clen!=m2.rlen)
throw new RuntimeException("dimensions do not match for matrix multiplication ("+m1.clen+"!="+m2.rlen+")");
int rl=m1.rlen;
int cl=m2.clen;
SparsityEstimate sp=estimateSparsityOnAggBinary(m1, m2, op);
if(result==null)
result=new MatrixBlockDSM(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
else
result.reset(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
if(op.sparseSafe)
sparseAggregateBinaryHelp(m1, m2, (MatrixBlockDSM)result, op);
else
aggBinSparseUnsafe(m1, m2, (MatrixBlockDSM)result, op);
return result;
}
public MatrixValue aggregateBinaryOperations(MatrixIndexes m1Index, MatrixValue m1Value, MatrixIndexes m2Index, MatrixValue m2Value,
MatrixValue result, AggregateBinaryOperator op, boolean partialMult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM m1=checkType(m1Value);
MatrixBlockDSM m2=checkType(m2Value);
checkType(result);
if ( partialMult ) {
// check if matrix block's row-column range falls within the whole vector's row-column range
}
else if(m1.clen!=m2.rlen)
throw new RuntimeException("dimensions do not match for matrix multiplication ("+m1.clen+"!="+m2.rlen+")");
int rl, cl;
SparsityEstimate sp;
if ( partialMult ) {
// TODO: avoid this code!!
rl = m1.rlen;
cl = 1;
sp = new SparsityEstimate(false,m1.rlen);
}
else {
rl=m1.rlen;
cl=m2.clen;
sp = estimateSparsityOnAggBinary(m1, m2, op);
}
if(result==null)
result=new MatrixBlockDSM(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
else
result.reset(rl, cl, sp.sparse, sp.estimatedNonZeros);//m1.sparse&&m2.sparse);
if(op.sparseSafe)
sparseAggregateBinaryHelp(m1Index, m1, m2Index, m2, (MatrixBlockDSM)result, op, partialMult);
else
aggBinSparseUnsafe(m1, m2, (MatrixBlockDSM)result, op);
return result;
}
private static void sparseAggregateBinaryHelp(MatrixIndexes m1Index, MatrixBlockDSM m1, MatrixIndexes m2Index, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op, boolean partialMult) throws DMLRuntimeException
{
//matrix multiplication
if(op.binaryFn instanceof Multiply && op.aggOp.increOp.fn instanceof Plus && !partialMult)
{
MatrixMultLib.matrixMult(m1, m2, result);
}
else
{
if(!m1.sparse && m2 != null && !m2.sparse )
aggBinDenseDense(m1, m2, result, op);
else if(m1.sparse && m2 != null && m2.sparse)
aggBinSparseSparse(m1, m2, result, op);
else if(m1.sparse)
aggBinSparseDense(m1Index, m1, m2Index, m2, result, op, partialMult);
else
aggBinDenseSparse(m1, m2, result, op);
}
}
private static void sparseAggregateBinaryHelp(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op) throws DMLRuntimeException
{
if(op.binaryFn instanceof Multiply && op.aggOp.increOp.fn instanceof Plus )
{
MatrixMultLib.matrixMult(m1, m2, result);
}
else
{
if(!m1.sparse && !m2.sparse)
aggBinDenseDense(m1, m2, result, op);
else if(m1.sparse && m2.sparse)
aggBinSparseSparse(m1, m2, result, op);
else if(m1.sparse)
aggBinSparseDense(m1, m2, result, op);
else
aggBinDenseSparse(m1, m2, result, op);
}
}
/**
* to perform aggregateBinary when both matrices are dense
*/
private static void aggBinDenseDense(MatrixBlockDSM m1, MatrixBlockDSM m2, MatrixBlockDSM result, AggregateBinaryOperator op) throws DMLRuntimeException
{
int j, l, i, aIndex, bIndex;
double temp;
double v;
double[] a = m1.getDenseArray();
double[] b = m2.getDenseArray();
if(a==null || b==null)
return;
for(l = 0; l < m1.clen; l++)
{
aIndex = l;
//cIndex = 0;
for(i = 0; i < m1.rlen; i++)
{
// aIndex = l + i * m1clen
temp = a[aIndex];
bIndex = l * m1.rlen;
for(j = 0; j < m2.clen; j++)
{
// cIndex = i * m1.rlen + j
// bIndex = l * m1.rlen + j
v = op.aggOp.increOp.fn.execute(result.quickGetValue(i, j), op.binaryFn.execute(temp, b[bIndex]));
result.quickSetValue(i, j, v);
//cIndex++;
bIndex++;
}
aIndex += m1.clen;
}
}
}
/*
* to perform aggregateBinary when the first matrix is dense and the second is sparse
*/
private static void aggBinDenseSparse(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op)
throws DMLRuntimeException
{
if(m2.sparseRows==null)
return;
for(int k=0; k<Math.min(m2.rlen, m2.sparseRows.length); k++)
{
if(m2.sparseRows[k]==null) continue;
int[] cols=m2.sparseRows[k].getIndexContainer();
double[] values=m2.sparseRows[k].getValueContainer();
for(int p=0; p<m2.sparseRows[k].size(); p++)
{
int j=cols[p];
for(int i=0; i<m1.rlen; i++)
{
double old=result.quickGetValue(i, j);
double aik=m1.quickGetValue(i, k);
double addValue=op.binaryFn.execute(aik, values[p]);
double newvalue=op.aggOp.increOp.fn.execute(old, addValue);
result.quickSetValue(i, j, newvalue);
}
}
}
}
private static void aggBinSparseDense(MatrixIndexes m1Index,
MatrixBlockDSM m1, MatrixIndexes m2Index, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op,
boolean partialMult) throws DMLRuntimeException {
if (m1.sparseRows == null)
return;
//System.out.println("#*#*#**# in special aggBinSparseDense ... ");
int end_l, incrA = 0, incrB = 0;
// l varies from 0..end_l, where the upper bound end_l is determined by
// the Matrix Input (not the vector input)
if (partialMult == false) {
// both A and B are matrices
end_l = m1.clen;
} else {
if (m2.isVector()) {
// A is a matrix and B is a vector
incrB = (int) UtilFunctions.cellIndexCalculation(m1Index
.getColumnIndex(), 1000, 0) - 1; // matrixB.l goes from
// incr+start_l to
// incr+end_l
end_l = incrB + m1.clen;
} else if (m1.isVector()) {
// A is a vector and B is a matrix
incrA = (int) UtilFunctions.cellIndexCalculation(m2Index
.getRowIndex(), 1000, 0) - 1; // matrixA.l goes from
// incr+start_l to
// incr+end_l
end_l = incrA + m2.rlen;
} else
throw new RuntimeException(
"Unexpected case in matrixMult w/ partialMult");
}
/*System.out.println("m1: [" + m1.rlen + "," + m1.clen + "] m2: ["
+ m2.rlen + "," + m2.clen + "] incrA: " + incrA + " incrB: "
+ incrB + ", end_l " + end_l);*/
for (int i = 0; i < Math.min(m1.rlen, m1.sparseRows.length); i++) {
if (m1.sparseRows[i] == null)
continue;
int[] cols = m1.sparseRows[i].getIndexContainer();
double[] values = m1.sparseRows[i].getValueContainer();
for (int j = 0; j < m2.clen; j++) {
double aij = 0;
/*int p = 0;
if (partialMult) {
// this code is executed when m1 is a vector and m2 is a
// matrix
while (m1.isVector() && cols[p] < incrA)
p++;
}*/
// when m1 and m2 are matrices : incrA=0 & end_l=m1.clen (#cols
// in whole m1)
// when m1 is matrix & m2 is vector: incrA=0 &
// end_l=m1.sparseRows[i].size()
// when m1 is vector & m2 is matrix: incrA=based on
// m2Index.rowIndex & end_l=incrA+m2.rlen (#rows in m2's block)
for (int p = incrA; p < m1.sparseRows[i].size()
&& cols[p] < end_l; p++) {
int k = cols[p];
double addValue = op.binaryFn.execute(values[p], m2
.quickGetValue(k + incrB, j));
aij = op.aggOp.increOp.fn.execute(aij, addValue);
}
result.appendValue(i, j, aij);
}
}
}
/*
* to perform aggregateBinary when the first matrix is sparse and the second is dense
*/
private static void aggBinSparseDense(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op)
throws DMLRuntimeException
{
if(m1.sparseRows==null)
return;
for(int i=0; i<Math.min(m1.rlen, m1.sparseRows.length); i++)
{
if(m1.sparseRows[i]==null) continue;
int[] cols=m1.sparseRows[i].getIndexContainer();
double[] values=m1.sparseRows[i].getValueContainer();
for(int j=0; j<m2.clen; j++)
{
double aij=0;
for(int p=0; p<m1.sparseRows[i].size(); p++)
{
int k=cols[p];
double addValue=op.binaryFn.execute(values[p], m2.quickGetValue(k, j));
aij=op.aggOp.increOp.fn.execute(aij, addValue);
}
result.appendValue(i, j, aij);
}
}
}
/*
* to perform aggregateBinary when both matrices are sparse
*/
private static void aggBinSparseSparse(MatrixBlockDSM m1, MatrixBlockDSM m2,
MatrixBlockDSM result, AggregateBinaryOperator op)
throws DMLRuntimeException
{
if(m1.sparseRows==null || m2.sparseRows==null)
return;
//double[] cache=null;
TreeMap<Integer, Double> cache=null;
if(result.isInSparseFormat())
{
//cache=new double[m2.getNumColumns()];
cache=new TreeMap<Integer, Double>();
}
for(int i=0; i<Math.min(m1.rlen, m1.sparseRows.length); i++)
{
if(m1.sparseRows[i]==null) continue;
int[] cols1=m1.sparseRows[i].getIndexContainer();
double[] values1=m1.sparseRows[i].getValueContainer();
for(int p=0; p<m1.sparseRows[i].size(); p++)
{
int k=cols1[p];
if(m2.sparseRows[k]==null) continue;
int[] cols2=m2.sparseRows[k].getIndexContainer();
double[] values2=m2.sparseRows[k].getValueContainer();
for(int q=0; q<m2.sparseRows[k].size(); q++)
{
int j=cols2[q];
double addValue=op.binaryFn.execute(values1[p], values2[q]);
if(result.isInSparseFormat())
{
//cache[j]=op.aggOp.increOp.fn.execute(cache[j], addValue);
Double old=cache.get(j);
if(old==null)
old=0.0;
cache.put(j, op.aggOp.increOp.fn.execute(old, addValue));
}else
{
double old=result.quickGetValue(i, j);
double newvalue=op.aggOp.increOp.fn.execute(old, addValue);
result.quickSetValue(i, j, newvalue);
}
}
}
if(result.isInSparseFormat())
{
/*for(int j=0; j<cache.length; j++)
{
if(cache[j]!=0)
{
result.appendValue(i, j, cache[j]);
cache[j]=0;
}
}*/
for(Entry<Integer, Double> e: cache.entrySet())
{
result.appendValue(i, e.getKey(), e.getValue());
}
cache.clear();
}
}
}
private static void aggBinSparseUnsafe(MatrixBlockDSM m1, MatrixBlockDSM m2, MatrixBlockDSM result,
AggregateBinaryOperator op) throws DMLRuntimeException
{
for(int i=0; i<m1.rlen; i++)
for(int j=0; j<m2.clen; j++)
{
double aggValue=op.aggOp.initialValue;
for(int k=0; k<m1.clen; k++)
{
double aik=m1.quickGetValue(i, k);
double bkj=m2.quickGetValue(k, j);
double addValue=op.binaryFn.execute(aik, bkj);
aggValue=op.aggOp.increOp.fn.execute(aggValue, addValue);
}
result.appendValue(i, j, aggValue);
}
}
/**
* Invocation from CP instructions. The aggregate is computed on the groups object
* against target and weights.
*
* Notes:
* * The computed number of groups is reused for multiple invocations with different target.
* * This implementation supports that the target is passed as column or row vector,
* in case of row vectors we also use sparse-safe implementations for sparse safe
* aggregation operators.
*
* @param tgt
* @param wghts
* @param ret
* @param op
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
public MatrixValue groupedAggOperations(MatrixValue tgt, MatrixValue wghts, MatrixValue ret, Operator op)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//setup input matrices
// this <- groups
MatrixBlockDSM target = checkType(tgt);
MatrixBlockDSM weights = checkType(wghts);
//check valid dimensions
if( this.getNumColumns() != 1 || (weights!=null && weights.getNumColumns()!=1) )
throw new DMLRuntimeException("groupedAggregate can only operate on 1-dimensional column matrices for groups and weights.");
if( target.getNumColumns() != 1 && op instanceof CMOperator )
throw new DMLRuntimeException("groupedAggregate can only operate on 1-dimensional column matrices for target (for this aggregation function).");
if( target.getNumColumns() != 1 && target.getNumRows()!=1 )
throw new DMLRuntimeException("groupedAggregate can only operate on 1-dimensional column or row matrix for target.");
if( this.getNumRows() != Math.max(target.getNumRows(),target.getNumColumns()) || (weights != null && this.getNumRows() != weights.getNumRows()) )
throw new DMLRuntimeException("groupedAggregate can only operate on matrices with equal dimensions.");
// Determine the number of groups
if( numGroups <= 0 ) //reuse if available
{
double min = this.min();
double max = this.max();
if ( min <= 0 )
throw new DMLRuntimeException("Invalid value (" + min + ") encountered in 'groups' while computing groupedAggregate");
if ( max <= 0 )
throw new DMLRuntimeException("Invalid value (" + max + ") encountered in 'groups' while computing groupedAggregate.");
numGroups = (int) max;
}
// Allocate result matrix
MatrixBlockDSM result = checkType(ret);
boolean result_sparsity = false;
if(result==null)
result=new MatrixBlockDSM(numGroups, 1, result_sparsity);
else
result.reset(numGroups, 1, result_sparsity);
// Compute the result
double w = 1; // default weight
//CM operator for count, mean, variance
//note: current support only for column vectors
if(op instanceof CMOperator) {
// initialize required objects for storing the result of CM operations
CM cmFn = CM.getCMFnObject(((CMOperator) op).getAggOpType());
CM_COV_Object[] cmValues = new CM_COV_Object[numGroups];
for ( int i=0; i < numGroups; i++ )
cmValues[i] = new CM_COV_Object();
for ( int i=0; i < this.getNumRows(); i++ ) {
int g = (int) this.quickGetValue(i, 0);
double d = target.quickGetValue(i,0);
if ( weights != null )
w = weights.quickGetValue(i,0);
// cmValues is 0-indexed, whereas range of values for g = [1,numGroups]
cmFn.execute(cmValues[g-1], d, w);
}
// extract the required value from each CM_COV_Object
for ( int i=0; i < numGroups; i++ )
// result is 0-indexed, so is cmValues
result.quickSetValue(i, 0, cmValues[i].getRequiredResult(op));
}
//Aggregate operator for sum (via kahan sum)
//note: support for row/column vectors and dense/sparse
else if( op instanceof AggregateOperator )
{
//the only aggregate operator that is supported here is sum,
//furthermore, we always use KahanPlus and hence aggop.correctionExists is true
AggregateOperator aggop = (AggregateOperator) op;
//default case for aggregate(sum)
groupedAggregateKahanPlus(target, weights, result, aggop);
}
else
throw new DMLRuntimeException("Invalid operator (" + op + ") encountered while processing groupedAggregate.");
return result;
}
/**
* This is a specific implementation for aggregate(fn="sum"), where we use KahanPlus for numerical
* stability. In contrast to other functions of aggregate, this implementation supports row and column
* vectors for target and exploits sparse representations since KahanPlus is sparse-safe.
*
* @param target
* @param weights
* @param op
* @throws DMLRuntimeException
*/
private void groupedAggregateKahanPlus( MatrixBlockDSM target, MatrixBlockDSM weights, MatrixBlockDSM result, AggregateOperator aggop ) throws DMLRuntimeException
{
boolean rowVector = target.getNumColumns()>1;
double w = 1; //default weight
//skip empty blocks (sparse-safe operation)
if( target.isEmptyBlock(false) )
return;
//init group buffers
KahanObject[] buffer = new KahanObject[numGroups];
for(int i=0; i < numGroups; i++ )
buffer[i] = new KahanObject(aggop.initialValue, 0);
if( rowVector ) //target is rowvector
{
if( target.sparse ) //SPARSE target
{
if( target.sparseRows[0]!=null )
{
int len = target.sparseRows[0].size();
int[] aix = target.sparseRows[0].getIndexContainer();
double[] avals = target.sparseRows[0].getValueContainer();
for( int j=0; j<len; j++ ) //for each nnz
{
int g = (int) this.quickGetValue(aix[j], 0);
if ( weights != null )
w = weights.quickGetValue(aix[j],0);
aggop.increOp.fn.execute(buffer[g-1], avals[j]*w);
}
}
}
else //DENSE target
{
for ( int i=0; i < this.getNumColumns(); i++ ) {
double d = target.denseBlock[ i ];
if( d != 0 ) //sparse-safe
{
int g = (int) this.quickGetValue(i, 0);
if ( weights != null )
w = weights.quickGetValue(i,0);
// buffer is 0-indexed, whereas range of values for g = [1,numGroups]
aggop.increOp.fn.execute(buffer[g-1], d*w);
}
}
}
}
else //column vector (always dense, but works for sparse as well)
{
for ( int i=0; i < this.getNumRows(); i++ )
{
double d = target.quickGetValue(i,0);
if( d != 0 ) //sparse-safe
{
int g = (int) this.quickGetValue(i, 0);
if ( weights != null )
w = weights.quickGetValue(i,0);
// buffer is 0-indexed, whereas range of values for g = [1,numGroups]
aggop.increOp.fn.execute(buffer[g-1], d*w);
}
}
}
// extract the results from group buffers
for ( int i=0; i < numGroups; i++ )
result.quickSetValue(i, 0, buffer[i]._sum);
}
public MatrixValue removeEmptyOperations( MatrixValue ret, boolean rows )
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//check for empty inputs
if( nonZeros==0 ) {
ret.reset(0, 0, false);
return ret;
}
MatrixBlockDSM result = checkType(ret);
if( rows )
return removeEmptyRows(result);
else //cols
return removeEmptyColumns(result);
}
/**
*
* @param ret
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
private MatrixBlockDSM removeEmptyRows(MatrixBlockDSM ret)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//scan block and determine empty rows
int rlen2 = 0;
boolean[] flags = new boolean[ rlen ];
if( sparse )
{
for ( int i=0; i < sparseRows.length; i++ ) {
if ( sparseRows[i] != null && sparseRows[i].size() > 0 )
{
flags[i] = false;
rlen2++;
}
else
flags[i] = true;
}
}
else
{
for(int i=0; i<rlen; i++) {
flags[i] = true;
int index = i*clen;
for(int j=0; j<clen; j++)
if( denseBlock[index++] != 0 )
{
flags[i] = false;
rlen2++;
break; //early abort for current row
}
}
}
//reset result and copy rows
ret.reset(rlen2, clen, sparse);
int rindex = 0;
for( int i=0; i<rlen; i++ )
if( !flags[i] )
{
//copy row to result
if(sparse)
{
ret.appendRow(rindex, sparseRows[i]);
}
else
{
if( ret.denseBlock==null )
ret.denseBlock = new double[ rlen2*clen ];
int index1 = i*clen;
int index2 = rindex*clen;
for(int j=0; j<clen; j++)
{
if( denseBlock[index1] != 0 )
{
ret.denseBlock[index2] = denseBlock[index1];
ret.nonZeros++;
}
index1++;
index2++;
}
}
rindex++;
}
//check sparsity
ret.examSparsity();
return ret;
}
/**
*
* @param ret
* @return
* @throws DMLRuntimeException
* @throws DMLUnsupportedOperationException
*/
private MatrixBlockDSM removeEmptyColumns(MatrixBlockDSM ret)
throws DMLRuntimeException, DMLUnsupportedOperationException
{
//scan block and determine empty cols
int clen2 = 0;
boolean[] flags = new boolean[ clen ];
for(int j=0; j<clen; j++) {
flags[j] = true;
for(int i=0; i<rlen; i++) {
double value = quickGetValue(i, j);
if( value != 0 )
{
flags[j] = false;
clen2++;
break; //early abort for current col
}
}
}
//reset result and copy rows
ret.reset(rlen, clen2, sparse);
int cindex = 0;
for( int j=0; j<clen; j++ )
if( !flags[j] )
{
//copy col to result
for( int i=0; i<rlen; i++ )
{
double value = quickGetValue(i, j);
if( value != 0 )
ret.quickSetValue(i, cindex, value);
}
cindex++;
}
//check sparsity
ret.examSparsity();
return ret;
}
@Override
public MatrixValue replaceOperations(MatrixValue result, double pattern, double replacement)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM ret = checkType(result);
examSparsity(); //ensure its in the right format
ret.reset(rlen, clen, sparse);
if( nonZeros == 0 && pattern != 0 )
return ret; //early abort
boolean NaNpattern = Double.isNaN(pattern);
if( sparse ) //SPARSE
{
if( pattern !=0d ) //SPARSE <- SPARSE (sparse-safe)
{
ret.adjustSparseRows(ret.rlen-1);
SparseRow[] a = sparseRows;
SparseRow[] c = ret.sparseRows;
for( int i=0; i<rlen; i++ )
{
SparseRow arow = a[ i ];
if( arow!=null && arow.size()>0 )
{
SparseRow crow = new SparseRow(arow.size());
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
for( int j=0; j<alen; j++ )
{
double val = avals[j];
if( val== pattern || (NaNpattern && Double.isNaN(val)) )
crow.append(aix[j], replacement);
else
crow.append(aix[j], val);
}
c[ i ] = crow;
}
}
}
else //DENSE <- SPARSE
{
ret.sparse = false;
ret.allocateDenseBlock();
SparseRow[] a = sparseRows;
double[] c = ret.denseBlock;
//initialize with replacement (since all 0 values, see SPARSITY_TURN_POINT)
Arrays.fill(c, replacement);
//overwrite with existing values (via scatter)
if( a != null ) //check for empty matrix
for( int i=0, cix=0; i<rlen; i++, cix+=clen )
{
SparseRow arow = a[ i ];
if( arow!=null && arow.size()>0 )
{
int alen = arow.size();
int[] aix = arow.getIndexContainer();
double[] avals = arow.getValueContainer();
for( int j=0; j<alen; j++ )
if( avals[ j ] != 0 )
c[ cix+aix[j] ] = avals[ j ];
}
}
}
}
else //DENSE <- DENSE
{
int mn = ret.rlen * ret.clen;
ret.allocateDenseBlock();
double[] a = denseBlock;
double[] c = ret.denseBlock;
for( int i=0; i<mn; i++ )
{
double val = a[i];
if( val== pattern || (NaNpattern && Double.isNaN(val)) )
c[i] = replacement;
else
c[i] = a[i];
}
}
ret.recomputeNonZeros();
ret.examSparsity();
return ret;
}
/**
* D = ctable(A,v2,W)
* this <- A; scalarThat <- v2; that2 <- W; result <- D
*
* (i1,j1,v1) from input1 (this)
* (v2) from sclar_input2 (scalarThat)
* (i3,j3,w) from input3 (that2)
*/
@Override
public void tertiaryOperations(Operator op, double scalarThat,
MatrixValue that2Val, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that2 = checkType(that2Val);
CTable ctable = CTable.getCTableFnObject();
double v2 = scalarThat;
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
double w = that2.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
/**
* D = ctable(A,v2,w)
* this <- A; scalar_that <- v2; scalar_that2 <- w; result <- D
*
* (i1,j1,v1) from input1 (this)
* (v2) from sclar_input2 (scalarThat)
* (w) from scalar_input3 (scalarThat2)
*/
@Override
public void tertiaryOperations(Operator op, double scalarThat,
double scalarThat2, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
CTable ctable = CTable.getCTableFnObject();
double v2 = scalarThat;
double w = scalarThat2;
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
/**
* Specific ctable case of ctable(seq(...),X), where X is the only
* matrix input. The 'left' input parameter specifies if the seq appeared
* on the left, otherwise it appeared on the right.
*
*/
@Override
public void tertiaryOperations(Operator op, MatrixIndexes ix1, double scalarThat,
boolean left, int brlen, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
CTable ctable = CTable.getCTableFnObject();
double w = scalarThat;
int offset = (int) ((ix1.getRowIndex()-1)*brlen);
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
if( left )
ctable.execute(offset+i+1, v1, w, ctableResult);
else
ctable.execute(v1, offset+i+1, w, ctableResult);
}
}
/**
* D = ctable(A,B,w)
* this <- A; that <- B; scalar_that2 <- w; result <- D
*
* (i1,j1,v1) from input1 (this)
* (i1,j1,v2) from input2 (that)
* (w) from scalar_input3 (scalarThat2)
*/
@Override
public void tertiaryOperations(Operator op, MatrixValue thatVal,
double scalarThat2, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that = checkType(thatVal);
CTable ctable = CTable.getCTableFnObject();
double w = scalarThat2;
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
double v2 = that.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
/**
* D = ctable(A,B,W)
* this <- A; that <- B; that2 <- W; result <- D
*
* (i1,j1,v1) from input1 (this)
* (i1,j1,v2) from input2 (that)
* (i1,j1,w) from input3 (that2)
*/
public void tertiaryOperations(Operator op, MatrixValue thatVal, MatrixValue that2Val, HashMap<MatrixIndexes, Double> ctableResult)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that = checkType(thatVal);
MatrixBlockDSM that2 = checkType(that2Val);
CTable ctable = CTable.getCTableFnObject();
//sparse-unsafe ctable execution
//(because input values of 0 are invalid and have to result in errors)
for( int i=0; i<rlen; i++ )
for( int j=0; j<clen; j++ )
{
double v1 = this.quickGetValue(i, j);
double v2 = that.quickGetValue(i, j);
double w = that2.quickGetValue(i, j);
ctable.execute(v1, v2, w, ctableResult);
}
}
public void binaryOperationsInPlace(BinaryOperator op, MatrixValue thatValue)
throws DMLUnsupportedOperationException, DMLRuntimeException
{
MatrixBlockDSM that=checkType(thatValue);
if(this.rlen!=that.rlen || this.clen!=that.clen)
throw new RuntimeException("block sizes are not matched for binary " +
"cell operations: "+this.rlen+"*"+this.clen+" vs "+ that.rlen+"*"
+that.clen);
// System.out.println("-- this:\n"+this);
// System.out.println("-- that:\n"+that);
if(op.sparseSafe)
sparseBinaryInPlaceHelp(op, that);
else
denseBinaryInPlaceHelp(op, that);
// System.out.println("-- this (result):\n"+this);
}
private void sparseBinaryInPlaceHelp(BinaryOperator op, MatrixBlockDSM that) throws DMLRuntimeException
{
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(resultSparse.sparse && !this.sparse)
denseToSparse();
else if(!resultSparse.sparse && this.sparse)
sparseToDense();
if(this.sparse && that.sparse)
{
//special case, if both matrices are all 0s, just return
if(this.sparseRows==null && that.sparseRows==null)
return;
if(this.sparseRows!=null)
adjustSparseRows(rlen-1);
if(that.sparseRows!=null)
that.adjustSparseRows(rlen-1);
if(this.sparseRows!=null && that.sparseRows!=null)
{
for(int r=0; r<rlen; r++)
{
if(this.sparseRows[r]==null && that.sparseRows[r]==null)
continue;
if(that.sparseRows[r]==null)
{
double[] values=this.sparseRows[r].getValueContainer();
for(int i=0; i<this.sparseRows[r].size(); i++)
values[i]=op.fn.execute(values[i], 0);
}else
{
int estimateSize=0;
if(this.sparseRows[r]!=null)
estimateSize+=this.sparseRows[r].size();
if(that.sparseRows[r]!=null)
estimateSize+=that.sparseRows[r].size();
estimateSize=Math.min(clen, estimateSize);
//temp
SparseRow thisRow=this.sparseRows[r];
this.sparseRows[r]=new SparseRow(estimateSize, clen);
if(thisRow!=null)
{
nonZeros-=thisRow.size();
mergeForSparseBinary(op, thisRow.getValueContainer(),
thisRow.getIndexContainer(), thisRow.size(),
that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), r, this);
}else
{
appendRightForSparseBinary(op, that.sparseRows[r].getValueContainer(),
that.sparseRows[r].getIndexContainer(), that.sparseRows[r].size(), 0, r, this);
}
}
}
}
else if(this.sparseRows==null)
{
this.sparseRows=new SparseRow[rlen];
for(int r=0; r<rlen; r++)
{
SparseRow brow = that.sparseRows[r];
if( brow!=null && brow.size()>0 )
{
this.sparseRows[r] = new SparseRow( brow.size(), clen );
appendRightForSparseBinary(op, brow.getValueContainer(), brow.getIndexContainer(), brow.size(), 0, r, this);
}
}
}
else //that.sparseRows==null
{
for(int r=0; r<rlen; r++)
{
SparseRow arow = this.sparseRows[r];
if( arow!=null && arow.size()>0 )
appendLeftForSparseBinary(op, arow.getValueContainer(), arow.getIndexContainer(), arow.size(), 0, r, this);
}
}
}else
{
double thisvalue, thatvalue, resultvalue;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
thisvalue=this.quickGetValue(r, c);
thatvalue=that.quickGetValue(r, c);
resultvalue=op.fn.execute(thisvalue, thatvalue);
this.quickSetValue(r, c, resultvalue);
}
}
}
private void denseBinaryInPlaceHelp(BinaryOperator op, MatrixBlockDSM that) throws DMLRuntimeException
{
SparsityEstimate resultSparse=estimateSparsityOnBinary(this, that, op);
if(resultSparse.sparse && !this.sparse)
denseToSparse();
else if(!resultSparse.sparse && this.sparse)
sparseToDense();
double v;
for(int r=0; r<rlen; r++)
for(int c=0; c<clen; c++)
{
v=op.fn.execute(this.quickGetValue(r, c), that.quickGetValue(r, c));
quickSetValue(r, c, v);
}
}
////////////////////////////////////////////////////////////////////////////////
/* public MatrixBlockDSM getRandomDenseMatrix_normal(int rows, int cols, long seed)
{
Random random=new Random(seed);
this.allocateDenseBlock();
RandNPair pair = new RandNPair();
int index = 0;
while ( index < rows*cols ) {
pair.compute(random);
this.denseBlock[index++] = pair.getFirst();
if ( index < rows*cols )
this.denseBlock[index++] = pair.getSecond();
}
this.updateNonZeros();
return this;
}
public MatrixBlockDSM getRandomSparseMatrix_normal(int rows, int cols, double sparsity, long seed)
{
double val;
Random random = new Random(System.currentTimeMillis());
RandN rn = new RandN(seed);
this.sparseRows=new SparseRow[rows];
for(int i=0; i<rows; i++)
{
this.sparseRows[i]=new SparseRow();
for(int j=0; j<cols; j++)
{
if(random.nextDouble()>sparsity)
continue;
val = rn.nextDouble();
this.sparseRows[i].append(j, val );
}
}
this.updateNonZeros();
return this;
}
*/
////////
// Data Generation Methods
// (rand, sequence)
/**
* Function to generate a matrix of random numbers. This is invoked from maptasks of
* DataGen MR job. The parameter <code>seed</code> denotes the block-level seed.
*
* @param pdf
* @param rows
* @param cols
* @param rowsInBlock
* @param colsInBlock
* @param sparsity
* @param min
* @param max
* @param seed
* @return
* @throws DMLRuntimeException
*/
public MatrixBlockDSM getRandomMatrix(String pdf, int rows, int cols, int rowsInBlock, int colsInBlock, double sparsity, double min, double max, long seed) throws DMLRuntimeException
{
return getRandomMatrix(pdf, rows, cols, rowsInBlock, colsInBlock, sparsity, min, max, null, seed);
}
/**
* Function to generate a matrix of random numbers. This is invoked both
* from CP as well as from MR. In case of CP, it generates an entire matrix
* block-by-block. A <code>bigrand</code> is passed so that block-level
* seeds are generated internally. In case of MR, it generates a single
* block for given block-level seed <code>bSeed</code>.
*
* When pdf="uniform", cell values are drawn from uniform distribution in
* range <code>[min,max]</code>.
*
* When pdf="normal", cell values are drawn from standard normal
* distribution N(0,1). The range of generated values will always be
* (-Inf,+Inf).
*
* @param rows
* @param cols
* @param rowsInBlock
* @param colsInBlock
* @param sparsity
* @param min
* @param max
* @param bigrand
* @param bSeed
* @return
* @throws DMLRuntimeException
*/
public MatrixBlockDSM getRandomMatrix(String pdf, int rows, int cols, int rowsInBlock, int colsInBlock, double sparsity, double min, double max, Well1024a bigrand, long bSeed) throws DMLRuntimeException
{
// Setup Pseudo Random Number Generator for cell values based on 'pdf'.
PRNGenerator valuePRNG = null;
if ( pdf.equalsIgnoreCase("uniform"))
valuePRNG = new UniformPRNGenerator();
else if ( pdf.equalsIgnoreCase("normal"))
valuePRNG = new NormalPRNGenerator();
else
throw new DMLRuntimeException("Unsupported distribution function for Rand: " + pdf);
/*
* Setup min and max for distributions other than "uniform". Min and Max
* are set up in such a way that the usual logic of
* (max-min)*prng.nextDouble() is still valid. This is done primarily to
* share the same code across different distributions.
*/
if ( pdf.equalsIgnoreCase("normal") ) {
min=0;
max=1;
}
// Determine the sparsity of output matrix
sparse = (sparsity < SPARCITY_TURN_POINT);
if(cols<=SKINNY_MATRIX_TURN_POINT) {
sparse=false;
}
this.reset(rows, cols, sparse);
// Special case shortcuts for efficiency
if ( pdf.equalsIgnoreCase("uniform")) {
//specific cases for efficiency
if ( min == 0.0 && max == 0.0 ) { //all zeros
// nothing to do here
return this;
}
else if( !sparse && sparsity==1.0d && min == max ) //equal values
{
allocateDenseBlock();
Arrays.fill(denseBlock, 0, rlen*clen, min);
nonZeros = rlen*clen;
return this;
}
}
// Allocate memory
if ( sparse ) {
sparseRows = new SparseRow[rows];
//note: individual sparse rows are allocated on demand,
//for consistentcy with memory estimates and prevent OOMs.
}
else {
this.allocateDenseBlock();
}
double range = max - min;
int nrb = (int) Math.ceil((double)rows/rowsInBlock);
int ncb = (int) Math.ceil((double)cols/colsInBlock);
int blockrows, blockcols, rowoffset, coloffset;
int blocknnz;
// loop throught row-block indices
for(int rbi=0; rbi < nrb; rbi++) {
blockrows = (rbi == nrb-1 ? (rows-rbi*rowsInBlock) : rowsInBlock);
rowoffset = rbi*rowsInBlock;
// loop throught column-block indices
for(int cbj=0; cbj < ncb; cbj++) {
blockcols = (cbj == ncb-1 ? (cols-cbj*colsInBlock) : colsInBlock);
coloffset = cbj*colsInBlock;
// Generate a block (rbi,cbj)
// select the appropriate block-level seed
long seed = -1;
if ( bigrand == null ) {
// case of MR: simply use the passed-in value
seed = bSeed;
}
else {
// case of CP: generate a block-level seed from matrix-level Well1024a seed
seed = bigrand.nextLong();
}
// Initialize the PRNGenerator for cell values
valuePRNG.init(seed);
// Initialize the PRNGenerator for determining cells that contain a non-zero value
// Note that, "pdf" parameter applies only to cell values and the individual cells
// are always selected uniformly at random.
UniformPRNGenerator nnzPRNG = new UniformPRNGenerator(seed);
// block-level sparsity, which may differ from overall sparsity in the matrix.
boolean localSparse = sparse && !(blockcols<=SKINNY_MATRIX_TURN_POINT);
if ( localSparse ) {
blocknnz = (int) Math.ceil((blockrows*sparsity)*blockcols);
for(int ind=0; ind<blocknnz; ind++) {
int i = nnzPRNG.nextInt(blockrows);
int j = nnzPRNG.nextInt(blockcols);
double v = nnzPRNG.nextDouble();
if( sparseRows[rowoffset+i]==null )
sparseRows[rowoffset+i]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[rowoffset+i].set(coloffset+j, v);
}
}
else {
if (sparsity == 1.0) {
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0, index = ((ii+rowoffset)*cols)+coloffset; jj < blockcols; jj++, index++) {
double val = min + (range * valuePRNG.nextDouble());
this.denseBlock[index] = val;
}
}
}
else {
if ( sparse ) {
/* This case evaluated only when this function is invoked from CP.
* In this case:
* sparse=true -> entire matrix is in sparse format and hence denseBlock=null
* localSparse=true -> local block is dense, and hence on MR side a denseBlock will be allocated
* i.e., we need to generate data in a dense-style but set values in sparseRows
*
*/
// In this case, entire matrix is in sparse format but the current block is dense
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0; jj < blockcols; jj++) {
if(nnzPRNG.nextDouble() <= sparsity) {
double val = min + (range * valuePRNG.nextDouble());
if( sparseRows[ii+rowoffset]==null )
sparseRows[ii+rowoffset]=new SparseRow(estimatedNNzsPerRow, clen);
sparseRows[ii+rowoffset].set(jj+coloffset, val);
}
}
}
}
else {
for(int ii=0; ii < blockrows; ii++) {
for(int jj=0, index = ((ii+rowoffset)*cols)+coloffset; jj < blockcols; jj++, index++) {
if(nnzPRNG.nextDouble() <= sparsity) {
double val = min + (range * valuePRNG.nextDouble());
this.denseBlock[index] = val;
}
}
}
}
}
} // sparse or dense
} // cbj
} // rbi
recomputeNonZeros();
return this;
}
/**
* Method to generate a sequence according to the given parameters. The
* generated sequence is always in dense format.
*
* Both end points specified <code>from</code> and <code>to</code> must be
* included in the generated sequence i.e., [from,to] both inclusive. Note
* that, <code>to</code> is included only if (to-from) is perfectly
* divisible by <code>incr</code>.
*
* For example, seq(0,1,0.5) generates (0.0 0.5 1.0)
* whereas seq(0,1,0.6) generates (0.0 0.6) but not (0.0 0.6 1.0)
*
* @param from
* @param to
* @param incr
* @return
* @throws DMLRuntimeException
*/
public MatrixBlockDSM getSequence(double from, double to, double incr) throws DMLRuntimeException {
boolean neg = (from > to);
if (neg != (incr < 0))
throw new DMLRuntimeException("Wrong sign for the increment in a call to seq()");
//System.out.println(System.nanoTime() + ": begin of seq()");
int rows = 1 + (int)Math.floor((to-from)/incr);
int cols = 1;
sparse = false; // sequence matrix is always dense
this.reset(rows, cols, sparse);
this.allocateDenseBlock();
//System.out.println(System.nanoTime() + ": MatrixBlockDSM.seq(): seq("+from+","+to+","+incr+") rows = " + rows);
this.denseBlock[0] = from;
for(int i=1; i < rows; i++) {
from += incr;
this.denseBlock[i] = from;
}
recomputeNonZeros();
//System.out.println(System.nanoTime() + ": end of seq()");
return this;
}
////////
// Misc methods
private static MatrixBlockDSM checkType(MatrixValue block) throws DMLUnsupportedOperationException
{
if( block!=null && !(block instanceof MatrixBlockDSM))
throw new DMLUnsupportedOperationException("the Matrix Value is not MatrixBlockDSM!");
return (MatrixBlockDSM) block;
}
private static boolean checkRealSparsity(long rlen, long clen, long nnz)
{
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if( clen<=SKINNY_MATRIX_TURN_POINT )
return false;
else
return (((double)nnz)/rlen/clen < SPARCITY_TURN_POINT);
}
private static boolean checkRealSparsity(MatrixBlockDSM m)
{
return checkRealSparsity( m, false );
}
private static boolean checkRealSparsity(MatrixBlockDSM m, boolean transpose)
{
int lrlen = (transpose) ? m.clen : m.rlen;
int lclen = (transpose) ? m.rlen : m.clen;
int lnnz = m.getNonZeros();
//handle vectors specially
//if result is a column vector, use dense format, otherwise use the normal process to decide
if(lclen<=SKINNY_MATRIX_TURN_POINT)
return false;
else
return (((double)lnnz)/lrlen/lclen < SPARCITY_TURN_POINT);
}
public void print()
{
System.out.println("sparse = "+sparse);
if(!sparse)
System.out.println("nonzeros = "+nonZeros);
for(int i=0; i<rlen; i++)
{
for(int j=0; j<clen; j++)
{
System.out.print(quickGetValue(i, j)+"\t");
}
System.out.println();
}
}
@Override
public int compareTo(Object arg0)
{
// don't compare blocks
return 0;
}
@Override
public String toString()
{
String ret="sparse? = "+sparse+"\n" ;
ret+="nonzeros = "+nonZeros+"\n";
ret+="size: "+rlen+" X "+clen+"\n";
boolean toprint=false;
if(!toprint)
return "sparse? = "+sparse+"\nnonzeros = "+nonZeros+"\nsize: "+rlen+" X "+clen+"\n";
if(sparse)
{
int len=0;
if(sparseRows!=null)
len=Math.min(rlen, sparseRows.length);
int i=0;
for(; i<len; i++)
{
ret+="row +"+i+": "+sparseRows[i]+"\n";
if(sparseRows[i]!=null)
{
for(int j=0; j<sparseRows[i].size(); j++)
if(sparseRows[i].getValueContainer()[j]!=0.0)
toprint=true;
}
}
for(; i<rlen; i++)
{
ret+="row +"+i+": null\n";
}
}else
{
if(denseBlock!=null)
{
int start=0;
for(int i=0; i<rlen; i++)
{
for(int j=0; j<clen; j++)
{
ret+=this.denseBlock[start+j]+"\t";
if(this.denseBlock[start+j]!=0.0)
toprint=true;
}
ret+="\n";
start+=clen;
}
}
}
return ret;
}
///////////////////////////
// Helper classes
public static class SparsityEstimate
{
public int estimatedNonZeros=0;
public boolean sparse=false;
public SparsityEstimate(boolean sps, int nnzs)
{
sparse=sps;
estimatedNonZeros=nnzs;
}
public SparsityEstimate(){}
}
public static class IJV
{
public int i=-1;
public int j=-1;
public double v=0;
public IJV()
{}
public IJV(int i, int j, double v)
{
set(i, j, v);
}
public void set(int i, int j, double v)
{
this.i=i;
this.j=j;
this.v=v;
}
public String toString()
{
return "("+i+", "+j+"): "+v;
}
}
public static class SparseCellIterator implements Iterator<IJV>
{
private int rlen=0;
private SparseRow[] sparseRows=null;
private int curRow=-1;
private int curColIndex=-1;
private int[] colIndexes=null;
private double[] values=null;
private boolean nothingLeft=false;
private IJV retijv=new IJV();
public SparseCellIterator(int nrows, SparseRow[] mtx)
{
rlen=nrows;
sparseRows=mtx;
curRow=0;
if(sparseRows==null)
nothingLeft=true;
else
findNextNonZeroRow();
}
private void findNextNonZeroRow() {
while(curRow<Math.min(rlen, sparseRows.length) && (sparseRows[curRow]==null || sparseRows[curRow].size()==0))
curRow++;
if(curRow>=Math.min(rlen, sparseRows.length))
nothingLeft=true;
else
{
curColIndex=0;
colIndexes=sparseRows[curRow].getIndexContainer();
values=sparseRows[curRow].getValueContainer();
}
}
@Override
public boolean hasNext() {
if(nothingLeft)
return false;
else
return true;
}
@Override
public IJV next() {
retijv.set(curRow, colIndexes[curColIndex], values[curColIndex]);
curColIndex++;
if(curColIndex>=sparseRows[curRow].size())
{
curRow++;
findNextNonZeroRow();
}
return retijv;
}
@Override
public void remove() {
throw new RuntimeException("SparseCellIterator.remove should not be called!");
}
}
}
| 66141: SystemML Engine Enhancements - Fixes grouped aggregate block operations (sparsity estimate, dense row vectors)
| SystemML/SystemML/DML/src/main/java/com/ibm/bi/dml/runtime/matrix/io/MatrixBlockDSM.java | 66141: SystemML Engine Enhancements - Fixes grouped aggregate block operations (sparsity estimate, dense row vectors) | <ide><path>ystemML/SystemML/DML/src/main/java/com/ibm/bi/dml/runtime/matrix/io/MatrixBlockDSM.java
<ide> return (ret && (((double)ennz)/rlenm1/clenm1) < SPARCITY_TURN_POINT);
<ide> }
<ide>
<add> private boolean estimateSparsityOnGroupedAgg( long rlen, long groups )
<add> {
<add> boolean ret = (groups>SKINNY_MATRIX_TURN_POINT);
<add>
<add> return (ret && (((double)rlen)/groups) < SPARCITY_TURN_POINT);
<add> }
<ide>
<ide> ////////
<ide> // Core block operations (called from instructions)
<ide>
<ide> // Allocate result matrix
<ide> MatrixBlockDSM result = checkType(ret);
<del> boolean result_sparsity = false;
<add> boolean result_sparsity = estimateSparsityOnGroupedAgg(rlen, numGroups);
<ide> if(result==null)
<ide> result=new MatrixBlockDSM(numGroups, 1, result_sparsity);
<ide> else
<ide> }
<ide> else //DENSE target
<ide> {
<del> for ( int i=0; i < this.getNumColumns(); i++ ) {
<add> for ( int i=0; i < target.getNumColumns(); i++ ) {
<ide> double d = target.denseBlock[ i ];
<ide> if( d != 0 ) //sparse-safe
<ide> { |
|
Java | apache-2.0 | 247c5f898d9cf927d571ddc47dfc25049530c486 | 0 | ronaldsmartin/Material-ViewPagerIndicator | package com.itsronald.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.Dimension;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Px;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.ViewParent;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* ViewPagerIndicator is a non-interactive indicator of the current, next,
* and previous pages of a {@link ViewPager}. It is intended to be used as a
* child view of a ViewPager widget in your XML layout.
*
* Add it as a child of a ViewPager in your layout file and set its
* android:layout_gravity to TOP or BOTTOM to pin it to the top or bottom
* of the ViewPager.
*/
@ViewPager.DecorView
public class ViewPagerIndicator extends ViewGroup {
@NonNull
private static final String TAG = "ViewPagerIndicator";
//region ViewPager
@NonNull
private final PageListener pageListener = new PageListener();
@Nullable
private ViewPager viewPager;
@Nullable
private WeakReference<PagerAdapter> pagerAdapterRef;
//endregion
//region Indicator Dots
@Dimension
static final int DEFAULT_DOT_PADDING_DIP = 6;
@NonNull
private final List<IndicatorDotView> indicatorDots = new ArrayList<>();
@NonNull
private final List<IndicatorDotPathView> dotPaths = new ArrayList<>();
private IndicatorDotView selectedDot; // @NonNull, but initialized in init().
@Px
private int dotPadding;
@Px
private int dotRadius;
@ColorInt
private int unselectedDotColor;
@ColorInt
private int selectedDotColor;
//endregion
//region State
private int gravity = Gravity.CENTER_VERTICAL;
private int lastKnownCurrentPage = -1;
private float lastKnownPositionOffset = -1;
private boolean isUpdatingPositions = false;
//endregion
//region Constructors
public ViewPagerIndicator(Context context) {
super(context);
init(context, null, 0 ,0);
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(@NonNull Context context,
@Nullable AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
TypedArray attributes = context
.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator, defStyleAttr, defStyleRes);
gravity = attributes.getInt(R.styleable.ViewPagerIndicator_android_gravity, gravity);
final float scale = getResources().getDisplayMetrics().density;
final int defaultDotPadding = (int) (DEFAULT_DOT_PADDING_DIP * scale + 0.5);
dotPadding = attributes
.getDimensionPixelSize(R.styleable.ViewPagerIndicator_dotPadding, defaultDotPadding);
final int defaultDotRadius = (int) (IndicatorDotView.DEFAULT_DOT_RADIUS_DIP * scale + 0.5);
dotRadius = attributes.getDimensionPixelSize(
R.styleable.ViewPagerIndicator_dotRadius,
defaultDotRadius
);
unselectedDotColor = attributes.getColor(
R.styleable.ViewPagerIndicator_unselectedDotColor,
IndicatorDotView.DEFAULT_UNSELECTED_DOT_COLOR
);
selectedDotColor = attributes.getColor(
R.styleable.ViewPagerIndicator_selectedDotColor,
IndicatorDotView.DEFAULT_SELECTED_DOT_COLOR
);
attributes.recycle();
selectedDot = new IndicatorDotView(context, null, defStyleAttr, defStyleRes);
selectedDot.setColor(selectedDotColor);
selectedDot.setRadius(dotRadius);
}
//endregion
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int heightPadding = getPaddingTop() + getPaddingBottom();
final int childHeightSpec = getChildMeasureSpec(heightMeasureSpec,
heightPadding, LayoutParams.WRAP_CONTENT);
final int widthPadding = getPaddingLeft() + getPaddingRight();
final int childWidthSpec = getChildMeasureSpec(widthMeasureSpec,
widthPadding, LayoutParams.WRAP_CONTENT);
// Measure subviews.
selectedDot.measure(childWidthSpec, childHeightSpec);
for (IndicatorDotView indicatorDot : indicatorDots) {
indicatorDot.measure(childWidthSpec, childHeightSpec);
}
for (IndicatorDotPathView dotPath : dotPaths) {
dotPath.measure(childWidthSpec, childHeightSpec);
}
// Calculate measurement for this view.
final int width;
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
/*
* Due to the implementation of onMeasure() in ViewPager, this case will always be
* called if vertical layout_gravity is specified on this view. Since the Material
* Design spec usually positions dot indicators like this at the bottom of pages, this
* case will be called almost all the time.
*/
width = MeasureSpec.getSize(widthMeasureSpec);
} else {
final int dotCount = indicatorDots.size();
final int totalDotWidth = selectedDot.getMeasuredWidth() * dotCount;
final int totalDotPadding = dotPadding * (dotCount - 1);
final int minWidth = ViewCompat.getMinimumWidth(this);
width = Math.max(minWidth, totalDotWidth + totalDotPadding + widthPadding);
}
final int height;
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode == MeasureSpec.EXACTLY) {
height = MeasureSpec.getSize(heightMeasureSpec);
} else {
final int indicatorHeight = selectedDot.getMeasuredHeight();
final int minHeight = ViewCompat.getMinimumHeight(this);
height = Math.max(minHeight, indicatorHeight + heightPadding);
}
final int childState = ViewCompat.getMeasuredHeightAndState(selectedDot);
final int measuredHeight = ViewCompat.resolveSizeAndState(height, heightMeasureSpec,
childState);
setMeasuredDimension(width, measuredHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
refresh();
}
private void refresh() {
if (viewPager != null) {
updateIndicators(viewPager.getCurrentItem(), viewPager.getAdapter());
final float offset = lastKnownPositionOffset >= 0 ? lastKnownPositionOffset : 0;
updateIndicatorPositions(lastKnownCurrentPage, offset, true);
}
}
@Override
protected void onAttachedToWindow() {
// See:
// https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#244
super.onAttachedToWindow();
final ViewParent parent = getParent();
if (!(parent instanceof ViewPager)) {
throw new IllegalStateException(
"ViewPagerIndicator must be a direct child of a ViewPager.");
}
final ViewPager pager = (ViewPager) parent;
viewPager = pager;
final PagerAdapter adapter = pager.getAdapter();
pager.addOnPageChangeListener(pageListener);
pager.addOnAdapterChangeListener(pageListener);
final PagerAdapter lastAdapter = pagerAdapterRef != null ? pagerAdapterRef.get() : null;
updateAdapter(lastAdapter, adapter);
}
@Override
protected void onDetachedFromWindow() {
// See:
// https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#263
super.onDetachedFromWindow();
if (viewPager != null) {
updateAdapter(viewPager.getAdapter(), null);
viewPager.removeOnPageChangeListener(pageListener);
viewPager.removeOnAdapterChangeListener(pageListener);
viewPager = null;
}
}
/**
* Update the ViewPager adapter being observed by the indicator. The
* <p>
* Taken from:
* https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#319
*
* @param oldAdapter The previous adapter being tracked by the indicator.
* @param newAdapter The previous adapter that should be tracked by the indicator.
*/
private void updateAdapter(@Nullable PagerAdapter oldAdapter,
@Nullable PagerAdapter newAdapter) {
if (oldAdapter != null) {
oldAdapter.unregisterDataSetObserver(pageListener);
pagerAdapterRef = null;
}
if (newAdapter != null) {
newAdapter.registerDataSetObserver(pageListener);
pagerAdapterRef = new WeakReference<>(newAdapter);
}
if (viewPager != null) {
lastKnownCurrentPage = -1;
lastKnownPositionOffset = -1;
updateIndicators(viewPager.getCurrentItem(), newAdapter);
invalidate();
requestLayout();
}
}
private void updateIndicators(int currentPage, @Nullable PagerAdapter pagerAdapter) {
final int pageCount = pagerAdapter == null ? 0 : pagerAdapter.getCount();
updateDotCount(pageCount);
lastKnownCurrentPage = currentPage;
if (!isUpdatingPositions) {
updateIndicatorPositions(currentPage, lastKnownPositionOffset, false);
}
}
private void updateDotCount(int newDotCount) {
final LayoutParams layoutParams =
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// Add unselected dots to layout.
int dotCount = indicatorDots.size();
if (dotCount < newDotCount) {
while (dotCount++ != newDotCount) {
final IndicatorDotView newDot = new IndicatorDotView(getContext());
newDot.setRadius(dotRadius);
newDot.setColor(unselectedDotColor);
indicatorDots.add(newDot);
addViewInLayout(newDot, -1, layoutParams, true);
}
} else if (dotCount > newDotCount) {
final List<IndicatorDotView> removedDots = indicatorDots
.subList(newDotCount, dotCount);
for (IndicatorDotView removedDot : removedDots) {
removeViewInLayout(removedDot);
}
indicatorDots.removeAll(removedDots);
}
// Make sure there is one fewer path than there are dots.
updatePathCount(newDotCount - 1);
// Add selected dot to layout.
if (newDotCount > 0) {
addViewInLayout(selectedDot, -1, layoutParams, true);
} else {
removeViewInLayout(selectedDot);
}
}
private void updatePathCount(final int newPathCount) {
int pathCount = dotPaths.size();
if (pathCount < newPathCount) {
final LayoutParams layoutParams =
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
while (pathCount++ != newPathCount) {
final IndicatorDotPathView newPath = new IndicatorDotPathView(
getContext(), getUnselectedDotColor(), getDotPadding(), getDotRadius()
);
dotPaths.add(newPath);
addViewInLayout(newPath, -1, layoutParams, true);
}
} else if (pathCount > newPathCount && newPathCount >= 0) {
final List<IndicatorDotPathView> pathsToRemove = dotPaths
.subList(newPathCount, pathCount);
for (IndicatorDotPathView dotPath : pathsToRemove) {
removeViewInLayout(dotPath);
}
dotPaths.removeAll(pathsToRemove);
}
}
/**
* Taken from:
* https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#336
*
* @param currentPage The index of the page we are on in the ViewPager.
* @param positionOffset The offset of the current page from horizontal center.
* @param forceUpdate Whether or not to force an update
*/
private void updateIndicatorPositions(int currentPage, float positionOffset, boolean forceUpdate) {
if (currentPage != lastKnownCurrentPage && viewPager != null) {
updateIndicators(currentPage, viewPager.getAdapter());
} else if (!forceUpdate && positionOffset == lastKnownPositionOffset) {
return;
}
isUpdatingPositions = true;
final int dotWidth = 2 * dotRadius;
final int top = calculateIndicatorDotTop();
final int bottom = top + dotWidth;
int left = calculateIndicatorDotStart();
int right = left + dotWidth;
for (int i = 0,
dotCount = indicatorDots.size(),
pathCount = dotPaths.size(); i < dotCount; ++i) {
final IndicatorDotView dotView = indicatorDots.get(i);
dotView.layout(left, top, right, bottom);
if (i < pathCount) {
final IndicatorDotPathView dotPath = dotPaths.get(i);
dotPath.layout(left, top, left + dotPath.getMeasuredWidth(), bottom);
}
if (i == currentPage) {
selectedDot.layout(left, top, right, bottom);
}
left = right + dotPadding;
right = left + dotWidth;
}
selectedDot.bringToFront();
lastKnownPositionOffset = positionOffset;
isUpdatingPositions = false;
}
/**
* Calculate the starting vertical position for the line of indicator dots.
* @return The first Y coordinate where the indicator dots start.
*/
@Px
private int calculateIndicatorDotTop() {
final int top;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (verticalGravity) {
default:
case Gravity.CENTER_VERTICAL:
top = (getHeight() - getPaddingTop() - getPaddingBottom()) / 2 - getDotRadius();
break;
case Gravity.TOP:
top = getPaddingTop();
break;
case Gravity.BOTTOM:
top = getHeight() - getPaddingBottom() - 2 * getDotRadius();
break;
}
return top;
}
/**
* Calculate the starting horizontal position for the line of indicator dots.
* Assumes dots are centered horizontally.
*
* @return The first X coordinate where the indicator dots start.
*/
@Px
private int calculateIndicatorDotStart() {
/*
* Calculate the start position by starting from the center of the view and moving left
* for half of the dots.
*/
final int dotCount = indicatorDots.size();
final float halfDotCount = dotCount / 2f;
final int dotWidth = 2 * dotRadius;
final float totalDotWidth = dotWidth * halfDotCount;
// # dot gaps = (numDots - 1), so # dot gaps / 2 = (numDots - 1) / 2 = halfDotCount - 0.5.
final float halfDotPaddingCount = Math.max(halfDotCount - 0.5f, 0);
final float totalDotPaddingWidth = dotPadding * halfDotPaddingCount;
int startPosition = getWidth() / 2;
startPosition -= totalDotWidth + totalDotPaddingWidth;
return startPosition;
}
@Nullable
private Animator pageChangeAnimator(int lastPageIndex, int newPageIndex) {
final IndicatorDotPathView dotPath = getDotPathForPageChange(lastPageIndex, newPageIndex);
final IndicatorDotView lastDot = getDotForPage(lastPageIndex);
if (dotPath == null || lastDot == null) return null;
final int pathDirection = getPathDirectionForPageChange(lastPageIndex, newPageIndex);
final Animator pathAnimator = dotPath.connectPathAndRetreatAnimator(pathDirection);
pathAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
lastDot.setVisibility(INVISIBLE);
}
});
final long dotSlideDuration = pathAnimator.getDuration() / 2;
final Animator selectedDotSlideAnimator =
selectedDotSlideAnimator(newPageIndex, dotSlideDuration, dotSlideDuration);
final Animator dotRevealAnimator = lastDot.revealAnimator();
final AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(pathAnimator);
animatorSet.playSequentially(pathAnimator, dotRevealAnimator);
return animatorSet;
}
@NonNull
private Animator selectedDotSlideAnimator(int newPageIndex,
long animationDuration,
long startDelay) {
final Rect newPageDotRect = new Rect();
final IndicatorDotView newPageDot = getDotForPage(newPageIndex);
if (newPageDot != null) {
newPageDot.getDrawingRect(newPageDotRect);
offsetDescendantRectToMyCoords(newPageDot, newPageDotRect);
offsetRectIntoDescendantCoords(selectedDot, newPageDotRect);
}
final float toX = newPageDotRect.left;
final float toY = newPageDotRect.top;
final Animator animator = selectedDot.slideAnimator(toX, toY, animationDuration);
animator.setStartDelay(startDelay);
return animator;
}
private class PageListener extends DataSetObserver
implements ViewPager.OnPageChangeListener, ViewPager.OnAdapterChangeListener {
private int scrollState;
@Override
public void onChanged() {
super.onChanged();
refresh();
}
//region ViewPager.OnPageChangeListener
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset > 0.5f) {
// Consider ourselves to be on the next page when we're 50% of the way there.
position++;
}
updateIndicatorPositions(position, positionOffset, false);
}
@Override
public void onPageSelected(int position) {
final Animator pageChangeAnimator = pageChangeAnimator(lastKnownCurrentPage, position);
if (scrollState == ViewPager.SCROLL_STATE_IDLE
&& viewPager != null) {
// Only update the text here if we're not dragging or settling.
refresh();
}
if (pageChangeAnimator != null) {
pageChangeAnimator.start();
}
}
@Override
public void onPageScrollStateChanged(int state) {
scrollState = state;
}
//endregion
//region ViewPager.OnAdapterChangeListener
@Override
public void onAdapterChanged(@NonNull ViewPager viewPager,
@Nullable PagerAdapter oldAdapter,
@Nullable PagerAdapter newAdapter) {
updateAdapter(oldAdapter, newAdapter);
}
//endregion
}
//region Accessors
@Nullable
private IndicatorDotView getDotForPage(int pageIndex) {
if (pageIndex > indicatorDots.size() - 1 || pageIndex < 0) return null;
return indicatorDots.get(pageIndex);
}
@Nullable
private IndicatorDotPathView getDotPathForPageChange(int oldPageIndex, int newPageIndex) {
if (oldPageIndex < 0 || newPageIndex < 0
|| oldPageIndex == newPageIndex)
return null;
final int dotPathIndex = oldPageIndex < newPageIndex ? oldPageIndex : newPageIndex;
return dotPathIndex >= dotPaths.size() ? null : dotPaths.get(dotPathIndex);
}
@IndicatorDotPathView.PathDirection
private int getPathDirectionForPageChange(int oldPageIndex, int newPageIndex) {
return oldPageIndex < newPageIndex ? IndicatorDotPathView.PATH_DIRECTION_RIGHT :
IndicatorDotPathView.PATH_DIRECTION_LEFT;
}
/**
* Get the {@link Gravity} used to position dots within the indicator.
* Only the vertical gravity component is used.
*/
public int getGravity() {
return gravity;
}
/**
* Set the {@link Gravity} used to position dots within the indicator.
* Only the vertical gravity component is used.
*
* @param newGravity {@link Gravity} constant for positioning indicator dots.
*/
public void setGravity(int newGravity) {
gravity = newGravity;
requestLayout();
}
@Px
public int getDotPadding() {
return dotPadding;
}
public void setDotPadding(@Px int newDotPadding) {
if (dotPadding == newDotPadding) return;
if (newDotPadding < 0) newDotPadding = 0;
dotPadding = newDotPadding;
invalidate();
requestLayout();
}
@Px
public int getDotRadius() {
return dotRadius;
}
public void setDotRadius(@Px int newRadius) {
if (dotRadius == newRadius) return;
if (newRadius < 0) newRadius = 0;
dotRadius = newRadius;
for (IndicatorDotView indicatorDot : indicatorDots) {
indicatorDot.setRadius(dotRadius);
}
invalidate();
requestLayout();
}
@ColorInt
public int getUnselectedDotColor() {
return unselectedDotColor;
}
public void setUnselectedDotColor(@ColorInt int color) {
unselectedDotColor = color;
for (IndicatorDotView indicatordot : indicatorDots) {
indicatordot.setColor(color);
indicatordot.invalidate();
}
}
@ColorInt
public int getSelectedDotColor() {
return selectedDotColor;
}
public void setSelectedDotColor(@ColorInt int color) {
selectedDotColor = color;
if (selectedDot != null) {
selectedDot.setColor(color);
selectedDot.invalidate();
}
}
//endregion
}
| material-viewpagerindicator/src/main/java/com/itsronald/widget/ViewPagerIndicator.java | package com.itsronald.widget;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Rect;
import android.os.Build;
import android.support.annotation.ColorInt;
import android.support.annotation.Dimension;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.Px;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup;
import android.view.ViewParent;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
/**
* ViewPagerIndicator is a non-interactive indicator of the current, next,
* and previous pages of a {@link ViewPager}. It is intended to be used as a
* child view of a ViewPager widget in your XML layout.
*
* Add it as a child of a ViewPager in your layout file and set its
* android:layout_gravity to TOP or BOTTOM to pin it to the top or bottom
* of the ViewPager.
*/
@ViewPager.DecorView
public class ViewPagerIndicator extends ViewGroup {
@NonNull
private static final String TAG = "ViewPagerIndicator";
//region ViewPager
@NonNull
private final PageListener pageListener = new PageListener();
@Nullable
private ViewPager viewPager;
@Nullable
private WeakReference<PagerAdapter> pagerAdapterRef;
//endregion
//region Indicator Dots
@Dimension
static final int DEFAULT_DOT_PADDING_DIP = 6;
@NonNull
private final List<IndicatorDotView> indicatorDots = new ArrayList<>();
@NonNull
private final List<IndicatorDotPathView> dotPaths = new ArrayList<>();
private IndicatorDotView selectedDot; // @NonNull, but initialized in init().
@Px
private int dotPadding;
@Px
private int dotRadius;
@ColorInt
private int unselectedDotColor;
@ColorInt
private int selectedDotColor;
//endregion
//region State
private int gravity = Gravity.CENTER_VERTICAL;
private int lastKnownCurrentPage = -1;
private float lastKnownPositionOffset = -1;
private boolean isUpdatingPositions = false;
//endregion
//region Constructors
public ViewPagerIndicator(Context context) {
super(context);
init(context, null, 0 ,0);
}
public ViewPagerIndicator(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, 0, 0);
}
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs, defStyleAttr, 0);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public ViewPagerIndicator(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs, defStyleAttr, defStyleRes);
}
private void init(@NonNull Context context,
@Nullable AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
TypedArray attributes = context
.obtainStyledAttributes(attrs, R.styleable.ViewPagerIndicator, defStyleAttr, defStyleRes);
gravity = attributes.getInt(R.styleable.ViewPagerIndicator_android_gravity, gravity);
final float scale = getResources().getDisplayMetrics().density;
final int defaultDotPadding = (int) (DEFAULT_DOT_PADDING_DIP * scale + 0.5);
dotPadding = attributes
.getDimensionPixelSize(R.styleable.ViewPagerIndicator_dotPadding, defaultDotPadding);
final int defaultDotRadius = (int) (IndicatorDotView.DEFAULT_DOT_RADIUS_DIP * scale + 0.5);
dotRadius = attributes.getDimensionPixelSize(
R.styleable.ViewPagerIndicator_dotRadius,
defaultDotRadius
);
unselectedDotColor = attributes.getColor(
R.styleable.ViewPagerIndicator_unselectedDotColor,
IndicatorDotView.DEFAULT_UNSELECTED_DOT_COLOR
);
selectedDotColor = attributes.getColor(
R.styleable.ViewPagerIndicator_selectedDotColor,
IndicatorDotView.DEFAULT_SELECTED_DOT_COLOR
);
attributes.recycle();
selectedDot = new IndicatorDotView(context, null, defStyleAttr, defStyleRes);
selectedDot.setColor(selectedDotColor);
selectedDot.setRadius(dotRadius);
}
//endregion
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int heightPadding = getPaddingTop() + getPaddingBottom();
final int childHeightSpec = getChildMeasureSpec(heightMeasureSpec,
heightPadding, LayoutParams.WRAP_CONTENT);
final int widthPadding = getPaddingLeft() + getPaddingRight();
final int childWidthSpec = getChildMeasureSpec(widthMeasureSpec,
widthPadding, LayoutParams.WRAP_CONTENT);
// Measure subviews.
selectedDot.measure(childWidthSpec, childHeightSpec);
for (IndicatorDotView indicatorDot : indicatorDots) {
indicatorDot.measure(childWidthSpec, childHeightSpec);
}
for (IndicatorDotPathView dotPath : dotPaths) {
dotPath.measure(childWidthSpec, childHeightSpec);
}
// Calculate measurement for this view.
final int width;
final int widthMode = MeasureSpec.getMode(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
/*
* Due to the implementation of onMeasure() in ViewPager, this case will always be
* called if vertical layout_gravity is specified on this view. Since the Material
* Design spec usually positions dot indicators like this at the bottom of pages, this
* case will be called almost all the time.
*/
width = MeasureSpec.getSize(widthMeasureSpec);
} else {
final int dotCount = indicatorDots.size();
final int totalDotWidth = selectedDot.getMeasuredWidth() * dotCount;
final int totalDotPadding = dotPadding * (dotCount - 1);
final int minWidth = ViewCompat.getMinimumWidth(this);
width = Math.max(minWidth, totalDotWidth + totalDotPadding + widthPadding);
}
final int height;
final int heightMode = MeasureSpec.getMode(heightMeasureSpec);
if (heightMode == MeasureSpec.EXACTLY) {
height = MeasureSpec.getSize(heightMeasureSpec);
} else {
final int indicatorHeight = selectedDot.getMeasuredHeight();
final int minHeight = ViewCompat.getMinimumHeight(this);
height = Math.max(minHeight, indicatorHeight + heightPadding);
}
final int childState = ViewCompat.getMeasuredHeightAndState(selectedDot);
final int measuredHeight = ViewCompat.resolveSizeAndState(height, heightMeasureSpec,
childState);
setMeasuredDimension(width, measuredHeight);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
refresh();
}
private void refresh() {
if (viewPager != null) {
updateIndicators(viewPager.getCurrentItem(), viewPager.getAdapter());
final float offset = lastKnownPositionOffset >= 0 ? lastKnownPositionOffset : 0;
updateIndicatorPositions(lastKnownCurrentPage, offset, true);
}
}
@Override
protected void onAttachedToWindow() {
// See:
// https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#244
super.onAttachedToWindow();
final ViewParent parent = getParent();
if (!(parent instanceof ViewPager)) {
throw new IllegalStateException(
"ViewPagerIndicator must be a direct child of a ViewPager.");
}
final ViewPager pager = (ViewPager) parent;
viewPager = pager;
final PagerAdapter adapter = pager.getAdapter();
pager.addOnPageChangeListener(pageListener);
pager.addOnAdapterChangeListener(pageListener);
final PagerAdapter lastAdapter = pagerAdapterRef != null ? pagerAdapterRef.get() : null;
updateAdapter(lastAdapter, adapter);
}
@Override
protected void onDetachedFromWindow() {
// See:
// https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#263
super.onDetachedFromWindow();
if (viewPager != null) {
updateAdapter(viewPager.getAdapter(), null);
viewPager.removeOnPageChangeListener(pageListener);
viewPager.removeOnAdapterChangeListener(pageListener);
viewPager = null;
}
}
/**
* Update the ViewPager adapter being observed by the indicator. The
* <p>
* Taken from:
* https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#319
*
* @param oldAdapter The previous adapter being tracked by the indicator.
* @param newAdapter The previous adapter that should be tracked by the indicator.
*/
private void updateAdapter(@Nullable PagerAdapter oldAdapter,
@Nullable PagerAdapter newAdapter) {
if (oldAdapter != null) {
oldAdapter.unregisterDataSetObserver(pageListener);
pagerAdapterRef = null;
}
if (newAdapter != null) {
newAdapter.registerDataSetObserver(pageListener);
pagerAdapterRef = new WeakReference<>(newAdapter);
}
if (viewPager != null) {
lastKnownCurrentPage = -1;
lastKnownPositionOffset = -1;
updateIndicators(viewPager.getCurrentItem(), newAdapter);
invalidate();
requestLayout();
}
}
private void updateIndicators(int currentPage, @Nullable PagerAdapter pagerAdapter) {
final int pageCount = pagerAdapter == null ? 0 : pagerAdapter.getCount();
updateDotCount(pageCount);
Log.d(TAG, "Num pages: " + pageCount);
lastKnownCurrentPage = currentPage;
Log.d(TAG, "Current page: " + lastKnownCurrentPage);
if (!isUpdatingPositions) {
updateIndicatorPositions(currentPage, lastKnownPositionOffset, false);
}
}
private void updateDotCount(int newDotCount) {
final LayoutParams layoutParams =
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
// Add unselected dots to layout.
int dotCount = indicatorDots.size();
if (dotCount < newDotCount) {
while (dotCount++ != newDotCount) {
final IndicatorDotView newDot = new IndicatorDotView(getContext());
newDot.setRadius(dotRadius);
newDot.setColor(unselectedDotColor);
indicatorDots.add(newDot);
addViewInLayout(newDot, -1, layoutParams, true);
}
} else if (dotCount > newDotCount) {
final List<IndicatorDotView> removedDots = indicatorDots
.subList(newDotCount, dotCount);
for (IndicatorDotView removedDot : removedDots) {
removeViewInLayout(removedDot);
}
indicatorDots.removeAll(removedDots);
}
// Make sure there is one fewer path than there are dots.
updatePathCount(newDotCount - 1);
// Add selected dot to layout.
if (newDotCount > 0) {
addViewInLayout(selectedDot, -1, layoutParams, true);
} else {
removeViewInLayout(selectedDot);
Log.d(TAG, "Removing selectedDot");
}
}
private void updatePathCount(final int newPathCount) {
int pathCount = dotPaths.size();
if (pathCount < newPathCount) {
final LayoutParams layoutParams =
new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
while (pathCount++ != newPathCount) {
final IndicatorDotPathView newPath = new IndicatorDotPathView(
getContext(), getUnselectedDotColor(), getDotPadding(), getDotRadius()
);
dotPaths.add(newPath);
addViewInLayout(newPath, -1, layoutParams, true);
}
} else if (pathCount > newPathCount && newPathCount >= 0) {
final List<IndicatorDotPathView> pathsToRemove = dotPaths
.subList(newPathCount, pathCount);
for (IndicatorDotPathView dotPath : pathsToRemove) {
removeViewInLayout(dotPath);
}
dotPaths.removeAll(pathsToRemove);
}
}
/**
* Taken from:
* https://android.googlesource.com/platform/frameworks/support/+/nougat-release/v4/java/android/support/v4/view/PagerTitleStrip.java#336
*
* @param currentPage The index of the page we are on in the ViewPager.
* @param positionOffset The offset of the current page from horizontal center.
* @param forceUpdate Whether or not to force an update
*/
private void updateIndicatorPositions(int currentPage, float positionOffset, boolean forceUpdate) {
if (currentPage != lastKnownCurrentPage && viewPager != null) {
updateIndicators(currentPage, viewPager.getAdapter());
} else if (!forceUpdate && positionOffset == lastKnownPositionOffset) {
return;
}
isUpdatingPositions = true;
final int dotWidth = 2 * dotRadius;
final int top = calculateIndicatorDotTop();
final int bottom = top + dotWidth;
int left = calculateIndicatorDotStart();
int right = left + dotWidth;
for (int i = 0,
dotCount = indicatorDots.size(),
pathCount = dotPaths.size(); i < dotCount; ++i) {
final IndicatorDotView dotView = indicatorDots.get(i);
dotView.layout(left, top, right, bottom);
if (i < pathCount) {
final IndicatorDotPathView dotPath = dotPaths.get(i);
dotPath.layout(left, top, left + dotPath.getMeasuredWidth(), bottom);
}
if (i == currentPage) {
selectedDot.layout(left, top, right, bottom);
}
left = right + dotPadding;
right = left + dotWidth;
}
selectedDot.bringToFront();
lastKnownPositionOffset = positionOffset;
isUpdatingPositions = false;
}
/**
* Calculate the starting vertical position for the line of indicator dots.
* @return The first Y coordinate where the indicator dots start.
*/
@Px
private int calculateIndicatorDotTop() {
final int top;
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (verticalGravity) {
default:
case Gravity.CENTER_VERTICAL:
top = (getHeight() - getPaddingTop() - getPaddingBottom()) / 2 - getDotRadius();
break;
case Gravity.TOP:
top = getPaddingTop();
break;
case Gravity.BOTTOM:
top = getHeight() - getPaddingBottom() - 2 * getDotRadius();
break;
}
return top;
}
/**
* Calculate the starting horizontal position for the line of indicator dots.
* Assumes dots are centered horizontally.
*
* @return The first X coordinate where the indicator dots start.
*/
@Px
private int calculateIndicatorDotStart() {
/*
* Calculate the start position by starting from the center of the view and moving left
* for half of the dots.
*/
final int dotCount = indicatorDots.size();
final float halfDotCount = dotCount / 2f;
final int dotWidth = 2 * dotRadius;
final float totalDotWidth = dotWidth * halfDotCount;
// # dot gaps = (numDots - 1), so # dot gaps / 2 = (numDots - 1) / 2 = halfDotCount - 0.5.
final float halfDotPaddingCount = Math.max(halfDotCount - 0.5f, 0);
final float totalDotPaddingWidth = dotPadding * halfDotPaddingCount;
int startPosition = getWidth() / 2;
startPosition -= totalDotWidth + totalDotPaddingWidth;
return startPosition;
}
@Nullable
private Animator pageChangeAnimator(int lastPageIndex, int newPageIndex) {
final IndicatorDotPathView dotPath = getDotPathForPageChange(lastPageIndex, newPageIndex);
final IndicatorDotView lastDot = getDotForPage(lastPageIndex);
if (dotPath == null || lastDot == null) return null;
final int pathDirection = getPathDirectionForPageChange(lastPageIndex, newPageIndex);
final Animator pathAnimator = dotPath.connectPathAndRetreatAnimator(pathDirection);
pathAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationStart(Animator animation) {
lastDot.setVisibility(INVISIBLE);
}
});
final long dotSlideDuration = pathAnimator.getDuration() / 2;
final Animator selectedDotSlideAnimator =
selectedDotSlideAnimator(newPageIndex, dotSlideDuration, dotSlideDuration);
final Animator dotRevealAnimator = lastDot.revealAnimator();
final AnimatorSet animatorSet = new AnimatorSet();
animatorSet.playTogether(pathAnimator);
animatorSet.playSequentially(pathAnimator, dotRevealAnimator);
return animatorSet;
}
@NonNull
private Animator selectedDotSlideAnimator(int newPageIndex,
long animationDuration,
long startDelay) {
final Rect newPageDotRect = new Rect();
final IndicatorDotView newPageDot = getDotForPage(newPageIndex);
if (newPageDot != null) {
newPageDot.getDrawingRect(newPageDotRect);
offsetDescendantRectToMyCoords(newPageDot, newPageDotRect);
offsetRectIntoDescendantCoords(selectedDot, newPageDotRect);
}
final float toX = newPageDotRect.left;
final float toY = newPageDotRect.top;
final Animator animator = selectedDot.slideAnimator(toX, toY, animationDuration);
animator.setStartDelay(startDelay);
return animator;
}
private class PageListener extends DataSetObserver
implements ViewPager.OnPageChangeListener, ViewPager.OnAdapterChangeListener {
private int scrollState;
@Override
public void onChanged() {
super.onChanged();
refresh();
}
//region ViewPager.OnPageChangeListener
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (positionOffset > 0.5f) {
// Consider ourselves to be on the next page when we're 50% of the way there.
position++;
}
updateIndicatorPositions(position, positionOffset, false);
}
@Override
public void onPageSelected(int position) {
final Animator pageChangeAnimator = pageChangeAnimator(lastKnownCurrentPage, position);
if (scrollState == ViewPager.SCROLL_STATE_IDLE
&& viewPager != null) {
// Only update the text here if we're not dragging or settling.
refresh();
}
if (pageChangeAnimator != null) {
pageChangeAnimator.start();
}
}
@Override
public void onPageScrollStateChanged(int state) {
scrollState = state;
}
//endregion
//region ViewPager.OnAdapterChangeListener
@Override
public void onAdapterChanged(@NonNull ViewPager viewPager,
@Nullable PagerAdapter oldAdapter,
@Nullable PagerAdapter newAdapter) {
updateAdapter(oldAdapter, newAdapter);
}
//endregion
}
//region Accessors
@Nullable
private IndicatorDotView getDotForPage(int pageIndex) {
if (pageIndex > indicatorDots.size() - 1 || pageIndex < 0) return null;
return indicatorDots.get(pageIndex);
}
@Nullable
private IndicatorDotPathView getDotPathForPageChange(int oldPageIndex, int newPageIndex) {
if (oldPageIndex < 0 || newPageIndex < 0
|| oldPageIndex > dotPaths.size() - 1 || newPageIndex > dotPaths.size() - 1
|| oldPageIndex == newPageIndex)
return null;
final int dotPathIndex = oldPageIndex < newPageIndex ? oldPageIndex : newPageIndex;
return dotPaths.get(dotPathIndex);
}
@IndicatorDotPathView.PathDirection
private int getPathDirectionForPageChange(int oldPageIndex, int newPageIndex) {
return oldPageIndex < newPageIndex ? IndicatorDotPathView.PATH_DIRECTION_RIGHT :
IndicatorDotPathView.PATH_DIRECTION_LEFT;
}
/**
* Get the {@link Gravity} used to position dots within the indicator.
* Only the vertical gravity component is used.
*/
public int getGravity() {
return gravity;
}
/**
* Set the {@link Gravity} used to position dots within the indicator.
* Only the vertical gravity component is used.
*
* @param newGravity {@link Gravity} constant for positioning indicator dots.
*/
public void setGravity(int newGravity) {
gravity = newGravity;
requestLayout();
}
@Px
public int getDotPadding() {
return dotPadding;
}
public void setDotPadding(@Px int newDotPadding) {
if (dotPadding == newDotPadding) return;
if (newDotPadding < 0) newDotPadding = 0;
dotPadding = newDotPadding;
invalidate();
requestLayout();
}
@Px
public int getDotRadius() {
return dotRadius;
}
public void setDotRadius(@Px int newRadius) {
if (dotRadius == newRadius) return;
if (newRadius < 0) newRadius = 0;
dotRadius = newRadius;
for (IndicatorDotView indicatorDot : indicatorDots) {
indicatorDot.setRadius(dotRadius);
}
invalidate();
requestLayout();
}
@ColorInt
public int getUnselectedDotColor() {
return unselectedDotColor;
}
public void setUnselectedDotColor(@ColorInt int color) {
unselectedDotColor = color;
for (IndicatorDotView indicatordot : indicatorDots) {
indicatordot.setColor(color);
indicatordot.invalidate();
}
}
@ColorInt
public int getSelectedDotColor() {
return selectedDotColor;
}
public void setSelectedDotColor(@ColorInt int color) {
selectedDotColor = color;
if (selectedDot != null) {
selectedDot.setColor(color);
selectedDot.invalidate();
}
}
//endregion
}
| Correct condition so path works for last indicator dot.
| material-viewpagerindicator/src/main/java/com/itsronald/widget/ViewPagerIndicator.java | Correct condition so path works for last indicator dot. | <ide><path>aterial-viewpagerindicator/src/main/java/com/itsronald/widget/ViewPagerIndicator.java
<ide> private void updateIndicators(int currentPage, @Nullable PagerAdapter pagerAdapter) {
<ide> final int pageCount = pagerAdapter == null ? 0 : pagerAdapter.getCount();
<ide> updateDotCount(pageCount);
<del> Log.d(TAG, "Num pages: " + pageCount);
<ide>
<ide> lastKnownCurrentPage = currentPage;
<del> Log.d(TAG, "Current page: " + lastKnownCurrentPage);
<ide>
<ide> if (!isUpdatingPositions) {
<ide> updateIndicatorPositions(currentPage, lastKnownPositionOffset, false);
<ide> addViewInLayout(selectedDot, -1, layoutParams, true);
<ide> } else {
<ide> removeViewInLayout(selectedDot);
<del> Log.d(TAG, "Removing selectedDot");
<ide> }
<ide> }
<ide>
<ide> @Nullable
<ide> private IndicatorDotPathView getDotPathForPageChange(int oldPageIndex, int newPageIndex) {
<ide> if (oldPageIndex < 0 || newPageIndex < 0
<del> || oldPageIndex > dotPaths.size() - 1 || newPageIndex > dotPaths.size() - 1
<ide> || oldPageIndex == newPageIndex)
<ide> return null;
<ide>
<ide> final int dotPathIndex = oldPageIndex < newPageIndex ? oldPageIndex : newPageIndex;
<del> return dotPaths.get(dotPathIndex);
<add> return dotPathIndex >= dotPaths.size() ? null : dotPaths.get(dotPathIndex);
<ide> }
<ide>
<ide> @IndicatorDotPathView.PathDirection |
|
Java | mit | error: pathspec 'src/dk/aau/d101f14/test/InformationCollector.java' did not match any file(s) known to git
| b2fd3725f718e1679c45525282475c2e217ffb84 | 1 | D101F14/TinyVM,D101F14/TinyVM,D101F14/TinyVM | package dk.aau.d101f14.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
public class InformationCollector {
public static void main(String[] args) {
String errorText = "";
ArrayList<String> errorList = new ArrayList<String>();
int normalTermination = 0;
int silentDataCorruption = 0;
int tinyVMNullReferenceException = 0;
int javaNullPointerException = 0;
int tinyVMOutOfMemoryException = 0;
int javaOutOfMemoryException = 0;
int tinyVMDivisionByZeroException = 0;
int tinyVMInvalidField = 0;
int javaArrayIndexOutOfBoundsException = 0;
int unknown = 0;
//Modify this to call the right file
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\Users\\Rune\\workspace\\TestOfExecutables\\bin\\ExecutableTest\\run.jar");
pb.redirectErrorStream();
try {
Process p = pb.start();
p.waitFor();
if(p.exitValue() == returnValues.NORMAL.getCode()){
//Normal termination
normalTermination++;
}else if(p.exitValue() == returnValues.JAVAFAULT.getCode()){
//Something went wrong
errorText = readString(p.getErrorStream());
if(errorText.contains("NullPointerException")){
javaNullPointerException++;
}else if(errorText.contains("ArrayIndexOutOfBoundsException")){
javaArrayIndexOutOfBoundsException++;
}else if(errorText.contains("OutOfMemoryException")){
javaOutOfMemoryException++;
}else{
unknown++;
errorList.add(errorText);
}
}else if(p.exitValue() == returnValues.NULLREF.getCode()){
tinyVMNullReferenceException++;
}else if(p.exitValue() == returnValues.OUTOFMEM.getCode()){
tinyVMOutOfMemoryException++;
}else if(p.exitValue() == returnValues.DIVBYZERO.getCode()){
tinyVMDivisionByZeroException++;
}else if(p.exitValue() == returnValues.FIELD.getCode()){
tinyVMInvalidField++;
}
} catch (Exception exp) {
exp.printStackTrace();
}
System.out.println("Information of execution termination:\n");
System.out.println(" Masked Error:\t\t\t\t " + normalTermination);
System.out.println(" Silent Data Corruption:\t\t " + silentDataCorruption);
System.out.println("(TinyVM) Null Reference Exception:\t\t " + tinyVMNullReferenceException);
System.out.println("(Java) Null Pointer Exception:\t\t " + javaNullPointerException);
System.out.println("(TinyVM) Out Of Memory Exception:\t\t " + tinyVMOutOfMemoryException);
System.out.println("(Java) Out Of Memory Exception:\t\t " + javaOutOfMemoryException);
System.out.println("(TinyVM) Division By Zero Exception:\t\t " + tinyVMDivisionByZeroException);
System.out.println("(TinyVM) Invalid Field:\t\t\t\t " + tinyVMInvalidField);
System.out.println("(Java) Array Index Out Of Bounds Exception:\t " + javaArrayIndexOutOfBoundsException);
System.out.println(" Unknown:\t\t\t\t " + unknown);
System.out.println("\n\n Log messages for sources of 'unknown':");
for(int i = 0; i < errorList.size(); i++){
System.out.println(i + errorList.get(i));
}
}
private static String readString(InputStream is){
StringBuilder sb = new StringBuilder(64);
int value = -1;
try {
while ((value = is.read()) != -1) {
sb.append((char)value);
}
} catch (IOException exp) {
exp.printStackTrace();
sb.append(exp.getMessage());
}
return sb.toString();
}
public enum returnValues{
NORMAL(0),JAVAFAULT(1),NULLREF(2),OUTOFMEM(3),DIVBYZERO(4),FIELD(5);
private int errorCode;
private returnValues(int id){
errorCode = id;
}
public int getCode(){
return errorCode;
}
}
}
| src/dk/aau/d101f14/test/InformationCollector.java | Add class for collecting information of tests
| src/dk/aau/d101f14/test/InformationCollector.java | Add class for collecting information of tests | <ide><path>rc/dk/aau/d101f14/test/InformationCollector.java
<add>package dk.aau.d101f14.test;
<add>
<add>import java.io.IOException;
<add>import java.io.InputStream;
<add>import java.util.ArrayList;
<add>
<add>public class InformationCollector {
<add>
<add> public static void main(String[] args) {
<add> String errorText = "";
<add> ArrayList<String> errorList = new ArrayList<String>();
<add> int normalTermination = 0;
<add> int silentDataCorruption = 0;
<add> int tinyVMNullReferenceException = 0;
<add> int javaNullPointerException = 0;
<add> int tinyVMOutOfMemoryException = 0;
<add> int javaOutOfMemoryException = 0;
<add> int tinyVMDivisionByZeroException = 0;
<add> int tinyVMInvalidField = 0;
<add> int javaArrayIndexOutOfBoundsException = 0;
<add> int unknown = 0;
<add>
<add> //Modify this to call the right file
<add> ProcessBuilder pb = new ProcessBuilder("java", "-jar", "C:\\Users\\Rune\\workspace\\TestOfExecutables\\bin\\ExecutableTest\\run.jar");
<add> pb.redirectErrorStream();
<add> try {
<add> Process p = pb.start();
<add>
<add> p.waitFor();
<add>
<add> if(p.exitValue() == returnValues.NORMAL.getCode()){
<add> //Normal termination
<add> normalTermination++;
<add> }else if(p.exitValue() == returnValues.JAVAFAULT.getCode()){
<add> //Something went wrong
<add> errorText = readString(p.getErrorStream());
<add>
<add> if(errorText.contains("NullPointerException")){
<add> javaNullPointerException++;
<add> }else if(errorText.contains("ArrayIndexOutOfBoundsException")){
<add> javaArrayIndexOutOfBoundsException++;
<add> }else if(errorText.contains("OutOfMemoryException")){
<add> javaOutOfMemoryException++;
<add> }else{
<add> unknown++;
<add> errorList.add(errorText);
<add> }
<add> }else if(p.exitValue() == returnValues.NULLREF.getCode()){
<add> tinyVMNullReferenceException++;
<add> }else if(p.exitValue() == returnValues.OUTOFMEM.getCode()){
<add> tinyVMOutOfMemoryException++;
<add> }else if(p.exitValue() == returnValues.DIVBYZERO.getCode()){
<add> tinyVMDivisionByZeroException++;
<add> }else if(p.exitValue() == returnValues.FIELD.getCode()){
<add> tinyVMInvalidField++;
<add> }
<add> } catch (Exception exp) {
<add> exp.printStackTrace();
<add> }
<add>
<add> System.out.println("Information of execution termination:\n");
<add> System.out.println(" Masked Error:\t\t\t\t " + normalTermination);
<add> System.out.println(" Silent Data Corruption:\t\t " + silentDataCorruption);
<add> System.out.println("(TinyVM) Null Reference Exception:\t\t " + tinyVMNullReferenceException);
<add> System.out.println("(Java) Null Pointer Exception:\t\t " + javaNullPointerException);
<add> System.out.println("(TinyVM) Out Of Memory Exception:\t\t " + tinyVMOutOfMemoryException);
<add> System.out.println("(Java) Out Of Memory Exception:\t\t " + javaOutOfMemoryException);
<add> System.out.println("(TinyVM) Division By Zero Exception:\t\t " + tinyVMDivisionByZeroException);
<add> System.out.println("(TinyVM) Invalid Field:\t\t\t\t " + tinyVMInvalidField);
<add> System.out.println("(Java) Array Index Out Of Bounds Exception:\t " + javaArrayIndexOutOfBoundsException);
<add> System.out.println(" Unknown:\t\t\t\t " + unknown);
<add>
<add> System.out.println("\n\n Log messages for sources of 'unknown':");
<add> for(int i = 0; i < errorList.size(); i++){
<add> System.out.println(i + errorList.get(i));
<add> }
<add> }
<add>
<add> private static String readString(InputStream is){
<add>
<add> StringBuilder sb = new StringBuilder(64);
<add> int value = -1;
<add> try {
<add> while ((value = is.read()) != -1) {
<add> sb.append((char)value);
<add> }
<add> } catch (IOException exp) {
<add> exp.printStackTrace();
<add> sb.append(exp.getMessage());
<add> }
<add> return sb.toString();
<add> }
<add>
<add>
<add> public enum returnValues{
<add> NORMAL(0),JAVAFAULT(1),NULLREF(2),OUTOFMEM(3),DIVBYZERO(4),FIELD(5);
<add>
<add> private int errorCode;
<add>
<add> private returnValues(int id){
<add> errorCode = id;
<add> }
<add>
<add> public int getCode(){
<add> return errorCode;
<add> }
<add>
<add> }
<add>} |
|
Java | apache-2.0 | 9e9d0d47b0e9e4d4b724b74056cf5624cf8fbb94 | 0 | krlohnes/tinkerpop,samiunn/incubator-tinkerpop,vtslab/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,artem-aliev/tinkerpop,apache/incubator-tinkerpop,robertdale/tinkerpop,newkek/incubator-tinkerpop,velo/incubator-tinkerpop,krlohnes/tinkerpop,krlohnes/tinkerpop,gdelafosse/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,robertdale/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,gdelafosse/incubator-tinkerpop,rmagen/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,RedSeal-co/incubator-tinkerpop,apache/tinkerpop,RussellSpitzer/incubator-tinkerpop,mpollmeier/tinkerpop3,apache/tinkerpop,n-tran/incubator-tinkerpop,jorgebay/tinkerpop,robertdale/tinkerpop,dalaro/incubator-tinkerpop,apache/tinkerpop,jorgebay/tinkerpop,samiunn/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,apache/incubator-tinkerpop,artem-aliev/tinkerpop,mpollmeier/tinkerpop3,Lab41/tinkerpop3,jorgebay/tinkerpop,velo/incubator-tinkerpop,samiunn/incubator-tinkerpop,vtslab/incubator-tinkerpop,apache/tinkerpop,apache/incubator-tinkerpop,apache/tinkerpop,RussellSpitzer/incubator-tinkerpop,dalaro/incubator-tinkerpop,edgarRd/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,robertdale/tinkerpop,RedSeal-co/incubator-tinkerpop,pluradj/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,BrynCooke/incubator-tinkerpop,dalaro/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,pluradj/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,rmagen/incubator-tinkerpop,pluradj/incubator-tinkerpop,n-tran/incubator-tinkerpop,newkek/incubator-tinkerpop,krlohnes/tinkerpop,robertdale/tinkerpop,rmagen/incubator-tinkerpop,edgarRd/incubator-tinkerpop,vtslab/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,velo/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,newkek/incubator-tinkerpop,Lab41/tinkerpop3,artem-aliev/tinkerpop,n-tran/incubator-tinkerpop,edgarRd/incubator-tinkerpop,artem-aliev/tinkerpop | package com.tinkerpop.blueprints.io.graphml;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.io.GraphWriter;
import com.tinkerpop.blueprints.io.LexicographicalElementComparator;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* GraphMLWriter writes a Graph to a GraphML OutputStream.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Joshua Shinavier (http://fortytwo.net)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphMLWriter implements GraphWriter {
private final Graph graph;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private Optional<String> xmlSchemaLocation;
private Optional<String> edgeLabelKey;
/**
* @param graph the Graph to pull the data from
*/
private GraphMLWriter(final Graph graph, final boolean normalize, final Map<String, String> vertexKeyTypes,
final Map<String, String> edgeKeyTypes, final String xmlSchemaLocation,
final String edgeLabelKey) {
this.graph = graph;
this.normalize = normalize;
this.vertexKeyTypes = vertexKeyTypes;
this.edgeKeyTypes = edgeKeyTypes;
this.xmlSchemaLocation = Optional.ofNullable(xmlSchemaLocation);
this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
}
/**
* Write the data in a Graph to a GraphML OutputStream.
*
* @param outputStream the GraphML OutputStream to write the Graph data to
* @throws IOException thrown if there is an error generating the GraphML data
*/
@Override
public void outputGraph(final OutputStream outputStream) throws IOException {
if (null == vertexKeyTypes || null == edgeKeyTypes) {
Map<String, String> vertexKeyTypes = new HashMap<>();
Map<String, String> edgeKeyTypes = new HashMap<>();
for (Vertex vertex : graph.query().vertices()) {
for (String key : vertex.getPropertyKeys()) {
if (!vertexKeyTypes.containsKey(key)) {
vertexKeyTypes.put(key, GraphMLWriter.getStringType(vertex.getProperty(key).getValue()));
}
}
for (Edge edge : vertex.query().direction(Direction.OUT).edges()) {
for (String key : edge.getPropertyKeys()) {
if (!edgeKeyTypes.containsKey(key)) {
edgeKeyTypes.put(key, GraphMLWriter.getStringType(edge.getProperty(key).getValue()));
}
}
}
}
if (null == this.vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
}
if (null == this.edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
}
}
// adding the edge label key will push the label into the data portion of the graphml otherwise it
// will live with the edge data itself (which won't validate against the graphml schema)
if (this.edgeLabelKey.isPresent() && null != this.edgeKeyTypes && null == this.edgeKeyTypes.get(this.edgeLabelKey.get()))
this.edgeKeyTypes.put(this.edgeLabelKey.get(), GraphMLTokens.STRING);
final XMLOutputFactory inputFactory = XMLOutputFactory.newInstance();
try {
XMLStreamWriter writer = inputFactory.createXMLStreamWriter(outputStream, "UTF8");
if (normalize) {
writer = new GraphMLWriterHelper.IndentingXMLStreamWriter(writer);
((GraphMLWriterHelper.IndentingXMLStreamWriter) writer).setIndentStep(" ");
}
writer.writeStartDocument();
writer.writeStartElement(GraphMLTokens.GRAPHML);
writer.writeAttribute(GraphMLTokens.XMLNS, GraphMLTokens.GRAPHML_XMLNS);
//XML Schema instance namespace definition (xsi)
writer.writeAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG,
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
//XML Schema location
writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
GraphMLTokens.GRAPHML_XMLNS + " " + this.xmlSchemaLocation.orElse(GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION));
// <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
Collection<String> keyset;
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(vertexKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else {
keyset = vertexKeyTypes.keySet();
}
for (String key : keyset) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, vertexKeyTypes.get(key));
writer.writeEndElement();
}
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(edgeKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else {
keyset = edgeKeyTypes.keySet();
}
for (String key : keyset) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, edgeKeyTypes.get(key));
writer.writeEndElement();
}
writer.writeStartElement(GraphMLTokens.GRAPH);
writer.writeAttribute(GraphMLTokens.ID, GraphMLTokens.G);
writer.writeAttribute(GraphMLTokens.EDGEDEFAULT, GraphMLTokens.DIRECTED);
Iterable<Vertex> vertices;
if (normalize) {
vertices = new ArrayList<>();
for (Vertex v : graph.query().vertices()) {
((Collection<Vertex>) vertices).add(v);
}
Collections.sort((List<Vertex>) vertices, new LexicographicalElementComparator());
} else {
vertices = graph.query().vertices();
}
for (Vertex vertex : vertices) {
writer.writeStartElement(GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ID, vertex.getId().toString());
Collection<String> keys;
if (normalize) {
keys = new ArrayList<>();
keys.addAll(vertex.getPropertyKeys());
Collections.sort((List<String>) keys);
} else {
keys = vertex.getPropertyKeys();
}
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = vertex.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
if (normalize) {
List<Edge> edges = new ArrayList<>();
for (Vertex vertex : graph.query().vertices()) {
for (Edge edge : vertex.query().direction(Direction.OUT).edges()) {
edges.add(edge);
}
}
Collections.sort(edges, new LexicographicalElementComparator());
for (Edge edge : edges) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
if (this.edgeLabelKey.isPresent()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey.get());
writer.writeCharacters(edge.getLabel());
writer.writeEndElement();
} else {
// this will not comply with the graphml schema but is here so that the label is not
// mixed up with properties.
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
}
final List<String> keys = new ArrayList<>();
keys.addAll(edge.getPropertyKeys());
Collections.sort(keys);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
} else {
for (Vertex vertex : graph.query().vertices()) {
for (Edge edge : vertex.query().direction(Direction.OUT).edges()) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
for (String key : edge.getPropertyKeys()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
writer.writeEndElement(); // graph
writer.writeEndElement(); // graphml
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (XMLStreamException xse) {
throw new IOException(xse);
}
}
private static String getStringType(final Object object) {
if (object instanceof String) {
return GraphMLTokens.STRING;
} else if (object instanceof Integer) {
return GraphMLTokens.INT;
} else if (object instanceof Long) {
return GraphMLTokens.LONG;
} else if (object instanceof Float) {
return GraphMLTokens.FLOAT;
} else if (object instanceof Double) {
return GraphMLTokens.DOUBLE;
} else if (object instanceof Boolean) {
return GraphMLTokens.BOOLEAN;
} else {
return GraphMLTokens.STRING;
}
}
public static final class Builder {
private final Graph g;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private String xmlSchemaLocation = null;
private String edgeLabelKey = null;
public Builder(final Graph g) {
if (null == g)
throw new IllegalArgumentException("Graph argument cannot be null");
this.g = g;
}
/**
* Normalized output is deterministic with respect to the order of elements and properties in the resulting
* XML document, and is compatible with line diff-based tools such as Git. Note: normalized output is
* memory-intensive and is not appropriate for very large graphs.
*
* @param normalize whether to normalize the output.
*/
public Builder setNormalize(final boolean normalize) {
this.normalize = normalize;
return this;
}
/**
* Map of the data types of the vertex keys.
*/
public Builder setVertexKeyTypes(final Map<String, String> vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
return this;
}
/**
* Map of the data types of the edge keys.
*/
public Builder setEdgeKeyTypes(final Map<String, String> edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
return this;
}
public Builder setXmlSchemaLocation(final String xmlSchemaLocation) {
this.xmlSchemaLocation = xmlSchemaLocation;
return this;
}
/**
* Set the name of the edge label in the GraphML. When this value is not set the value of the Edge.getLabel()
* is written as a "label" attribute on the edge element. This does not validate against the GraphML schema.
* If this value is set then the the value of Edge.getLabel() is written as a data element on the edge and
* the appropriate key element is added to define it in the GraphML
*
* @param edgeLabelKey if the label of an edge will be handled by the data property.
*/
public Builder setEdgeLabelKey(final String edgeLabelKey) {
this.edgeLabelKey = edgeLabelKey;
return this;
}
public GraphMLWriter build() {
return new GraphMLWriter(g, normalize, vertexKeyTypes, edgeKeyTypes, xmlSchemaLocation, edgeLabelKey);
}
}
}
| blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java | package com.tinkerpop.blueprints.io.graphml;
import com.tinkerpop.blueprints.Direction;
import com.tinkerpop.blueprints.Edge;
import com.tinkerpop.blueprints.Graph;
import com.tinkerpop.blueprints.Vertex;
import com.tinkerpop.blueprints.io.GraphWriter;
import com.tinkerpop.blueprints.io.LexicographicalElementComparator;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* GraphMLWriter writes a Graph to a GraphML OutputStream.
*
* @author Marko A. Rodriguez (http://markorodriguez.com)
* @author Joshua Shinavier (http://fortytwo.net)
* @author Stephen Mallette (http://stephen.genoprime.com)
*/
public class GraphMLWriter implements GraphWriter {
private final Graph graph;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private String xmlSchemaLocation = null;
private Optional<String> edgeLabelKey;
/**
* @param graph the Graph to pull the data from
*/
private GraphMLWriter(final Graph graph, final boolean normalize, final Map<String, String> vertexKeyTypes,
final Map<String, String> edgeKeyTypes, final String xmlSchemaLocation,
final String edgeLabelKey) {
this.graph = graph;
this.normalize = normalize;
this.vertexKeyTypes = vertexKeyTypes;
this.edgeKeyTypes = edgeKeyTypes;
this.xmlSchemaLocation = xmlSchemaLocation;
this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
}
/**
* Write the data in a Graph to a GraphML OutputStream.
*
* @param outputStream the GraphML OutputStream to write the Graph data to
* @throws IOException thrown if there is an error generating the GraphML data
*/
@Override
public void outputGraph(final OutputStream outputStream) throws IOException {
if (null == vertexKeyTypes || null == edgeKeyTypes) {
Map<String, String> vertexKeyTypes = new HashMap<>();
Map<String, String> edgeKeyTypes = new HashMap<>();
for (Vertex vertex : graph.query().vertices()) {
for (String key : vertex.getPropertyKeys()) {
if (!vertexKeyTypes.containsKey(key)) {
vertexKeyTypes.put(key, GraphMLWriter.getStringType(vertex.getProperty(key).getValue()));
}
}
for (Edge edge : vertex.query().direction(Direction.OUT).edges()) {
for (String key : edge.getPropertyKeys()) {
if (!edgeKeyTypes.containsKey(key)) {
edgeKeyTypes.put(key, GraphMLWriter.getStringType(edge.getProperty(key).getValue()));
}
}
}
}
if (null == this.vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
}
if (null == this.edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
}
}
// adding the edge label key will push the label into the data portion of the graphml otherwise it
// will live with the edge data itself (which won't validate against the graphml schema)
if (this.edgeLabelKey.isPresent() && null != this.edgeKeyTypes && null == this.edgeKeyTypes.get(this.edgeLabelKey.get()))
this.edgeKeyTypes.put(this.edgeLabelKey.get(), GraphMLTokens.STRING);
final XMLOutputFactory inputFactory = XMLOutputFactory.newInstance();
try {
XMLStreamWriter writer = inputFactory.createXMLStreamWriter(outputStream, "UTF8");
if (normalize) {
writer = new GraphMLWriterHelper.IndentingXMLStreamWriter(writer);
((GraphMLWriterHelper.IndentingXMLStreamWriter) writer).setIndentStep(" ");
}
writer.writeStartDocument();
writer.writeStartElement(GraphMLTokens.GRAPHML);
writer.writeAttribute(GraphMLTokens.XMLNS, GraphMLTokens.GRAPHML_XMLNS);
//XML Schema instance namespace definition (xsi)
writer.writeAttribute(XMLConstants.XMLNS_ATTRIBUTE + ":" + GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG,
XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
//XML Schema location
writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
GraphMLTokens.GRAPHML_XMLNS + " " + (this.xmlSchemaLocation == null ?
GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION : this.xmlSchemaLocation));
// <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
Collection<String> keyset;
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(vertexKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else {
keyset = vertexKeyTypes.keySet();
}
for (String key : keyset) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, vertexKeyTypes.get(key));
writer.writeEndElement();
}
if (normalize) {
keyset = new ArrayList<>();
keyset.addAll(edgeKeyTypes.keySet());
Collections.sort((List<String>) keyset);
} else {
keyset = edgeKeyTypes.keySet();
}
for (String key : keyset) {
writer.writeStartElement(GraphMLTokens.KEY);
writer.writeAttribute(GraphMLTokens.ID, key);
writer.writeAttribute(GraphMLTokens.FOR, GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ATTR_NAME, key);
writer.writeAttribute(GraphMLTokens.ATTR_TYPE, edgeKeyTypes.get(key));
writer.writeEndElement();
}
writer.writeStartElement(GraphMLTokens.GRAPH);
writer.writeAttribute(GraphMLTokens.ID, GraphMLTokens.G);
writer.writeAttribute(GraphMLTokens.EDGEDEFAULT, GraphMLTokens.DIRECTED);
Iterable<Vertex> vertices;
if (normalize) {
vertices = new ArrayList<>();
for (Vertex v : graph.query().vertices()) {
((Collection<Vertex>) vertices).add(v);
}
Collections.sort((List<Vertex>) vertices, new LexicographicalElementComparator());
} else {
vertices = graph.query().vertices();
}
for (Vertex vertex : vertices) {
writer.writeStartElement(GraphMLTokens.NODE);
writer.writeAttribute(GraphMLTokens.ID, vertex.getId().toString());
Collection<String> keys;
if (normalize) {
keys = new ArrayList<>();
keys.addAll(vertex.getPropertyKeys());
Collections.sort((List<String>) keys);
} else {
keys = vertex.getPropertyKeys();
}
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = vertex.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
if (normalize) {
List<Edge> edges = new ArrayList<>();
for (Vertex vertex : graph.query().vertices()) {
for (Edge edge : vertex.query().direction(Direction.OUT).edges()) {
edges.add(edge);
}
}
Collections.sort(edges, new LexicographicalElementComparator());
for (Edge edge : edges) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
if (this.edgeLabelKey.isPresent()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, this.edgeLabelKey.get());
writer.writeCharacters(edge.getLabel());
writer.writeEndElement();
} else {
// this will not comply with the graphml schema but is here so that the label is not
// mixed up with properties.
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
}
final List<String> keys = new ArrayList<>();
keys.addAll(edge.getPropertyKeys());
Collections.sort(keys);
for (String key : keys) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
} else {
for (Vertex vertex : graph.query().vertices()) {
for (Edge edge : vertex.query().direction(Direction.OUT).edges()) {
writer.writeStartElement(GraphMLTokens.EDGE);
writer.writeAttribute(GraphMLTokens.ID, edge.getId().toString());
writer.writeAttribute(GraphMLTokens.SOURCE, edge.getVertex(Direction.OUT).getId().toString());
writer.writeAttribute(GraphMLTokens.TARGET, edge.getVertex(Direction.IN).getId().toString());
writer.writeAttribute(GraphMLTokens.LABEL, edge.getLabel());
for (String key : edge.getPropertyKeys()) {
writer.writeStartElement(GraphMLTokens.DATA);
writer.writeAttribute(GraphMLTokens.KEY, key);
Object value = edge.getProperty(key).getValue();
if (null != value) {
writer.writeCharacters(value.toString());
}
writer.writeEndElement();
}
writer.writeEndElement();
}
}
}
writer.writeEndElement(); // graph
writer.writeEndElement(); // graphml
writer.writeEndDocument();
writer.flush();
writer.close();
} catch (XMLStreamException xse) {
throw new IOException(xse);
}
}
private static String getStringType(final Object object) {
if (object instanceof String) {
return GraphMLTokens.STRING;
} else if (object instanceof Integer) {
return GraphMLTokens.INT;
} else if (object instanceof Long) {
return GraphMLTokens.LONG;
} else if (object instanceof Float) {
return GraphMLTokens.FLOAT;
} else if (object instanceof Double) {
return GraphMLTokens.DOUBLE;
} else if (object instanceof Boolean) {
return GraphMLTokens.BOOLEAN;
} else {
return GraphMLTokens.STRING;
}
}
public static final class Builder {
private final Graph g;
private boolean normalize = false;
private Map<String, String> vertexKeyTypes = null;
private Map<String, String> edgeKeyTypes = null;
private String xmlSchemaLocation = null;
private String edgeLabelKey = null;
public Builder(final Graph g) {
if (null == g)
throw new IllegalArgumentException("Graph argument cannot be null");
this.g = g;
}
/**
* Normalized output is deterministic with respect to the order of elements and properties in the resulting
* XML document, and is compatible with line diff-based tools such as Git. Note: normalized output is
* memory-intensive and is not appropriate for very large graphs.
*
* @param normalize whether to normalize the output.
*/
public Builder setNormalize(final boolean normalize) {
this.normalize = normalize;
return this;
}
/**
* Map of the data types of the vertex keys.
*/
public Builder setVertexKeyTypes(final Map<String, String> vertexKeyTypes) {
this.vertexKeyTypes = vertexKeyTypes;
return this;
}
/**
* Map of the data types of the edge keys.
*/
public Builder setEdgeKeyTypes(final Map<String, String> edgeKeyTypes) {
this.edgeKeyTypes = edgeKeyTypes;
return this;
}
public Builder setXmlSchemaLocation(final String xmlSchemaLocation) {
this.xmlSchemaLocation = xmlSchemaLocation;
return this;
}
/**
* Set the name of the edge label in the GraphML. When this value is not set the value of the Edge.getLabel()
* is written as a "label" attribute on the edge element. This does not validate against the GraphML schema.
* If this value is set then the the value of Edge.getLabel() is written as a data element on the edge and
* the appropriate key element is added to define it in the GraphML
*
* @param edgeLabelKey if the label of an edge will be handled by the data property.
*/
public Builder setEdgeLabelKey(final String edgeLabelKey) {
this.edgeLabelKey = edgeLabelKey;
return this;
}
public GraphMLWriter build() {
return new GraphMLWriter(g, normalize, vertexKeyTypes, edgeKeyTypes, xmlSchemaLocation, edgeLabelKey);
}
}
}
| Convert XMLSchemaLocation setting to Optional in GraphMLWriter.
| blueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java | Convert XMLSchemaLocation setting to Optional in GraphMLWriter. | <ide><path>lueprints/blueprints-io/src/main/java/com/tinkerpop/blueprints/io/graphml/GraphMLWriter.java
<ide> private Map<String, String> vertexKeyTypes = null;
<ide> private Map<String, String> edgeKeyTypes = null;
<ide>
<del> private String xmlSchemaLocation = null;
<add> private Optional<String> xmlSchemaLocation;
<ide> private Optional<String> edgeLabelKey;
<ide>
<ide> /**
<ide> this.normalize = normalize;
<ide> this.vertexKeyTypes = vertexKeyTypes;
<ide> this.edgeKeyTypes = edgeKeyTypes;
<del> this.xmlSchemaLocation = xmlSchemaLocation;
<add> this.xmlSchemaLocation = Optional.ofNullable(xmlSchemaLocation);
<ide> this.edgeLabelKey = Optional.ofNullable(edgeLabelKey);
<ide> }
<ide>
<ide> XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);
<ide> //XML Schema location
<ide> writer.writeAttribute(GraphMLTokens.XML_SCHEMA_NAMESPACE_TAG + ":" + GraphMLTokens.XML_SCHEMA_LOCATION_ATTRIBUTE,
<del> GraphMLTokens.GRAPHML_XMLNS + " " + (this.xmlSchemaLocation == null ?
<del> GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION : this.xmlSchemaLocation));
<add> GraphMLTokens.GRAPHML_XMLNS + " " + this.xmlSchemaLocation.orElse(GraphMLTokens.DEFAULT_GRAPHML_SCHEMA_LOCATION));
<ide>
<ide> // <key id="weight" for="edge" attr.name="weight" attr.type="float"/>
<ide> Collection<String> keyset; |
|
Java | mit | c4d909689e6f071278c63c4625508e3fc02b2a86 | 0 | mitdbg/modeldb,mitdbg/modeldb,mitdbg/modeldb,mitdbg/modeldb,mitdbg/modeldb | package edu.mit.csail.db.ml.server.algorithm.similarity;
import edu.mit.csail.db.ml.server.algorithm.similarity.comparators.*;
import edu.mit.csail.db.ml.server.storage.TransformerDao;
import jooq.sqlite.gen.Tables;
import jooq.sqlite.gen.tables.records.LinearmodelRecord;
import modeldb.BadRequestException;
import modeldb.ModelCompMetric;
import modeldb.ResourceNotFoundException;
import org.jooq.DSLContext;
import org.jooq.TableField;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
* This exposes the similarModels method that allows finding models similar to a model with a given ID.
*/
public class SimilarModels {
// TODO: Should this go into the conf file?
private static final int MODEL_LIMIT = 1000;
/**
* This creates the appropriate ModelComparator object for a given comparison metric.
* @param compMetric - The model comparison metric.
* @return The ModelComparator object that corresponds to the compMetric.
*/
private static ModelComparator comparatorForCompMetric(ModelCompMetric compMetric) {
switch (compMetric) {
case MODEL_TYPE: return new TransformerTypeComparator();
case PROBLEM_TYPE: return new ProblemTypeComparator();
case EXPERIMENT_RUN: return new ExperimentRunComparator();
case PROJECT: return new ProjectComparator();
case RMSE: return new LinearModelComparator() {
@Override
public TableField<LinearmodelRecord, Double> getComparisonField() {
return Tables.LINEARMODEL.RMSE;
}
};
case EXPLAINED_VARIANCE: return new LinearModelComparator() {
@Override
public TableField<LinearmodelRecord, Double> getComparisonField() {
return Tables.LINEARMODEL.EXPLAINEDVARIANCE;
}
};
case R2: return new LinearModelComparator() {
@Override
public TableField<LinearmodelRecord, Double> getComparisonField() {
return Tables.LINEARMODEL.R2;
}
};
default: return new DummyComparator();
}
}
/**
* Find the models similar to the model with the given ID.
* @param modelId - The ID of the given model. This method will find models similar to this model.
* @param compMetrics - The metrics by which to measure similarity. The first metric is the most important and thus
* models that are most similar according to this metric will be first in the returned list. Each
* successive metric is used to break ties in the previous metric.
* @param numModels - The maximum number of models that should be returned.
* @param ctx - The context for accessing the database.
* @return The IDs of similar models, with the most similar model first and successively less similar
* models following.
*/
public static List<Integer> similarModels(
int modelId,
List<ModelCompMetric> compMetrics,
int numModels,
DSLContext ctx
) throws ResourceNotFoundException, BadRequestException {
// Fail if modelID doesn't exist.
if (!TransformerDao.exists(modelId, ctx)) {
throw new ResourceNotFoundException(String.format(
"Cannot find models similar to Transformer %d because that Transformer does not exist",
modelId
));
}
// Fail if number of models is invalid.
if (numModels <= 0) {
throw new BadRequestException(String.format(
"You can't ask for %d similar models, you must request a positive number of models",
numModels
));
}
// Find the similar models.
List<Integer> resultingModels = compMetrics
.stream()
.map(SimilarModels::comparatorForCompMetric)
.reduce(
Collections.<Integer>emptyList(),
(partial, comparator) -> comparator.similarModels(modelId, partial, MODEL_LIMIT, ctx),
(oldModels, newModels) -> newModels
)
.stream()
.filter(s -> !s.equals(modelId))
.collect(Collectors.toList());
// Return at most numModels models.
return resultingModels.subList(0, Math.min(resultingModels.size(), numModels));
}
}
| server/src/main/java/edu/mit/csail/db/ml/server/algorithm/similarity/SimilarModels.java | package edu.mit.csail.db.ml.server.algorithm.similarity;
import edu.mit.csail.db.ml.server.algorithm.similarity.comparators.*;
import edu.mit.csail.db.ml.server.storage.TransformerDao;
import jooq.sqlite.gen.Tables;
import jooq.sqlite.gen.tables.records.LinearmodelRecord;
import modeldb.BadRequestException;
import modeldb.ModelCompMetric;
import modeldb.ResourceNotFoundException;
import org.jooq.DSLContext;
import org.jooq.TableField;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SimilarModels {
// TODO: Should this go into the conf file?
private static final int MODEL_LIMIT = 1000;
private static ModelComparator comparatorForCompMetric(ModelCompMetric compMetric) {
switch (compMetric) {
case MODEL_TYPE: return new TransformerTypeComparator();
case PROBLEM_TYPE: return new ProblemTypeComparator();
case EXPERIMENT_RUN: return new ExperimentRunComparator();
case PROJECT: return new ProjectComparator();
case RMSE: return new LinearModelComparator() {
@Override
public TableField<LinearmodelRecord, Double> getComparisonField() {
return Tables.LINEARMODEL.RMSE;
}
};
case EXPLAINED_VARIANCE: return new LinearModelComparator() {
@Override
public TableField<LinearmodelRecord, Double> getComparisonField() {
return Tables.LINEARMODEL.EXPLAINEDVARIANCE;
}
};
case R2: return new LinearModelComparator() {
@Override
public TableField<LinearmodelRecord, Double> getComparisonField() {
return Tables.LINEARMODEL.R2;
}
};
default: return new DummyComparator();
}
}
public static List<Integer> similarModels(
int modelId,
List<ModelCompMetric> compMetrics,
int numModels,
DSLContext ctx
) throws ResourceNotFoundException, BadRequestException {
if (!TransformerDao.exists(modelId, ctx)) {
throw new ResourceNotFoundException(String.format(
"Cannot find models similar to Transformer %d because that Transformer does not exist",
modelId
));
}
if (numModels <= 0) {
throw new BadRequestException(String.format(
"You can't ask for %d similar models, you must request a positive number of models",
numModels
));
}
List<Integer> resultingModels = compMetrics
.stream()
.map(SimilarModels::comparatorForCompMetric)
.reduce(
Collections.<Integer>emptyList(),
(partial, comparator) -> comparator.similarModels(modelId, partial, MODEL_LIMIT, ctx),
(oldModels, newModels) -> newModels
)
.stream()
.filter(s -> !s.equals(modelId))
.collect(Collectors.toList());
return resultingModels.subList(0, Math.min(resultingModels.size(), numModels));
}
}
| Comment similarModels
| server/src/main/java/edu/mit/csail/db/ml/server/algorithm/similarity/SimilarModels.java | Comment similarModels | <ide><path>erver/src/main/java/edu/mit/csail/db/ml/server/algorithm/similarity/SimilarModels.java
<ide> import java.util.List;
<ide> import java.util.stream.Collectors;
<ide>
<add>/**
<add> * This exposes the similarModels method that allows finding models similar to a model with a given ID.
<add> */
<ide> public class SimilarModels {
<ide> // TODO: Should this go into the conf file?
<ide> private static final int MODEL_LIMIT = 1000;
<ide>
<add> /**
<add> * This creates the appropriate ModelComparator object for a given comparison metric.
<add> * @param compMetric - The model comparison metric.
<add> * @return The ModelComparator object that corresponds to the compMetric.
<add> */
<ide> private static ModelComparator comparatorForCompMetric(ModelCompMetric compMetric) {
<ide> switch (compMetric) {
<ide> case MODEL_TYPE: return new TransformerTypeComparator();
<ide> }
<ide> }
<ide>
<add> /**
<add> * Find the models similar to the model with the given ID.
<add> * @param modelId - The ID of the given model. This method will find models similar to this model.
<add> * @param compMetrics - The metrics by which to measure similarity. The first metric is the most important and thus
<add> * models that are most similar according to this metric will be first in the returned list. Each
<add> * successive metric is used to break ties in the previous metric.
<add> * @param numModels - The maximum number of models that should be returned.
<add> * @param ctx - The context for accessing the database.
<add> * @return The IDs of similar models, with the most similar model first and successively less similar
<add> * models following.
<add> */
<ide> public static List<Integer> similarModels(
<ide> int modelId,
<ide> List<ModelCompMetric> compMetrics,
<ide> int numModels,
<ide> DSLContext ctx
<ide> ) throws ResourceNotFoundException, BadRequestException {
<add> // Fail if modelID doesn't exist.
<ide> if (!TransformerDao.exists(modelId, ctx)) {
<ide> throw new ResourceNotFoundException(String.format(
<ide> "Cannot find models similar to Transformer %d because that Transformer does not exist",
<ide> modelId
<ide> ));
<ide> }
<add>
<add> // Fail if number of models is invalid.
<ide> if (numModels <= 0) {
<ide> throw new BadRequestException(String.format(
<ide> "You can't ask for %d similar models, you must request a positive number of models",
<ide> numModels
<ide> ));
<ide> }
<add>
<add> // Find the similar models.
<ide> List<Integer> resultingModels = compMetrics
<ide> .stream()
<ide> .map(SimilarModels::comparatorForCompMetric)
<ide> .stream()
<ide> .filter(s -> !s.equals(modelId))
<ide> .collect(Collectors.toList());
<add>
<add> // Return at most numModels models.
<ide> return resultingModels.subList(0, Math.min(resultingModels.size(), numModels));
<ide> }
<ide> } |
|
Java | apache-2.0 | 3588f05ed54efd42b719b2873bde49d65d8293a6 | 0 | rmuir/randomizedtesting,randomizedtesting/randomizedtesting,rmuir/randomizedtesting,carrotsearch/randomizedtesting,rmuir/randomizedtesting,carrotsearch/randomizedtesting,javanna/randomizedtesting,randomizedtesting/randomizedtesting,randomizedtesting/randomizedtesting,carrotsearch/randomizedtesting,javanna/randomizedtesting,carrotsearch/randomizedtesting,randomizedtesting/randomizedtesting,carrotsearch/randomizedtesting,rmuir/randomizedtesting,rmuir/randomizedtesting,javanna/randomizedtesting,javanna/randomizedtesting,randomizedtesting/randomizedtesting | package com.carrotsearch.ant.tasks.junit4.listeners;
import java.io.IOException;
import java.io.Writer;
/**
* Prefixes every new line with a given byte [], synchronizing multiple streams to emit consistent lines.
*/
class PrefixedWriter extends Writer {
private final static char LF = '\n';
private final Writer sink;
private final String prefix;
private final StringBuilder lineBuffer = new StringBuilder();
private final int maxLineLength;
public PrefixedWriter(String prefix, Writer sink, int maxLineLength) {
super(sink);
this.sink = sink;
this.prefix = prefix;
this.maxLineLength = maxLineLength;
}
@Override
public void write(int c) throws IOException {
if (lineBuffer.length() == maxLineLength || c == LF) {
sink.write(prefix);
sink.write(lineBuffer.toString());
sink.write(LF);
lineBuffer.setLength(0);
if (c != LF) {
lineBuffer.append((char) c);
}
} else {
lineBuffer.append((char) c);
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
for (int i = off; i < off + len; i++) {
write(cbuf[i]);
}
}
@Override
public void flush() throws IOException {
// don't pass flushes.
}
@Override
public void close() throws IOException {
throw new UnsupportedOperationException();
}
/**
* Complete the current line.
*/
public void completeLine() throws IOException {
if (lineBuffer.length() > 0) {
write(LF);
}
}
}
| junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/PrefixedWriter.java | package com.carrotsearch.ant.tasks.junit4.listeners;
import java.io.IOException;
import java.io.Writer;
/**
* Prefixes every new line with a given byte [], synchronizing multiple streams to emit consistent lines.
*/
class PrefixedWriter extends Writer {
private final static char LF = '\n';
private final Writer sink;
private final String prefix;
private final StringBuilder lineBuffer = new StringBuilder();
private final int maxLineLength;
public PrefixedWriter(String prefix, Writer sink, int maxLineLength) {
super(sink);
this.sink = sink;
this.prefix = prefix;
this.maxLineLength = maxLineLength;
}
@Override
public void write(int c) throws IOException {
if (lineBuffer.length() == maxLineLength || c == LF) {
sink.write(prefix);
sink.write(lineBuffer.toString());
sink.write(LF);
lineBuffer.setLength(0);
if (c != LF) {
lineBuffer.append((char) c);
}
} else {
lineBuffer.append((char) c);
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
for (int i = off; i < off + len; i++) {
write(cbuf[i]);
}
}
@Override
public void flush() throws IOException {
sink.flush();
}
@Override
public void close() throws IOException {
throw new UnsupportedOperationException();
}
/**
* Complete the current line.
*/
public void completeLine() throws IOException {
if (lineBuffer.length() > 0) {
write(LF);
}
}
}
| Don't pass flushes immediately.
| junit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/PrefixedWriter.java | Don't pass flushes immediately. | <ide><path>unit4-ant/src/main/java/com/carrotsearch/ant/tasks/junit4/listeners/PrefixedWriter.java
<ide>
<ide> @Override
<ide> public void flush() throws IOException {
<del> sink.flush();
<add> // don't pass flushes.
<ide> }
<ide>
<ide> @Override |
|
Java | bsd-3-clause | f985c6352b305e7c82cfa786e76222128724465e | 0 | dyanarose/jsonld-java,giorgos1987/jsonld-java,westei/jsonld-java,westei/jsonld-java,giorgos1987/jsonld-java,tristan/jsonld-java,jsonld-java/jsonld-java,dyanarose/jsonld-java,tristan/jsonld-java | package com.github.jsonldjava.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.openrdf.model.BNode;
import org.openrdf.model.Graph;
import org.openrdf.model.Literal;
import org.openrdf.model.Model;
import org.openrdf.model.Namespace;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import com.github.jsonldjava.core.JSONLDProcessingError;
import com.github.jsonldjava.core.RDFDatasetUtils;
public class SesameRDFParser implements
com.github.jsonldjava.core.RDFParser {
public void setPrefix(String fullUri, String prefix) {
// TODO: graphs?
//_context.put(prefix, fullUri);
}
@SuppressWarnings("deprecation")
public void importGraph(Graph model, Resource... contexts) {
Map<String,Object> result = RDFDatasetUtils.getInitialRDFDatasetResult();
if(model instanceof Model) {
Set<Namespace> namespaces = ((Model) model).getNamespaces();
for (Namespace nextNs : namespaces) {
setPrefix(nextNs.getName(), nextNs.getPrefix());
}
}
Iterator<Statement> statements = model
.match(null, null, null, contexts);
while (statements.hasNext()) {
handleStatement(result, statements.next());
}
// TODO: return something? i'm leaving this to Ansell to fix up to match his requirements
}
public void handleStatement(Map<String,Object> result, Statement nextStatement) {
// TODO: from a basic look at the code it seems some of these could be null
// null values for IRIs will probably break things further down the line
// and i'm not sure yet if this should be something handled later on, or
// something that should be checked here
final String subject = getResourceValue(nextStatement.getSubject());
final String predicate = getResourceValue(nextStatement.getPredicate());
final Value object = nextStatement.getObject();
final String graphName = getResourceValue(nextStatement.getContext());
if (object instanceof Literal) {
Literal literal = (Literal) object;
String value = literal.getLabel();
String language = literal.getLanguage();
String datatype = getResourceValue(literal.getDatatype());
RDFDatasetUtils.addTripleToRDFDatasetResult(result, graphName,
RDFDatasetUtils.generateTriple(subject, predicate, value, datatype, language));
} else {
RDFDatasetUtils.addTripleToRDFDatasetResult(result, graphName,
RDFDatasetUtils.generateTriple(subject, predicate, getResourceValue((Resource)object)));
}
}
private String getResourceValue(Resource subject) {
if (subject == null) {
return null;
} else if (subject instanceof URI) {
return subject.stringValue();
} else if (subject instanceof BNode) {
return "_:" + subject.stringValue();
}
throw new IllegalStateException("Did not recognise resource type: "
+ subject.getClass().getName());
}
@Override
public Map<String,Object> parse(Object input) throws JSONLDProcessingError {
Map<String,Object> result = RDFDatasetUtils.getInitialRDFDatasetResult();
if (input instanceof Statement) {
handleStatement(result, (Statement) input);
} else if (input instanceof Graph) {
for (Statement nextStatement : (Graph) input) {
handleStatement(result, nextStatement);
}
}
return result;
}
}
| integration/sesame/src/main/java/com/github/jsonldjava/impl/SesameRDFParser.java | package com.github.jsonldjava.impl;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.openrdf.model.BNode;
import org.openrdf.model.Graph;
import org.openrdf.model.Literal;
import org.openrdf.model.Resource;
import org.openrdf.model.Statement;
import org.openrdf.model.URI;
import org.openrdf.model.Value;
import com.github.jsonldjava.core.JSONLDProcessingError;
import com.github.jsonldjava.core.RDFDatasetUtils;
public class SesameRDFParser implements
com.github.jsonldjava.core.RDFParser {
@SuppressWarnings("deprecation")
public void importGraph(Graph model, Resource... contexts) {
Map<String,Object> result = RDFDatasetUtils.getInitialRDFDatasetResult();
Iterator<Statement> statements = model
.match(null, null, null, contexts);
while (statements.hasNext()) {
handleStatement(result, statements.next());
}
// TODO: return something? i'm leaving this to Ansell to fix up to match his requirements
}
public void handleStatement(Map<String,Object> result, Statement nextStatement) {
// TODO: from a basic look at the code it seems some of these could be null
// null values for IRIs will probably break things further down the line
// and i'm not sure yet if this should be something handled later on, or
// something that should be checked here
final String subject = getResourceValue(nextStatement.getSubject());
final String predicate = getResourceValue(nextStatement.getPredicate());
final Value object = nextStatement.getObject();
final String graphName = getResourceValue(nextStatement.getContext());
if (object instanceof Literal) {
Literal literal = (Literal) object;
String value = literal.getLabel();
String language = literal.getLanguage();
String datatype = getResourceValue(literal.getDatatype());
RDFDatasetUtils.addTripleToRDFDatasetResult(result, graphName,
RDFDatasetUtils.generateTriple(subject, predicate, value, datatype, language));
} else {
RDFDatasetUtils.addTripleToRDFDatasetResult(result, graphName,
RDFDatasetUtils.generateTriple(subject, predicate, getResourceValue((Resource)object)));
}
}
private String getResourceValue(Resource subject) {
if (subject == null) {
return null;
} else if (subject instanceof URI) {
return subject.stringValue();
} else if (subject instanceof BNode) {
return "_:" + subject.stringValue();
}
throw new IllegalStateException("Did not recognise resource type: "
+ subject.getClass().getName());
}
@Override
public Map<String,Object> parse(Object input) throws JSONLDProcessingError {
Map<String,Object> result = RDFDatasetUtils.getInitialRDFDatasetResult();
if (input instanceof Statement) {
handleStatement(result, (Statement) input);
} else if (input instanceof Graph) {
for (Statement nextStatement : (Graph) input) {
handleStatement(result, nextStatement);
}
}
return result;
}
}
| Add stub support for namespaces passing through in similar way to Jena
strategy | integration/sesame/src/main/java/com/github/jsonldjava/impl/SesameRDFParser.java | Add stub support for namespaces passing through in similar way to Jena strategy | <ide><path>ntegration/sesame/src/main/java/com/github/jsonldjava/impl/SesameRDFParser.java
<ide> import java.util.LinkedHashMap;
<ide> import java.util.List;
<ide> import java.util.Map;
<add>import java.util.Set;
<ide>
<ide> import org.openrdf.model.BNode;
<ide> import org.openrdf.model.Graph;
<ide> import org.openrdf.model.Literal;
<add>import org.openrdf.model.Model;
<add>import org.openrdf.model.Namespace;
<ide> import org.openrdf.model.Resource;
<ide> import org.openrdf.model.Statement;
<ide> import org.openrdf.model.URI;
<ide> public class SesameRDFParser implements
<ide> com.github.jsonldjava.core.RDFParser {
<ide>
<add> public void setPrefix(String fullUri, String prefix) {
<add> // TODO: graphs?
<add> //_context.put(prefix, fullUri);
<add> }
<add>
<ide> @SuppressWarnings("deprecation")
<ide> public void importGraph(Graph model, Resource... contexts) {
<ide> Map<String,Object> result = RDFDatasetUtils.getInitialRDFDatasetResult();
<add>
<add> if(model instanceof Model) {
<add> Set<Namespace> namespaces = ((Model) model).getNamespaces();
<add> for (Namespace nextNs : namespaces) {
<add> setPrefix(nextNs.getName(), nextNs.getPrefix());
<add> }
<add> }
<add>
<ide> Iterator<Statement> statements = model
<ide> .match(null, null, null, contexts);
<ide> while (statements.hasNext()) { |
|
Java | apache-2.0 | b24fb46e0739f15f874713d7c7a41c31571a1724 | 0 | Rauks/PixelRunner | package org.game.runner;
import android.view.KeyEvent;
import java.io.IOException;
import org.andengine.engine.Engine;
import org.andengine.engine.LimitedFPSEngine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.util.FPSLogger;
import org.andengine.ui.activity.BaseGameActivity;
import org.game.runner.manager.AudioManager;
import org.game.runner.manager.ResourcesManager;
import org.game.runner.manager.SceneManager;
import org.andengine.util.debug.Debug;
public class GameActivity extends BaseGameActivity{
public static float CAMERA_WIDTH = 800;
public static float CAMERA_HEIGHT = 480;
private android.media.AudioManager phoneAudioManager;
private Camera camera;
private ResourcesManager resourcesManager;
private SceneManager sceneManager;
private boolean isEnginePaused = false;
@Override
public EngineOptions onCreateEngineOptions() {
this.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(800, 480), this.camera);
engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
@Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {
return new LimitedFPSEngine(pEngineOptions, 60);
}
@Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException {
ResourcesManager.prepareManager(this.mEngine, this, this.camera, getVertexBufferObjectManager());
this.resourcesManager = ResourcesManager.getInstance();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException {
SceneManager.getInstance().createLoadingScene(pOnCreateSceneCallback);
}
@Override
public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException {
this.mEngine.enableVibrator(this);
this.mEngine.registerUpdateHandler(new FPSLogger());
this.phoneAudioManager = (android.media.AudioManager)getSystemService(AUDIO_SERVICE);
this.mEngine.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback(){
@Override
public void onTimePassed(final TimerHandler pTimerHandler){
GameActivity.this.mEngine.unregisterUpdateHandler(pTimerHandler);
SceneManager.getInstance().createSplashScene();
}
}));
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (this.isGameLoaded()){
AudioManager.getInstance().stop();
System.exit(0);
}
}
@Override
public synchronized void onPauseGame() {
super.onPauseGame();
Debug.d("PIXEL : PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE");
if (this.isGameLoaded()){
SceneManager.getInstance().getCurrentScene().onPause();
}
this.isEnginePaused = true;
}
@Override
public void onResumeGame() {
super.onResumeGame();
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
}
return false;
}
@Override
public void onWindowFocusChanged(final boolean pHasWindowFocus) {
super.onWindowFocusChanged(pHasWindowFocus);
Debug.d("PIXEL : RESUME RESUME RESUME RESUME RESUME RESUME RESUME RESUME");
if (pHasWindowFocus && this.isEnginePaused) {
this.isEnginePaused = false;
if (this.isGameLoaded()){
SceneManager.getInstance().getCurrentScene().onResume();
}
}
}
public void vibrate(long pMilliseconds){
if(!this.isMute()){
this.mEngine.vibrate(pMilliseconds);
}
}
public void vibrate(long[] pMillisecondsPattern){
if(!this.isMute()){
this.mEngine.vibrate(pMillisecondsPattern, -1);
}
}
public boolean isMute(){
return this.phoneAudioManager.getStreamVolume(android.media.AudioManager.STREAM_MUSIC) == 0;
}
}
| src/org/game/runner/GameActivity.java | package org.game.runner;
import android.view.KeyEvent;
import java.io.IOException;
import org.andengine.engine.Engine;
import org.andengine.engine.LimitedFPSEngine;
import org.andengine.engine.camera.Camera;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.WakeLockOptions;
import org.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.util.FPSLogger;
import org.andengine.ui.activity.BaseGameActivity;
import org.game.runner.manager.AudioManager;
import org.game.runner.manager.ResourcesManager;
import org.game.runner.manager.SceneManager;
public class GameActivity extends BaseGameActivity{
public static float CAMERA_WIDTH = 800;
public static float CAMERA_HEIGHT = 480;
private android.media.AudioManager phoneAudioManager;
private Camera camera;
private ResourcesManager resourcesManager;
private SceneManager sceneManager;
@Override
public EngineOptions onCreateEngineOptions() {
this.camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(800, 480), this.camera);
engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
@Override
public Engine onCreateEngine(EngineOptions pEngineOptions) {
return new LimitedFPSEngine(pEngineOptions, 60);
}
@Override
public void onCreateResources(OnCreateResourcesCallback pOnCreateResourcesCallback) throws IOException {
ResourcesManager.prepareManager(this.mEngine, this, this.camera, getVertexBufferObjectManager());
this.resourcesManager = ResourcesManager.getInstance();
pOnCreateResourcesCallback.onCreateResourcesFinished();
}
@Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback) throws IOException {
SceneManager.getInstance().createLoadingScene(pOnCreateSceneCallback);
}
@Override
public void onPopulateScene(Scene pScene, OnPopulateSceneCallback pOnPopulateSceneCallback) throws IOException {
this.mEngine.enableVibrator(this);
this.mEngine.registerUpdateHandler(new FPSLogger());
this.phoneAudioManager = (android.media.AudioManager)getSystemService(AUDIO_SERVICE);
this.mEngine.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback(){
@Override
public void onTimePassed(final TimerHandler pTimerHandler){
GameActivity.this.mEngine.unregisterUpdateHandler(pTimerHandler);
SceneManager.getInstance().createSplashScene();
}
}));
pOnPopulateSceneCallback.onPopulateSceneFinished();
}
@Override
protected void onDestroy() {
super.onDestroy();
if (this.isGameLoaded()){
AudioManager.getInstance().stop();
System.exit(0);
}
}
@Override
public synchronized void onPauseGame() {
super.onPauseGame();
if (this.isGameLoaded()){
SceneManager.getInstance().getCurrentScene().onPause();
}
}
@Override
public synchronized void onResumeGame() {
super.onResumeGame();
if (this.isGameLoaded()){
SceneManager.getInstance().getCurrentScene().onResume();
}
}
@Override
protected void onPause() {
super.onPause();
if (this.isGameLoaded()){
SceneManager.getInstance().getCurrentScene().onPause();
}
}
@Override
protected synchronized void onResume() {
super.onResume();
if (this.isGameLoaded()){
SceneManager.getInstance().getCurrentScene().onResume();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK){
SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
}
return false;
}
public void vibrate(long pMilliseconds){
if(!this.isMute()){
this.mEngine.vibrate(pMilliseconds);
}
}
public void vibrate(long[] pMillisecondsPattern){
if(!this.isMute()){
this.mEngine.vibrate(pMillisecondsPattern, -1);
}
}
public boolean isMute(){
return this.phoneAudioManager.getStreamVolume(android.media.AudioManager.STREAM_MUSIC) == 0;
}
}
| Fix pause & resume audio playback (zombie phone)
| src/org/game/runner/GameActivity.java | Fix pause & resume audio playback (zombie phone) | <ide><path>rc/org/game/runner/GameActivity.java
<ide> import org.game.runner.manager.AudioManager;
<ide> import org.game.runner.manager.ResourcesManager;
<ide> import org.game.runner.manager.SceneManager;
<add>import org.andengine.util.debug.Debug;
<ide>
<ide> public class GameActivity extends BaseGameActivity{
<ide> public static float CAMERA_WIDTH = 800;
<ide> private Camera camera;
<ide> private ResourcesManager resourcesManager;
<ide> private SceneManager sceneManager;
<add> private boolean isEnginePaused = false;
<ide>
<ide> @Override
<ide> public EngineOptions onCreateEngineOptions() {
<ide> @Override
<ide> public synchronized void onPauseGame() {
<ide> super.onPauseGame();
<add> Debug.d("PIXEL : PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE PAUSE");
<ide> if (this.isGameLoaded()){
<ide> SceneManager.getInstance().getCurrentScene().onPause();
<ide> }
<add> this.isEnginePaused = true;
<add> }
<add>
<add> @Override
<add> public void onResumeGame() {
<add> super.onResumeGame();
<ide> }
<ide>
<del> @Override
<del> public synchronized void onResumeGame() {
<del> super.onResumeGame();
<del> if (this.isGameLoaded()){
<del> SceneManager.getInstance().getCurrentScene().onResume();
<del> }
<del> }
<del> @Override
<del> protected void onPause() {
<del> super.onPause();
<del> if (this.isGameLoaded()){
<del> SceneManager.getInstance().getCurrentScene().onPause();
<del> }
<del> }
<del>
<del> @Override
<del> protected synchronized void onResume() {
<del> super.onResume();
<del> if (this.isGameLoaded()){
<del> SceneManager.getInstance().getCurrentScene().onResume();
<del> }
<del> }
<ide> @Override
<ide> public boolean onKeyDown(int keyCode, KeyEvent event) {
<ide> if (keyCode == KeyEvent.KEYCODE_BACK){
<ide> SceneManager.getInstance().getCurrentScene().onBackKeyPressed();
<ide> }
<ide> return false;
<add> }
<add>
<add> @Override
<add> public void onWindowFocusChanged(final boolean pHasWindowFocus) {
<add> super.onWindowFocusChanged(pHasWindowFocus);
<add> Debug.d("PIXEL : RESUME RESUME RESUME RESUME RESUME RESUME RESUME RESUME");
<add> if (pHasWindowFocus && this.isEnginePaused) {
<add> this.isEnginePaused = false;
<add> if (this.isGameLoaded()){
<add> SceneManager.getInstance().getCurrentScene().onResume();
<add> }
<add> }
<ide> }
<ide>
<ide> public void vibrate(long pMilliseconds){ |
|
Java | mit | b3bc7750208886460827b5bc4cfa3ef2f3f4f131 | 0 | wyrzyk/atlassian-connect-plugin-archetype,wyrzyk/atlassian-connect-plugin-archetype | package it.wyrzyk.archetypes.web.lifecycle;
import com.jayway.restassured.module.mockmvc.response.MockMvcResponse;
import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import wyrzyk.archetypes.config.WebConfiguration;
import wyrzyk.archetypes.web.lifecycle.LifecycleService;
import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.assertj.core.api.Assertions.assertThat;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfiguration.class})
public class LifecycleResourceTest {
private static final String LIFECYCLE_PATH = "/lifecycle";
private static final String LIFECYCLE_INSTALLED_PATH = LIFECYCLE_PATH + "/installed";
private static final String LIFECYCLE_ENABLED_PATH = LIFECYCLE_PATH + "/enabled";
private static final String LIFECYCLE_DISABLED_PATH = LIFECYCLE_PATH + "/disabled";
private static final String LIFECYCLE_UNINSTALLED_PATH = LIFECYCLE_PATH + "/uninstalled";
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private LifecycleService lifecycleService;
private MockMvcRequestSpecification mockMvc;
@Before
public void setupMockMvc() {
mockMvc = given().webAppContextSetup(webApplicationContext);
}
@Test
@Transactional
@Rollback(true)
public void testIfInstalledMethodReturns200or204() throws Exception {
createInstalled(prepareDefaultRequestBuilder().build())
.then()
.statusCode(Matchers.isOneOf(200, 204));
}
@Test
@Transactional
@Rollback(true)
public void testIfInitializePayloadSaved() throws Exception {
assertThat(lifecycleService.countClients()).isZero();
createInstalled(prepareDefaultRequestBuilder()
.clientKey("clientKey")
.build());
assertThat(lifecycleService.countClients())
.isEqualTo(1);
assertThat(lifecycleService.findClient("clientKey")).isNotEmpty();
}
@Test
@Transactional
@Rollback(true)
public void testTwoPayloadsSaved() throws Exception {
assertThat(lifecycleService.countClients()).isZero();
createInstalled(prepareDefaultRequestBuilder()
.clientKey("1")
.build());
createInstalled(prepareDefaultRequestBuilder()
.clientKey("2")
.build());
assertThat(lifecycleService.countClients())
.isEqualTo(2);
assertThat(lifecycleService.findClient("1")).isNotEmpty();
assertThat(lifecycleService.findClient("2")).isNotEmpty();
}
@Test
@Transactional
@Rollback(true)
public void testIfPayloadIsUpdated() throws Exception { //todo: determine if it's a bug or expected behaviour
assertThat(lifecycleService.countClients()).isZero();
createInstalled(prepareDefaultRequestBuilder()
.clientKey("1")
.sharedSecret("old")
.build());
createInstalled(prepareDefaultRequestBuilder()
.sharedSecret("new")
.clientKey("1")
.build());
assertThat(lifecycleService.countClients())
.isEqualTo(1);
assertThat(lifecycleService.findClient("1")).isNotEmpty();
assertThat(lifecycleService.findClient("1").get().getSharedSecret()).isEqualTo("new");
}
@Test
@Transactional
@Rollback(true)
public void testWholeLifecycle() throws Exception {
assertThat(lifecycleService.countClients()).isZero();
final String clientKey = "clientKey";
final LifecycleRequestMock preparedRequest = prepareDefaultRequestBuilder()
.clientKey(clientKey)
.build();
createInstalled(preparedRequest);
assertThat(lifecycleService.isInstalled(clientKey)).isTrue();
assertThat(lifecycleService.isEnabled(clientKey)).isFalse();
createLifecycleRequest(LIFECYCLE_ENABLED_PATH, preparedRequest, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJxc2giOiJiNGYzMjJmNGRkMjQ2OTFiYmViNjZhZjkwZmNiZWE0MjAxMDkyMDA5YmM2MzA0MDc0YTg5NGRjMTQyOWFhOTA2IiwiaXNzIjoiamlyYTo1ZDQzMWQ5Yy0zZWU4LTQyNmEtYjM2NS1mNjc2ODljNTExYTMiLCJjb250ZXh0Ijp7fSwiZXhwIjoxNDYxNzc3MTMzLCJpYXQiOjE0NjE3NzY5NTN9.NTun8Cy_ipFu7BHzuvAVa4liuq4Xk4JwLw6z0kdGAJM");
assertThat(lifecycleService.isEnabled(clientKey)).isTrue();
createLifecycleRequest(LIFECYCLE_DISABLED_PATH, preparedRequest, "");
assertThat(lifecycleService.isEnabled(clientKey)).isFalse();
createLifecycleRequest(LIFECYCLE_UNINSTALLED_PATH, preparedRequest, "");
assertThat(lifecycleService.isInstalled(clientKey)).isFalse();
}
private MockMvcResponse createInstalled(LifecycleRequestMock request) {
return createLifecycleRequest(LIFECYCLE_INSTALLED_PATH, request, "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInFzaCI6ImEzYzgyZDc2MTY2YWQ2ODM3YmE3NzYzNmFlNDZmZTkyNTQxYmVlNTg1YTNjNzAyNzhjNjgyYWM2MjQxZWNmYTIiLCJpc3MiOiJqaXJhOjVkNDMxZDljLTNlZTgtNDI2YS1iMzY1LWY2NzY4OWM1MTFhMyIsImNvbnRleHQiOnsidXNlciI6eyJ1c2VyS2V5IjoiYWRtaW4iLCJ1c2VybmFtZSI6ImFkbWluIiwiZGlzcGxheU5hbWUiOiJhZG1pbiJ9fSwiZXhwIjoxNDYxNzc3MTMyLCJpYXQiOjE0NjE3NzY5NTJ9.-aY71bfoQKokY3Ha_DB2Uq56-tAfxCLDZf-r856XcB8");
}
private MockMvcResponse createLifecycleRequest(String resourcePath, LifecycleRequestMock request, String jwtPayload) {
return mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE)
.param("user_key", "admin")
.header("Authorization", "JWT" + jwtPayload)
.body(request)
.when()
.post(resourcePath);
}
private LifecycleRequestMock.LifecycleRequestMockBuilder prepareDefaultRequestBuilder() {
return LifecycleRequestMock.builder()
.key("wyrzyk.archetypes.atlassian-connect-plugin")
.clientKey("jira:5d431d9c-3ee8-426a-b365-f67689c511a3")
.publicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCesbDSDJn70fRG/wH4KyWjIWWxIjqvIbLiZcgv0OdTwlGRCa/5+CIBmjpj4WELCNVp0/1vHXX3RdeQe6HZ/0kmP3ptViqcyj9YdvC+WBwpYx5Z6Nula5asdwc3jG3tD9spAmv0EfoXrSbQrn2a145cJvgo5VrE3Z4j5UWD4sqQXwIDAQAB")
.sharedSecret("28b8a704-879a-45fe-94ad-09fb3760a5e5")
.serverVersion("72002")
.pluginsVersion("1.1.84")
.baseUrl("http://localhost:2990/jira")
.productType("jira")
.description("Atlassian JIRA at http://localhost:2990/jira")
.serviceEntitlementNumber("SEN-number")
.eventType("installed");
}
}
| src/test/java/it/wyrzyk/archetypes/web/lifecycle/LifecycleResourceTest.java | package it.wyrzyk.archetypes.web.lifecycle;
import com.jayway.restassured.module.mockmvc.response.MockMvcResponse;
import com.jayway.restassured.module.mockmvc.specification.MockMvcRequestSpecification;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;
import wyrzyk.archetypes.config.WebConfiguration;
import wyrzyk.archetypes.web.lifecycle.LifecycleService;
import static com.jayway.restassured.module.mockmvc.RestAssuredMockMvc.given;
import static org.assertj.core.api.Assertions.assertThat;
@WebAppConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {WebConfiguration.class})
public class LifecycleResourceTest {
private static final String LIFECYCLE_PATH = "/lifecycle";
private static final String LIFECYCLE_INSTALLED_PATH = LIFECYCLE_PATH + "/installed";
private static final String LIFECYCLE_ENABLED_PATH = LIFECYCLE_PATH + "/enabled";
private static final String LIFECYCLE_DISABLED_PATH = LIFECYCLE_PATH + "/disabled";
private static final String LIFECYCLE_UNINSTALLED_PATH = LIFECYCLE_PATH + "/uninstalled";
@Autowired
private WebApplicationContext webApplicationContext;
@Autowired
private LifecycleService lifecycleService;
private MockMvcRequestSpecification mockMvc;
@Before
public void setupMockMvc() {
mockMvc = given().webAppContextSetup(webApplicationContext);
}
@Test
@Transactional
@Rollback(true)
public void testIfInstalledMethodReturns200or204() throws Exception {
createInstalled(prepareDefaultRequestBuilder().build())
.then()
.statusCode(Matchers.isOneOf(200, 204));
}
@Test
@Transactional
@Rollback(true)
public void testIfInitializePayloadSaved() throws Exception {
assertThat(lifecycleService.countClients()).isZero();
createInstalled(prepareDefaultRequestBuilder()
.clientKey("clientKey")
.build());
assertThat(lifecycleService.countClients())
.isEqualTo(1);
assertThat(lifecycleService.findClient("clientKey")).isNotEmpty();
}
@Test
@Transactional
@Rollback(true)
public void testTwoPayloadsSaved() throws Exception {
assertThat(lifecycleService.countClients()).isZero();
createInstalled(prepareDefaultRequestBuilder()
.clientKey("1")
.build());
createInstalled(prepareDefaultRequestBuilder()
.clientKey("2")
.build());
assertThat(lifecycleService.countClients())
.isEqualTo(2);
assertThat(lifecycleService.findClient("1")).isNotEmpty();
assertThat(lifecycleService.findClient("2")).isNotEmpty();
}
@Test
@Transactional
@Rollback(true)
public void testIfPayloadIsUpdated() throws Exception { //todo: determine if it's a bug or expected behaviour
assertThat(lifecycleService.countClients()).isZero();
createInstalled(prepareDefaultRequestBuilder()
.clientKey("1")
.sharedSecret("old")
.build());
createInstalled(prepareDefaultRequestBuilder()
.sharedSecret("new")
.clientKey("1")
.build());
assertThat(lifecycleService.countClients())
.isEqualTo(1);
assertThat(lifecycleService.findClient("1")).isNotEmpty();
assertThat(lifecycleService.findClient("1").get().getSharedSecret()).isEqualTo("new");
}
@Test
@Transactional
@Rollback(true)
public void testWholeLifecycle() throws Exception {
assertThat(lifecycleService.countClients()).isZero();
final String clientKey = "clientKey";
final LifecycleRequestMock preparedRequest = prepareDefaultRequestBuilder()
.clientKey(clientKey)
.build();
createInstalled(preparedRequest);
assertThat(lifecycleService.isInstalled(clientKey)).isTrue();
createLifecycleRequest(LIFECYCLE_ENABLED_PATH, preparedRequest);
assertThat(lifecycleService.isEnabled(clientKey)).isTrue();
createLifecycleRequest(LIFECYCLE_DISABLED_PATH, preparedRequest);
assertThat(lifecycleService.isEnabled(clientKey)).isFalse();
createLifecycleRequest(LIFECYCLE_UNINSTALLED_PATH, preparedRequest);
assertThat(lifecycleService.isInstalled(clientKey)).isFalse();
}
private MockMvcResponse createInstalled(LifecycleRequestMock request) {
return createLifecycleRequest(LIFECYCLE_INSTALLED_PATH, request);
}
private MockMvcResponse createLifecycleRequest(String resourcePath, LifecycleRequestMock request) {
return mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE)
.body(request)
.when()
.post(resourcePath);
}
private LifecycleRequestMock.LifecycleRequestMockBuilder prepareDefaultRequestBuilder() {
return LifecycleRequestMock.builder()
.key("installed-addon-key")
.clientKey("1")
.publicKey("MIGfZRWzwIDAQAB")
.sharedSecret("a-secret-key-not-to-be-lost")
.serverVersion("server-version")
.pluginsVersion("version-of-connect")
.baseUrl("http://example.atlassian.net")
.productType("jira")
.description("Atlassian JIRA at https://example.atlassian.net")
.serviceEntitlementNumber("SEN-number")
.eventType("installed");
}
}
| fixed mock data in lifecycle resource test
| src/test/java/it/wyrzyk/archetypes/web/lifecycle/LifecycleResourceTest.java | fixed mock data in lifecycle resource test | <ide><path>rc/test/java/it/wyrzyk/archetypes/web/lifecycle/LifecycleResourceTest.java
<ide> .build();
<ide> createInstalled(preparedRequest);
<ide> assertThat(lifecycleService.isInstalled(clientKey)).isTrue();
<add> assertThat(lifecycleService.isEnabled(clientKey)).isFalse();
<ide>
<del> createLifecycleRequest(LIFECYCLE_ENABLED_PATH, preparedRequest);
<add> createLifecycleRequest(LIFECYCLE_ENABLED_PATH, preparedRequest, "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJxc2giOiJiNGYzMjJmNGRkMjQ2OTFiYmViNjZhZjkwZmNiZWE0MjAxMDkyMDA5YmM2MzA0MDc0YTg5NGRjMTQyOWFhOTA2IiwiaXNzIjoiamlyYTo1ZDQzMWQ5Yy0zZWU4LTQyNmEtYjM2NS1mNjc2ODljNTExYTMiLCJjb250ZXh0Ijp7fSwiZXhwIjoxNDYxNzc3MTMzLCJpYXQiOjE0NjE3NzY5NTN9.NTun8Cy_ipFu7BHzuvAVa4liuq4Xk4JwLw6z0kdGAJM");
<ide> assertThat(lifecycleService.isEnabled(clientKey)).isTrue();
<ide>
<del> createLifecycleRequest(LIFECYCLE_DISABLED_PATH, preparedRequest);
<add> createLifecycleRequest(LIFECYCLE_DISABLED_PATH, preparedRequest, "");
<ide> assertThat(lifecycleService.isEnabled(clientKey)).isFalse();
<ide>
<del> createLifecycleRequest(LIFECYCLE_UNINSTALLED_PATH, preparedRequest);
<add> createLifecycleRequest(LIFECYCLE_UNINSTALLED_PATH, preparedRequest, "");
<ide> assertThat(lifecycleService.isInstalled(clientKey)).isFalse();
<ide> }
<ide>
<ide> private MockMvcResponse createInstalled(LifecycleRequestMock request) {
<del> return createLifecycleRequest(LIFECYCLE_INSTALLED_PATH, request);
<add> return createLifecycleRequest(LIFECYCLE_INSTALLED_PATH, request, "JWT eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJhZG1pbiIsInFzaCI6ImEzYzgyZDc2MTY2YWQ2ODM3YmE3NzYzNmFlNDZmZTkyNTQxYmVlNTg1YTNjNzAyNzhjNjgyYWM2MjQxZWNmYTIiLCJpc3MiOiJqaXJhOjVkNDMxZDljLTNlZTgtNDI2YS1iMzY1LWY2NzY4OWM1MTFhMyIsImNvbnRleHQiOnsidXNlciI6eyJ1c2VyS2V5IjoiYWRtaW4iLCJ1c2VybmFtZSI6ImFkbWluIiwiZGlzcGxheU5hbWUiOiJhZG1pbiJ9fSwiZXhwIjoxNDYxNzc3MTMyLCJpYXQiOjE0NjE3NzY5NTJ9.-aY71bfoQKokY3Ha_DB2Uq56-tAfxCLDZf-r856XcB8");
<ide> }
<ide>
<del> private MockMvcResponse createLifecycleRequest(String resourcePath, LifecycleRequestMock request) {
<add> private MockMvcResponse createLifecycleRequest(String resourcePath, LifecycleRequestMock request, String jwtPayload) {
<ide> return mockMvc.contentType(MediaType.APPLICATION_JSON_VALUE)
<add> .param("user_key", "admin")
<add> .header("Authorization", "JWT" + jwtPayload)
<ide> .body(request)
<ide> .when()
<ide> .post(resourcePath);
<ide>
<ide> private LifecycleRequestMock.LifecycleRequestMockBuilder prepareDefaultRequestBuilder() {
<ide> return LifecycleRequestMock.builder()
<del> .key("installed-addon-key")
<del> .clientKey("1")
<del> .publicKey("MIGfZRWzwIDAQAB")
<del> .sharedSecret("a-secret-key-not-to-be-lost")
<del> .serverVersion("server-version")
<del> .pluginsVersion("version-of-connect")
<del> .baseUrl("http://example.atlassian.net")
<add> .key("wyrzyk.archetypes.atlassian-connect-plugin")
<add> .clientKey("jira:5d431d9c-3ee8-426a-b365-f67689c511a3")
<add> .publicKey("MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCesbDSDJn70fRG/wH4KyWjIWWxIjqvIbLiZcgv0OdTwlGRCa/5+CIBmjpj4WELCNVp0/1vHXX3RdeQe6HZ/0kmP3ptViqcyj9YdvC+WBwpYx5Z6Nula5asdwc3jG3tD9spAmv0EfoXrSbQrn2a145cJvgo5VrE3Z4j5UWD4sqQXwIDAQAB")
<add> .sharedSecret("28b8a704-879a-45fe-94ad-09fb3760a5e5")
<add> .serverVersion("72002")
<add> .pluginsVersion("1.1.84")
<add> .baseUrl("http://localhost:2990/jira")
<ide> .productType("jira")
<del> .description("Atlassian JIRA at https://example.atlassian.net")
<add> .description("Atlassian JIRA at http://localhost:2990/jira")
<ide> .serviceEntitlementNumber("SEN-number")
<ide> .eventType("installed");
<ide> } |
|
Java | apache-2.0 | 4aac91f517c89f6354a9fe611e02e4dc8b3fbac2 | 0 | intfrr/orientdb,giastfader/orientdb,rprabhat/orientdb,wyzssw/orientdb,wouterv/orientdb,tempbottle/orientdb,rprabhat/orientdb,mmacfadden/orientdb,tempbottle/orientdb,joansmith/orientdb,orientechnologies/orientdb,wyzssw/orientdb,alonsod86/orientdb,allanmoso/orientdb,rprabhat/orientdb,allanmoso/orientdb,intfrr/orientdb,allanmoso/orientdb,jdillon/orientdb,orientechnologies/orientdb,alonsod86/orientdb,mbhulin/orientdb,sanyaade-g2g-repos/orientdb,giastfader/orientdb,alonsod86/orientdb,mbhulin/orientdb,wyzssw/orientdb,cstamas/orientdb,tempbottle/orientdb,mmacfadden/orientdb,alonsod86/orientdb,mmacfadden/orientdb,mmacfadden/orientdb,jdillon/orientdb,sanyaade-g2g-repos/orientdb,sanyaade-g2g-repos/orientdb,joansmith/orientdb,giastfader/orientdb,intfrr/orientdb,cstamas/orientdb,sanyaade-g2g-repos/orientdb,giastfader/orientdb,wouterv/orientdb,cstamas/orientdb,intfrr/orientdb,orientechnologies/orientdb,jdillon/orientdb,orientechnologies/orientdb,wouterv/orientdb,wyzssw/orientdb,tempbottle/orientdb,joansmith/orientdb,allanmoso/orientdb,mbhulin/orientdb,wouterv/orientdb,cstamas/orientdb,mbhulin/orientdb,joansmith/orientdb,rprabhat/orientdb | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.index.hashindex.local.cache;
import com.orientechnologies.common.concur.lock.ONewLockManager;
import com.orientechnologies.common.concur.lock.OReadersWriterSpinLock;
import com.orientechnologies.common.directmemory.ODirectMemoryPointer;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.exception.OAllCacheEntriesAreUsedException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.serialization.serializer.binary.OBinarySerializerFactory;
import com.orientechnologies.orient.core.storage.fs.OFileClassic;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OLocalPaginatedStorage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.ODirtyPage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.zip.CRC32;
/**
* @author Andrey Lomakin
* @since 7/23/13
*/
public class OWOWCache {
// we add 8 bytes before and after cache pages to prevent word tearing in mt case.
public static final int PAGE_PADDING = 8;
public static final String NAME_ID_MAP_EXTENSION = ".cm";
private static final String NAME_ID_MAP = "name_id_map" + NAME_ID_MAP_EXTENSION;
public static final int MIN_CACHE_SIZE = 16;
public static final long MAGIC_NUMBER = 0xFACB03FEL;
private final long freeSpaceLimit = (OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT
.getValueAsLong() + OGlobalConfiguration.WAL_MAX_SIZE
.getValueAsLong()) * 1024L * 1024L;
private final long diskSizeCheckInterval = OGlobalConfiguration.DISC_CACHE_FREE_SPACE_CHECK_INTERVAL
.getValueAsInteger() * 1000;
private final List<WeakReference<LowDiskSpaceListener>> listeners = new CopyOnWriteArrayList<WeakReference<LowDiskSpaceListener>>();
private final AtomicLong lastDiskSpaceCheck = new AtomicLong(System.currentTimeMillis());
private final String storagePath;
private final ConcurrentSkipListMap<GroupKey, WriteGroup> writeGroups = new ConcurrentSkipListMap<GroupKey, WriteGroup>();
private final OBinarySerializer<String> stringSerializer;
private final Map<Long, OFileClassic> files;
private final boolean syncOnPageFlush;
private final int pageSize;
private final long groupTTL;
private final OWriteAheadLog writeAheadLog;
private final AtomicInteger cacheSize = new AtomicInteger();
private final ONewLockManager<GroupKey> lockManager = new ONewLockManager<GroupKey>();
private final OLocalPaginatedStorage storageLocal;
private final OReadersWriterSpinLock filesLock = new OReadersWriterSpinLock();
private final ScheduledExecutorService commitExecutor;
private final ExecutorService lowSpaceEventsPublisher;
private Map<String, Long> nameIdMap;
private RandomAccessFile nameIdMapHolder;
private volatile int cacheMaxSize;
private long fileCounter = 0;
private GroupKey lastGroupKey = new GroupKey(0, -1);
private File nameIdMapHolderFile;
private final AtomicLong allocatedSpace = new AtomicLong();
public OWOWCache(boolean syncOnPageFlush, int pageSize, long groupTTL, OWriteAheadLog writeAheadLog, long pageFlushInterval,
int cacheMaxSize, OLocalPaginatedStorage storageLocal, boolean checkMinSize) {
filesLock.acquireWriteLock();
try {
this.files = new ConcurrentHashMap<Long, OFileClassic>();
this.syncOnPageFlush = syncOnPageFlush;
this.pageSize = pageSize;
this.groupTTL = groupTTL;
this.writeAheadLog = writeAheadLog;
this.cacheMaxSize = cacheMaxSize;
this.storageLocal = storageLocal;
this.storagePath = storageLocal.getVariableParser().resolveVariables(storageLocal.getStoragePath());
final OBinarySerializerFactory binarySerializerFactory = storageLocal.getComponentsFactory().binarySerializerFactory;
this.stringSerializer = binarySerializerFactory.getObjectSerializer(OType.STRING);
if (checkMinSize && this.cacheMaxSize < MIN_CACHE_SIZE)
this.cacheMaxSize = MIN_CACHE_SIZE;
commitExecutor = Executors.newSingleThreadScheduledExecutor(new FlushThreadFactory(storageLocal.getName()));
lowSpaceEventsPublisher = Executors.newCachedThreadPool(new LowSpaceEventsPublisherFactory(storageLocal.getName()));
if (pageFlushInterval > 0)
commitExecutor.scheduleWithFixedDelay(new PeriodicFlushTask(), pageFlushInterval, pageFlushInterval, TimeUnit.MILLISECONDS);
} finally {
filesLock.releaseWriteLock();
}
}
public void startFuzzyCheckpoints() {
if (writeAheadLog != null) {
final long fuzzyCheckPointInterval = OGlobalConfiguration.WAL_FUZZY_CHECKPOINT_INTERVAL.getValueAsInteger();
commitExecutor.scheduleWithFixedDelay(new PeriodicalFuzzyCheckpointTask(), fuzzyCheckPointInterval, fuzzyCheckPointInterval,
TimeUnit.SECONDS);
}
}
public void addLowDiskSpaceListener(LowDiskSpaceListener listener) {
listeners.add(new WeakReference<LowDiskSpaceListener>(listener));
}
public void removeLowDiskSpaceListener(LowDiskSpaceListener listener) {
final Iterator<WeakReference<LowDiskSpaceListener>> iterator = listeners.iterator();
List<WeakReference<LowDiskSpaceListener>> itemsToRemove = new ArrayList<WeakReference<LowDiskSpaceListener>>();
for (WeakReference<LowDiskSpaceListener> ref : listeners) {
final LowDiskSpaceListener lowDiskSpaceListener = ref.get();
if (lowDiskSpaceListener == null || lowDiskSpaceListener.equals(listener))
itemsToRemove.add(ref);
}
for (WeakReference<LowDiskSpaceListener> ref : itemsToRemove)
listeners.remove(ref);
}
private void addAllocatedSpace(long diff) {
if (diff == 0)
return;
allocatedSpace.addAndGet(diff);
final long ts = System.currentTimeMillis();
final long lastSpaceCheck = lastDiskSpaceCheck.get();
if (ts - lastSpaceCheck > diskSizeCheckInterval) {
final File storageDir = new File(storagePath);
long freeSpace = storageDir.getFreeSpace();
long effectiveFreeSpace = freeSpace - allocatedSpace.get();
if (effectiveFreeSpace < freeSpaceLimit) {
writeAheadLog.flush();
Future<?> future = commitExecutor.submit(new PeriodicalFuzzyCheckpointTask());
try {
future.get();
} catch (Exception e) {
OLogManager.instance().error(this, "Error during fuzzy checkpoint execution for storage %s .", e, storageLocal.getName());
}
freeSpace = storageDir.getFreeSpace();
effectiveFreeSpace = freeSpace - allocatedSpace.get();
if (effectiveFreeSpace < freeSpaceLimit)
callLowSpaceListeners(new LowDiskSpaceInformation(effectiveFreeSpace, freeSpaceLimit));
}
lastDiskSpaceCheck.lazySet(ts);
}
}
private void callLowSpaceListeners(final LowDiskSpaceInformation information) {
lowSpaceEventsPublisher.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (WeakReference<LowDiskSpaceListener> lowDiskSpaceListenerWeakReference : listeners) {
final LowDiskSpaceListener listener = lowDiskSpaceListenerWeakReference.get();
if (listener != null)
try {
listener.lowDiskSpace(information);
} catch (Exception e) {
OLogManager.instance().error(this,
"Error during notification of low disk space for storage " + storageLocal.getName(), e);
}
}
return null;
}
});
}
private static int calculatePageCrc(byte[] pageData) {
int systemSize = OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE;
final CRC32 crc32 = new CRC32();
crc32.update(pageData, systemSize, pageData.length - systemSize);
return (int) crc32.getValue();
}
public long openFile(String fileName) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
Long fileId = nameIdMap.get(fileName);
OFileClassic fileClassic;
if (fileId == null)
fileClassic = null;
else
fileClassic = files.get(fileId);
if (fileClassic == null) {
fileId = ++fileCounter;
fileClassic = createFile(fileName);
files.put(fileId, fileClassic);
nameIdMap.put(fileName, fileId);
writeNameIdEntry(new NameFileIdEntry(fileName, fileId), true);
}
openFile(fileClassic);
return fileId;
} finally {
filesLock.releaseWriteLock();
}
}
public void openFile(String fileName, long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
OFileClassic fileClassic;
Long existingFileId = nameIdMap.get(fileName);
if (existingFileId != null) {
if (existingFileId == fileId)
fileClassic = files.get(fileId);
else
throw new OStorageException("File with given name already exists but has different id " + existingFileId
+ " vs. proposed " + fileId);
} else {
if (fileCounter < fileId)
fileCounter = fileId;
fileClassic = createFile(fileName);
files.put(fileId, fileClassic);
nameIdMap.put(fileName, fileId);
writeNameIdEntry(new NameFileIdEntry(fileName, fileId), true);
}
openFile(fileClassic);
} finally {
filesLock.releaseWriteLock();
}
}
public void lock() throws IOException {
for (OFileClassic file : files.values()) {
file.lock();
}
}
public void unlock() throws IOException {
for (OFileClassic file : files.values()) {
file.unlock();
}
}
public void openFile(long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
final OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null)
throw new OStorageException("File with id " + fileId + " does not exist.");
openFile(fileClassic);
} finally {
filesLock.releaseWriteLock();
}
}
public boolean exists(String fileName) {
filesLock.acquireReadLock();
try {
if (nameIdMap != null && nameIdMap.containsKey(fileName))
return true;
final File file = new File(storageLocal.getVariableParser().resolveVariables(
storageLocal.getStoragePath() + File.separator + fileName));
return file.exists();
} finally {
filesLock.releaseReadLock();
}
}
public boolean exists(long fileId) {
filesLock.acquireReadLock();
try {
final OFileClassic file = files.get(fileId);
if (file == null)
return false;
return file.exists();
} finally {
filesLock.releaseReadLock();
}
}
public Future store(final long fileId, final long pageIndex, final OCachePointer dataPointer) {
Future future = null;
filesLock.acquireReadLock();
try {
final GroupKey groupKey = new GroupKey(fileId, pageIndex >>> 4);
Lock groupLock = lockManager.acquireExclusiveLock(groupKey);
try {
WriteGroup writeGroup = writeGroups.get(groupKey);
if (writeGroup == null) {
writeGroup = new WriteGroup(System.currentTimeMillis());
writeGroups.put(groupKey, writeGroup);
}
int entryIndex = (int) (pageIndex & 15);
if (writeGroup.pages[entryIndex] == null) {
dataPointer.incrementReferrer();
writeGroup.pages[entryIndex] = dataPointer;
cacheSize.incrementAndGet();
} else {
if (!writeGroup.pages[entryIndex].equals(dataPointer)) {
writeGroup.pages[entryIndex].decrementReferrer();
dataPointer.incrementReferrer();
writeGroup.pages[entryIndex] = dataPointer;
}
}
writeGroup.recencyBit = true;
} finally {
lockManager.releaseLock(groupLock);
}
if (cacheSize.get() > cacheMaxSize) {
future = commitExecutor.submit(new PeriodicFlushTask());
}
return future;
} finally {
filesLock.releaseReadLock();
}
}
public OCachePointer load(long fileId, long pageIndex) throws IOException {
filesLock.acquireReadLock();
try {
final GroupKey groupKey = new GroupKey(fileId, pageIndex >>> 4);
Lock groupLock = lockManager.acquireSharedLock(groupKey);
try {
final WriteGroup writeGroup = writeGroups.get(groupKey);
OCachePointer pagePointer;
if (writeGroup == null) {
pagePointer = cacheFileContent(fileId, pageIndex);
pagePointer.incrementReferrer();
return pagePointer;
}
final int entryIndex = (int) (pageIndex & 15);
pagePointer = writeGroup.pages[entryIndex];
if (pagePointer == null)
pagePointer = cacheFileContent(fileId, pageIndex);
pagePointer.incrementReferrer();
return pagePointer;
} finally {
lockManager.releaseLock(groupLock);
}
} finally {
filesLock.releaseReadLock();
}
}
public void flush(long fileId) {
final Future<Void> future = commitExecutor.submit(new FileFlushTask(fileId));
try {
future.get();
} catch (InterruptedException e) {
Thread.interrupted();
throw new OException("File flush was interrupted", e);
} catch (Exception e) {
throw new OException("File flush was abnormally terminated", e);
}
}
public void flush() {
for (long fileId : files.keySet())
flush(fileId);
}
public long getFilledUpTo(long fileId) throws IOException {
filesLock.acquireReadLock();
try {
return files.get(fileId).getFilledUpTo() / pageSize;
} finally {
filesLock.releaseReadLock();
}
}
public long getAllocatedPages() {
return cacheSize.get();
}
public boolean isOpen(long fileId) {
filesLock.acquireReadLock();
try {
OFileClassic fileClassic = files.get(fileId);
if (fileClassic != null)
return fileClassic.isOpen();
return false;
} finally {
filesLock.releaseReadLock();
}
}
public long isOpen(String fileName) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
final Long fileId = nameIdMap.get(fileName);
if (fileId == null)
return -1;
final OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null || !fileClassic.isOpen())
return -1;
return fileId;
} finally {
filesLock.releaseWriteLock();
}
}
public void setSoftlyClosed(long fileId, boolean softlyClosed) throws IOException {
filesLock.acquireWriteLock();
try {
OFileClassic fileClassic = files.get(fileId);
if (fileClassic != null && fileClassic.isOpen())
fileClassic.setSoftlyClosed(softlyClosed);
} finally {
filesLock.releaseWriteLock();
}
}
public void setSoftlyClosed(boolean softlyClosed) throws IOException {
filesLock.acquireWriteLock();
try {
for (long fileId : files.keySet())
setSoftlyClosed(fileId, softlyClosed);
} finally {
filesLock.releaseWriteLock();
}
}
public boolean wasSoftlyClosed(long fileId) throws IOException {
filesLock.acquireReadLock();
try {
OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null)
return false;
return fileClassic.wasSoftlyClosed();
} finally {
filesLock.releaseReadLock();
}
}
public void deleteFile(long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
final String name = doDeleteFile(fileId);
if (name != null) {
nameIdMap.remove(name);
writeNameIdEntry(new NameFileIdEntry(name, -1), true);
}
} finally {
filesLock.releaseWriteLock();
}
}
public void truncateFile(long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
removeCachedPages(fileId);
files.get(fileId).shrink(0);
} finally {
filesLock.releaseWriteLock();
}
}
public void renameFile(long fileId, String oldFileName, String newFileName) throws IOException {
filesLock.acquireWriteLock();
try {
if (!files.containsKey(fileId))
return;
final OFileClassic file = files.get(fileId);
final String osFileName = file.getName();
if (osFileName.startsWith(oldFileName)) {
final File newFile = new File(storageLocal.getStoragePath() + File.separator + newFileName
+ osFileName.substring(osFileName.lastIndexOf(oldFileName) + oldFileName.length()));
boolean renamed = file.renameTo(newFile);
while (!renamed) {
renamed = file.renameTo(newFile);
}
}
nameIdMap.remove(oldFileName);
nameIdMap.put(newFileName, fileId);
writeNameIdEntry(new NameFileIdEntry(oldFileName, -1), false);
writeNameIdEntry(new NameFileIdEntry(newFileName, fileId), true);
} finally {
filesLock.releaseWriteLock();
}
}
public void close() throws IOException {
flush();
if (!commitExecutor.isShutdown()) {
commitExecutor.shutdown();
try {
if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES))
throw new OException("Background data flush task can not be stopped.");
} catch (InterruptedException e) {
OLogManager.instance().error(this, "Data flush thread was interrupted");
Thread.interrupted();
throw new OException("Data flush thread was interrupted", e);
}
}
filesLock.acquireWriteLock();
try {
for (OFileClassic fileClassic : files.values()) {
if (fileClassic.isOpen())
fileClassic.close();
}
if (nameIdMapHolder != null) {
nameIdMapHolder.setLength(0);
for (Map.Entry<String, Long> entry : nameIdMap.entrySet()) {
writeNameIdEntry(new NameFileIdEntry(entry.getKey(), entry.getValue()), false);
}
nameIdMapHolder.getFD().sync();
nameIdMapHolder.close();
}
} finally {
filesLock.releaseWriteLock();
}
}
public void close(long fileId, boolean flush) throws IOException {
filesLock.acquireWriteLock();
try {
if (!isOpen(fileId))
return;
if (flush)
flush(fileId);
else
removeCachedPages(fileId);
files.get(fileId).close();
} finally {
filesLock.releaseWriteLock();
}
}
public OPageDataVerificationError[] checkStoredPages(OCommandOutputListener commandOutputListener) {
final int notificationTimeOut = 5000;
final List<OPageDataVerificationError> errors = new ArrayList<OPageDataVerificationError>();
filesLock.acquireWriteLock();
try {
for (long fileId : files.keySet()) {
OFileClassic fileClassic = files.get(fileId);
boolean fileIsCorrect;
try {
if (commandOutputListener != null)
commandOutputListener.onMessage("Flashing file " + fileClassic.getName() + "... ");
flush(fileId);
if (commandOutputListener != null)
commandOutputListener.onMessage("Start verification of content of " + fileClassic.getName() + "file ...");
long time = System.currentTimeMillis();
long filledUpTo = fileClassic.getFilledUpTo();
fileIsCorrect = true;
for (long pos = 0; pos < filledUpTo; pos += pageSize) {
boolean checkSumIncorrect = false;
boolean magicNumberIncorrect = false;
byte[] data = new byte[pageSize];
fileClassic.read(pos, data, data.length);
long magicNumber = OLongSerializer.INSTANCE.deserializeNative(data, 0);
if (magicNumber != MAGIC_NUMBER) {
magicNumberIncorrect = true;
if (commandOutputListener != null)
commandOutputListener.onMessage("Error: Magic number for page " + (pos / pageSize) + " in file "
+ fileClassic.getName() + " does not much !!!");
fileIsCorrect = false;
}
final int storedCRC32 = OIntegerSerializer.INSTANCE.deserializeNative(data, OLongSerializer.LONG_SIZE);
final int calculatedCRC32 = calculatePageCrc(data);
if (storedCRC32 != calculatedCRC32) {
checkSumIncorrect = true;
if (commandOutputListener != null)
commandOutputListener.onMessage("Error: Checksum for page " + (pos / pageSize) + " in file "
+ fileClassic.getName() + " is incorrect !!!");
fileIsCorrect = false;
}
if (magicNumberIncorrect || checkSumIncorrect)
errors.add(new OPageDataVerificationError(magicNumberIncorrect, checkSumIncorrect, pos / pageSize, fileClassic
.getName()));
if (commandOutputListener != null && System.currentTimeMillis() - time > notificationTimeOut) {
time = notificationTimeOut;
commandOutputListener.onMessage((pos / pageSize) + " pages were processed ...");
}
}
} catch (IOException ioe) {
if (commandOutputListener != null)
commandOutputListener.onMessage("Error: Error during processing of file " + fileClassic.getName() + ". "
+ ioe.getMessage());
fileIsCorrect = false;
}
if (!fileIsCorrect) {
if (commandOutputListener != null)
commandOutputListener.onMessage("Verification of file " + fileClassic.getName() + " is finished with errors.");
} else {
if (commandOutputListener != null)
commandOutputListener.onMessage("Verification of file " + fileClassic.getName() + " is successfully finished.");
}
}
return errors.toArray(new OPageDataVerificationError[errors.size()]);
} finally {
filesLock.releaseWriteLock();
}
}
public void delete() throws IOException {
filesLock.acquireWriteLock();
try {
for (long fileId : files.keySet())
doDeleteFile(fileId);
if (nameIdMapHolderFile != null) {
if (nameIdMapHolderFile.exists()) {
nameIdMapHolder.close();
if (!nameIdMapHolderFile.delete())
throw new OStorageException("Can not delete disk cache file which contains name-id mapping.");
}
nameIdMapHolder = null;
nameIdMapHolderFile = null;
}
} finally {
filesLock.releaseWriteLock();
}
if (!commitExecutor.isShutdown()) {
commitExecutor.shutdown();
try {
if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES))
throw new OException("Background data flush task can not be stopped.");
} catch (InterruptedException e) {
OLogManager.instance().error(this, "Data flush thread was interrupted");
Thread.interrupted();
throw new OException("Data flush thread was interrupted", e);
}
}
}
public String fileNameById(long fileId) {
filesLock.acquireReadLock();
try {
return files.get(fileId).getName();
} finally {
filesLock.releaseReadLock();
}
}
private void openFile(OFileClassic fileClassic) throws IOException {
if (fileClassic.exists()) {
if (!fileClassic.isOpen())
fileClassic.open();
} else {
fileClassic.create(-1);
fileClassic.synch();
}
}
private void initNameIdMapping() throws IOException {
if (nameIdMapHolder == null) {
final File storagePath = new File(storageLocal.getStoragePath());
if (!storagePath.exists())
if (!storagePath.mkdirs())
throw new OStorageException("Can not create directories for the path " + storagePath);
nameIdMapHolderFile = new File(storagePath, NAME_ID_MAP);
nameIdMapHolder = new RandomAccessFile(nameIdMapHolderFile, "rw");
readNameIdMap();
}
}
private OFileClassic createFile(String fileName) {
OFileClassic fileClassic = new OFileClassic();
String path = storageLocal.getVariableParser().resolveVariables(storageLocal.getStoragePath() + File.separator + fileName);
fileClassic.init(path, storageLocal.getMode());
return fileClassic;
}
private void readNameIdMap() throws IOException {
nameIdMap = new ConcurrentHashMap<String, Long>();
long localFileCounter = -1;
nameIdMapHolder.seek(0);
NameFileIdEntry nameFileIdEntry;
while ((nameFileIdEntry = readNextNameIdEntry()) != null) {
if (localFileCounter < nameFileIdEntry.fileId)
localFileCounter = nameFileIdEntry.fileId;
if (nameFileIdEntry.fileId >= 0)
nameIdMap.put(nameFileIdEntry.name, nameFileIdEntry.fileId);
else
nameIdMap.remove(nameFileIdEntry.name);
}
if (localFileCounter > 0)
fileCounter = localFileCounter;
for (Map.Entry<String, Long> nameIdEntry : nameIdMap.entrySet()) {
if (!files.containsKey(nameIdEntry.getValue())) {
OFileClassic fileClassic = createFile(nameIdEntry.getKey());
files.put(nameIdEntry.getValue(), fileClassic);
}
}
}
private NameFileIdEntry readNextNameIdEntry() throws IOException {
try {
final int nameSize = nameIdMapHolder.readInt();
byte[] serializedName = new byte[nameSize];
nameIdMapHolder.readFully(serializedName);
final String name = stringSerializer.deserialize(serializedName, 0);
final long fileId = nameIdMapHolder.readLong();
return new NameFileIdEntry(name, fileId);
} catch (EOFException eof) {
return null;
}
}
private void writeNameIdEntry(NameFileIdEntry nameFileIdEntry, boolean sync) throws IOException {
nameIdMapHolder.seek(nameIdMapHolder.length());
final int nameSize = stringSerializer.getObjectSize(nameFileIdEntry.name);
byte[] serializedName = new byte[nameSize];
stringSerializer.serialize(nameFileIdEntry.name, serializedName, 0);
nameIdMapHolder.writeInt(nameSize);
nameIdMapHolder.write(serializedName);
nameIdMapHolder.writeLong(nameFileIdEntry.fileId);
if (sync)
nameIdMapHolder.getFD().sync();
}
private String doDeleteFile(long fileId) throws IOException {
if (isOpen(fileId))
truncateFile(fileId);
final OFileClassic fileClassic = files.remove(fileId);
String name = null;
if (fileClassic != null) {
name = fileClassic.getName();
if (fileClassic.exists())
fileClassic.delete();
}
return name;
}
private void removeCachedPages(long fileId) {
Future<Void> future = commitExecutor.submit(new RemoveFilePagesTask(fileId));
try {
future.get();
} catch (InterruptedException e) {
Thread.interrupted();
throw new OException("File data removal was interrupted", e);
} catch (Exception e) {
throw new OException("File data removal was abnormally terminated", e);
}
}
private OCachePointer cacheFileContent(long fileId, long pageIndex) throws IOException {
final long startPosition = pageIndex * pageSize;
final long endPosition = startPosition + pageSize;
byte[] content = new byte[pageSize + 2 * PAGE_PADDING];
OCachePointer dataPointer;
final OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null)
throw new IllegalArgumentException("File with id " + fileId + " not found in WOW Cache");
OLogSequenceNumber lastLsn;
if (writeAheadLog != null)
lastLsn = writeAheadLog.getFlushedLSN();
else
lastLsn = new OLogSequenceNumber(-1, -1);
if (fileClassic.getFilledUpTo() >= endPosition) {
fileClassic.read(startPosition, content, content.length - 2 * PAGE_PADDING, PAGE_PADDING);
final ODirectMemoryPointer pointer = new ODirectMemoryPointer(content);
dataPointer = new OCachePointer(pointer, lastLsn);
} else {
final int space = (int) (endPosition - fileClassic.getFilledUpTo());
fileClassic.allocateSpace(space);
addAllocatedSpace(space);
final ODirectMemoryPointer pointer = new ODirectMemoryPointer(content);
dataPointer = new OCachePointer(pointer, lastLsn);
}
return dataPointer;
}
private void flushPage(long fileId, long pageIndex, ODirectMemoryPointer dataPointer) throws IOException {
if (writeAheadLog != null) {
OLogSequenceNumber lsn = ODurablePage.getLogSequenceNumberFromPage(dataPointer);
OLogSequenceNumber flushedLSN = writeAheadLog.getFlushedLSN();
if (flushedLSN == null || flushedLSN.compareTo(lsn) < 0)
writeAheadLog.flush();
}
final byte[] content = dataPointer.get(PAGE_PADDING, pageSize);
OLongSerializer.INSTANCE.serializeNative(MAGIC_NUMBER, content, 0);
final int crc32 = calculatePageCrc(content);
OIntegerSerializer.INSTANCE.serializeNative(crc32, content, OLongSerializer.LONG_SIZE);
final OFileClassic fileClassic = files.get(fileId);
final long spaceDiff = fileClassic.write(pageIndex * pageSize, content);
assert spaceDiff >= 0;
addAllocatedSpace(-spaceDiff);
if (syncOnPageFlush)
fileClassic.synch();
}
private static final class NameFileIdEntry {
private final String name;
private final long fileId;
private NameFileIdEntry(String name, long fileId) {
this.name = name;
this.fileId = fileId;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
NameFileIdEntry that = (NameFileIdEntry) o;
if (fileId != that.fileId)
return false;
if (!name.equals(that.name))
return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (int) (fileId ^ (fileId >>> 32));
return result;
}
}
private final class GroupKey implements Comparable<GroupKey> {
private final long fileId;
private final long groupIndex;
private GroupKey(long fileId, long groupIndex) {
this.fileId = fileId;
this.groupIndex = groupIndex;
}
@Override
public int compareTo(GroupKey other) {
if (fileId > other.fileId)
return 1;
if (fileId < other.fileId)
return -1;
if (groupIndex > other.groupIndex)
return 1;
if (groupIndex < other.groupIndex)
return -1;
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GroupKey groupKey = (GroupKey) o;
if (fileId != groupKey.fileId)
return false;
if (groupIndex != groupKey.groupIndex)
return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (fileId ^ (fileId >>> 32));
result = 31 * result + (int) (groupIndex ^ (groupIndex >>> 32));
return result;
}
@Override
public String toString() {
return "GroupKey{" + "fileId=" + fileId + ", groupIndex=" + groupIndex + '}';
}
}
private final class PeriodicFlushTask implements Runnable {
@Override
public void run() {
try {
if (writeGroups.isEmpty())
return;
int writeGroupsToFlush;
boolean useForceSync = false;
double threshold = ((double) cacheSize.get()) / cacheMaxSize;
if (threshold > 0.8) {
writeGroupsToFlush = (int) (0.2 * writeGroups.size());
useForceSync = true;
} else if (threshold > 0.9) {
writeGroupsToFlush = (int) (0.4 * writeGroups.size());
useForceSync = true;
} else
writeGroupsToFlush = 1;
if (writeGroupsToFlush < 1)
writeGroupsToFlush = 1;
int flushedGroups = 0;
flushedGroups = flushRing(writeGroupsToFlush, flushedGroups, false);
if (flushedGroups < writeGroupsToFlush && useForceSync)
flushedGroups = flushRing(writeGroupsToFlush, flushedGroups, true);
if (flushedGroups < writeGroupsToFlush && cacheSize.get() > cacheMaxSize) {
if (OGlobalConfiguration.SERVER_CACHE_INCREASE_ON_DEMAND.getValueAsBoolean()) {
final long oldCacheMaxSize = cacheMaxSize;
cacheMaxSize = (int) Math.ceil(cacheMaxSize * (1 + OGlobalConfiguration.SERVER_CACHE_INCREASE_STEP.getValueAsFloat()));
OLogManager.instance().warn(this, "Write cache size is increased from %d to %d", oldCacheMaxSize, cacheMaxSize);
} else {
throw new OAllCacheEntriesAreUsedException("All records in write cache are used!");
}
}
} catch (Exception e) {
OLogManager.instance().error(this, "Exception during data flush.", e);
}
}
private int flushRing(int writeGroupsToFlush, int flushedGroups, boolean forceFlush) throws IOException {
NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.tailMap(lastGroupKey, false);
if (!subMap.isEmpty()) {
flushedGroups = iterateBySubRing(subMap, writeGroupsToFlush, 0, forceFlush);
if (flushedGroups < writeGroupsToFlush) {
if (!subMap.isEmpty()) {
subMap = writeGroups.headMap(subMap.firstKey(), false);
flushedGroups = iterateBySubRing(subMap, writeGroupsToFlush, flushedGroups, forceFlush);
}
}
} else
flushedGroups = iterateBySubRing(writeGroups, writeGroupsToFlush, flushedGroups, forceFlush);
return flushedGroups;
}
private int iterateBySubRing(NavigableMap<GroupKey, WriteGroup> subMap, int writeGroupsToFlush, int flushedWriteGroups,
boolean forceFlush) throws IOException {
Iterator<Map.Entry<GroupKey, WriteGroup>> entriesIterator = subMap.entrySet().iterator();
long currentTime = System.currentTimeMillis();
groupsLoop: while (entriesIterator.hasNext() && flushedWriteGroups < writeGroupsToFlush) {
Map.Entry<GroupKey, WriteGroup> entry = entriesIterator.next();
final WriteGroup group = entry.getValue();
final GroupKey groupKey = entry.getKey();
final boolean weakLockMode = group.creationTime - currentTime < groupTTL && !forceFlush;
if (group.recencyBit && weakLockMode) {
group.recencyBit = false;
continue;
}
Lock groupLock = lockManager.acquireExclusiveLock(entry.getKey());
try {
if (group.recencyBit && weakLockMode)
group.recencyBit = false;
else {
group.recencyBit = false;
int flushedPages = 0;
for (int i = 0; i < 16; i++) {
final OCachePointer pagePointer = group.pages[i];
if (pagePointer != null) {
if (!pagePointer.tryAcquireSharedLock())
continue groupsLoop;
try {
flushPage(groupKey.fileId, (groupKey.groupIndex << 4) + i, pagePointer.getDataPointer());
flushedPages++;
final OLogSequenceNumber flushedLSN = ODurablePage.getLogSequenceNumberFromPage(pagePointer.getDataPointer());
pagePointer.setLastFlushedLsn(flushedLSN);
} finally {
pagePointer.releaseSharedLock();
}
}
}
for (OCachePointer pagePointer : group.pages)
if (pagePointer != null)
pagePointer.decrementReferrer();
entriesIterator.remove();
flushedWriteGroups++;
cacheSize.addAndGet(-flushedPages);
}
} finally {
lockManager.releaseLock(groupLock);
}
lastGroupKey = groupKey;
}
return flushedWriteGroups;
}
}
private final class PeriodicalFuzzyCheckpointTask implements Runnable {
private PeriodicalFuzzyCheckpointTask() {
}
@Override
public void run() {
OLogSequenceNumber minLsn = writeAheadLog.getFlushedLSN();
for (Map.Entry<GroupKey, WriteGroup> entry : writeGroups.entrySet()) {
Lock groupLock = lockManager.acquireExclusiveLock(entry.getKey());
try {
WriteGroup group = entry.getValue();
for (int i = 0; i < 16; i++) {
final OCachePointer pagePointer = group.pages[i];
if (pagePointer != null) {
if (minLsn.compareTo(pagePointer.getLastFlushedLsn()) > 0) {
minLsn = pagePointer.getLastFlushedLsn();
}
}
}
} finally {
lockManager.releaseLock(groupLock);
}
}
OLogManager.instance().debug(this, "Start fuzzy checkpoint flushed LSN is %s", minLsn);
try {
writeAheadLog.logFuzzyCheckPointStart(minLsn);
for (OFileClassic fileClassic : files.values()) {
fileClassic.synch();
}
writeAheadLog.logFuzzyCheckPointEnd();
writeAheadLog.flush();
if (minLsn.compareTo(new OLogSequenceNumber(-1, -1)) > 0)
writeAheadLog.cutTill(minLsn);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error during fuzzy checkpoint", ioe);
}
OLogManager.instance().debug(this, "End fuzzy checkpoint");
}
}
private final class FileFlushTask implements Callable<Void> {
private final long fileId;
private FileFlushTask(long fileId) {
this.fileId = fileId;
}
@Override
public Void call() throws Exception {
final GroupKey firstKey = new GroupKey(fileId, 0);
final GroupKey lastKey = new GroupKey(fileId, Long.MAX_VALUE);
NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.subMap(firstKey, true, lastKey, true);
Iterator<Map.Entry<GroupKey, WriteGroup>> entryIterator = subMap.entrySet().iterator();
groupsLoop: while (entryIterator.hasNext()) {
Map.Entry<GroupKey, WriteGroup> entry = entryIterator.next();
final WriteGroup writeGroup = entry.getValue();
final GroupKey groupKey = entry.getKey();
Lock groupLock = lockManager.acquireExclusiveLock(groupKey);
try {
int flushedPages = 0;
for (int i = 0; i < 16; i++) {
OCachePointer pagePointer = writeGroup.pages[i];
if (pagePointer != null) {
if (!pagePointer.tryAcquireSharedLock())
continue groupsLoop;
try {
flushPage(groupKey.fileId, (groupKey.groupIndex << 4) + i, pagePointer.getDataPointer());
flushedPages++;
} finally {
pagePointer.releaseSharedLock();
}
}
}
for (OCachePointer pagePointer : writeGroup.pages)
if (pagePointer != null)
pagePointer.decrementReferrer();
cacheSize.addAndGet(-flushedPages);
entryIterator.remove();
} finally {
lockManager.releaseLock(groupLock);
}
}
files.get(fileId).synch();
return null;
}
}
private final class RemoveFilePagesTask implements Callable<Void> {
private final long fileId;
private RemoveFilePagesTask(long fileId) {
this.fileId = fileId;
}
@Override
public Void call() throws Exception {
final GroupKey firstKey = new GroupKey(fileId, 0);
final GroupKey lastKey = new GroupKey(fileId, Long.MAX_VALUE);
NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.subMap(firstKey, true, lastKey, true);
Iterator<Map.Entry<GroupKey, WriteGroup>> entryIterator = subMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<GroupKey, WriteGroup> entry = entryIterator.next();
WriteGroup writeGroup = entry.getValue();
GroupKey groupKey = entry.getKey();
Lock groupLock = lockManager.acquireExclusiveLock(groupKey);
try {
for (OCachePointer pagePointer : writeGroup.pages) {
if (pagePointer != null) {
pagePointer.acquireExclusiveLock();
try {
pagePointer.decrementReferrer();
cacheSize.decrementAndGet();
} finally {
pagePointer.releaseExclusiveLock();
}
}
}
entryIterator.remove();
} finally {
lockManager.releaseLock(groupLock);
}
}
return null;
}
}
public interface LowDiskSpaceListener {
void lowDiskSpace(LowDiskSpaceInformation information);
}
public class LowDiskSpaceInformation {
public long freeSpace;
public long requiredSpace;
public LowDiskSpaceInformation(long freeSpace, long requiredSpace) {
this.freeSpace = freeSpace;
this.requiredSpace = requiredSpace;
}
}
private static class FlushThreadFactory implements ThreadFactory {
private final String storageName;
private FlushThreadFactory(String storageName) {
this.storageName = storageName;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("OrientDB Write Cache Flush Task (" + storageName + ")");
return thread;
}
}
private static class LowSpaceEventsPublisherFactory implements ThreadFactory {
private final String storageName;
private LowSpaceEventsPublisherFactory(String storageName) {
this.storageName = storageName;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("OrientDB Low Disk Space Publisher (" + storageName + ")");
return thread;
}
}
}
| core/src/main/java/com/orientechnologies/orient/core/index/hashindex/local/cache/OWOWCache.java | /*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.index.hashindex.local.cache;
import com.orientechnologies.common.concur.lock.ONewLockManager;
import com.orientechnologies.common.concur.lock.OReadersWriterSpinLock;
import com.orientechnologies.common.directmemory.ODirectMemoryPointer;
import com.orientechnologies.common.exception.OException;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.common.serialization.types.OBinarySerializer;
import com.orientechnologies.common.serialization.types.OIntegerSerializer;
import com.orientechnologies.common.serialization.types.OLongSerializer;
import com.orientechnologies.orient.core.command.OCommandOutputListener;
import com.orientechnologies.orient.core.config.OGlobalConfiguration;
import com.orientechnologies.orient.core.exception.OAllCacheEntriesAreUsedException;
import com.orientechnologies.orient.core.exception.OStorageException;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.serialization.serializer.binary.OBinarySerializerFactory;
import com.orientechnologies.orient.core.storage.fs.OFileClassic;
import com.orientechnologies.orient.core.storage.impl.local.paginated.OLocalPaginatedStorage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.base.ODurablePage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.ODirtyPage;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OLogSequenceNumber;
import com.orientechnologies.orient.core.storage.impl.local.paginated.wal.OWriteAheadLog;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.zip.CRC32;
/**
* @author Andrey Lomakin
* @since 7/23/13
*/
public class OWOWCache {
// we add 8 bytes before and after cache pages to prevent word tearing in mt case.
public static final int PAGE_PADDING = 8;
public static final String NAME_ID_MAP_EXTENSION = ".cm";
private static final String NAME_ID_MAP = "name_id_map" + NAME_ID_MAP_EXTENSION;
public static final int MIN_CACHE_SIZE = 16;
public static final long MAGIC_NUMBER = 0xFACB03FEL;
private final long freeSpaceLimit = (OGlobalConfiguration.DISK_CACHE_FREE_SPACE_LIMIT
.getValueAsLong() + OGlobalConfiguration.WAL_MAX_SIZE
.getValueAsLong()) * 1024L * 1024L;
private final long diskSizeCheckInterval = OGlobalConfiguration.DISC_CACHE_FREE_SPACE_CHECK_INTERVAL
.getValueAsInteger() * 1000;
private final List<WeakReference<LowDiskSpaceListener>> listeners = new CopyOnWriteArrayList<WeakReference<LowDiskSpaceListener>>();
private final AtomicLong lastDiskSpaceCheck = new AtomicLong(System.currentTimeMillis());
private final String storagePath;
private final ConcurrentSkipListMap<GroupKey, WriteGroup> writeGroups = new ConcurrentSkipListMap<GroupKey, WriteGroup>();
private final OBinarySerializer<String> stringSerializer;
private final Map<Long, OFileClassic> files;
private final boolean syncOnPageFlush;
private final int pageSize;
private final long groupTTL;
private final OWriteAheadLog writeAheadLog;
private final AtomicInteger cacheSize = new AtomicInteger();
private final ONewLockManager<GroupKey> lockManager = new ONewLockManager<GroupKey>();
private final OLocalPaginatedStorage storageLocal;
private final OReadersWriterSpinLock filesLock = new OReadersWriterSpinLock();
private final ScheduledExecutorService commitExecutor;
private final ExecutorService lowSpaceEventsPublisher;
private Map<String, Long> nameIdMap;
private RandomAccessFile nameIdMapHolder;
private volatile int cacheMaxSize;
private long fileCounter = 0;
private GroupKey lastGroupKey = new GroupKey(0, -1);
private File nameIdMapHolderFile;
private final AtomicLong allocatedSpace = new AtomicLong();
public OWOWCache(boolean syncOnPageFlush, int pageSize, long groupTTL, OWriteAheadLog writeAheadLog, long pageFlushInterval,
int cacheMaxSize, OLocalPaginatedStorage storageLocal, boolean checkMinSize) {
filesLock.acquireWriteLock();
try {
this.files = new ConcurrentHashMap<Long, OFileClassic>();
this.syncOnPageFlush = syncOnPageFlush;
this.pageSize = pageSize;
this.groupTTL = groupTTL;
this.writeAheadLog = writeAheadLog;
this.cacheMaxSize = cacheMaxSize;
this.storageLocal = storageLocal;
this.storagePath = storageLocal.getVariableParser().resolveVariables(storageLocal.getStoragePath());
final OBinarySerializerFactory binarySerializerFactory = storageLocal.getComponentsFactory().binarySerializerFactory;
this.stringSerializer = binarySerializerFactory.getObjectSerializer(OType.STRING);
if (checkMinSize && this.cacheMaxSize < MIN_CACHE_SIZE)
this.cacheMaxSize = MIN_CACHE_SIZE;
commitExecutor = Executors.newSingleThreadScheduledExecutor(new FlushThreadFactory(storageLocal.getName()));
lowSpaceEventsPublisher = Executors.newCachedThreadPool(new LowSpaceEventsPublisherFactory(storageLocal.getName()));
if (pageFlushInterval > 0)
commitExecutor.scheduleWithFixedDelay(new PeriodicFlushTask(), pageFlushInterval, pageFlushInterval, TimeUnit.MILLISECONDS);
} finally {
filesLock.releaseWriteLock();
}
}
public void startFuzzyCheckpoints() {
if (writeAheadLog != null) {
final long fuzzyCheckPointInterval = OGlobalConfiguration.WAL_FUZZY_CHECKPOINT_INTERVAL.getValueAsInteger();
commitExecutor.scheduleWithFixedDelay(new PeriodicalFuzzyCheckpointTask(), fuzzyCheckPointInterval, fuzzyCheckPointInterval,
TimeUnit.SECONDS);
}
}
public void addLowDiskSpaceListener(LowDiskSpaceListener listener) {
listeners.add(new WeakReference<LowDiskSpaceListener>(listener));
}
public void removeLowDiskSpaceListener(LowDiskSpaceListener listener) {
final Iterator<WeakReference<LowDiskSpaceListener>> iterator = listeners.iterator();
List<WeakReference<LowDiskSpaceListener>> itemsToRemove = new ArrayList<WeakReference<LowDiskSpaceListener>>();
for (WeakReference<LowDiskSpaceListener> ref : listeners) {
final LowDiskSpaceListener lowDiskSpaceListener = ref.get();
if (lowDiskSpaceListener == null || lowDiskSpaceListener.equals(listener))
itemsToRemove.add(ref);
}
for (WeakReference<LowDiskSpaceListener> ref : itemsToRemove)
listeners.remove(ref);
}
private void addAllocatedSpace(long diff) {
if (diff == 0)
return;
allocatedSpace.addAndGet(diff);
final long ts = System.currentTimeMillis();
final long lastSpaceCheck = lastDiskSpaceCheck.get();
if (ts - lastSpaceCheck > diskSizeCheckInterval) {
final File storageDir = new File(storagePath);
final long freeSpace = storageDir.getFreeSpace();
final long effectiveFreeSpace = freeSpace - allocatedSpace.get();
if (effectiveFreeSpace < freeSpaceLimit) {
callLowSpaceListeners(new LowDiskSpaceInformation(effectiveFreeSpace, freeSpaceLimit));
}
lastDiskSpaceCheck.lazySet(ts);
}
}
private void callLowSpaceListeners(final LowDiskSpaceInformation information) {
lowSpaceEventsPublisher.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
for (WeakReference<LowDiskSpaceListener> lowDiskSpaceListenerWeakReference : listeners) {
final LowDiskSpaceListener listener = lowDiskSpaceListenerWeakReference.get();
if (listener != null)
try {
listener.lowDiskSpace(information);
} catch (Exception e) {
OLogManager.instance().error(this,
"Error during notification of low disk space for storage " + storageLocal.getName(), e);
}
}
return null;
}
});
}
private static int calculatePageCrc(byte[] pageData) {
int systemSize = OLongSerializer.LONG_SIZE + OIntegerSerializer.INT_SIZE;
final CRC32 crc32 = new CRC32();
crc32.update(pageData, systemSize, pageData.length - systemSize);
return (int) crc32.getValue();
}
public long openFile(String fileName) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
Long fileId = nameIdMap.get(fileName);
OFileClassic fileClassic;
if (fileId == null)
fileClassic = null;
else
fileClassic = files.get(fileId);
if (fileClassic == null) {
fileId = ++fileCounter;
fileClassic = createFile(fileName);
files.put(fileId, fileClassic);
nameIdMap.put(fileName, fileId);
writeNameIdEntry(new NameFileIdEntry(fileName, fileId), true);
}
openFile(fileClassic);
return fileId;
} finally {
filesLock.releaseWriteLock();
}
}
public void openFile(String fileName, long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
OFileClassic fileClassic;
Long existingFileId = nameIdMap.get(fileName);
if (existingFileId != null) {
if (existingFileId == fileId)
fileClassic = files.get(fileId);
else
throw new OStorageException("File with given name already exists but has different id " + existingFileId
+ " vs. proposed " + fileId);
} else {
if (fileCounter < fileId)
fileCounter = fileId;
fileClassic = createFile(fileName);
files.put(fileId, fileClassic);
nameIdMap.put(fileName, fileId);
writeNameIdEntry(new NameFileIdEntry(fileName, fileId), true);
}
openFile(fileClassic);
} finally {
filesLock.releaseWriteLock();
}
}
public void lock() throws IOException {
for (OFileClassic file : files.values()) {
file.lock();
}
}
public void unlock() throws IOException {
for (OFileClassic file : files.values()) {
file.unlock();
}
}
public void openFile(long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
final OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null)
throw new OStorageException("File with id " + fileId + " does not exist.");
openFile(fileClassic);
} finally {
filesLock.releaseWriteLock();
}
}
public boolean exists(String fileName) {
filesLock.acquireReadLock();
try {
if (nameIdMap != null && nameIdMap.containsKey(fileName))
return true;
final File file = new File(storageLocal.getVariableParser().resolveVariables(
storageLocal.getStoragePath() + File.separator + fileName));
return file.exists();
} finally {
filesLock.releaseReadLock();
}
}
public boolean exists(long fileId) {
filesLock.acquireReadLock();
try {
final OFileClassic file = files.get(fileId);
if (file == null)
return false;
return file.exists();
} finally {
filesLock.releaseReadLock();
}
}
public Future store(final long fileId, final long pageIndex, final OCachePointer dataPointer) {
Future future = null;
filesLock.acquireReadLock();
try {
final GroupKey groupKey = new GroupKey(fileId, pageIndex >>> 4);
Lock groupLock = lockManager.acquireExclusiveLock(groupKey);
try {
WriteGroup writeGroup = writeGroups.get(groupKey);
if (writeGroup == null) {
writeGroup = new WriteGroup(System.currentTimeMillis());
writeGroups.put(groupKey, writeGroup);
}
int entryIndex = (int) (pageIndex & 15);
if (writeGroup.pages[entryIndex] == null) {
dataPointer.incrementReferrer();
writeGroup.pages[entryIndex] = dataPointer;
cacheSize.incrementAndGet();
} else {
if (!writeGroup.pages[entryIndex].equals(dataPointer)) {
writeGroup.pages[entryIndex].decrementReferrer();
dataPointer.incrementReferrer();
writeGroup.pages[entryIndex] = dataPointer;
}
}
writeGroup.recencyBit = true;
} finally {
lockManager.releaseLock(groupLock);
}
if (cacheSize.get() > cacheMaxSize) {
future = commitExecutor.submit(new PeriodicFlushTask());
}
return future;
} finally {
filesLock.releaseReadLock();
}
}
public OCachePointer load(long fileId, long pageIndex) throws IOException {
filesLock.acquireReadLock();
try {
final GroupKey groupKey = new GroupKey(fileId, pageIndex >>> 4);
Lock groupLock = lockManager.acquireSharedLock(groupKey);
try {
final WriteGroup writeGroup = writeGroups.get(groupKey);
OCachePointer pagePointer;
if (writeGroup == null) {
pagePointer = cacheFileContent(fileId, pageIndex);
pagePointer.incrementReferrer();
return pagePointer;
}
final int entryIndex = (int) (pageIndex & 15);
pagePointer = writeGroup.pages[entryIndex];
if (pagePointer == null)
pagePointer = cacheFileContent(fileId, pageIndex);
pagePointer.incrementReferrer();
return pagePointer;
} finally {
lockManager.releaseLock(groupLock);
}
} finally {
filesLock.releaseReadLock();
}
}
public void flush(long fileId) {
final Future<Void> future = commitExecutor.submit(new FileFlushTask(fileId));
try {
future.get();
} catch (InterruptedException e) {
Thread.interrupted();
throw new OException("File flush was interrupted", e);
} catch (Exception e) {
throw new OException("File flush was abnormally terminated", e);
}
}
public void flush() {
for (long fileId : files.keySet())
flush(fileId);
}
public long getFilledUpTo(long fileId) throws IOException {
filesLock.acquireReadLock();
try {
return files.get(fileId).getFilledUpTo() / pageSize;
} finally {
filesLock.releaseReadLock();
}
}
public long getAllocatedPages() {
return cacheSize.get();
}
public boolean isOpen(long fileId) {
filesLock.acquireReadLock();
try {
OFileClassic fileClassic = files.get(fileId);
if (fileClassic != null)
return fileClassic.isOpen();
return false;
} finally {
filesLock.releaseReadLock();
}
}
public long isOpen(String fileName) throws IOException {
filesLock.acquireWriteLock();
try {
initNameIdMapping();
final Long fileId = nameIdMap.get(fileName);
if (fileId == null)
return -1;
final OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null || !fileClassic.isOpen())
return -1;
return fileId;
} finally {
filesLock.releaseWriteLock();
}
}
public void setSoftlyClosed(long fileId, boolean softlyClosed) throws IOException {
filesLock.acquireWriteLock();
try {
OFileClassic fileClassic = files.get(fileId);
if (fileClassic != null && fileClassic.isOpen())
fileClassic.setSoftlyClosed(softlyClosed);
} finally {
filesLock.releaseWriteLock();
}
}
public void setSoftlyClosed(boolean softlyClosed) throws IOException {
filesLock.acquireWriteLock();
try {
for (long fileId : files.keySet())
setSoftlyClosed(fileId, softlyClosed);
} finally {
filesLock.releaseWriteLock();
}
}
public boolean wasSoftlyClosed(long fileId) throws IOException {
filesLock.acquireReadLock();
try {
OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null)
return false;
return fileClassic.wasSoftlyClosed();
} finally {
filesLock.releaseReadLock();
}
}
public void deleteFile(long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
final String name = doDeleteFile(fileId);
if (name != null) {
nameIdMap.remove(name);
writeNameIdEntry(new NameFileIdEntry(name, -1), true);
}
} finally {
filesLock.releaseWriteLock();
}
}
public void truncateFile(long fileId) throws IOException {
filesLock.acquireWriteLock();
try {
removeCachedPages(fileId);
files.get(fileId).shrink(0);
} finally {
filesLock.releaseWriteLock();
}
}
public void renameFile(long fileId, String oldFileName, String newFileName) throws IOException {
filesLock.acquireWriteLock();
try {
if (!files.containsKey(fileId))
return;
final OFileClassic file = files.get(fileId);
final String osFileName = file.getName();
if (osFileName.startsWith(oldFileName)) {
final File newFile = new File(storageLocal.getStoragePath() + File.separator + newFileName
+ osFileName.substring(osFileName.lastIndexOf(oldFileName) + oldFileName.length()));
boolean renamed = file.renameTo(newFile);
while (!renamed) {
renamed = file.renameTo(newFile);
}
}
nameIdMap.remove(oldFileName);
nameIdMap.put(newFileName, fileId);
writeNameIdEntry(new NameFileIdEntry(oldFileName, -1), false);
writeNameIdEntry(new NameFileIdEntry(newFileName, fileId), true);
} finally {
filesLock.releaseWriteLock();
}
}
public void close() throws IOException {
flush();
if (!commitExecutor.isShutdown()) {
commitExecutor.shutdown();
try {
if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES))
throw new OException("Background data flush task can not be stopped.");
} catch (InterruptedException e) {
OLogManager.instance().error(this, "Data flush thread was interrupted");
Thread.interrupted();
throw new OException("Data flush thread was interrupted", e);
}
}
filesLock.acquireWriteLock();
try {
for (OFileClassic fileClassic : files.values()) {
if (fileClassic.isOpen())
fileClassic.close();
}
if (nameIdMapHolder != null) {
nameIdMapHolder.setLength(0);
for (Map.Entry<String, Long> entry : nameIdMap.entrySet()) {
writeNameIdEntry(new NameFileIdEntry(entry.getKey(), entry.getValue()), false);
}
nameIdMapHolder.getFD().sync();
nameIdMapHolder.close();
}
} finally {
filesLock.releaseWriteLock();
}
}
public void close(long fileId, boolean flush) throws IOException {
filesLock.acquireWriteLock();
try {
if (!isOpen(fileId))
return;
if (flush)
flush(fileId);
else
removeCachedPages(fileId);
files.get(fileId).close();
} finally {
filesLock.releaseWriteLock();
}
}
public OPageDataVerificationError[] checkStoredPages(OCommandOutputListener commandOutputListener) {
final int notificationTimeOut = 5000;
final List<OPageDataVerificationError> errors = new ArrayList<OPageDataVerificationError>();
filesLock.acquireWriteLock();
try {
for (long fileId : files.keySet()) {
OFileClassic fileClassic = files.get(fileId);
boolean fileIsCorrect;
try {
if (commandOutputListener != null)
commandOutputListener.onMessage("Flashing file " + fileClassic.getName() + "... ");
flush(fileId);
if (commandOutputListener != null)
commandOutputListener.onMessage("Start verification of content of " + fileClassic.getName() + "file ...");
long time = System.currentTimeMillis();
long filledUpTo = fileClassic.getFilledUpTo();
fileIsCorrect = true;
for (long pos = 0; pos < filledUpTo; pos += pageSize) {
boolean checkSumIncorrect = false;
boolean magicNumberIncorrect = false;
byte[] data = new byte[pageSize];
fileClassic.read(pos, data, data.length);
long magicNumber = OLongSerializer.INSTANCE.deserializeNative(data, 0);
if (magicNumber != MAGIC_NUMBER) {
magicNumberIncorrect = true;
if (commandOutputListener != null)
commandOutputListener.onMessage("Error: Magic number for page " + (pos / pageSize) + " in file "
+ fileClassic.getName() + " does not much !!!");
fileIsCorrect = false;
}
final int storedCRC32 = OIntegerSerializer.INSTANCE.deserializeNative(data, OLongSerializer.LONG_SIZE);
final int calculatedCRC32 = calculatePageCrc(data);
if (storedCRC32 != calculatedCRC32) {
checkSumIncorrect = true;
if (commandOutputListener != null)
commandOutputListener.onMessage("Error: Checksum for page " + (pos / pageSize) + " in file "
+ fileClassic.getName() + " is incorrect !!!");
fileIsCorrect = false;
}
if (magicNumberIncorrect || checkSumIncorrect)
errors.add(new OPageDataVerificationError(magicNumberIncorrect, checkSumIncorrect, pos / pageSize, fileClassic
.getName()));
if (commandOutputListener != null && System.currentTimeMillis() - time > notificationTimeOut) {
time = notificationTimeOut;
commandOutputListener.onMessage((pos / pageSize) + " pages were processed ...");
}
}
} catch (IOException ioe) {
if (commandOutputListener != null)
commandOutputListener.onMessage("Error: Error during processing of file " + fileClassic.getName() + ". "
+ ioe.getMessage());
fileIsCorrect = false;
}
if (!fileIsCorrect) {
if (commandOutputListener != null)
commandOutputListener.onMessage("Verification of file " + fileClassic.getName() + " is finished with errors.");
} else {
if (commandOutputListener != null)
commandOutputListener.onMessage("Verification of file " + fileClassic.getName() + " is successfully finished.");
}
}
return errors.toArray(new OPageDataVerificationError[errors.size()]);
} finally {
filesLock.releaseWriteLock();
}
}
public void delete() throws IOException {
filesLock.acquireWriteLock();
try {
for (long fileId : files.keySet())
doDeleteFile(fileId);
if (nameIdMapHolderFile != null) {
if (nameIdMapHolderFile.exists()) {
nameIdMapHolder.close();
if (!nameIdMapHolderFile.delete())
throw new OStorageException("Can not delete disk cache file which contains name-id mapping.");
}
nameIdMapHolder = null;
nameIdMapHolderFile = null;
}
} finally {
filesLock.releaseWriteLock();
}
if (!commitExecutor.isShutdown()) {
commitExecutor.shutdown();
try {
if (!commitExecutor.awaitTermination(5, TimeUnit.MINUTES))
throw new OException("Background data flush task can not be stopped.");
} catch (InterruptedException e) {
OLogManager.instance().error(this, "Data flush thread was interrupted");
Thread.interrupted();
throw new OException("Data flush thread was interrupted", e);
}
}
}
public String fileNameById(long fileId) {
filesLock.acquireReadLock();
try {
return files.get(fileId).getName();
} finally {
filesLock.releaseReadLock();
}
}
private void openFile(OFileClassic fileClassic) throws IOException {
if (fileClassic.exists()) {
if (!fileClassic.isOpen())
fileClassic.open();
} else {
fileClassic.create(-1);
fileClassic.synch();
}
}
private void initNameIdMapping() throws IOException {
if (nameIdMapHolder == null) {
final File storagePath = new File(storageLocal.getStoragePath());
if (!storagePath.exists())
if (!storagePath.mkdirs())
throw new OStorageException("Can not create directories for the path " + storagePath);
nameIdMapHolderFile = new File(storagePath, NAME_ID_MAP);
nameIdMapHolder = new RandomAccessFile(nameIdMapHolderFile, "rw");
readNameIdMap();
}
}
private OFileClassic createFile(String fileName) {
OFileClassic fileClassic = new OFileClassic();
String path = storageLocal.getVariableParser().resolveVariables(storageLocal.getStoragePath() + File.separator + fileName);
fileClassic.init(path, storageLocal.getMode());
return fileClassic;
}
private void readNameIdMap() throws IOException {
nameIdMap = new ConcurrentHashMap<String, Long>();
long localFileCounter = -1;
nameIdMapHolder.seek(0);
NameFileIdEntry nameFileIdEntry;
while ((nameFileIdEntry = readNextNameIdEntry()) != null) {
if (localFileCounter < nameFileIdEntry.fileId)
localFileCounter = nameFileIdEntry.fileId;
if (nameFileIdEntry.fileId >= 0)
nameIdMap.put(nameFileIdEntry.name, nameFileIdEntry.fileId);
else
nameIdMap.remove(nameFileIdEntry.name);
}
if (localFileCounter > 0)
fileCounter = localFileCounter;
for (Map.Entry<String, Long> nameIdEntry : nameIdMap.entrySet()) {
if (!files.containsKey(nameIdEntry.getValue())) {
OFileClassic fileClassic = createFile(nameIdEntry.getKey());
files.put(nameIdEntry.getValue(), fileClassic);
}
}
}
private NameFileIdEntry readNextNameIdEntry() throws IOException {
try {
final int nameSize = nameIdMapHolder.readInt();
byte[] serializedName = new byte[nameSize];
nameIdMapHolder.readFully(serializedName);
final String name = stringSerializer.deserialize(serializedName, 0);
final long fileId = nameIdMapHolder.readLong();
return new NameFileIdEntry(name, fileId);
} catch (EOFException eof) {
return null;
}
}
private void writeNameIdEntry(NameFileIdEntry nameFileIdEntry, boolean sync) throws IOException {
nameIdMapHolder.seek(nameIdMapHolder.length());
final int nameSize = stringSerializer.getObjectSize(nameFileIdEntry.name);
byte[] serializedName = new byte[nameSize];
stringSerializer.serialize(nameFileIdEntry.name, serializedName, 0);
nameIdMapHolder.writeInt(nameSize);
nameIdMapHolder.write(serializedName);
nameIdMapHolder.writeLong(nameFileIdEntry.fileId);
if (sync)
nameIdMapHolder.getFD().sync();
}
private String doDeleteFile(long fileId) throws IOException {
if (isOpen(fileId))
truncateFile(fileId);
final OFileClassic fileClassic = files.remove(fileId);
String name = null;
if (fileClassic != null) {
name = fileClassic.getName();
if (fileClassic.exists())
fileClassic.delete();
}
return name;
}
private void removeCachedPages(long fileId) {
Future<Void> future = commitExecutor.submit(new RemoveFilePagesTask(fileId));
try {
future.get();
} catch (InterruptedException e) {
Thread.interrupted();
throw new OException("File data removal was interrupted", e);
} catch (Exception e) {
throw new OException("File data removal was abnormally terminated", e);
}
}
private OCachePointer cacheFileContent(long fileId, long pageIndex) throws IOException {
final long startPosition = pageIndex * pageSize;
final long endPosition = startPosition + pageSize;
byte[] content = new byte[pageSize + 2 * PAGE_PADDING];
OCachePointer dataPointer;
final OFileClassic fileClassic = files.get(fileId);
if (fileClassic == null)
throw new IllegalArgumentException("File with id " + fileId + " not found in WOW Cache");
OLogSequenceNumber lastLsn;
if (writeAheadLog != null)
lastLsn = writeAheadLog.getFlushedLSN();
else
lastLsn = new OLogSequenceNumber(-1, -1);
if (fileClassic.getFilledUpTo() >= endPosition) {
fileClassic.read(startPosition, content, content.length - 2 * PAGE_PADDING, PAGE_PADDING);
final ODirectMemoryPointer pointer = new ODirectMemoryPointer(content);
dataPointer = new OCachePointer(pointer, lastLsn);
} else {
final int space = (int) (endPosition - fileClassic.getFilledUpTo());
fileClassic.allocateSpace(space);
addAllocatedSpace(space);
final ODirectMemoryPointer pointer = new ODirectMemoryPointer(content);
dataPointer = new OCachePointer(pointer, lastLsn);
}
return dataPointer;
}
private void flushPage(long fileId, long pageIndex, ODirectMemoryPointer dataPointer) throws IOException {
if (writeAheadLog != null) {
OLogSequenceNumber lsn = ODurablePage.getLogSequenceNumberFromPage(dataPointer);
OLogSequenceNumber flushedLSN = writeAheadLog.getFlushedLSN();
if (flushedLSN == null || flushedLSN.compareTo(lsn) < 0)
writeAheadLog.flush();
}
final byte[] content = dataPointer.get(PAGE_PADDING, pageSize);
OLongSerializer.INSTANCE.serializeNative(MAGIC_NUMBER, content, 0);
final int crc32 = calculatePageCrc(content);
OIntegerSerializer.INSTANCE.serializeNative(crc32, content, OLongSerializer.LONG_SIZE);
final OFileClassic fileClassic = files.get(fileId);
final long spaceDiff = fileClassic.write(pageIndex * pageSize, content);
assert spaceDiff >= 0;
addAllocatedSpace(-spaceDiff);
if (syncOnPageFlush)
fileClassic.synch();
}
private static final class NameFileIdEntry {
private final String name;
private final long fileId;
private NameFileIdEntry(String name, long fileId) {
this.name = name;
this.fileId = fileId;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
NameFileIdEntry that = (NameFileIdEntry) o;
if (fileId != that.fileId)
return false;
if (!name.equals(that.name))
return false;
return true;
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + (int) (fileId ^ (fileId >>> 32));
return result;
}
}
private final class GroupKey implements Comparable<GroupKey> {
private final long fileId;
private final long groupIndex;
private GroupKey(long fileId, long groupIndex) {
this.fileId = fileId;
this.groupIndex = groupIndex;
}
@Override
public int compareTo(GroupKey other) {
if (fileId > other.fileId)
return 1;
if (fileId < other.fileId)
return -1;
if (groupIndex > other.groupIndex)
return 1;
if (groupIndex < other.groupIndex)
return -1;
return 0;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
GroupKey groupKey = (GroupKey) o;
if (fileId != groupKey.fileId)
return false;
if (groupIndex != groupKey.groupIndex)
return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (fileId ^ (fileId >>> 32));
result = 31 * result + (int) (groupIndex ^ (groupIndex >>> 32));
return result;
}
@Override
public String toString() {
return "GroupKey{" + "fileId=" + fileId + ", groupIndex=" + groupIndex + '}';
}
}
private final class PeriodicFlushTask implements Runnable {
@Override
public void run() {
try {
if (writeGroups.isEmpty())
return;
int writeGroupsToFlush;
boolean useForceSync = false;
double threshold = ((double) cacheSize.get()) / cacheMaxSize;
if (threshold > 0.8) {
writeGroupsToFlush = (int) (0.2 * writeGroups.size());
useForceSync = true;
} else if (threshold > 0.9) {
writeGroupsToFlush = (int) (0.4 * writeGroups.size());
useForceSync = true;
} else
writeGroupsToFlush = 1;
if (writeGroupsToFlush < 1)
writeGroupsToFlush = 1;
int flushedGroups = 0;
flushedGroups = flushRing(writeGroupsToFlush, flushedGroups, false);
if (flushedGroups < writeGroupsToFlush && useForceSync)
flushedGroups = flushRing(writeGroupsToFlush, flushedGroups, true);
if (flushedGroups < writeGroupsToFlush && cacheSize.get() > cacheMaxSize) {
if (OGlobalConfiguration.SERVER_CACHE_INCREASE_ON_DEMAND.getValueAsBoolean()) {
final long oldCacheMaxSize = cacheMaxSize;
cacheMaxSize = (int) Math.ceil(cacheMaxSize * (1 + OGlobalConfiguration.SERVER_CACHE_INCREASE_STEP.getValueAsFloat()));
OLogManager.instance().warn(this, "Write cache size is increased from %d to %d", oldCacheMaxSize, cacheMaxSize);
} else {
throw new OAllCacheEntriesAreUsedException("All records in write cache are used!");
}
}
} catch (Exception e) {
OLogManager.instance().error(this, "Exception during data flush.", e);
}
}
private int flushRing(int writeGroupsToFlush, int flushedGroups, boolean forceFlush) throws IOException {
NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.tailMap(lastGroupKey, false);
if (!subMap.isEmpty()) {
flushedGroups = iterateBySubRing(subMap, writeGroupsToFlush, 0, forceFlush);
if (flushedGroups < writeGroupsToFlush) {
if (!subMap.isEmpty()) {
subMap = writeGroups.headMap(subMap.firstKey(), false);
flushedGroups = iterateBySubRing(subMap, writeGroupsToFlush, flushedGroups, forceFlush);
}
}
} else
flushedGroups = iterateBySubRing(writeGroups, writeGroupsToFlush, flushedGroups, forceFlush);
return flushedGroups;
}
private int iterateBySubRing(NavigableMap<GroupKey, WriteGroup> subMap, int writeGroupsToFlush, int flushedWriteGroups,
boolean forceFlush) throws IOException {
Iterator<Map.Entry<GroupKey, WriteGroup>> entriesIterator = subMap.entrySet().iterator();
long currentTime = System.currentTimeMillis();
groupsLoop: while (entriesIterator.hasNext() && flushedWriteGroups < writeGroupsToFlush) {
Map.Entry<GroupKey, WriteGroup> entry = entriesIterator.next();
final WriteGroup group = entry.getValue();
final GroupKey groupKey = entry.getKey();
final boolean weakLockMode = group.creationTime - currentTime < groupTTL && !forceFlush;
if (group.recencyBit && weakLockMode) {
group.recencyBit = false;
continue;
}
Lock groupLock = lockManager.acquireExclusiveLock(entry.getKey());
try {
if (group.recencyBit && weakLockMode)
group.recencyBit = false;
else {
group.recencyBit = false;
int flushedPages = 0;
for (int i = 0; i < 16; i++) {
final OCachePointer pagePointer = group.pages[i];
if (pagePointer != null) {
if (!pagePointer.tryAcquireSharedLock())
continue groupsLoop;
try {
flushPage(groupKey.fileId, (groupKey.groupIndex << 4) + i, pagePointer.getDataPointer());
flushedPages++;
final OLogSequenceNumber flushedLSN = ODurablePage.getLogSequenceNumberFromPage(pagePointer.getDataPointer());
pagePointer.setLastFlushedLsn(flushedLSN);
} finally {
pagePointer.releaseSharedLock();
}
}
}
for (OCachePointer pagePointer : group.pages)
if (pagePointer != null)
pagePointer.decrementReferrer();
entriesIterator.remove();
flushedWriteGroups++;
cacheSize.addAndGet(-flushedPages);
}
} finally {
lockManager.releaseLock(groupLock);
}
lastGroupKey = groupKey;
}
return flushedWriteGroups;
}
}
private final class PeriodicalFuzzyCheckpointTask implements Runnable {
private OLogSequenceNumber flushedLsn = new OLogSequenceNumber(-1, -1);
private PeriodicalFuzzyCheckpointTask() {
}
@Override
public void run() {
OLogSequenceNumber minLsn = writeAheadLog.getFlushedLSN();
for (Map.Entry<GroupKey, WriteGroup> entry : writeGroups.entrySet()) {
Lock groupLock = lockManager.acquireExclusiveLock(entry.getKey());
try {
WriteGroup group = entry.getValue();
for (int i = 0; i < 16; i++) {
final OCachePointer pagePointer = group.pages[i];
if (pagePointer != null) {
if (minLsn.compareTo(pagePointer.getLastFlushedLsn()) > 0) {
minLsn = pagePointer.getLastFlushedLsn();
}
}
}
} finally {
lockManager.releaseLock(groupLock);
}
}
if (flushedLsn.compareTo(minLsn) < 0)
flushedLsn = minLsn;
OLogManager.instance().debug(this, "Start fuzzy checkpoint flushed LSN is %s", flushedLsn);
try {
writeAheadLog.logFuzzyCheckPointStart(flushedLsn);
for (OFileClassic fileClassic : files.values()) {
fileClassic.synch();
}
writeAheadLog.logFuzzyCheckPointEnd();
writeAheadLog.flush();
if (flushedLsn.compareTo(new OLogSequenceNumber(-1, -1)) > 0)
writeAheadLog.cutTill(flushedLsn);
} catch (IOException ioe) {
OLogManager.instance().error(this, "Error during fuzzy checkpoint", ioe);
}
OLogManager.instance().debug(this, "End fuzzy checkpoint");
}
}
private final class FileFlushTask implements Callable<Void> {
private final long fileId;
private FileFlushTask(long fileId) {
this.fileId = fileId;
}
@Override
public Void call() throws Exception {
final GroupKey firstKey = new GroupKey(fileId, 0);
final GroupKey lastKey = new GroupKey(fileId, Long.MAX_VALUE);
NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.subMap(firstKey, true, lastKey, true);
Iterator<Map.Entry<GroupKey, WriteGroup>> entryIterator = subMap.entrySet().iterator();
groupsLoop: while (entryIterator.hasNext()) {
Map.Entry<GroupKey, WriteGroup> entry = entryIterator.next();
final WriteGroup writeGroup = entry.getValue();
final GroupKey groupKey = entry.getKey();
Lock groupLock = lockManager.acquireExclusiveLock(groupKey);
try {
int flushedPages = 0;
for (int i = 0; i < 16; i++) {
OCachePointer pagePointer = writeGroup.pages[i];
if (pagePointer != null) {
if (!pagePointer.tryAcquireSharedLock())
continue groupsLoop;
try {
flushPage(groupKey.fileId, (groupKey.groupIndex << 4) + i, pagePointer.getDataPointer());
flushedPages++;
} finally {
pagePointer.releaseSharedLock();
}
}
}
for (OCachePointer pagePointer : writeGroup.pages)
if (pagePointer != null)
pagePointer.decrementReferrer();
cacheSize.addAndGet(-flushedPages);
entryIterator.remove();
} finally {
lockManager.releaseLock(groupLock);
}
}
files.get(fileId).synch();
return null;
}
}
private final class RemoveFilePagesTask implements Callable<Void> {
private final long fileId;
private RemoveFilePagesTask(long fileId) {
this.fileId = fileId;
}
@Override
public Void call() throws Exception {
final GroupKey firstKey = new GroupKey(fileId, 0);
final GroupKey lastKey = new GroupKey(fileId, Long.MAX_VALUE);
NavigableMap<GroupKey, WriteGroup> subMap = writeGroups.subMap(firstKey, true, lastKey, true);
Iterator<Map.Entry<GroupKey, WriteGroup>> entryIterator = subMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<GroupKey, WriteGroup> entry = entryIterator.next();
WriteGroup writeGroup = entry.getValue();
GroupKey groupKey = entry.getKey();
Lock groupLock = lockManager.acquireExclusiveLock(groupKey);
try {
for (OCachePointer pagePointer : writeGroup.pages) {
if (pagePointer != null) {
pagePointer.acquireExclusiveLock();
try {
pagePointer.decrementReferrer();
cacheSize.decrementAndGet();
} finally {
pagePointer.releaseExclusiveLock();
}
}
}
entryIterator.remove();
} finally {
lockManager.releaseLock(groupLock);
}
}
return null;
}
}
public interface LowDiskSpaceListener {
void lowDiskSpace(LowDiskSpaceInformation information);
}
public class LowDiskSpaceInformation {
public long freeSpace;
public long requiredSpace;
public LowDiskSpaceInformation(long freeSpace, long requiredSpace) {
this.freeSpace = freeSpace;
this.requiredSpace = requiredSpace;
}
}
private static class FlushThreadFactory implements ThreadFactory {
private final String storageName;
private FlushThreadFactory(String storageName) {
this.storageName = storageName;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("OrientDB Write Cache Flush Task (" + storageName + ")");
return thread;
}
}
private static class LowSpaceEventsPublisherFactory implements ThreadFactory {
private final String storageName;
private LowSpaceEventsPublisherFactory(String storageName) {
this.storageName = storageName;
}
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName("OrientDB Low Disk Space Publisher (" + storageName + ")");
return thread;
}
}
}
| Issue #3342 was fixed.
| core/src/main/java/com/orientechnologies/orient/core/index/hashindex/local/cache/OWOWCache.java | Issue #3342 was fixed. | <ide><path>ore/src/main/java/com/orientechnologies/orient/core/index/hashindex/local/cache/OWOWCache.java
<ide>
<ide> if (ts - lastSpaceCheck > diskSizeCheckInterval) {
<ide> final File storageDir = new File(storagePath);
<del> final long freeSpace = storageDir.getFreeSpace();
<del> final long effectiveFreeSpace = freeSpace - allocatedSpace.get();
<add>
<add> long freeSpace = storageDir.getFreeSpace();
<add> long effectiveFreeSpace = freeSpace - allocatedSpace.get();
<add>
<ide> if (effectiveFreeSpace < freeSpaceLimit) {
<del> callLowSpaceListeners(new LowDiskSpaceInformation(effectiveFreeSpace, freeSpaceLimit));
<add> writeAheadLog.flush();
<add>
<add> Future<?> future = commitExecutor.submit(new PeriodicalFuzzyCheckpointTask());
<add> try {
<add> future.get();
<add> } catch (Exception e) {
<add> OLogManager.instance().error(this, "Error during fuzzy checkpoint execution for storage %s .", e, storageLocal.getName());
<add> }
<add>
<add> freeSpace = storageDir.getFreeSpace();
<add> effectiveFreeSpace = freeSpace - allocatedSpace.get();
<add>
<add> if (effectiveFreeSpace < freeSpaceLimit)
<add> callLowSpaceListeners(new LowDiskSpaceInformation(effectiveFreeSpace, freeSpaceLimit));
<ide> }
<ide>
<ide> lastDiskSpaceCheck.lazySet(ts);
<ide> }
<ide>
<ide> private final class PeriodicalFuzzyCheckpointTask implements Runnable {
<del> private OLogSequenceNumber flushedLsn = new OLogSequenceNumber(-1, -1);
<del>
<ide> private PeriodicalFuzzyCheckpointTask() {
<ide> }
<ide>
<ide> }
<ide> }
<ide>
<del> if (flushedLsn.compareTo(minLsn) < 0)
<del> flushedLsn = minLsn;
<del>
<del> OLogManager.instance().debug(this, "Start fuzzy checkpoint flushed LSN is %s", flushedLsn);
<add> OLogManager.instance().debug(this, "Start fuzzy checkpoint flushed LSN is %s", minLsn);
<ide> try {
<del> writeAheadLog.logFuzzyCheckPointStart(flushedLsn);
<add> writeAheadLog.logFuzzyCheckPointStart(minLsn);
<ide> for (OFileClassic fileClassic : files.values()) {
<ide> fileClassic.synch();
<ide> }
<ide> writeAheadLog.logFuzzyCheckPointEnd();
<ide> writeAheadLog.flush();
<ide>
<del> if (flushedLsn.compareTo(new OLogSequenceNumber(-1, -1)) > 0)
<del> writeAheadLog.cutTill(flushedLsn);
<add> if (minLsn.compareTo(new OLogSequenceNumber(-1, -1)) > 0)
<add> writeAheadLog.cutTill(minLsn);
<ide> } catch (IOException ioe) {
<ide> OLogManager.instance().error(this, "Error during fuzzy checkpoint", ioe);
<ide> } |
|
Java | apache-2.0 | 26bd0c0167fbb9d24f0500ba4f9fa2f54ead4ace | 0 | liuyuanyuan/dbeaver,AndrewKhitrin/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,liuyuanyuan/dbeaver,liuyuanyuan/dbeaver,ruspl-afed/dbeaver,AndrewKhitrin/dbeaver,AndrewKhitrin/dbeaver,ruspl-afed/dbeaver,AndrewKhitrin/dbeaver | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.model.runtime;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
/**
* Abstract Database Job
*/
public abstract class AbstractJob extends Job
{
private static final Log log = Log.getLog(AbstractJob.class);
public static final int TIMEOUT_BEFORE_BLOCK_CANCEL = 250;
private DBRProgressMonitor progressMonitor;
private volatile boolean finished = false;
private volatile boolean blockCanceled = false;
private AbstractJob attachedJob = null;
// Attached job may be used to "overwrite" current job.
// It happens if some other AbstractJob runs in sync mode
protected final static ThreadLocal<AbstractJob> CURRENT_JOB = new ThreadLocal<>();
protected AbstractJob(String name)
{
super(name);
}
public boolean isFinished() {
return finished;
}
protected Thread getActiveThread()
{
final Thread thread = getThread();
return thread == null ? Thread.currentThread() : thread;
}
public void setAttachedJob(AbstractJob attachedJob) {
this.attachedJob = attachedJob;
}
public final IStatus runDirectly(DBRProgressMonitor monitor)
{
progressMonitor = monitor;
blockCanceled = false;
try {
finished = false;
IStatus result;
try {
result = this.run(progressMonitor);
} catch (Throwable e) {
result = GeneralUtils.makeExceptionStatus(e);
}
return result;
} finally {
finished = true;
}
}
@Override
protected final IStatus run(IProgressMonitor monitor)
{
progressMonitor = RuntimeUtils.makeMonitor(monitor);
blockCanceled = false;
CURRENT_JOB.set(this);
final Thread currentThread = Thread.currentThread();
final String oldThreadName = currentThread.getName();
try {
finished = false;
RuntimeUtils.setThreadName(getName());
return this.run(progressMonitor);
} finally {
CURRENT_JOB.remove();
finished = true;
currentThread.setName(oldThreadName);
}
}
protected abstract IStatus run(DBRProgressMonitor monitor);
@Override
protected void canceling()
{
if (attachedJob != null) {
attachedJob.canceling();
return;
}
// Run canceling job
if (!blockCanceled) {
Job cancelJob = new Job("Cancel block") { //$NON-N LS-1$
@Override
protected IStatus run(IProgressMonitor monitor)
{
if (!finished && !blockCanceled) {
try {
BlockCanceler.cancelBlock(progressMonitor, getActiveThread());
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
} catch (Throwable e) {
log.debug("Cancel error", e);
return Status.CANCEL_STATUS;
}
blockCanceled = true;
}
return Status.OK_STATUS;
}
};
try {
// Schedule cancel after short pause
cancelJob.schedule(TIMEOUT_BEFORE_BLOCK_CANCEL);
} catch (Exception e) {
// If this happens during shutdown and job manager is not active
log.debug(e);
}
}
}
} | plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/runtime/AbstractJob.java | /*
* DBeaver - Universal Database Manager
* Copyright (C) 2010-2017 Serge Rider ([email protected])
*
* 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.jkiss.dbeaver.model.runtime;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.utils.GeneralUtils;
import org.jkiss.dbeaver.utils.RuntimeUtils;
/**
* Abstract Database Job
*/
public abstract class AbstractJob extends Job
{
private static final Log log = Log.getLog(AbstractJob.class);
public static final int TIMEOUT_BEFORE_BLOCK_CANCEL = 400;
private DBRProgressMonitor progressMonitor;
private volatile boolean finished = false;
private volatile boolean blockCanceled = false;
private int cancelTimeout = TIMEOUT_BEFORE_BLOCK_CANCEL;
private AbstractJob attachedJob = null;
// Attached job may be used to "overwrite" current job.
// It happens if some other AbstractJob runs in sync mode
protected final static ThreadLocal<AbstractJob> CURRENT_JOB = new ThreadLocal<>();
protected AbstractJob(String name)
{
super(name);
}
public int getCancelTimeout()
{
return cancelTimeout;
}
public void setCancelTimeout(int cancelTimeout)
{
this.cancelTimeout = cancelTimeout;
}
public boolean isFinished() {
return finished;
}
protected Thread getActiveThread()
{
final Thread thread = getThread();
return thread == null ? Thread.currentThread() : thread;
}
public void setAttachedJob(AbstractJob attachedJob) {
this.attachedJob = attachedJob;
}
public final IStatus runDirectly(DBRProgressMonitor monitor)
{
progressMonitor = monitor;
blockCanceled = false;
try {
finished = false;
IStatus result;
try {
result = this.run(progressMonitor);
} catch (Throwable e) {
result = GeneralUtils.makeExceptionStatus(e);
}
return result;
} finally {
finished = true;
}
}
@Override
protected final IStatus run(IProgressMonitor monitor)
{
progressMonitor = RuntimeUtils.makeMonitor(monitor);
blockCanceled = false;
CURRENT_JOB.set(this);
final Thread currentThread = Thread.currentThread();
final String oldThreadName = currentThread.getName();
try {
finished = false;
RuntimeUtils.setThreadName(getName());
return this.run(progressMonitor);
} finally {
CURRENT_JOB.remove();
finished = true;
currentThread.setName(oldThreadName);
}
}
protected abstract IStatus run(DBRProgressMonitor monitor);
@Override
protected void canceling()
{
if (attachedJob != null) {
attachedJob.canceling();
return;
}
// Run canceling job
if (!blockCanceled) {
Job cancelJob = new Job("Cancel block") { //$NON-N LS-1$
@Override
protected IStatus run(IProgressMonitor monitor)
{
if (!finished && !blockCanceled) {
try {
BlockCanceler.cancelBlock(progressMonitor, getActiveThread());
} catch (DBException e) {
return GeneralUtils.makeExceptionStatus(e);
} catch (Throwable e) {
log.debug("Cancel error", e);
return Status.CANCEL_STATUS;
}
blockCanceled = true;
}
return Status.OK_STATUS;
}
};
try {
// Cancel it in three seconds
cancelJob.schedule(cancelTimeout);
} catch (Exception e) {
// If this happens during shutdown and job manager is not active
//log.debug(e);
}
}
}
} | #1356 Query/session cancel enhancements
| plugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/runtime/AbstractJob.java | #1356 Query/session cancel enhancements | <ide><path>lugins/org.jkiss.dbeaver.model/src/org/jkiss/dbeaver/model/runtime/AbstractJob.java
<ide> {
<ide> private static final Log log = Log.getLog(AbstractJob.class);
<ide>
<del> public static final int TIMEOUT_BEFORE_BLOCK_CANCEL = 400;
<add> public static final int TIMEOUT_BEFORE_BLOCK_CANCEL = 250;
<ide>
<ide> private DBRProgressMonitor progressMonitor;
<ide> private volatile boolean finished = false;
<ide> private volatile boolean blockCanceled = false;
<del> private int cancelTimeout = TIMEOUT_BEFORE_BLOCK_CANCEL;
<ide> private AbstractJob attachedJob = null;
<ide>
<ide> // Attached job may be used to "overwrite" current job.
<ide> protected AbstractJob(String name)
<ide> {
<ide> super(name);
<del> }
<del>
<del> public int getCancelTimeout()
<del> {
<del> return cancelTimeout;
<del> }
<del>
<del> public void setCancelTimeout(int cancelTimeout)
<del> {
<del> this.cancelTimeout = cancelTimeout;
<ide> }
<ide>
<ide> public boolean isFinished() {
<ide> }
<ide> };
<ide> try {
<del> // Cancel it in three seconds
<del> cancelJob.schedule(cancelTimeout);
<add> // Schedule cancel after short pause
<add> cancelJob.schedule(TIMEOUT_BEFORE_BLOCK_CANCEL);
<ide> } catch (Exception e) {
<ide> // If this happens during shutdown and job manager is not active
<del> //log.debug(e);
<add> log.debug(e);
<ide> }
<ide> }
<ide> } |
|
JavaScript | bsd-3-clause | 6b61e66b39b676e174497cead9151d0dae6db869 | 0 | eatskolnikov/toggl-button,andreimoldo/toggl-button,bitbull-team/toggl-button,topdown/toggl-button,glensc/toggl-button,bitbull-team/toggl-button,glensc/toggl-button,glensc/toggl-button,topdown/toggl-button,andreimoldo/toggl-button,eatskolnikov/toggl-button | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
togglbutton.render('.ha:not(.toggl)', {observe: true}, function (elem) {
var link,
description = $('h2', elem),
project = $('.hX:last-of-type .hN', elem);
if (!description) {
return;
}
link = togglbutton.createTimerLink({
className: 'google-mail',
description: description.textContent,
projectName: !!project && project.textContent.split('/').pop()
});
elem.appendChild(link);
}); | src/scripts/content/google-mail.js | /*jslint indent: 2 */
/*global $: false, document: false, togglbutton: false*/
'use strict';
togglbutton.render('.ha:not(.toggl)', {observe: true}, function (elem) {
var link,
description = $('h2', elem).textContent,
project = $('.hX:last-of-type .hN', elem).textContent.split('/').pop();
link = togglbutton.createTimerLink({
className: 'google-mail',
description: description,
projectName: project
});
elem.appendChild(link);
}); | Added failsafe to Google mail
| src/scripts/content/google-mail.js | Added failsafe to Google mail | <ide><path>rc/scripts/content/google-mail.js
<ide>
<ide> togglbutton.render('.ha:not(.toggl)', {observe: true}, function (elem) {
<ide> var link,
<del> description = $('h2', elem).textContent,
<del> project = $('.hX:last-of-type .hN', elem).textContent.split('/').pop();
<add> description = $('h2', elem),
<add> project = $('.hX:last-of-type .hN', elem);
<add>
<add> if (!description) {
<add> return;
<add> }
<ide>
<ide> link = togglbutton.createTimerLink({
<ide> className: 'google-mail',
<del> description: description,
<del> projectName: project
<add> description: description.textContent,
<add> projectName: !!project && project.textContent.split('/').pop()
<ide> });
<ide>
<ide> elem.appendChild(link); |
|
Java | apache-2.0 | d4e3fa581a08617207e37347651e42566ab97c29 | 0 | baszero/yanel,wyona/yanel,wyona/yanel,wyona/yanel,baszero/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel,wyona/yanel,baszero/yanel | package org.wyona.yanel.servlet;
import java.util.HashMap;
import java.util.Iterator;
import org.wyona.security.core.api.Identity;
/**
* Identity map associating the identities of a user with the realms the user might be signed in (A user can be signed in to multiple realms with different indentities)
*/
public class IdentityMap extends HashMap {
/**
* @see java.lang.Object#toString()
*/
public String toString() {
StringBuilder buf = new StringBuilder();
Iterator iter = this.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object value = this.get(key);
if (value instanceof Identity) {
buf.append(((Identity)value).getUsername());
buf.append(" (" + key + " realm)");
if (iter.hasNext()) {
buf.append(", ");
}
}
}
return buf.toString();
}
}
| src/webapp/src/java/org/wyona/yanel/servlet/IdentityMap.java | package org.wyona.yanel.servlet;
import java.util.HashMap;
import java.util.Iterator;
import org.wyona.security.core.api.Identity;
/**
* Identity map to get a nice toString() output
*/
public class IdentityMap extends HashMap {
public String toString() {
StringBuffer buf = new StringBuffer();
Iterator iter = this.keySet().iterator();
while (iter.hasNext()) {
Object key = iter.next();
Object value = this.get(key);
if (value instanceof Identity) {
buf.append(((Identity)value).getUsername());
buf.append(" (" + key + " realm)");
if (iter.hasNext()) {
buf.append(", ");
}
}
}
return buf.toString();
}
}
| javadoc clarified and improved and String buffer by builder replaced
| src/webapp/src/java/org/wyona/yanel/servlet/IdentityMap.java | javadoc clarified and improved and String buffer by builder replaced | <ide><path>rc/webapp/src/java/org/wyona/yanel/servlet/IdentityMap.java
<ide> import org.wyona.security.core.api.Identity;
<ide>
<ide> /**
<del> * Identity map to get a nice toString() output
<add> * Identity map associating the identities of a user with the realms the user might be signed in (A user can be signed in to multiple realms with different indentities)
<ide> */
<ide> public class IdentityMap extends HashMap {
<ide>
<add> /**
<add> * @see java.lang.Object#toString()
<add> */
<ide> public String toString() {
<del> StringBuffer buf = new StringBuffer();
<add> StringBuilder buf = new StringBuilder();
<ide> Iterator iter = this.keySet().iterator();
<ide> while (iter.hasNext()) {
<ide> Object key = iter.next(); |
|
JavaScript | mit | da4a13d4d85ef51041ed8e8649a55fceeffc7ff4 | 0 | wakaber/Dollchan-Extension-Tools,Y0ba/Dollchan-Extension-Tools,Y0ba/Dollchan-Extension-Tools,lisanyan/Dollchan-Extension-Tools,2Rainbow/Dollchan-Extension-Tools,SthephanShinkufag/Dollchan-Extension-Tools,miku-nyan/Dollchan-Extension-Tools,aslian/Dollchan-Extension-Tools,SthephanShinkufag/Dollchan-Extension-Tools | // ==UserScript==
// @name Dollchan Extension Tools
// @version 14.2.17.0
// @namespace http://www.freedollchan.org/scripts/*
// @author Sthephan Shinkufag @ FreeDollChan
// @copyright (C)2084, Bender Bending Rodriguez
// @description Doing some profit for imageboards
// @icon https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Icon.png
// @updateURL https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js
// @run-at document-start
// @include http://*
// @include https://*
// ==/UserScript==
(function de_main_func(scriptStorage) {
var version = '14.2.17.0',
defaultCfg = {
'language': 0, // script language [0=ru, 1=en]
'hideBySpell': 1, // hide posts by spells
'spells': '', // user defined spells
'sortSpells': 0, // sort spells when applying
'menuHiddBtn': 1, // menu on hide button
'hideRefPsts': 0, // hide post with references to hidden posts
'delHiddPost': 0, // delete hidden posts
'ajaxUpdThr': 1, // auto update threads
'updThrDelay': 60, // threads update interval in sec
'noErrInTitle': 0, // don't show error number in title except 404
'favIcoBlink': 1, // favicon blinking, if new posts detected
'markNewPosts': 1, // new posts marking on page focus
'desktNotif': 0, // desktop notifications, if new posts detected
'expandPosts': 2, // expand shorted posts [0=off, 1=auto, 2=on click]
'postBtnsCSS': 2, // post buttons style [0=text, 1=classic, 2=solid grey]
'noSpoilers': 1, // open spoilers
'noPostNames': 0, // hide post names
'noPostScrl': 1, // no scroll in posts
'correctTime': 0, // correct time in posts
'timeOffset': '+0', // offset in hours
'timePattern': '', // find pattern
'timeRPattern': '', // replace pattern
'expandImgs': 2, // expand images by click [0=off, 1=in post, 2=by center]
'resizeImgs': 1, // resize large images
'maskImgs': 0, // mask images
'preLoadImgs': 0, // pre-load images
'findImgFile': 0, // detect built-in files in images
'openImgs': 0, // open images in posts
'openGIFs': 0, // open only GIFs in posts
'imgSrcBtns': 1, // add image search buttons
'linksNavig': 2, // navigation by >>links [0=off, 1=no map, 2=+refmap]
'linksOver': 100, // delay appearance in ms
'linksOut': 1500, // delay disappearance in ms
'markViewed': 0, // mark viewed posts
'strikeHidd': 0, // strike >>links to hidden posts
'noNavigHidd': 0, // don't show previews for hidden posts
'crossLinks': 0, // replace http: to >>/b/links
'insertNum': 1, // insert >>link on postnumber click
'addMP3': 1, // embed mp3 links
'addImgs': 0, // embed links to images
'addYouTube': 3, // embed YouTube links [0=off, 1=onclick, 2=player, 3=preview+player, 4=only preview]
'YTubeType': 0, // player type [0=flash, 1=HTML5]
'YTubeWidth': 360, // player width
'YTubeHeigh': 270, // player height
'YTubeHD': 0, // hd video quality
'YTubeTitles': 0, // convert links to titles
'addVimeo': 1, // embed vimeo links
'ajaxReply': 2, // posting with AJAX (0=no, 1=iframe, 2=HTML5)
'postSameImg': 1, // ability to post same images
'removeEXIF': 1, // remove EXIF data from JPEGs
'removeFName': 0, // remove file name
'addPostForm': 2, // postform displayed [0=at top, 1=at bottom, 2=hidden, 3=hanging]
'scrAfterRep': 0, // scroll to the bottom after reply
'favOnReply': 1, // add thread to favorites on reply
'addSageBtn': 1, // email field -> sage btn
'saveSage': 1, // remember sage
'sageReply': 0, // reply with sage
'warnSubjTrip': 0, // warn if subject field contains tripcode
'captchaLang': 1, // language input in captcha [0=off, 1=en, 2=ru]
'addTextBtns': 1, // text format buttons [0=off, 1=graphics, 2=text, 3=usual]
'txtBtnsLoc': 0, // located at [0=top, 1=bottom]
'passwValue': '', // user password value
'userName': 0, // user name
'nameValue': '', // value
'userSignat': 0, // user signature
'signatValue': '', // value
'noBoardRule': 1, // hide board rules
'noGoto': 1, // hide goto field
'noPassword': 1, // hide password field
'scriptStyle': 0, // script style [0=glass black, 1=glass blue, 2=solid grey]
'userCSS': 0, // user style
'userCSSTxt': '', // css text
'expandPanel': 0, // show full main panel
'attachPanel': 1, // attach main panel
'panelCounter': 1, // posts/images counter in script panel
'rePageTitle': 1, // replace page title in threads
'animation': 1, // animation in script
'closePopups': 0, // auto-close popups
'keybNavig': 1, // keyboard navigation
'loadPages': 1, // number of pages that are loaded on F5
'updScript': 1, // check for script's update
'scrUpdIntrv': 1, // check interval in days (every val+1 day)
'textaWidth': 500, // textarea width
'textaHeight': 160 // textarea height
},
Lng = {
cfg: {
'hideBySpell': ['Заклинания: ', 'Magic spells: '],
'sortSpells': ['Сортировать спеллы и удалять дубликаты', 'Sort spells and delete duplicates'],
'menuHiddBtn': ['Дополнительное меню кнопок скрытия ', 'Additional menu of hide buttons'],
'hideRefPsts': ['Скрывать ответы на скрытые посты*', 'Hide replies to hidden posts*'],
'delHiddPost': ['Удалять скрытые посты', 'Delete hidden posts'],
'ajaxUpdThr': ['AJAX обновление треда ', 'AJAX thread update '],
'updThrDelay': [' (сек)', ' (sec)'],
'noErrInTitle': ['Не показывать номер ошибки в заголовке', 'Don\'t show error number in title'],
'favIcoBlink': ['Мигать фавиконом при новых постах', 'Favicon blinking on new posts'],
'markNewPosts': ['Выделять новые посты при переключении на тред', 'Mark new posts on page focus'],
'desktNotif': ['Уведомления на рабочем столе', 'Desktop notifications'],
'expandPosts': {
sel: [['Откл.', 'Авто', 'По клику'], ['Disable', 'Auto', 'On click']],
txt: ['AJAX загрузка сокращенных постов*', 'AJAX upload of shorted posts*']
},
'postBtnsCSS': {
sel: [['Text', 'Classic', 'Solid grey'], ['Text', 'Classic', 'Solid grey']],
txt: ['Стиль кнопок постов*', 'Post buttons style*']
},
'noSpoilers': ['Открывать текстовые спойлеры', 'Open text spoilers'],
'noPostNames': ['Скрывать имена в постах', 'Hide names in posts'],
'noPostScrl': ['Без скролла в постах', 'No scroll in posts'],
'keybNavig': ['Навигация с помощью клавиатуры ', 'Navigation with keyboard '],
'loadPages': [' Количество страниц, загружаемых по F5', ' Number of pages that are loaded on F5 '],
'correctTime': ['Корректировать время в постах* ', 'Correct time in posts* '],
'timeOffset': [' Разница во времени', ' Time difference'],
'timePattern': [' Шаблон поиска', ' Find pattern'],
'timeRPattern': [' Шаблон замены', ' Replace pattern'],
'expandImgs': {
sel: [['Откл.', 'В посте', 'По центру'], ['Disable', 'In post', 'By center']],
txt: ['раскрывать изображения по клику', 'expand images on click']
},
'resizeImgs': ['Уменьшать в экран большие изображения', 'Resize large images to fit screen'],
'preLoadImgs': ['Предварительно загружать изображения*', 'Pre-load images*'],
'findImgFile': ['Распознавать встроенные файлы в изображениях*', 'Detect built-in files in images*'],
'openImgs': ['Скачивать полные версии изображений*', 'Download full version of images*'],
'openGIFs': ['Скачивать только GIFы*', 'Download GIFs only*'],
'imgSrcBtns': ['Добавлять кнопки для поиска изображений*', 'Add image search buttons*'],
'linksNavig': {
sel: [['Откл.', 'Без карты', 'С картой'], ['Disable', 'No map', 'With map']],
txt: ['навигация по >>ссылкам* ', 'navigation by >>links* ']
},
'linksOver': [' задержка появления (мс)', ' delay appearance (ms)'],
'linksOut': [' задержка пропадания (мс)', ' delay disappearance (ms)'],
'markViewed': ['Отмечать просмотренные посты*', 'Mark viewed posts*'],
'strikeHidd': ['Зачеркивать >>ссылки на скрытые посты', 'Strike >>links to hidden posts'],
'noNavigHidd': ['Не отображать превью для скрытых постов', 'Don\'t show previews for hidden posts'],
'crossLinks': ['Преобразовывать http:// в >>/b/ссылки*', 'Replace http:// with >>/b/links*'],
'insertNum': ['Вставлять >>ссылку по клику на №поста*', 'Insert >>link on №postnumber click*'],
'addMP3': ['Добавлять плейер к mp3 ссылкам* ', 'Add player to mp3 links* '],
'addVimeo': ['Добавлять плейер к Vimeo ссылкам* ', 'Add player to Vimeo links* '],
'addImgs': ['Загружать изображения к .jpg-, .png-, .gif-ссылкам*', 'Load images to .jpg-, .png-, .gif-links*'],
'addYouTube': {
sel: [['Ничего', 'Плейер по клику', 'Авто плейер', 'Превью+плейер', 'Только превью'], ['Nothing', 'On click player', 'Auto player', 'Preview+player', 'Only preview']],
txt: ['к YouTube-ссылкам* ', 'to YouTube-links* ']
},
'YTubeType': {
sel: [['Flash', 'HTML5'], ['Flash', 'HTML5']],
txt: ['', '']
},
'YTubeHD': ['HD ', 'HD '],
'YTubeTitles': ['Загружать названия к YouTube-ссылкам*', 'Load titles into YouTube-links*'],
'ajaxReply': {
sel: [['Откл.', 'Iframe', 'HTML5'], ['Disable', 'Iframe', 'HTML5']],
txt: ['AJAX отправка постов*', 'posting with AJAX*']
},
'postSameImg': ['Возможность отправки одинаковых изображений', 'Ability to post same images'],
'removeEXIF': ['Удалять EXIF из отправляемых JPEG-изображений', 'Remove EXIF from uploaded JPEG-images'],
'removeFName': ['Удалять имя из отправляемых файлов', 'Remove names from uploaded files'],
'addPostForm': {
sel: [['Сверху', 'Внизу', 'Скрытая', 'Отдельная'], ['At top', 'At bottom', 'Hidden', 'Hanging']],
txt: ['форма ответа в треде* ', 'reply form in thread* ']
},
'scrAfterRep': ['Перемещаться в конец треда после отправки', 'Scroll to the bottom after reply'],
'favOnReply': ['Добавлять тред в избранное при ответе', 'Add thread to favorites on reply'],
'addSageBtn': ['Sage вместо поля E-mail* ', 'Sage button instead of E-mail field* '],
'warnSubjTrip': ['Предупреждать при наличии трип-кода в поле тема', 'Warn if field subject contains trip-code'],
'saveSage': ['запоминать сажу', 'remember sage'],
'captchaLang': {
sel: [['Откл.', 'Eng', 'Rus'], ['Disable', 'Eng', 'Rus']],
txt: ['язык ввода капчи', 'language input in captcha']
},
'addTextBtns': {
sel: [['Откл.', 'Графич.', 'Упрощ.', 'Стандарт.'], ['Disable', 'As images', 'As text', 'Standard']],
txt: ['кнопки форматирования текста ', 'text format buttons ']
},
'txtBtnsLoc': ['внизу', 'at bottom'],
'userPassw': [' Постоянный пароль ', ' Fixed password '],
'userName': ['Постоянное имя', 'Fixed name'],
'userSignat': ['Постоянная подпись', 'Fixed signature'],
'noBoardRule': ['правила ', 'rules '],
'noGoto': ['поле goto ', 'goto field '],
'noPassword': ['пароль', 'password'],
'scriptStyle': {
sel: [['Glass black', 'Glass blue', 'Solid grey'], ['Glass black', 'Glass blue', 'Solid grey']],
txt: ['стиль скрипта', 'script style']
},
'userCSS': ['Пользовательский CSS ', 'User CSS '],
'attachPanel': ['Прикрепить главную панель', 'Attach main panel'],
'panelCounter': ['Счетчик постов/изображений на главной панели', 'Counter of posts/images on main panel'],
'rePageTitle': ['Название треда в заголовке вкладки*', 'Thread title in page tab*'],
'animation': ['CSS3 анимация в скрипте', 'CSS3 animation in script'],
'closePopups': ['Автоматически закрывать уведомления', 'Close popups automatically'],
'updScript': ['Автоматически проверять обновления скрипта', 'Check for script update automatically'],
'scrUpdIntrv': {
sel: [['Каждый день', 'Каждые 2 дня', 'Каждую неделю', 'Каждые 2 недели', 'Каждый месяц'], ['Every day', 'Every 2 days', 'Every week', 'Every 2 week', 'Every month']],
txt: ['', '']
},
'language': {
sel: [['Ru', 'En'], ['Ru', 'En']],
txt: ['', '']
}
},
txtBtn: [
['Жирный', 'Bold'],
['Наклонный', 'Italic'],
['Подчеркнутый', 'Underlined'],
['Зачеркнутый', 'Strike'],
['Спойлер', 'Spoiler'],
['Код', 'Code'],
['Верхний индекс', 'Superscript'],
['Нижний индекс', 'Subscript'],
['Цитировать выделенное', 'Quote selected']
],
cfgTab: {
'filters': ['Фильтры', 'Filters'],
'posts': ['Посты', 'Posts'],
'images': ['Картинки', 'Images'],
'links': ['Ссылки', 'Links'],
'form': ['Форма', 'Form'],
'common': ['Общее', 'Common'],
'info': ['Инфо', 'Info']
},
panelBtn: {
'attach': ['Прикрепить/Открепить', 'Attach/Detach'],
'settings': ['Настройки', 'Settings'],
'hidden': ['Скрытое', 'Hidden'],
'favor': ['Избранное', 'Favorites'],
'refresh': ['Обновить', 'Refresh'],
'goback': ['Назад', 'Go back'],
'gonext': ['Следующая', 'Next'],
'goup': ['Наверх', 'To the top'],
'godown': ['В конец', 'To the bottom'],
'expimg': ['Раскрыть картинки', 'Expand images'],
'preimg': ['Предзагрузка картинок', 'Preload images'],
'maskimg': ['Маскировать картинки', 'Mask images'],
'upd-on': ['Выключить автообновление треда', 'Disable thread autoupdate'],
'upd-off': ['Включить автообновление треда', 'Enable thread autoupdate'],
'audio-off':['Звуковое оповещение о новых постах', 'Sound notification about new posts'],
'catalog': ['Каталог', 'Catalog'],
'counter': ['Постов/Изображений в треде', 'Posts/Images in thread'],
'imgload': ['Сохранить изображения из треда', 'Save images from thread']
},
selHiderMenu: {
'sel': ['Скрывать выделенное', 'Hide selected text'],
'name': ['Скрывать имя', 'Hide name'],
'trip': ['Скрывать трип-код', 'Hide with trip-code'],
'img': ['Скрывать изображение', 'Hide with image'],
'ihash': ['Скрывать схожие изобр.', 'Hide similar images'],
'text': ['Скрыть схожий текст', 'Hide similar text'],
'noimg': ['Скрывать без изображений', 'Hide without images'],
'notext': ['Скрывать без текста', 'Hide without text']
},
selExpandThrd: [
['5 постов', '15 постов', '30 постов', '50 постов', '100 постов'],
['5 posts', '15 posts', '30 posts', '50 posts', '100 posts']
],
selAjaxPages: [
['1 страница', '2 страницы', '3 страницы', '4 страницы', '5 страниц'],
['1 page', '2 pages', '3 pages', '4 pages', '5 pages']
],
selAudioNotif: [
['Каждые 30 сек.', 'Каждую минуту', 'Каждые 2 мин.', 'Каждые 5 мин.'],
['Every 30 sec.', 'Every minute', 'Every 2 min.', 'Every 5 min.']
],
keyNavEdit: [
'%l%i24 – предыдущая страница%/l' +
'%l%i217 – следующая страница%/l' +
'%l%i23 – скрыть текущий пост/тред%/l' +
'%l%i33 – раскрыть текущий тред%/l' +
'%l%i22 – быстрый ответ или создать тред%/l' +
'%l%i25t – отправить пост%/l' +
'%l%i21 – тред (на доске)/пост (в треде) ниже%/l' +
'%l%i20 – тред (на доске)/пост (в треде) выше%/l' +
'%l%i31 – пост (на доске) ниже%/l' +
'%l%i30 – пост (на доске) выше%/l' +
'%l%i32 – открыть тред%/l' +
'%l%i210 – открыть/закрыть настройки%/l' +
'%l%i26 – открыть/закрыть избранное%/l' +
'%l%i27 – открыть/закрыть скрытые посты%/l' +
'%l%i28 – открыть/закрыть панель%/l' +
'%l%i29 – включить/выключить маскировку изображений%/l' +
'%l%i40 – обновить тред%/l' +
'%l%i211 – раскрыть изображение текущего поста%/l' +
'%l%i212t – жирный%/l' +
'%l%i213t – курсив%/l' +
'%l%i214t – зачеркнутый%/l' +
'%l%i215t – спойлер%/l' +
'%l%i216t – код%/l',
'%l%i24 – previous page%/l' +
'%l%i217 – next page%/l' +
'%l%i23 – hide current post/thread%/l' +
'%l%i33 – expand current thread%/l' +
'%l%i22 – quick reply or create thread%/l' +
'%l%i25t – send post%/l' +
'%l%i21 – thread (on board) / post (in thread) below%/l' +
'%l%i20 – thread (on board) / post (in thread) above%/l' +
'%l%i31 – on board post below%/l' +
'%l%i30 – on board post above%/l' +
'%l%i32 – open thread%/l' +
'%l%i210 – open/close Settings%/l' +
'%l%i26 – open/close Favorites%/l' +
'%l%i27 – open/close Hidden Posts Table%/l' +
'%l%i28 – open/close the main panel%/l' +
'%l%i29 – turn on/off masking images%/l' +
'%l%i40 – update thread%/l' +
'%l%i211 – expand current post\'s images%/l' +
'%l%i212t – bold%/l' +
'%l%i213t – italic%/l' +
'%l%i214t – strike%/l' +
'%l%i215t – spoiler%/l' +
'%l%i216t – code%/l'
],
month: [
['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
],
fullMonth: [
['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'],
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
],
week: [
['Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'],
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
],
editor: {
cfg: ['Редактирование настроек:', 'Edit settings:'],
hidden: ['Редактирование скрытых тредов:', 'Edit hidden threads:'],
favor: ['Редактирование избранного:', 'Edit favorites:'],
css: ['Редактирование CSS', 'Edit CSS']
},
newPost: [
[' новый пост', ' новых поста', ' новых постов', '. Последний:'],
[' new post', ' new posts', ' new posts', '. Latest: ']
],
add: ['Добавить', 'Add'],
apply: ['Применить', 'Apply'],
clear: ['Очистить', 'Clear'],
refresh: ['Обновить', 'Refresh'],
load: ['Загрузить', 'Load'],
save: ['Сохранить', 'Save'],
edit: ['Правка', 'Edit'],
reset: ['Сброс', 'Reset'],
remove: ['Удалить', 'Remove'],
info: ['Инфо', 'Info'],
undo: ['Отмена', 'Undo'],
change: ['Сменить', 'Change'],
reply: ['Ответ', 'Reply'],
loading: ['Загрузка...', 'Loading...'],
checking: ['Проверка...', 'Checking...'],
deleting: ['Удаление...', 'Deleting...'],
error: ['Ошибка:', 'Error:'],
noConnect: ['Ошибка подключения', 'Connection failed'],
thrNotFound: ['Тред недоступен (№', 'Thread is unavailable (№'],
succDeleted: ['Успешно удалено!', 'Succesfully deleted!'],
errDelete: ['Не могу удалить:\n', 'Can\'t delete:\n'],
cTimeError: ['Неправильные настройки времени', 'Invalid time settings'],
noGlobalCfg: ['Глобальные настройки не найдены', 'Global config not found'],
postNotFound: ['Пост не найден', 'Post not found'],
dontShow: ['Не отображать: ', 'Do not show: '],
checkNow: ['Проверить сейчас', 'Check now'],
updAvail: ['Доступно обновление!', 'Update available!'],
haveLatest: ['У вас стоит самая последняя версия!', 'You have latest version!'],
storage: ['Хранение: ', 'Storage: '],
thrViewed: ['Тредов просмотрено: ', 'Threads viewed: '],
thrCreated: ['Тредов создано: ', 'Threads created: '],
thrHidden: ['Тредов скрыто: ', 'Threads hidden: '],
postsSent: ['Постов отправлено: ', 'Posts sent: '],
total: ['Всего: ', 'Total: '],
debug: ['Отладка', 'Debug'],
infoDebug: ['Информация для отладки', 'Information for debugging'],
loadGlobal: ['Загрузить глобальные настройки', 'Load global settings'],
saveGlobal: ['Сохранить настройки как глобальные', 'Save settings as global'],
editInTxt: ['Правка в текстовом формате', 'Edit in text format'],
resetCfg: ['Сбросить в настройки по умолчанию', 'Reset settings to defaults'],
conReset: ['Данное действие удалит все ваши настройки и закладки. Продолжить?', 'This will delete all your preferences and favourites. Continue?'],
clrSelected: ['Удалить выделенные записи', 'Remove selected notes'],
saveChanges: ['Сохранить внесенные изменения', 'Save your changes'],
infoCount: ['Обновить счетчики постов', 'Refresh posts counters'],
infoPage: ['Проверить актуальность тредов (до 5 страницы)', 'Check for threads actuality (up to 5 page)'],
clrDeleted: ['Очистить записи недоступных тредов', 'Clear notes of inaccessible threads'],
hiddenPosts: ['Скрытые посты на странице', 'Hidden posts on page'],
hiddenThrds: ['Скрытые треды', 'Hidden threads'],
noHidPosts: ['На этой странице нет скрытых постов...', 'No hidden posts on this page...'],
noHidThrds: ['Нет скрытых тредов...', 'No hidden threads...'],
expandAll: ['Раскрыть все', 'Expand all'],
invalidData: ['Некорректный формат данных', 'Incorrect data format'],
favThrds: ['Избранные треды:', 'Favorite threads:'],
noFavThrds: ['Нет избранных тредов...', 'Favorites is empty...'],
reply: ['Ответ', 'Reply'],
replyTo: ['Ответ в', 'Reply to'],
replies: ['Ответы:', 'Replies:'],
postsOmitted: ['Пропущено ответов: ', 'Posts omitted: '],
collapseThrd: ['Свернуть тред', 'Collapse thread'],
deleted: ['удалён', 'deleted'],
getNewPosts: ['Получить новые посты', 'Get new posts'],
page: ['Страница', 'Page'],
hiddenThrd: ['Скрытый тред:', 'Hidden thread:'],
makeThrd: ['Создать тред', 'Create thread'],
makeReply: ['Ответить', 'Make reply'],
hideForm: ['Закрыть форму', 'Hide form'],
search: ['Искать в ', 'Search in '],
wait: ['Ждите', 'Wait'],
addFile: ['+ файл', '+ file'],
helpAddFile: ['Добавить .ogg, .rar, .zip, или .7z к картинке', 'Add .ogg, .rar, .zip, or .7z to image '],
downloadFile: ['Скачать содержащийся в картинке файл', 'Download existing file from image'],
fileCorrupt: ['Файл повреждён: ', 'File is corrupted: '],
subjHasTrip: ['Поле "Тема" содержит трипкод', '"Subject" field contains tripcode'],
loadImage: ['Загружаются изображения: ', 'Loading images: '],
loadFile: ['Загружаются файлы: ', 'Loading files: '],
cantLoad: ['Не могу загрузить ', 'Can\'t load '],
willSavePview: ['Будет сохранено превью', 'Thumb will be saved'],
loadErrors: ['Во время загрузки произошли ошибки:', 'Warning:'],
errCorruptData: ['Ошибка: сервер отправил повреждённые данные', 'Error: server sent corrupted data'],
nextImg: ['Следующее изображение', 'Next image'],
prevImg: ['Предыдущее изображение', 'Previous image'],
seSyntaxErr: ['синтаксическая ошибка в аргументе спелла: %s', 'syntax error in argument of spell: %s'],
seUnknown: ['неизвестный спелл: %s', 'unknown spell: %s'],
seMissOp: ['пропущен оператор', 'missing operator'],
seMissArg: ['пропущен аргумент спелла: %s', 'missing argument of spell: %s'],
seMissSpell: ['пропущен спелл', 'missing spell'],
seErrRegex: ['синтаксическая ошибка в регулярном выражении: %s', 'syntax error in regular expression: %s'],
seUnexpChar: ['неожиданный символ: %s', 'unexpected character: %s'],
seMissClBkt: ['пропущена закрывающаяся скобка', 'missing ) in parenthetical'],
seRow: [' (строка ', ' (row '],
seCol: [', столбец ', ', column ']
},
doc = window.document, aProto = Array.prototype,
Cfg, comCfg, hThr, Favor, pByNum, sVis, bUVis, uVis, needScroll,
aib, nav, brd, TNum, pageNum, updater, youTube, keyNav, firstThr, lastThr, visPosts = 2,
pr, dForm, dummy, spells,
Images_ = {preloading: false, afterpreload: null, progressId: null, canvas: null},
oldTime, timeLog = [], dTime,
ajaxInterval, lang, quotetxt = '', liteMode, isExpImg, isPreImg,
$each = Function.prototype.call.bind(aProto.forEach),
emptyFn = function() {};
//============================================================================================================
// UTILITIES
//============================================================================================================
function $Q(path, root) {
return root.querySelectorAll(path);
}
function $q(path, root) {
return root.querySelector(path);
}
function $C(id, root) {
return root.getElementsByClassName(id);
}
function $c(id, root) {
return root.getElementsByClassName(id)[0];
}
function $id(id) {
return doc.getElementById(id);
}
function $T(id, root) {
return root.getElementsByTagName(id);
}
function $t(id, root) {
return root.getElementsByTagName(id)[0];
}
function $append(el, nodes) {
for(var i = 0, len = nodes.length; i < len; i++) {
if(nodes[i]) {
el.appendChild(nodes[i]);
}
}
}
function $before(el, node) {
el.parentNode.insertBefore(node, el);
}
function $after(el, node) {
el.parentNode.insertBefore(node, el.nextSibling);
}
function $add(html) {
dummy.innerHTML = html;
return dummy.firstChild;
}
function $new(tag, attr, events) {
var el = doc.createElement(tag);
if(attr) {
for(var key in attr) {
key === 'text' ? el.textContent = attr[key] :
key === 'value' ? el.value = attr[key] :
el.setAttribute(key, attr[key]);
}
}
if(events) {
for(var key in events) {
el.addEventListener(key, events[key], false);
}
}
return el;
}
function $New(tag, attr, nodes) {
var el = $new(tag, attr, null);
$append(el, nodes);
return el;
}
function $txt(el) {
return doc.createTextNode(el);
}
function $btn(val, ttl, Fn) {
return $new('input', {'type': 'button', 'value': val, 'title': ttl}, {'click': Fn});
}
function $script(text) {
$del(doc.head.appendChild($new('script', {'type': 'text/javascript', 'text': text}, null)));
}
function $css(text) {
return doc.head.appendChild($new('style', {'type': 'text/css', 'text': text}, null));
}
function $if(cond, el) {
return cond ? el : null;
}
function $disp(el) {
el.style.display = el.style.display === 'none' ? '' : 'none';
}
function $del(el) {
if(el) {
el.parentNode.removeChild(el);
}
}
function $DOM(html) {
var myDoc = doc.implementation.createHTMLDocument('');
myDoc.documentElement.innerHTML = html;
return myDoc;
}
function $getStyle(el, prop) {
return getComputedStyle(el).getPropertyValue(prop);
}
function $pd(e) {
e.preventDefault();
}
function $txtInsert(el, txt) {
var scrtop = el.scrollTop,
start = el.selectionStart;
el.value = el.value.substr(0, start) + txt + el.value.substr(el.selectionEnd);
el.setSelectionRange(start + txt.length, start + txt.length);
el.focus();
el.scrollTop = scrtop;
}
function $txtSelect() {
return (nav.Opera ? doc.getSelection() : window.getSelection()).toString();
}
function $isEmpty(obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
return false;
}
}
return true;
}
function $log(txt) {
var newTime = Date.now(),
time = newTime - oldTime;
if(time > 1) {
timeLog.push(txt + ': ' + time + 'ms');
oldTime = newTime;
}
}
function $xhr(obj) {
var h, xhr = new window.XMLHttpRequest();
if(obj['onreadystatechange']) {
xhr.onreadystatechange = obj['onreadystatechange'].bind(window, xhr);
}
if(obj['onload']) {
xhr.onload = obj['onload'].bind(window, xhr);
}
xhr.open(obj['method'], obj['url'], true);
if(obj['responseType']) {
xhr.responseType = obj['responseType'];
}
for(h in obj['headers']) {
xhr.setRequestHeader(h, obj['headers'][h]);
}
xhr.send(obj['data'] || null);
return xhr;
}
function $queue(maxNum, Fn, endFn) {
this.array = [];
this.length = this.index = this.running = 0;
this.num = 1;
this.fn = Fn;
this.endFn = endFn;
this.max = maxNum;
this.freeSlots = [];
while(maxNum--) {
this.freeSlots.push(maxNum);
}
this.completed = this.paused = false;
}
$queue.prototype = {
run: function(data) {
if(this.paused || this.running === this.max) {
this.array.push(data);
this.length++;
} else {
this.fn(this.freeSlots.pop(), this.num++, data);
this.running++;
}
},
end: function(qIdx) {
if(!this.paused && this.index < this.length) {
this.fn(qIdx, this.num++, this.array[this.index++]);
return;
}
this.running--;
this.freeSlots.push(qIdx);
if(!this.paused && this.completed && this.running === 0) {
this.endFn();
}
},
complete: function() {
if(this.index >= this.length && this.running === 0) {
this.endFn();
} else {
this.completed = true;
}
},
pause: function() {
this.paused = true;
},
'continue': function() {
this.paused = false;
if(this.index >= this.length) {
if(this.completed) {
this.endFn();
}
return;
}
while(this.index < this.length && this.running !== this.max) {
this.fn(this.freeSlots.pop(), this.num++, this.array[this.index++]);
this.running++;
}
}
};
function $tar() {
this._data = [];
}
$tar.prototype = {
addFile: function(filepath, input) {
var i, checksum, nameLen, fileSize = input.length,
header = new Uint8Array(512);
for(i = 0, nameLen = Math.min(filepath.length, 100); i < nameLen; ++i) {
header[i] = filepath.charCodeAt(i) & 0xFF;
}
this._padSet(header, 100, '100777', 8); // fileMode
this._padSet(header, 108, '0', 8); // uid
this._padSet(header, 116, '0', 8); // gid
this._padSet(header, 124, fileSize.toString(8), 13); // fileSize
this._padSet(header, 136, Math.floor(Date.now() / 1000).toString(8), 12); // mtime
this._padSet(header, 148, ' ', 8); // checksum
header[156] = 0x30; // type ('0')
for(i = checksum = 0; i < 157; i++) {
checksum += header[i];
}
this._padSet(header, 148, checksum.toString(8), 8); // checksum
this._data.push(header);
this._data.push(input);
if((i = Math.ceil(fileSize / 512) * 512 - fileSize) !== 0) {
this._data.push(new Uint8Array(i));
}
},
addString: function(filepath, str) {
var i, len, data, sDat = unescape(encodeURIComponent(str));
for(i = 0, len = sDat.length, data = new Uint8Array(len); i < len; ++i) {
data[i] = sDat.charCodeAt(i) & 0xFF;
}
this.addFile(filepath, data);
},
get: function() {
this._data.push(new Uint8Array(1024));
return new Blob(this._data, {'type': 'application/x-tar'});
},
_padSet: function(data, offset, num, len) {
var i = 0, nLen = num.length;
len -= 2;
while(nLen < len) {
data[offset++] = 0x20; // ' '
len--;
}
while(i < nLen) {
data[offset++] = num.charCodeAt(i++);
}
data[offset] = 0x20; // ' '
}
};
function $workers(source, count) {
var i, wrk, wUrl;
if(nav.Firefox) {
wUrl = 'data:text/javascript,' + source;
wrk = unsafeWindow.Worker;
} else {
wUrl = window.URL.createObjectURL(new Blob([source], {'type': 'text/javascript'}));
this.url = wUrl;
wrk = Worker;
}
for(i = 0; i < count; ++i) {
this[i] = new wrk(wUrl);
}
}
$workers.prototype = {
url: null,
clear: function() {
if(this.url !== null) {
window.URL.revokeObjectURL(this.url);
}
}
};
function regQuote(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|\-])/g, '\\$1');
}
function getImages(el) {
return el.querySelectorAll('.thumb, .de-thumb, .ca_thumb, ' +
'img[src*="thumb"], img[src*="/spoiler"], img[src^="blob:"]');
}
function fixBrd(b) {
return '/' + b + (b ? '/' : '');
}
function getAbsLink(url) {
return url[1] === '/' ? aib.prot + url :
url[0] === '/' ? aib.prot + '//' + aib.host + url : url;
}
function getErrorMessage(eCode, eMsg) {
return eCode === 0 ? eMsg || Lng.noConnect[lang] : 'HTTP [' + eCode + '] ' + eMsg;
}
function getAncestor(el, tagName) {
do {
el = el.parentElement;
} while(el && el.tagName !== tagName);
return el;
}
function getPrettyErrorMessage(e) {
return e.stack ? (nav.WebKit ? e.stack :
e.name + ': ' + e.message + '\n' +
(nav.Firefox ? e.stack.replace(/^([^@]*).*\/(.+)$/gm, function(str, fName, line) {
return ' at ' + (fName ? fName + ' (' + line + ')' : line);
}) : e.stack)
) : e.name + ': ' + e.message;
}
function toRegExp(str, noG) {
var l = str.lastIndexOf('/'),
flags = str.substr(l + 1);
return new RegExp(str.substr(1, l - 1), noG ? flags.replace('g', '') : flags);
}
//============================================================================================================
// STORAGE & CONFIG
//============================================================================================================
function getStored(id) {
return nav.isGM ? GM_getValue(id) :
nav.isSStorage ? scriptStorage.getItem(id) :
localStorage.getItem(id);
}
function setStored(id, value) {
if(nav.isGM) {
GM_setValue(id, value);
} else if(nav.isSStorage) {
scriptStorage.setItem(id, value);
} else {
localStorage.setItem(id, value);
}
}
function delStored(id) {
if(nav.isGM) {
GM_deleteValue(id);
} else if(nav.isSStorage) {
scriptStorage.removeItem(id);
} else {
localStorage.removeItem(id);
}
}
function getStoredObj(id) {
try {
var data = JSON.parse(getStored(id));
} finally {
return data || {};
}
}
function saveComCfg(dm, obj) {
comCfg = getStoredObj('DESU_Config');
if(obj) {
comCfg[dm] = obj;
} else {
delete comCfg[dm];
}
setStored('DESU_Config', JSON.stringify(comCfg) || '');
}
function saveCfg(id, val) {
if(Cfg[id] !== val) {
Cfg[id] = val;
saveComCfg(aib.dm, Cfg);
}
}
function readCfg() {
comCfg = getStoredObj('DESU_Config');
if(!(aib.dm in comCfg) || $isEmpty(Cfg = comCfg[aib.dm])) {
Cfg = {};
if(nav.isGlobal) {
for(var i in comCfg['global']) {
Cfg[i] = comCfg['global'][i];
}
}
Cfg['captchaLang'] = aib.ru ? 2 : 1;
Cfg['correctTime'] = 0;
}
Cfg.__proto__ = defaultCfg;
if(!Cfg['timeOffset']) {
Cfg['timeOffset'] = '+0';
}
if(!Cfg['timePattern']) {
Cfg['timePattern'] = aib.timePattern;
}
if(nav.noBlob) {
Cfg['preLoadImgs'] = 0;
if(Cfg['ajaxReply'] === 2) {
Cfg['ajaxReply'] = 1;
}
}
if(aib.tiny && Cfg['ajaxReply'] === 2) {
Cfg['ajaxReply'] = 1;
}
if(!nav.Firefox) {
defaultCfg['favIcoBlink'] = 0;
}
if(!('Notification' in window)) {
Cfg['desktNotif'] = 0;
}
if(nav.Opera) {
if(nav.oldOpera) {
if(!nav.isGM) {
Cfg['YTubeTitles'] = 0;
}
Cfg['animation'] = 0;
}
if(Cfg['YTubeType'] === 2) {
Cfg['YTubeType'] = 1;
}
Cfg['preLoadImgs'] = 0;
Cfg['findImgFile'] = 0;
if(!nav.isGM) {
Cfg['updScript'] = 0;
}
}
if(Cfg['updThrDelay'] < 10) {
Cfg['updThrDelay'] = 10;
}
if(!Cfg['saveSage']) {
Cfg['sageReply'] = 0;
}
if(!Cfg['passwValue']) {
Cfg['passwValue'] = Math.round(Math.random() * 1e15).toString(32);
}
if(!Cfg['stats']) {
Cfg['stats'] = {'view': 0, 'op': 0, 'reply': 0};
}
if(TNum) {
Cfg['stats']['view']++;
}
saveComCfg(aib.dm, Cfg);
lang = Cfg['language'];
if(Cfg['correctTime']) {
dTime = new dateTime(Cfg['timePattern'], Cfg['timeRPattern'], Cfg['timeOffset'], lang, function(rp) {
saveCfg('timeRPattern', rp);
});
}
if(aib.dobr) {
aib.hDTFix = new dateTime(
'yyyy-nn-dd-hh-ii-ss',
'_d _M _y (_w) _h:_i ',
Cfg['timeOffset'] || 0,
Cfg['correctTime'] ? lang : 1,
null
);
}
}
function toggleCfg(id) {
saveCfg(id, +!Cfg[id]);
}
function readPosts() {
var data, str = TNum ? sessionStorage['de-hidden-' + brd + TNum] : null;
if(typeof str === 'string') {
data = str.split(',');
if(data.length === 4 && +data[0] === (Cfg['hideBySpell'] ? spells.hash : 0) &&
(data[1] in pByNum) && pByNum[data[1]].count === +data[2])
{
sVis = data[3].split('');
return;
}
}
sVis = [];
}
function readUserPosts() {
bUVis = getStoredObj('DESU_Posts_' + aib.dm);
uVis = bUVis[brd];
if(!uVis) {
bUVis[brd] = uVis = getStoredObj('DESU_Posts_' + aib.dm + '_' + brd);
delStored('DESU_Posts_' + aib.dm + '_' + brd);
}
hThr = getStoredObj('DESU_Threads_' + aib.dm);
if(!(brd in hThr)) {
hThr[brd] = {};
}
}
function savePosts() {
if(TNum) {
var lPost = firstThr.lastNotDeleted;
sessionStorage['de-hidden-' + brd + TNum] = (Cfg['hideBySpell'] ? spells.hash : '0') +
',' + lPost.num + ',' + lPost.count + ',' + sVis.join('');
}
saveHiddenThreads(false);
toggleContent('hid', true);
}
function saveUserPosts() {
var minDate, b, vis, key, str = JSON.stringify(bUVis);
if(str.length > 1e6) {
minDate = Date.now() - 5 * 24 * 3600 * 1000;
for(b in bUVis) {
if(bUVis.hasOwnProperty(b)) {
vis = bUVis[b];
for(key in vis) {
if(vis.hasOwnProperty(key) && vis[key][1] < minDate) {
delete vis[key];
}
}
}
}
str = JSON.stringify(bUVis);
}
setStored('DESU_Posts_' + aib.dm, str);
toggleContent('hid', true);
}
function saveHiddenThreads(updContent) {
setStored('DESU_Threads_' + aib.dm, JSON.stringify(hThr));
if(updContent) {
toggleContent('hid', true);
}
}
function readFavorites() {
Favor = getStoredObj('DESU_Favorites');
}
function saveFavorites() {
setStored('DESU_Favorites', JSON.stringify(Favor));
toggleContent('fav', true);
}
function removeFavorites(h, b, tNum) {
delete Favor[h][b][tNum];
if($isEmpty(Favor[h][b])) {
delete Favor[h][b];
}
if($isEmpty(Favor[h])) {
delete Favor[h];
}
if(pByNum[tNum]) {
($c('de-btn-fav-sel', pByNum[tNum].btns) || {}).className = 'de-btn-fav';
}
}
function toggleFavorites(post, btn) {
var h = aib.host,
b = brd,
tNum = post.num;
if(!btn) {
return;
}
readFavorites();
if(Favor[h] && Favor[h][b] && Favor[h][b][tNum]) {
removeFavorites(h, b, tNum);
saveFavorites();
return;
}
if(!Favor[h]) {
Favor[h] = {};
}
if(!Favor[h][b]) {
Favor[h][b] = {};
}
Favor[h][b][tNum] = {
'cnt': post.thr.pcount,
'txt': post.title,
'url': aib.getThrdUrl(brd, tNum)
};
btn.className = 'de-btn-fav-sel';
saveFavorites();
}
function readViewedPosts() {
if(Cfg['markViewed']) {
var data = sessionStorage['de-viewed'];
if(data) {
data.split(',').forEach(function(pNum) {
var post = pByNum[pNum];
if(post) {
post.el.classList.add('de-viewed');
post.viewed = true;
}
});
}
}
}
//============================================================================================================
// MAIN PANEL
//============================================================================================================
function pButton(id, href, hasHotkey) {
return '<li><a id="de-btn-' + id + '" class="de-abtn" ' + (hasHotkey ? 'de-' : '') + 'title="' +
Lng.panelBtn[id][lang] +'" href="' + href + '"></a></li>';
}
function addPanel() {
var panel, evtObject, imgLen = getImages(dForm).length;
(pr.pArea[0] || dForm).insertAdjacentHTML('beforebegin',
'<div id="de-main" lang="' + getThemeLang() + '">' +
'<div class="de-content"></div>' +
'<div id="de-panel">' +
'<span id="de-btn-logo" title="' + Lng.panelBtn['attach'][lang] + '"></span>' +
'<ul id="de-panel-btns"' + (Cfg['expandPanel'] ? '>' : ' style="display: none">') +
pButton('settings', '#', true) +
pButton('hidden', '#', true) +
pButton('favor', '#', true) +
(aib.arch ? '' :
pButton('refresh', '#', false) +
(!TNum && (pageNum === aib.firstPage) ? '' :
pButton('goback', aib.getPageUrl(brd, pageNum - 1), true)) +
(TNum || pageNum === aib.lastPage ? '' :
pButton('gonext', aib.getPageUrl(brd, pageNum + 1), true))
) + pButton('goup', '#', false) +
pButton('godown', '#', false) +
(imgLen === 0 ? '' :
pButton('expimg', '#', false) +
(Cfg['preLoadImgs'] || nav.Opera || nav.noBlob ? '' : pButton('preimg', '#', false)) +
pButton('maskimg', '#', true)) +
(!TNum ? '' :
pButton(Cfg['ajaxUpdThr'] ? 'upd-on' : 'upd-off', '#', false) +
(nav.Safari ? '' : pButton('audio-off', '#', false))) +
(!aib.nul && !aib.abu && (!aib.fch || aib.arch) ? '' :
pButton('catalog', '//' + aib.host + '/' + (aib.abu ?
'makaba/makaba.fcgi?task=catalog&board=' + brd : brd + '/catalog.html'), false)) +
(!TNum && !aib.arch? '' :
(nav.Opera || nav.noBlob ? '' : pButton('imgload', '#', false)) +
'<div id="de-panel-info"><span title="' + Lng.panelBtn['counter'][lang] +
'">' + firstThr.pcount + '/' + imgLen + '</span></div>') +
'</ul>' +
'</div>' +
'<div id="de-img-btns" style="display: none">' +
'<div id="de-img-btn-next" title="' + Lng.nextImg[lang] + '"><div></div></div>' +
'<div id="de-img-btn-prev" title="' + Lng.prevImg[lang] + '"><div></div></div></div>' +
'<div id="de-alert"></div>' +
'<hr style="clear: both;">' +
'</div>'
);
panel = $id('de-panel');
evtObject = {
attach: false,
odelay: 0,
panel: panel,
setTitleWithKey: function(el, isGlob, idx) {
var title = el.getAttribute('de-title');
if(keyNav) {
title += ' [' + KeyEditListener.getStrKey(isGlob ? keyNav.gKeys[idx] : keyNav.ntKeys[idx]) + ']';
}
el.title = title;
},
handleEvent: function(e) {
switch(e.type) {
case 'click':
switch(e.target.id) {
case 'de-btn-logo':
if(Cfg['expandPanel']) {
this.panel.lastChild.style.display = 'none';
this.attach = false;
} else {
this.attach = true;
}
toggleCfg('expandPanel');
return;
case 'de-btn-settings': this.attach = toggleContent('cfg', false); break;
case 'de-btn-hidden': this.attach = toggleContent('hid', false); break;
case 'de-btn-favor': this.attach = toggleContent('fav', false); break;
case 'de-btn-refresh': window.location.reload(); break;
case 'de-btn-goup': scrollTo(0, 0); break;
case 'de-btn-godown': scrollTo(0, doc.body.scrollHeight || doc.body.offsetHeight); break;
case 'de-btn-expimg':
isExpImg = !isExpImg;
$del($c('de-img-center', doc));
for(var post = firstThr.op; post; post = post.next) {
post.toggleImages(isExpImg);
}
break;
case 'de-btn-preimg':
isPreImg = !isPreImg;
preloadImages(null);
break;
case 'de-btn-maskimg':
toggleCfg('maskImgs');
updateCSS();
break;
case 'de-btn-upd-on':
case 'de-btn-upd-off':
case 'de-btn-upd-warn':
if(updater.enabled) {
updater.disable();
} else {
updater.enable();
}
break;
case 'de-btn-audio-on':
case 'de-btn-audio-off':
if(updater.toggleAudio(0)) {
updater.enable();
e.target.id = 'de-btn-audio-on';
} else {
e.target.id = 'de-btn-audio-off';
}
$del($c('de-menu', doc));
break;
case 'de-btn-imgload':
if($id('de-alert-imgload')) {
break;
}
if(Images_.preloading) {
$alert(Lng.loading[lang], 'imgload', true);
Images_.afterpreload = loadDocFiles.bind(null, true);
Images_.progressId = 'imgload';
} else {
loadDocFiles(true);
}
break;
default: return;
}
$pd(e);
return;
case 'mouseover':
if(!Cfg['expandPanel']) {
clearTimeout(this.odelay);
this.panel.lastChild.style.display = '';
}
switch(e.target.id) {
case 'de-btn-settings': this.setTitleWithKey(e.target, true, 10); break;
case 'de-btn-hidden': this.setTitleWithKey(e.target, true, 7); break;
case 'de-btn-favor': this.setTitleWithKey(e.target, true, 6); break;
case 'de-btn-goback': this.setTitleWithKey(e.target, true, 4); break;
case 'de-btn-gonext': this.setTitleWithKey(e.target, false, 3); break;
case 'de-btn-maskimg': this.setTitleWithKey(e.target, true, 9); break;
case 'de-btn-refresh':
if(TNum) {
return;
}
case 'de-btn-audio-off': addMenu(e);
}
return;
default: // mouseout
if(!Cfg['expandPanel'] && !this.attach) {
this.odelay = setTimeout(function(obj) {
obj.panel.lastChild.style.display = 'none';
obj.attach = false;
}, 500, this);
}
switch(e.target.id) {
case 'de-btn-refresh':
case 'de-btn-audio-off': removeMenu(e); break;
}
}
}
};
panel.addEventListener('click', evtObject, true);
panel.addEventListener('mouseover', evtObject, false);
panel.addEventListener('mouseout', evtObject, false);
}
function toggleContent(name, isUpd) {
if(liteMode) {
return false;
}
var remove, el = $c('de-content', doc),
id = 'de-content-' + name;
if(!el) {
return false;
}
if(isUpd && el.id !== id) {
return true;
}
remove = !isUpd && el.id === id;
if(el.hasChildNodes() && Cfg['animation']) {
nav.animEvent(el, function(node) {
showContent(node, id, name, remove);
id = name = remove = null;
});
el.className = 'de-content de-cfg-close';
return !remove;
} else {
showContent(el, id, name, remove);
return !remove;
}
}
function addContentBlock(parent, title) {
return parent.appendChild($New('div', {'class': 'de-content-block'}, [
$new('input', {'type': 'checkbox'}, {'click': function() {
var el, res = this.checked, i = 0, els = $Q('.de-entry > div > input', this.parentNode);
for(; el = els[i++];) {
el.checked = res;
}
}}),
$new('b', {'text': title}, null)
]));
}
function showContent(cont, id, name, remove) {
var h, b, tNum, i, els, post, cln, block;
cont.innerHTML = cont.style.backgroundColor = '';
if(remove) {
cont.removeAttribute('id');
return;
}
cont.id = id;
if(name === 'cfg') {
addSettings(cont);
} else if(Cfg['attachPanel']) {
cont.style.backgroundColor = $getStyle(doc.body, 'background-color');
}
if(name === 'hid') {
for(i = 0, els = $C('de-post-hid', dForm); post = els[i++];) {
if(post.isOp) {
continue;
}
(cln = post.cloneNode(true)).removeAttribute('id');
cln.style.display = '';
if(cln.classList.contains(aib.cRPost)) {
cln.classList.add('de-cloned-post');
} else {
cln.className = aib.cReply + ' de-cloned-post';
}
cln.post = Object.create(cln.clone = post.post);
cln.post.el = cln;
cln.btn = $q('.de-btn-hide, .de-btn-hide-user', cln);
cln.btn.parentNode.className = 'de-ppanel';
cln.btn.onclick = function() {
this.toggleContent(this.hidden = !this.hidden);
}.bind(cln);
(block || (block = cont.appendChild(
$add('<div class="de-content-block"><b>' + Lng.hiddenPosts[lang] + ':</b></div>')
))).appendChild($New('div', {'class': 'de-entry'}, [cln]));
}
if(block) {
$append(cont, [
$btn(Lng.expandAll[lang], '', function() {
$each($Q('.de-cloned-post', this.parentNode), function(el) {
var post = el.post;
post.toggleContent(post.hidden = !post.hidden);
});
this.value = this.value === Lng.undo[lang] ? Lng.expandAll[lang] : Lng.undo[lang];
}),
$btn(Lng.save[lang], '', function() {
$each($Q('.de-cloned-post', this.parentNode), function(date, el) {
if(!el.post.hidden) {
el.clone.setUserVisib(false, date, true);
}
}.bind(null, Date.now()));
saveUserPosts();
})
]);
} else {
cont.appendChild($new('b', {'text': Lng.noHidPosts[lang]}, null));
}
$append(cont, [
doc.createElement('hr'),
$new('b', {'text': ($isEmpty(hThr) ? Lng.noHidThrds[lang] : Lng.hiddenThrds[lang] + ':')}, null)
]);
for(b in hThr) {
if(!$isEmpty(hThr[b])) {
block = addContentBlock(cont, '/' + b);
for(tNum in hThr[b]) {
block.insertAdjacentHTML('beforeend', '<div class="de-entry" info="' + b + ';' +
tNum + '"><div class="' + aib.cReply + '"><input type="checkbox"><a href="' +
aib.getThrdUrl(b, tNum) + '" target="_blank">№' + tNum + '</a> - ' +
hThr[b][tNum] + '</div></div>');
}
}
}
$append(cont, [
doc.createElement('hr'),
addEditButton('hidden', hThr, true, function(data) {
hThr = data;
if(!(brd in hThr)) {
hThr[brd] = {};
}
firstThr.updateHidden(hThr[brd]);
saveHiddenThreads(true);
localStorage['__de-threads'] = JSON.stringify(hThr);
localStorage.removeItem('__de-threads');
}),
$btn(Lng.clear[lang], Lng.clrDeleted[lang], function() {
$each($Q('.de-entry[info]', this.parentNode), function(el) {
var arr = el.getAttribute('info').split(';');
ajaxLoad(aib.getThrdUrl(arr[0], arr[1]), false, null, function(eCode, eMsg, xhr) {
if(eCode === 404) {
delete hThr[this[0]][this[1]];
saveHiddenThreads(true);
}
}.bind(arr));
});
}),
$btn(Lng.remove[lang], Lng.clrSelected[lang], function() {
$each($Q('.de-entry[info]', this.parentNode), function(date, el) {
var post, arr = el.getAttribute('info').split(';');
if($t('input', el).checked) {
if(arr[1] in pByNum) {
pByNum[arr[1]].setUserVisib(false, date, true);
} else {
localStorage['__de-post'] = JSON.stringify({
'brd': arr[0],
'date': date,
'isOp': true,
'num': arr[1],
'hide': false
});
localStorage.removeItem('__de-post');
}
delete hThr[arr[0]][arr[1]];
}
}.bind(null, Date.now()));
saveHiddenThreads(true);
})
]);
}
if(name === 'fav') {
readFavorites();
for(h in Favor) {
for(b in Favor[h]) {
block = addContentBlock(cont, h + '/' + b);
for(tNum in Favor[h][b]) {
i = Favor[h][b][tNum];
if(!i['url'].startsWith('http')) {
i['url'] = (h === aib.host ? aib.prot + '//' : 'http://') + h + i['url'];
}
block.appendChild($New('div', {'class': 'de-entry', 'info': h + ';' + b + ';' + tNum}, [
$New('div', {'class': aib.cReply}, [
$add('<input type="checkbox">'),
$new('span', {'class': 'de-btn-expthr'}, {'click': loadFavorThread}),
$add('<a href="' + i['url'] + '">№' + tNum + '</a>'),
$add('<span class="de-fav-title"> - ' + i['txt'] + '</span>'),
$add('<span class="de-fav-inf-page"></span>'),
$add('<span class="de-fav-inf-posts">[<span class="de-fav-inf-old">' +
i['cnt'] + '</span>]</span>')
])
]));
}
}
}
cont.insertAdjacentHTML('afterbegin', '<b>' + (Lng[block ? 'favThrds' : 'noFavThrds'][lang]) + '</b>');
$append(cont, [
doc.createElement('hr'),
addEditButton('favor', Favor, true, function(data) {
Favor = data;
setStored('DESU_Favorites', JSON.stringify(Favor));
toggleContent('fav', true);
}),
$btn(Lng.info[lang], Lng.infoCount[lang], function() {
$each($C('de-entry', doc), function(el) {
var c, arr = el.getAttribute('info').split(';'),
f = Favor[arr[0]][arr[1]][arr[2]];
if(arr[0] !== aib.host) {
return;
}
c = $c('de-fav-inf-posts', el).firstElementChild;
c.className = 'de-wait';
c.textContent = '';
ajaxLoad(aib.getThrdUrl(arr[1], arr[2]), true, function(form, xhr) {
var cnt = aib.getPosts(form).length + 1;
c.textContent = cnt;
if(cnt > f.cnt) {
c.className = 'de-fav-inf-new';
f.cnt = cnt;
setStored('DESU_Favorites', JSON.stringify(Favor));
} else {
c.className = 'de-fav-inf-old';
}
c = f = null;
}, function(eCode, eMsg, xhr) {
c.textContent = getErrorMessage(eCode, eMsg);
c.className = 'de-fav-inf-old';
c = null;
});
});
}),
$btn(Lng.page[lang], Lng.infoPage[lang], function() {
var i = 6,
loaded = 0;
$alert(Lng.loading[lang], 'load-pages', true);
while(i--) {
ajaxLoad(aib.getPageUrl(brd, i), true, function(idx, form, xhr) {
for(var arr, el, len = this.length, i = 0; i < len; ++i) {
arr = this[i].getAttribute('info').split(';');
if(arr[0] === aib.host && arr[1] === brd) {
el = $c('de-fav-inf-page', this[i]);
if((new RegExp('(?:№|No.|>)\\s*' + arr[2] + '\\s*<'))
.test(form.innerHTML))
{
el.innerHTML = '@' + idx;
} else if(loaded === 5 && !el.textContent.contains('@')) {
el.innerHTML = '@?';
}
}
}
if(loaded === 5) {
closeAlert($id('de-alert-load-pages'));
}
loaded++;
}.bind($C('de-entry', doc), i), function(eCode, eMsg, xhr) {
if(loaded === 5) {
closeAlert($id('de-alert-load-pages'));
}
loaded++;
});
}
}),
$btn(Lng.clear[lang], Lng.clrDeleted[lang], function() {
$each($C('de-entry', doc), function(el) {
var arr = el.getAttribute('info').split(';');
ajaxLoad(Favor[arr[0]][arr[1]][arr[2]]['url'], false, null, function(eCode, eMsg, xhr) {
if(eCode === 404) {
removeFavorites(arr[0], arr[1], arr[2]);
saveFavorites();
arr = null;
}
});
});
}),
$btn(Lng.remove[lang], Lng.clrSelected[lang], function() {
$each($C('de-entry', doc), function(el) {
var arr = el.getAttribute('info').split(';');
if($t('input', el).checked) {
removeFavorites(arr[0], arr[1], arr[2]);
}
});
saveFavorites();
})
]);
}
if(Cfg['animation']) {
cont.className = 'de-content de-cfg-open';
}
}
//============================================================================================================
// SETTINGS WINDOW
//============================================================================================================
function fixSettings() {
function toggleBox(state, arr) {
var i = arr.length,
nState = !state;
while(i--) {
($q(arr[i], doc) || {}).disabled = nState;
}
}
toggleBox(Cfg['ajaxUpdThr'], [
'input[info="noErrInTitle"]',
'input[info="favIcoBlink"]',
'input[info="markNewPosts"]',
'input[info="desktNotif"]'
]);
toggleBox(Cfg['expandImgs'], ['input[info="resizeImgs"]']);
toggleBox(Cfg['preLoadImgs'], ['input[info="findImgFile"]']);
toggleBox(Cfg['openImgs'], ['input[info="openGIFs"]']);
toggleBox(Cfg['linksNavig'], [
'input[info="linksOver"]',
'input[info="linksOut"]',
'input[info="markViewed"]',
'input[info="strikeHidd"]',
'input[info="noNavigHidd"]'
]);
toggleBox(Cfg['addYouTube'] && Cfg['addYouTube'] !== 4, [
'select[info="YTubeType"]', 'input[info="YTubeHD"]', 'input[info="addVimeo"]'
]);
toggleBox(Cfg['addYouTube'], [
'input[info="YTubeWidth"]', 'input[info="YTubeHeigh"]', 'input[info="YTubeTitles"]'
]);
toggleBox(Cfg['ajaxReply'] === 2, [
'input[info="postSameImg"]', 'input[info="removeEXIF"]', 'input[info="removeFName"]'
]);
toggleBox(Cfg['addTextBtns'], ['input[info="txtBtnsLoc"]']);
toggleBox(Cfg['updScript'], ['select[info="scrUpdIntrv"]']);
toggleBox(Cfg['keybNavig'], ['input[info="loadPages"]']);
}
function lBox(id, isBlock, Fn) {
var el = $new('input', {'info': id, 'type': 'checkbox'}, {'click': function() {
toggleCfg(this.getAttribute('info'));
fixSettings();
if(Fn) {
Fn(this);
}
}});
el.checked = Cfg[id];
return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + Lng.cfg[id][lang])]);
}
function inpTxt(id, size, Fn) {
return $new('input', {'info': id, 'type': 'text', 'size': size, 'value': Cfg[id]}, {
'keyup': Fn ? Fn : function() {
saveCfg(this.getAttribute('info'), this.value);
}
});
}
function optSel(id, isBlock, Fn) {
for(var i = 0, x = Lng.cfg[id], len = x.sel[lang].length, el, opt = ''; i < len; i++) {
opt += '<option value="' + i + '">' + x.sel[lang][i] + '</option>';
}
el = $add('<select info="' + id + '">' + opt + '</select>');
el.addEventListener('change', Fn || function() {
saveCfg(this.getAttribute('info'), this.selectedIndex);
fixSettings();
}, false);
el.selectedIndex = Cfg[id];
return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + x.txt[lang])]);
}
function cfgTab(name) {
return $New('div', {'class': aib.cReply + ' de-cfg-tab-back', 'selected': false}, [$new('div', {
'class': 'de-cfg-tab',
'text': Lng.cfgTab[name][lang],
'info': name}, {
'click': function() {
var el, id, pN = this.parentNode;
if(pN.getAttribute('selected') === 'true') {
return;
}
if(el = $c('de-cfg-body', doc)) {
el.className = 'de-cfg-unvis';
$q('.de-cfg-tab-back[selected="true"]', doc).setAttribute('selected', false);
}
pN.setAttribute('selected', true);
if(!(el = $id('de-cfg-' + (id = this.getAttribute('info'))))) {
$after($id('de-cfg-bar'), el =
id === 'posts' ? getCfgPosts() :
id === 'images' ? getCfgImages() :
id === 'links' ? getCfgLinks() :
id === 'form' ? getCfgForm() :
id === 'common' ? getCfgCommon() :
getCfgInfo()
);
}
el.className = 'de-cfg-body';
if(id === 'filters') {
$id('de-spell-edit').value = spells.list;
}
fixSettings();
}
})]);
}
function updRowMeter() {
var str, top = this.scrollTop,
el = this.parentNode.previousSibling.firstChild,
num = el.numLines || 1,
i = 15;
if(num - i < ((top / 12) | 0 + 1)) {
str = '';
while(i--) {
str += num++ + '<br>';
}
el.insertAdjacentHTML('beforeend', str);
el.numLines = num;
}
el.scrollTop = top;
}
function getCfgFilters() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-filters'}, [
lBox('hideBySpell', false, toggleSpells),
$New('div', {'id': 'de-spell-panel'}, [
$new('a', {
'id': 'de-btn-addspell',
'text': Lng.add[lang],
'href': '#',
'class': 'de-abtn'}, {
'click': $pd,
'mouseover': addMenu,
'mouseout': removeMenu
}),
$new('a', {'text': Lng.apply[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) {
$pd(e);
saveCfg('hideBySpell', 1);
$q('input[info="hideBySpell"]', doc).checked = true;
toggleSpells();
}}),
$new('a', {'text': Lng.clear[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) {
$pd(e);
$id('de-spell-edit').value = '';
toggleSpells();
}}),
$add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Spells-' +
(lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>')
]),
$New('div', {'id': 'de-spell-div'}, [
$add('<div><div id="de-spell-rowmeter"></div></div>'),
$New('div', null, [$new('textarea', {'id': 'de-spell-edit', 'wrap': 'off'}, {
'keydown': updRowMeter,
'scroll': updRowMeter
})])
]),
lBox('sortSpells', true, function() {
if (Cfg['sortSpells']) {
toggleSpells();
}
}),
lBox('menuHiddBtn', true, null),
lBox('hideRefPsts', true, null),
lBox('delHiddPost', true, function() {
$each($C('de-post-hid', dForm), function(el) {
var wrap = el.post.wrap,
hide = !wrap.classList.contains('de-hidden');
if(hide) {
wrap.insertAdjacentHTML('beforebegin',
'<span style="counter-increment: de-cnt 1;"></span>');
} else {
$del(wrap.previousSibling);
}
wrap.classList.toggle('de-hidden');
});
updateCSS();
})
]);
}
function getCfgPosts() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-posts'}, [
lBox('ajaxUpdThr', false, TNum ? function() {
if(Cfg['ajaxUpdThr']) {
updater.enable();
} else {
updater.disable();
}
} : null),
$New('label', null, [
inpTxt('updThrDelay', 4, null),
$txt(Lng.cfg['updThrDelay'][lang])
]),
$New('div', {'class': 'de-cfg-depend'}, [
lBox('noErrInTitle', true, null),
lBox('favIcoBlink', true, null),
lBox('markNewPosts', true, function() {
firstThr.clearPostsMarks();
}),
$if('Notification' in window, lBox('desktNotif', true, function() {
if(Cfg['desktNotif']) {
Notification.requestPermission();
}
}))
]),
optSel('expandPosts', true, null),
optSel('postBtnsCSS', true, null),
lBox('noSpoilers', true, updateCSS),
lBox('noPostNames', true, updateCSS),
lBox('noPostScrl', true, updateCSS),
$New('div', null, [
lBox('correctTime', false, dateTime.toggleSettings),
$add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Settings-time-' +
(lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>')
]),
$New('div', {'class': 'de-cfg-depend'}, [
$New('div', null, [
inpTxt('timeOffset', 3, null),
$txt(Lng.cfg['timeOffset'][lang])
]),
$New('div', null, [
inpTxt('timePattern', 30, null),
$txt(Lng.cfg['timePattern'][lang])
]),
$New('div', null, [
inpTxt('timeRPattern', 30, null),
$txt(Lng.cfg['timeRPattern'][lang])
])
])
]);
}
function getCfgImages() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-images'}, [
optSel('expandImgs', true, null),
$New('div', {'style': 'padding-left: 25px;'}, [ lBox('resizeImgs', false, null)]),
$if(!nav.noBlob && !nav.Opera, lBox('preLoadImgs', true, null)),
$if(!nav.noBlob && !nav.Opera, $New('div', {'class': 'de-cfg-depend'}, [
lBox('findImgFile', true, null)
])),
lBox('openImgs', true, null),
$New('div', {'class': 'de-cfg-depend'}, [ lBox('openGIFs', false, null)]),
lBox('imgSrcBtns', true, null)
]);
}
function getCfgLinks() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-links'}, [
optSel('linksNavig', true, null),
$New('div', {'class': 'de-cfg-depend'}, [
$New('div', null, [
inpTxt('linksOver', 6, function() {
saveCfg('linksOver', +this.value | 0);
}),
$txt(Lng.cfg['linksOver'][lang])
]),
$New('div', null, [
inpTxt('linksOut', 6, function() {
saveCfg('linksOut', +this.value | 0);
}),
$txt(Lng.cfg['linksOut'][lang])
]),
lBox('markViewed', true, null),
lBox('strikeHidd', true, null),
lBox('noNavigHidd', true, null)
]),
lBox('crossLinks', true, null),
lBox('insertNum', true, null),
lBox('addMP3', true, null),
lBox('addImgs', true, null),
optSel('addYouTube', true, null),
$New('div', {'class': 'de-cfg-depend'}, [
$New('div', null, [
optSel('YTubeType', false, null),
inpTxt('YTubeWidth', 6, null),
$txt('×'),
inpTxt('YTubeHeigh', 6, null),
$txt(' '),
lBox('YTubeHD', false, null)
]),
$if(!nav.oldOpera || nav.isGM, lBox('YTubeTitles', false, null)),
lBox('addVimeo', true, null)
])
]);
}
function getCfgForm() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-form'}, [
optSel('ajaxReply', true, null),
$if(pr.form && !nav.noBlob, $New('div', {'class': 'de-cfg-depend'}, [
lBox('postSameImg', true, null),
lBox('removeEXIF', true, null),
lBox('removeFName', true, null)
])),
$if(pr.form, optSel('addPostForm', true, null)),
$if(pr.form, lBox('scrAfterRep', true, null)),
lBox('favOnReply', true, null),
$if(pr.mail, $New('div', null, [
lBox('addSageBtn', false, null),
lBox('saveSage', false, null)
])),
$if(pr.subj, lBox('warnSubjTrip', false, null)),
$if(pr.capTr, optSel('captchaLang', true, null)),
$if(pr.txta, $New('div', null, [
optSel('addTextBtns', false, function() {
saveCfg('addTextBtns', this.selectedIndex);
pr.addTextPanel();
}),
lBox('txtBtnsLoc', false, pr.addTextPanel.bind(pr))
])),
$if(pr.passw, $New('div', null, [
inpTxt('passwValue', 20, PostForm.setUserPassw),
$txt(Lng.cfg['userPassw'][lang]),
$btn(Lng.change[lang], '', function() {
$q('input[info="passwValue"]', doc).value = Math.round(Math.random() * 1e15).toString(32);
PostForm.setUserPassw();
})
])),
$if(pr.name, $New('div', null, [
inpTxt('nameValue', 20, PostForm.setUserName),
lBox('userName', false, PostForm.setUserName)
])),
$if(pr.txta, $New('div', null, [
inpTxt('signatValue', 20, null),
lBox('userSignat', false, null)
])),
$New('div', null, [
$txt(Lng.dontShow[lang]),
lBox('noBoardRule', false, updateCSS),
$if(pr.gothr, lBox('noGoto', false, function() {
$disp(pr.gothr);
})),
$if(pr.passw, lBox('noPassword', false, function() {
$disp(pr.passw.parentNode.parentNode);
}))
])
]);
}
function getCfgCommon() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-common'}, [
optSel('scriptStyle', true, function() {
saveCfg('scriptStyle', this.selectedIndex);
$id('de-main').lang = getThemeLang();
}),
$New('div', null, [
lBox('userCSS', false, updateCSS),
addEditButton('css', Cfg['userCSSTxt'], false, function() {
saveCfg('userCSSTxt', this.value);
updateCSS();
toggleContent('cfg', true);
})
]),
lBox('attachPanel', true, function() {
toggleContent('cfg', false);
updateCSS();
}),
lBox('panelCounter', true, updateCSS),
lBox('rePageTitle', true, null),
$if(nav.Anim, lBox('animation', true, null)),
lBox('closePopups', true, null),
$New('div', null, [
lBox('keybNavig', false, function() {
if(Cfg['keybNavig']) {
if(keyNav) {
keyNav.enable();
} else {
keyNav = new KeyNavigation();
}
} else if(keyNav) {
keyNav.disable();
}
}),
$btn(Lng.edit[lang], '', function(e) {
$pd(e);
if($id('de-alert-edit-keybnavig')) {
return;
}
var aEl, evtListener, keys = KeyNavigation.readKeys(),
temp = KeyEditListener.getEditMarkup(keys);
$alert(temp[1], 'edit-keybnavig', false);
aEl = $id('de-alert-edit-keybnavig');
evtListener = new KeyEditListener(aEl, keys, temp[0]);
aEl.addEventListener('focus', evtListener, true);
aEl.addEventListener('blur', evtListener, true);
aEl.addEventListener('click', evtListener, true);
aEl.addEventListener('keydown', evtListener, true);
aEl.addEventListener('keyup', evtListener, true);
})
]),
$New('div', {'class': 'de-cfg-depend'}, [
inpTxt('loadPages', 4, null),
$txt(Lng.cfg['loadPages'][lang])
]),
$if(!nav.Opera || nav.isGM, $New('div', null, [
lBox('updScript', true, null),
$New('div', {'class': 'de-cfg-depend'}, [
optSel('scrUpdIntrv', false, null),
$btn(Lng.checkNow[lang], '', function() {
var el = $id('de-cfg-updresult');
el.innerHTML = '<span class="de-wait">' + Lng.checking[lang] + '</div>';
checkForUpdates(true, function(html) {
el.innerHTML = html;
});
})
]),
$new('div', {'id': 'de-cfg-updresult'}, null)
]))
]);
}
function getCfgInfo() {
var getHiddenThrCount = function () {
var b, tNum, count = 0;
for(b in hThr) {
for(tNum in hThr[b]) {
count++;
}
}
return count;
}
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-info'}, [
$add('<div style="padding-bottom: 10px;">' +
'<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/versions" ' +
'target="_blank">v' + version + '</a> | ' +
'<a href="http://www.freedollchan.org/scripts/" target="_blank">Freedollchan</a> | ' +
'<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/' +
(lang ? 'home-en/' : '') + '" target="_blank">Github</a></div>'),
$add('<div><div style="display: inline-block; vertical-align: top; width: 186px; height: 235px;">' +
Lng.thrViewed[lang] + Cfg['stats']['view'] + '<br>' +
Lng.thrCreated[lang] + Cfg['stats']['op'] + '<br>' +
Lng.thrHidden[lang] + getHiddenThrCount() + '<br>' +
Lng.postsSent[lang] + Cfg['stats']['reply'] + '</div>' +
'<div style="display: inline-block; padding-left: 7px; height: 235px; ' +
'border-left: 1px solid grey;">' + timeLog.join('<br>') + '</div></div>'),
$btn(Lng.debug[lang], Lng.infoDebug[lang], function() {
$alert(Lng.infoDebug[lang] +
':<textarea readonly id="de-debug-info" class="de-editor"></textarea>', 'help-debug', false);
$id('de-debug-info').value = JSON.stringify({
'version': version,
'location': String(window.location),
'nav': nav,
'cfg': Cfg,
'sSpells': spells.list.split('\n'),
'oSpells': sessionStorage['de-spells-' + brd + TNum],
'perf': timeLog
}, function(key, value) {
if(key in defaultCfg) {
if(value === defaultCfg[key] || key === 'nameValue' || key === 'passwValue' ||
key === 'signatValue')
{
return void 0;
}
}
return key === 'stats' ? void 0 : value;
}, '\t');
})
]);
}
function addEditButton(name, val, isJSON, Fn) {
return $btn(Lng.edit[lang], Lng.editInTxt[lang], function() {
var ta = $new('textarea', {
'class': 'de-editor',
'value': isJSON ? JSON.stringify(val, null, '\t') : val
}, null);
$alert('', 'edit-' + name, false);
$append($c('de-alert-msg', $id('de-alert-edit-' + name)), [
$txt(Lng.editor[name][lang]),
ta,
$btn(Lng.save[lang], Lng.saveChanges[lang], isJSON ? function(fun, aName) {
var data;
try {
data = JSON.parse(this.value.trim().replace(/[\n\r\t]/g, '') || '{}');
} finally {
if(data) {
fun(data);
closeAlert($id('de-alert-edit-' + aName));
closeAlert($id('de-alert-err-invaliddata'));
} else {
$alert(Lng.invalidData[lang], 'err-invaliddata', false);
}
}
}.bind(ta, Fn, name) : Fn.bind(ta))
]);
});
}
function addSettings(Set) {
Set.appendChild($New('div', {'class': aib.cReply}, [
$new('div', {'id': 'de-cfg-head', 'text': 'Dollchan Extension Tools'}, null),
$New('div', {'id': 'de-cfg-bar'}, [
cfgTab('filters'),
cfgTab('posts'),
cfgTab('images'),
cfgTab('links'),
$if(pr.form || pr.oeForm, cfgTab('form')),
cfgTab('common'),
cfgTab('info')
]),
getCfgFilters(),
$New('div', {'id': 'de-cfg-btns'}, [
optSel('language', false, function() {
saveCfg('language', lang = this.selectedIndex);
$del($id('de-main'));
$del($id('de-css'));
$del($id('de-css-dynamic'));
scriptCSS();
addPanel();
toggleContent('cfg', false);
}),
$New('div', {'style': 'float: right;'}, [
addEditButton('cfg', Cfg, true, function(data) {
saveComCfg(aib.dm, data);
}),
$if(nav.isGlobal, $btn(Lng.load[lang], Lng.loadGlobal[lang], function() {
if(('global' in comCfg) && !$isEmpty(comCfg['global'])) {
saveComCfg(aib.dm, null);
window.location.reload();
} else {
$alert(Lng.noGlobalCfg[lang], 'err-noglobalcfg', false);
}
})),
$if(nav.isGlobal, $btn(Lng.save[lang], Lng.saveGlobal[lang], function() {
var i, obj = {},
com = comCfg[aib.dm];
for(i in com) {
if(com[i] !== defaultCfg[i] && i !== 'stats') {
obj[i] = com[i];
}
}
saveComCfg('global', obj);
toggleContent('cfg', true);
})),
$btn(Lng.reset[lang], Lng.resetCfg[lang], function() {
if(confirm(Lng.conReset[lang])) {
delStored('DESU_Config');
delStored('DESU_Favorites');
delStored('DESU_Threads');
delStored('DESU_keys');
window.location.reload();
}
})
]),
$new('div', {'style': 'clear: both;'}, null)
])
]));
$c('de-cfg-tab', Set).click();
updRowMeter.call($id('de-spell-edit'));
}
//============================================================================================================
// MENUS & POPUPS
//============================================================================================================
function closeAlert(el) {
if(el) {
el.closeTimeout = null;
if(Cfg['animation']) {
nav.animEvent(el, function(node) {
var p = node && node.parentNode;
if(p) {
p.removeChild(node);
}
});
el.classList.add('de-close');
} else {
$del(el);
}
}
}
function $alert(txt, id, wait) {
var node, el = $id('de-alert-' + id),
cBtn = 'de-alert-btn' + (wait ? ' de-wait' : ''),
tBtn = wait ? '' : '\u2716 ';
if(el) {
$t('div', el).innerHTML = txt.trim();
node = $t('span', el);
node.className = cBtn;
node.textContent = tBtn;
clearTimeout(el.closeTimeout);
if(!wait && Cfg['animation']) {
nav.animEvent(el, function(node) {
node.classList.remove('de-blink');
});
el.classList.add('de-blink');
}
} else {
el = $id('de-alert').appendChild($New('div', {'class': aib.cReply, 'id': 'de-alert-' + id}, [
$new('span', {'class': cBtn, 'text': tBtn}, {'click': function() {
closeAlert(this.parentNode);
}}),
$add('<div class="de-alert-msg">' + txt.trim() + '</div>')
]));
if(Cfg['animation']) {
nav.animEvent(el, function(node) {
node.classList.remove('de-open');
});
el.classList.add('de-open');
}
}
if(Cfg['closePopups'] && !wait && !id.contains('help') && !id.contains('edit')) {
el.closeTimeout = setTimeout(closeAlert, 4e3, el);
}
}
function showMenu(el, html, inPanel, onclick) {
var y, pos, menu, cr = el.getBoundingClientRect();
if(Cfg['attachPanel'] && inPanel) {
pos = 'fixed';
y = 'bottom: 25';
} else {
pos = 'absolute';
y = 'top: ' + (window.pageYOffset + cr.bottom);
}
doc.body.insertAdjacentHTML('beforeend', '<div class="' + aib.cReply + ' de-menu" style="position: ' +
pos + '; right: ' + (doc.documentElement.clientWidth - cr.right - window.pageXOffset) +
'px; ' + y + 'px;">' + html + '</div>');
menu = doc.body.lastChild;
menu.addEventListener('mouseover', function(e) {
clearTimeout(e.currentTarget.odelay);
}, true);
menu.addEventListener('mouseout', removeMenu, true);
menu.addEventListener('click', function(e) {
var el = e.target;
if(el.className === 'de-menu-item') {
this(el);
do {
el = el.parentElement;
} while (!el.classList.contains('de-menu'));
$del(el);
}
}.bind(onclick), false);
}
function addMenu(e) {
e.target.odelay = setTimeout(function(el) {
switch(el.id) {
case 'de-btn-addspell': addSpellMenu(el); return;
case 'de-btn-refresh': addAjaxPagesMenu(el); return;
case 'de-btn-audio-off': addAudioNotifMenu(el); return;
}
}, Cfg['linksOver'], e.target);
}
function removeMenu(e) {
var el, rt = e.relatedTarget;
clearTimeout(e.target.odelay);
if(!rt || !nav.matchesSelector(rt, '.de-menu, .de-menu > div, .de-menu-item')) {
if(el = $c('de-menu', doc)) {
el.odelay = setTimeout($del, 75, el);
}
}
}
function addSpellMenu(el) {
showMenu(el, '<div style="display: inline-block; border-right: 1px solid grey;">' +
'<span class="de-menu-item">' + ('#words,#exp,#exph,#imgn,#ihash,#subj,#name,#trip,#img,<br>')
.split(',').join('</span><span class="de-menu-item">') +
'</span></div><div style="display: inline-block;"><span class="de-menu-item">' +
('#sage,#op,#tlen,#all,#video,#vauthor,#num,#wipe,#rep,#outrep')
.split(',').join('</span><span class="de-menu-item">') + '</span></div>', false,
function(el) {
var exp = el.textContent,
idx = Spells.names.indexOf(exp.substr(1));
$txtInsert($id('de-spell-edit'), exp + (
TNum && exp !== '#op' && exp !== '#rep' && exp !== '#outrep' ? '[' + brd + ',' + TNum + ']' : ''
) + (Spells.needArg[idx] ? '(' : ''));
});
}
function addAjaxPagesMenu(el) {
showMenu(el, '<span class="de-menu-item">' +
Lng.selAjaxPages[lang].join('</span><span class="de-menu-item">') + '</span>', true,
function(el) {
loadPages(aProto.indexOf.call(el.parentNode.children, el) + 1);
});
}
function addAudioNotifMenu(el) {
showMenu(el, '<span class="de-menu-item">' +
Lng.selAudioNotif[lang].join('</span><span class="de-menu-item">') + '</span>', true,
function(el) {
var i = aProto.indexOf.call(el.parentNode.children, el);
updater.enable();
updater.toggleAudio(i === 0 ? 3e4 : i === 1 ? 6e4 : i === 2 ? 12e4 : 3e5);
$id('de-btn-audio-off').id = 'de-btn-audio-on';
});
}
//============================================================================================================
// KEYBOARD NAVIGATION
//============================================================================================================
function KeyNavigation() {
var keys = KeyNavigation.readKeys();
this.cPost = null;
this.enabled = true;
this.lastPage = pageNum;
this.lastPageOffset = 0;
this.gKeys = keys[2];
this.ntKeys = keys[3];
this.tKeys = keys[4];
doc.addEventListener('keydown', this, true);
}
KeyNavigation.version = 4;
KeyNavigation.readKeys = function() {
var tKeys, keys, str = getStored('DESU_keys');
if(!str) {
return KeyNavigation.getDefaultKeys();
}
try {
keys = JSON.parse(str);
} finally {
if(!keys) {
return KeyNavigation.getDefaultKeys();
}
if(keys[0] !== KeyNavigation.version) {
tKeys = KeyNavigation.getDefaultKeys();
switch(keys[0]) {
case 1:
keys[2][11] = tKeys[2][11];
keys[4] = tKeys[4];
case 2:
keys[2][12] = tKeys[2][12];
keys[2][13] = tKeys[2][13];
keys[2][14] = tKeys[2][14];
keys[2][15] = tKeys[2][15];
keys[2][16] = tKeys[2][16];
case 3:
keys[2][17] = keys[3][3];
keys[3][3] = keys[3].splice(4, 1)[0];
}
keys[0] = KeyNavigation.version;
setStored('DESU_keys', JSON.stringify(keys));
}
if(keys[1] ^ !!nav.Firefox) {
var mapFunc = nav.Firefox ? function mapFuncFF(key) {
switch(key) {
case 189: return 173;
case 187: return 61;
case 186: return 59;
default: return key;
}
} : function mapFuncNonFF(key) {
switch(key) {
case 173: return 189;
case 61: return 187;
case 59: return 186;
default: return key;
}
};
keys[1] = !!nav.Firefox;
keys[2] = keys[2].map(mapFunc);
keys[3] = keys[3].map(mapFunc);
setStored('DESU_keys', JSON.stringify(keys));
}
return keys;
}
};
KeyNavigation.getDefaultKeys = function() {
var isFirefox = !!nav.Firefox;
var globKeys = [
/* One post/thread above */ 0x004B /* = K */,
/* One post/thread below */ 0x004A /* = J */,
/* Reply or create thread */ 0x0052 /* = R */,
/* Hide selected thread/post */ 0x0048 /* = H */,
/* Open previous page */ 0x1025 /* = Ctrl + left arrow */,
/* Send post (txt) */ 0xC00D /* = Alt + Enter */,
/* Open/close favorites posts*/ 0x4046 /* = Alt + F */,
/* Open/close hidden posts */ 0x4048 /* = Alt + H */,
/* Open/close panel */ 0x0050 /* = P */,
/* Mask/unmask images */ 0x0042 /* = B */,
/* Open/close settings */ 0x4053 /* = Alt + S */,
/* Expand current image */ 0x0049 /* = I */,
/* Bold text */ 0xC042 /* = Alt + B */,
/* Italic text */ 0xC049 /* = Alt + I */,
/* Strike text */ 0xC054 /* = Alt + T */,
/* Spoiler text */ 0xC050 /* = Alt + P */,
/* Code text */ 0xC043 /* = Alt + C */,
/* Open next page/picture */ 0x1027 /* = Ctrl + right arrow*/
];
var nonThrKeys = [
/* One post above */ 0x004D /* = M */,
/* One post below */ 0x004E /* = N */,
/* Open thread */ 0x0056 /* = V */,
/* Expand thread */ 0x0045 /* = E */
];
var thrKeys = [
/* Update thread */ 0x0055 /* = U */
];
return [KeyNavigation.version, isFirefox, globKeys, nonThrKeys, thrKeys];
};
KeyNavigation.prototype = {
paused: false,
clear: function(lastPage) {
this.cPost = null;
this.lastPage = lastPage;
this.lastPageOffset = 0;
},
disable: function() {
if(this.enabled) {
if(this.cPost) {
this.cPost.unselect();
}
doc.removeEventListener('keydown', this, true);
this.enabled = false;
}
},
enable: function() {
if(!this.enabled) {
this.clear(pageNum);
doc.addEventListener('keydown', this, true);
this.enabled = true;
}
},
handleEvent: function(e) {
if(this.paused) {
return;
}
var temp, post, scrollToThread, globIdx, idx, curTh = e.target.tagName,
kc = e.keyCode | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) |
(e.altKey ? 0x4000 : 0) | (curTh === 'TEXTAREA' ||
(curTh === 'INPUT' && e.target.type === 'text') ? 0x8000 : 0);
if(kc === 0x74 || kc === 0x8074) { // F5
if(TNum) {
return;
}
loadPages(+Cfg['loadPages']);
} else if(kc === 0x1B) { // ESC
if($c('de-img-full de-img-center', doc)) {
$c('de-img-full de-img-center', doc).click();
return;
}
if(this.cPost) {
this.cPost.unselect();
this.cPost = null;
}
if(TNum) {
firstThr.clearPostsMarks();
}
this.lastPageOffset = 0;
} else if(kc === 0x801B) { // ESC (txt)
e.target.blur();
} else {
globIdx = this.gKeys.indexOf(kc);
switch(globIdx) {
case 2: // Reply or create thread
if(pr.form) {
if(!this.cPost && TNum && Cfg['addPostForm'] === 3) {
this.cPost = firstThr.op;
}
if(this.cPost) {
pr.showQuickReply(this.cPost, this.cPost.num, true);
} else {
pr.showMainReply(Cfg['addPostForm'] === 1, null);
}
}
break;
case 3: // Hide selected thread/post
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
post.toggleUserVisib();
this._scroll(post, false, post.isOp);
}
break;
case 4: // Open previous page/picture
if($c('de-img-full de-img-center', doc)) {
$id('de-img-btn-prev').click();
} else if(TNum || pageNum !== aib.firstPage) {
window.location.pathname = aib.getPageUrl(brd, TNum ? 0 : pageNum - 1);
}
break;
case 5: // Send post (txt)
if(e.target !== pr.txta && e.target !== pr.cap) {
return;
}
pr.subm.click();
break;
case 6: // Open/close favorites posts
toggleContent('fav', false);
break;
case 7: // Open/close hidden posts
toggleContent('hid', false);
break;
case 8: // Open/close panel
$disp($id('de-panel').lastChild);
break;
case 9: // Mask/unmask images
toggleCfg('maskImgs');
updateCSS();
break;
case 10: // Open/close settings
toggleContent('cfg', false);
break;
case 11: // Expand current image
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
post.toggleImages(!post.imagesExpanded);
}
break;
case 12: // Bold text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-bold').click();
break;
case 13: // Italic text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-italic').click();
break;
case 14: // Strike text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-strike').click();
break;
case 15: // Spoiler text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-spoil').click();
break;
case 16: // Code text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-code').click();
break;
case 17: // Open next page/picture
if($c('de-img-full de-img-center', doc)) {
$id('de-img-btn-next').click();
} else if(!TNum && this.lastPage !== aib.lastPage) {
window.location.pathname = aib.getPageUrl(brd, this.lastPage + 1);
}
break;
case -1:
if(TNum) {
idx = this.tKeys.indexOf(kc);
if(idx === 0) { // Update thread
Thread.loadNewPosts(null);
break;
}
return;
}
idx = this.ntKeys.indexOf(kc);
if(idx === -1) {
return;
} else if(idx === 2) { // Open thread
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
if(nav.Firefox) {
GM_openInTab(aib.getThrdUrl(brd, post.tNum), false, true);
} else {
window.open(aib.getThrdUrl(brd, post.tNum), '_blank');
}
}
break;
} else if(idx === 3) { // Expand/collapse thread
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
if(post.thr.loadedOnce && post.thr.omitted === 0) {
temp = post.thr.nextNotHidden;
post.thr.load(visPosts, !!temp, null);
post = (temp || post.thr).op;
} else {
post.thr.load(1, false, null);
post = post.thr.op;
}
scrollTo(0, pageYOffset + post.topCoord);
if(this.cPost && this.cPost !== post) {
this.cPost.unselect();
this.cPost = post;
}
}
break;
}
default:
scrollToThread = !TNum && (globIdx === 0 || globIdx === 1);
this._scroll(this._getFirstVisPost(scrollToThread, false), globIdx === 0 || idx === 0,
scrollToThread);
}
}
e.stopPropagation();
$pd(e);
},
pause: function() {
this.paused = true;
},
resume: function(keys) {
this.gKeys = keys[2];
this.ntKeys = keys[3];
this.tKeys = keys[4];
this.paused = false;
},
_getFirstVisPost: function(getThread, getFull) {
var post, tPost;
if(this.lastPageOffset !== pageYOffset) {
post = getThread ? firstThr : firstThr.op;
while(post.topCoord < 1) {
tPost = post.next;
if(!tPost) {
break;
}
post = tPost;
}
if(this.cPost) {
this.cPost.unselect();
}
this.cPost = getThread ? getFull ? post.op : post.op.prev : getFull ? post : post.prev;
this.lastPageOffset = pageYOffset;
}
return this.cPost;
},
_getNextVisPost: function(cPost, isOp, toUp) {
var thr;
if(isOp) {
thr = cPost ? toUp ? cPost.thr.prevNotHidden : cPost.thr.nextNotHidden :
firstThr.hidden ? firstThr.nextNotHidden : firstThr;
return thr ? thr.op : null;
}
return cPost ? cPost.getAdjacentVisPost(toUp) : firstTht.hidden ||
firstThr.op.hidden ? firstThr.op.getAdjacentVisPost(toUp) : firstThr.op;
},
_scroll: function(post, toUp, toThread) {
var next = this._getNextVisPost(post, toThread, toUp);
if(!next) {
if(!TNum && (toUp ? pageNum > aib.firstPage : this.lastPage < aib.lastPage)) {
window.location.pathname = aib.getPageUrl(brd, toUp ? pageNum - 1 : this.lastPage + 1);
}
return;
}
if(post) {
post.unselect();
}
if(toThread) {
next.el.scrollIntoView();
} else {
scrollTo(0, pageYOffset + next.el.getBoundingClientRect().top -
Post.sizing.wHeight / 2 + next.el.clientHeight / 2);
}
this.lastPageOffset = pageYOffset;
next.select();
this.cPost = next;
}
}
function KeyEditListener(alertEl, keys, allKeys) {
var j, k, i, len, aInputs = aProto.slice.call($C('de-input-key', alertEl));
for(i = 0, len = allKeys.length; i < len; ++i) {
k = allKeys[i];
if(k !== 0) {
for(j = i + 1; j < len; ++j) {
if(k === allKeys[j]) {
aInputs[i].classList.add('de-error-key');
aInputs[j].classList.add('de-error-key');
break;
}
}
}
}
this.aEl = alertEl;
this.keys = keys;
this.initKeys = JSON.parse(JSON.stringify(keys));
this.allKeys = allKeys;
this.allInputs = aInputs;
this.errCount = $C('de-error-key', alertEl).length;
if(this.errCount !== 0) {
this.saveButton.disabled = true;
}
}
// Browsers have different codes for these keys (see KeyNavigation.readKeys):
// Firefox - '-' - 173, '=' - 61, ';' - 59
// Chrome/Opera: '-' - 189, '=' - 187, ';' - 186
KeyEditListener.keyCodes = ['',,,,,,,,'Backspace',/* Tab */,,,,'Enter',,,'Shift','Ctrl','Alt',
/* Pause/Break */,/* Caps Lock */,,,,,,,/* Escape */,,,,,'Space',/* Page Up */,
/* Page Down */,/* End */,/* Home */,'←','↑','→','↓',,,,,/* Insert */,/* Delete */,,'0','1','2',
'3','4','5','6','7','8','9',,';',,'=',,,,'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',/* Left WIN Key */,/* Right WIN Key */,
/* Select key */,,,'Numpad 0','Numpad 1','Numpad 2','Numpad 3','Numpad 4','Numpad 5','Numpad 6',
'Numpad 7','Numpad 8','Numpad 9','Numpad *','Numpad +',,'Numpad -','Numpad .','Numpad /',
/* F1 */,/* F2 */,/* F3 */,/* F4 */,/* F5 */,/* F6 */,/* F7 */,/* F8 */,/* F9 */,/* F10 */,
/* F11 */,/* F12 */,,,,,,,,,,,,,,,,,,,,,/* Num Lock */,/* Scroll Lock */,,,,,,,,,,,,,,,,,,,,,,,,
,,,,'-',,,,,,,,,,,,,';','=',',','-','.','/','`',,,,,,,,,,,,,,,,,,,,,,,,,,,'[','\\',']','\''
];
KeyEditListener.getStrKey = function(key) {
var str = '';
if(key & 0x1000) {
str += 'Ctrl + ';
}
if(key & 0x2000) {
str += 'Shift + ';
}
if(key & 0x4000) {
str += 'Alt + ';
}
str += KeyEditListener.keyCodes[key & 0xFFF];
return str;
}
KeyEditListener.getEditMarkup = function(keys) {
var allKeys = [];
var html = Lng.keyNavEdit[lang]
.replace(/%l/g, '<label class="de-block">')
.replace(/%\/l/g, '</label>')
.replace(/%i([2-4])([0-9]+)(t)?/g, function(aKeys, all, id1, id2, isText) {
var key = this[+id1][+id2];
aKeys.push(key);
return '<input class="de-input-key" type="text" de-id1="' + id1 + '" de-id2="' + id2 +
'" size="26" value="' + KeyEditListener.getStrKey(key) +
(isText ? '" de-text' : '"' ) + ' readonly></input>';
}.bind(keys, allKeys)) +
'<input type="button" id="de-keys-save" value="' + Lng.save[lang] + '"></input>' +
'<input type="button" id="de-keys-reset" value="' + Lng.reset[lang] + '"></input>';
return [allKeys, html];
};
KeyEditListener.prototype = {
cEl: null,
cKey: -1,
errorInput: false,
get saveButton() {
var val = $id('de-keys-save');
Object.defineProperty(this, 'saveButton', { value: val, configurable: true });
return val;
},
handleEvent: function(e) {
var key, keyStr, keys, str, id, temp, el = e.target;
switch(e.type) {
case 'blur':
if(keyNav && this.errCount === 0) {
keyNav.resume(this.keys);
}
this.cEl = null;
return;
case 'focus':
if(keyNav) {
keyNav.pause();
}
this.cEl = el;
return;
case 'click':
if(el.id === 'de-keys-reset') {
this.keys = KeyNavigation.getDefaultKeys();
this.initKeys = KeyNavigation.getDefaultKeys();
if(keyNav) {
keyNav.resume(this.keys);
}
temp = KeyEditListener.getEditMarkup(this.keys);
this.allKeys = temp[0];
$c('de-alert-msg', this.aEl).innerHTML = temp[1];
this.allInputs = aProto.slice.call($C('de-input-key', this.aEl));
this.errCount = 0;
delete this.saveButton;
break;
} else if(el.id === 'de-keys-save') {
keys = this.keys;
setStored('DESU_keys', JSON.stringify(keys));
} else if(el.className === 'de-alert-btn') {
keys = this.initKeys;
} else {
return;
}
if(keyNav) {
keyNav.resume(keys);
}
closeAlert($id('de-alert-edit-keybnavig'));
break;
case 'keydown':
if(!this.cEl) {
return;
}
key = e.keyCode;
if(key === 0x1B || key === 0x2E) { // ESC, DEL
this.cEl.value = '';
this.cKey = 0;
this.errorInput = false;
break;
}
keyStr = KeyEditListener.keyCodes[key];
if(keyStr == null) {
this.cKey = -1;
return;
}
str = '';
if(e.ctrlKey) {
str += 'Ctrl + ';
}
if(e.shiftKey) {
str += 'Shift + ';
}
if(e.altKey) {
str += 'Alt + ';
}
if(key === 16 || key === 17 || key === 18) {
this.errorInput = true;
} else {
this.cKey = key | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) |
(e.altKey ? 0x4000 : 0) | (this.cEl.hasAttribute('de-text') ? 0x8000 : 0);
this.errorInput = false;
str += keyStr;
}
this.cEl.value = str;
break;
case 'keyup':
var idx, rIdx, oKey, rEl, isError, el = this.cEl,
key = this.cKey;
if(!el || key === -1) {
return;
}
isError = el.classList.contains('de-error-key');
if(!this.errorInput && key !== -1) {
idx = this.allInputs.indexOf(el);
oKey = this.allKeys[idx];
if(oKey === key) {
this.errorInput = false;
break;
}
rIdx = key === 0 ? -1 : this.allKeys.indexOf(key);
this.allKeys[idx] = key;
if(isError) {
idx = this.allKeys.indexOf(oKey);
if(idx !== -1 && this.allKeys.indexOf(oKey, idx + 1) === -1) {
rEl = this.allInputs[idx];
if(rEl.classList.contains('de-error-key')) {
this.errCount--;
rEl.classList.remove('de-error-key');
}
}
if(rIdx === -1) {
this.errCount--;
el.classList.remove('de-error-key');
}
}
if(rIdx === -1) {
this.keys[+el.getAttribute('de-id1')][+el.getAttribute('de-id2')] = key;
if(this.errCount === 0) {
this.saveButton.disabled = false;
}
this.errorInput = false;
break;
}
rEl = this.allInputs[rIdx];
if(!rEl.classList.contains('de-error-key')) {
this.errCount++;
rEl.classList.add('de-error-key');
}
}
if(!isError) {
this.errCount++;
el.classList.add('de-error-key');
}
if(this.errCount !== 0) {
this.saveButton.disabled = true;
}
}
$pd(e);
}
};
//============================================================================================================
// FORM SUBMIT
//============================================================================================================
function getSubmitResponse(dc, isFrame) {
var i, els, el, err = '', form = $q(aib.qDForm, dc);
if(dc.body.hasChildNodes() && !form) {
for(i = 0, els = $Q(aib.qError, dc); el = els[i++];) {
err += el.innerHTML + '\n';
}
if(!(err = err.replace(/<a [^>]+>Назад.+|<br.+/, ''))) {
err = Lng.error[lang] + '\n' + dc.body.innerHTML;
}
err = /:null|successful|uploaded|updating|обновл|удален[о\.]/i.test(err) ? '' : err.replace(/"/g, "'");
}
return [(isFrame ? window.location : form ? aib.getThrdUrl(brd, aib.getTNum(form)) : ''), err];
}
function checkUpload(response) {
if(aib.krau) {
pr.form.action = pr.form.action.split('?')[0];
$id('postform_row_progress').style.display = 'none';
aib.btnZeroLUTime.click();
}
var err = response[1];
if(err) {
if(pr.isQuick) {
pr.setReply(true, false);
}
if(/captch|капч|подтвер|verifizie/i.test(err)) {
pr.refreshCapImg(true);
}
$alert(err, 'upload', false);
return;
}
pr.txta.value = '';
if(pr.file) {
pr.delFileUtils(getAncestor(pr.file, aib.trTag), true);
if(aib.krau) {
var fileInputs = $Q('input[type="file"]', $id('files_parent'));
if(fileInputs.length > 1) {
$each(fileInputs, function(input, index) {
if(index > 0) {
$del(input.parentNode);
}
});
aib.btnSetFCntToOne.click();
}
}
}
if(pr.video) {
pr.video.value = '';
}
Cfg['stats'][pr.tNum ? 'reply' : 'op']++;
saveComCfg(aib.dm, Cfg);
if(!pr.tNum) {
window.location = response[0];
return;
}
if(TNum) {
firstThr.clearPostsMarks();
firstThr.loadNew(function(eCode, eMsg, np, xhr) {
infoLoadErrors(eCode, eMsg, 0);
closeAlert($id('de-alert-upload'));
if(Cfg['scrAfterRep']) {
scrollTo(0, pageYOffset + firstThr.last.el.getBoundingClientRect().top);
}
}, true);
} else {
pByNum[pr.tNum].thr.load(visPosts, false, closeAlert.bind(window, $id('de-alert-upload')));
}
pr.closeQReply();
pr.refreshCapImg(false);
}
function endDelete() {
var el = $id('de-alert-deleting');
if(el) {
closeAlert(el);
$alert(Lng.succDeleted[lang], 'deleted', false);
}
}
function checkDelete(response) {
if(response[1]) {
$alert(Lng.errDelete[lang] + response[1], 'deleting', false);
return;
}
var el, i, els, len, post, tNums = [],
num = (doc.location.hash.match(/\d+/) || [null])[0];
if(num && (post = pByNum[num])) {
if(!post.isOp) {
post.el.className = aib.cReply;
}
doc.location.hash = '';
}
for(i = 0, els = $Q('.' + aib.cRPost + ' input:checked', dForm), len = els.length; i < len; ++i) {
el = els[i];
el.checked = false;
if(!TNum && tNums.indexOf(num = aib.getPostEl(el).post.tNum) === -1) {
tNums.push(num);
}
}
if(TNum) {
firstThr.clearPostsMarks();
firstThr.loadNew(function(eCode, eMsg, np, xhr) {
infoLoadErrors(eCode, eMsg, 0);
endDelete();
}, false);
} else {
tNums.forEach(function(tNum) {
pByNum[tNum].thr.load(visPosts, false, endDelete);
});
}
}
function html5Submit(form, button, fn) {
this.boundary = '---------------------------' + Math.round(Math.random() * 1e11);
this.data = [];
this.busy = 0;
this.error = false;
this.url = form.action;
this.fn = fn;
$each($Q('input:not([type="submit"]):not([type="button"]), textarea, select', form),
this.append.bind(this));
this.append(button);
this.submit();
}
html5Submit.prototype = {
append: function(el) {
var file, fName, idx, fr,
pre = '--' + this.boundary + '\r\nContent-Disposition: form-data; name="' + el.name + '"';
if(el.type === 'file' && el.files.length > 0) {
file = el.files[0];
fName = file.name;
this.data.push(pre + '; filename="' + (
!Cfg['removeFName'] ? fName : ' ' + fName.substring(fName.lastIndexOf('.'))
) + '"\r\nContent-type: ' + file.type + '\r\n\r\n', null, '\r\n');
idx = this.data.length - 2;
if(!/^image\/(?:png|jpeg)$/.test(file.type)) {
this.data[idx] = file;
return;
}
fr = new FileReader();
fr.onload = function(name, e) {
var dat = this.clearImage(e.target.result, !!el.imgFile);
if(dat) {
if(el.imgFile) {
dat.push(el.imgFile);
}
if(Cfg['postSameImg']) {
dat.push(String(Math.round(Math.random() * 1e6)));
}
this.data[idx] = new Blob(dat);
this.busy--;
this.submit();
} else {
this.error = true;
$alert(Lng.fileCorrupt[lang] + name, 'upload', false);
}
}.bind(this, fName);
fr.readAsArrayBuffer(file);
this.busy++;
} else if(el.type !== 'checkbox' || el.checked) {
this.data.push(pre + '\r\n\r\n' + el.value + '\r\n');
}
},
submit: function() {
if(this.error || this.busy !== 0) {
return;
}
this.data.push('--' + this.boundary + '--\r\n');
$xhr({
'method': 'POST',
'headers': {'Content-type': 'multipart/form-data; boundary=' + this.boundary},
'data': new Blob(this.data),
'url': nav.fixLink(this.url),
'onreadystatechange': function(xhr) {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
this(getSubmitResponse($DOM(xhr.responseText), false));
} else {
$alert(xhr.status === 0 ? Lng.noConnect[lang] :
'HTTP [' + xhr.status + '] ' + xhr.statusText, 'upload', false);
}
}
}.bind(this.fn)
});
},
readExif: function(data, off, len) {
var i, j, dE, tag, tgLen, xRes = 0,
yRes = 0,
resT = 0,
dv = new DataView(data, off),
le = String.fromCharCode(dv.getUint8(0), dv.getUint8(1)) !== 'MM';
if(dv.getUint16(2, le) !== 0x2A) {
return null;
}
i = dv.getUint32(4, le);
if(i > len) {
return null;
}
for(tgLen = dv.getUint16(i, le), j = 0; j < tgLen; j++) {
tag = dv.getUint16(dE = i + 2 + 12 * j, le);
if(tag !== 0x011A && tag !== 0x011B && tag !== 0x0128) {
continue;
}
if(tag === 0x0128) {
resT = dv.getUint16(dE + 8, le) - 1;
} else {
dE = dv.getUint32(dE + 8, le);
if(dE > len) {
return null;
}
if(tag === 0x11A) {
xRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le));
} else {
yRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le));
}
}
}
xRes = xRes || yRes;
yRes = yRes || xRes;
return new Uint8Array([resT, xRes >> 8, xRes & 0xFF, yRes >> 8, yRes & 0xFF]);
},
clearImage: function(data, delExtraData) {
var tmp, i, len, deep, rv, lIdx, jpgDat, img = new Uint8Array(data),
rExif = !!Cfg['removeEXIF'];
if(!Cfg['postSameImg'] && !rExif && !delExtraData) {
return [img];
}
if(img[0] === 0xFF && img[1] === 0xD8) {
for(i = 2, deep = 1, len = img.length - 1, rv = [null, null], lIdx = 2, jpgDat = null; i < len; ) {
if(img[i] === 0xFF) {
if(rExif) {
if(!jpgDat && deep === 1) {
if(img[i + 1] === 0xE1 && img[i + 4] === 0x45) {
jpgDat = this.readExif(data, i + 10, (img[i + 2] << 8) + img[i + 3]);
} else if(img[i + 1] === 0xE0 && img[i + 7] === 0x46) {
jpgDat = img.subarray(i + 11, i + 16);
}
}
if((img[i + 1] >> 4) === 0xE || img[i + 1] === 0xFE) {
if(lIdx !== i) {
rv.push(img.subarray(lIdx, i));
}
i += 2 + (img[i + 2] << 8) + img[i + 3];
lIdx = i;
continue;
}
} else if(img[i + 1] === 0xD8) {
deep++;
i++;
continue;
}
if(img[i + 1] === 0xD9 && --deep === 0) {
break;
}
}
i++;
}
i += 2;
if(!delExtraData && len - i > 75) {
i = len;
}
if(lIdx === 2) {
return i === len ? [img] : [new Uint8Array(data, 0, i)];
}
rv[0] = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0, 0, 0x0D, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1]);
rv[1] = jpgDat || new Uint8Array([0, 0, 1, 0, 1]);
rv.push(img.subarray(lIdx, i));
return rv;
}
if(img[0] === 0x89 && img[1] === 0x50) {
for(i = 0, len = img.length - 7; i < len && (img[i] !== 0x49 ||
img[i + 1] !== 0x45 || img[i + 2] !== 0x4E || img[i + 3] !== 0x44); i++) {}
i += 8;
return i === len || (!delExtraData && len - i > 75) ? [img] : [new Uint8Array(data, 0, i)];
}
return null;
}
};
//============================================================================================================
// CONTENT FEATURES
//============================================================================================================
function initMessageFunctions() {
window.addEventListener('message', function(e) {
var temp, data = e.data.substring(1);
switch(e.data[0]) {
case 'A':
temp = data.split('$#$');
if(temp[0] === 'de-iframe-pform') {
checkUpload([temp[1], temp[2]]);
} else {
checkDelete([temp[1], temp[2]]);
}
$q('iframe[name="' + temp[0] + '"]', doc).src = 'about:blank';
return;
case 'B':
$del($id('de-fav-wait'));
$id('de-iframe-fav').style.height = data + 'px';
return;
}
}, false);
}
function detectImgFile(ab) {
var i, j, dat = new Uint8Array(ab),
len = dat.length;
/* JPG [ff d8 ff e0] = [яШяа] */
if(dat[0] === 0xFF && dat[1] === 0xD8) {
for(i = 0, j = 0; i < len - 1; i++) {
if(dat[i] === 0xFF) {
/* Built-in JPG */
if(dat[i + 1] === 0xD8) {
j++;
/* JPG end [ff d9] */
} else if(dat[i + 1] === 0xD9 && --j === 0) {
i += 2;
break;
}
}
}
/* PNG [89 50 4e 47] = [‰PNG] */
} else if(dat[0] === 0x89 && dat[1] === 0x50) {
for(i = 0; i < len - 7; i++) {
/* PNG end [49 45 4e 44 ae 42 60 82] */
if(dat[i] === 0x49 && dat[i + 1] === 0x45 && dat[i + 2] === 0x4E && dat[i + 3] === 0x44) {
i += 8;
break;
}
}
} else {
return {};
}
/* Ignore small files */
if(i !== len && len - i > 60) {
for(len = i + 90; i < len; i++) {
/* 7Z [37 7a bc af] = [7zјЇ] */
if(dat[i] === 0x37 && dat[i + 1] === 0x7A && dat[i + 2] === 0xBC) {
return {'type': 0, 'idx': i, 'data': ab};
/* ZIP [50 4b 03 04] = [PK..] */
} else if(dat[i] === 0x50 && dat[i + 1] === 0x4B && dat[i + 2] === 0x03) {
return {'type': 1, 'idx': i, 'data': ab};
/* RAR [52 61 72 21] = [Rar!] */
} else if(dat[i] === 0x52 && dat[i + 1] === 0x61 && dat[i + 2] === 0x72) {
return {'type': 2, 'idx': i, 'data': ab};
/* OGG [4f 67 67 53] = [OggS] */
} else if(dat[i] === 0x4F && dat[i + 1] === 0x67 && dat[i + 2] === 0x67) {
return {'type': 3, 'idx': i, 'data': ab};
/* MP3 [0x49 0x44 0x33] = [ID3] */
} else if(dat[i] === 0x49 && dat[i + 1] === 0x44 && dat[i + 2] === 0x33) {
return {'type': 4, 'idx': i, 'data': ab};
}
}
}
return {};
}
function workerQueue(mReqs, wrkFn, errFn) {
if(!nav.hasWorker) {
this.run = this._runSync.bind(wrkFn);
return;
}
this.queue = new $queue(mReqs, this._createWrk.bind(this), null);
this.run = this._runWrk;
this.wrks = new $workers('self.onmessage = function(e) {\
var info = (' + String(wrkFn) + ')(e.data[1]);\
if(info.data) {\
self.postMessage([e.data[0], info], [info.data]);\
} else {\
self.postMessage([e.data[0], info]);\
}\
}', mReqs);
this.errFn = errFn;
}
workerQueue.prototype = {
_runSync: function(data, transferObjs, Fn) {
Fn(this(data));
},
onMess: function(Fn, e) {
this.queue.end(e.data[0]);
Fn(e.data[1]);
},
onErr: function(qIdx, e) {
this.queue.end(qIdx);
this.errFn(e);
},
_runWrk: function(data, transObjs, Fn) {
this.queue.run([data, transObjs, this.onMess.bind(this, Fn)]);
},
_createWrk: function(qIdx, num, data) {
var w = this.wrks[qIdx];
w.onmessage = data[2];
w.onerror = this.onErr.bind(this, qIdx);
w.postMessage([qIdx, data[0]], data[1]);
},
clear: function() {
this.wrks.clear();
this.wrks = null;
}
};
function addImgFileIcon(fName, info) {
var app, ext, type = info['type'];
if(typeof type !== 'undefined') {
if(type === 2) {
app = 'application/x-rar-compressed';
ext = 'rar';
} else if(type === 1) {
app = 'application/zip';
ext = 'zip';
} else if(type === 0) {
app = 'application/x-7z-compressed';
ext = '7z';
} else if(type === 3) {
app = 'audio/ogg';
ext = 'ogg';
} else {
app = 'audio/mpeg';
ext = 'mp3';
}
this.insertAdjacentHTML('afterend', '<a href="' + window.URL.createObjectURL(
new Blob([new Uint8Array(info['data']).subarray(info['idx'])], {'type': app})
) + '" class="de-img-' + (type > 2 ? 'audio' : 'arch') + '" title="' + Lng.downloadFile[lang] +
'" download="' + fName.substring(0, fName.lastIndexOf('.')) + '.' + ext + '">.' + ext + '</a>'
);
}
}
function downloadImgData(url, Fn) {
downloadObjInfo({
'method': 'GET',
'url': url,
'onreadystatechange': function onDownloaded(url, e) {
if(e.readyState !== 4) {
return;
}
var isAb = e.responseType === 'arraybuffer';
if(e.status === 0 && isAb) {
Fn(new Uint8Array(e.response));
} else if(e.status !== 200) {
if(e.status === 404 || !url) {
Fn(null);
} else {
downloadObjInfo({
'method': 'GET',
'url': url,
'onreadystatechange': onDownloaded.bind(null, null)
});
}
} else if(isAb) {
Fn(new Uint8Array(e.response));
} else {
for(var len, i = 0, txt = e.responseText, rv = new Uint8Array(len = txt.length); i < len; ++i) {
rv[i] = txt.charCodeAt(i) & 0xFF;
}
Fn(rv);
}
}.bind(null, url)
});
}
function downloadObjInfo(obj) {
if(nav.Firefox && aib.fch && !obj.url.startsWith('blob')) {
obj['overrideMimeType'] = 'text/plain; charset=x-user-defined';
GM_xmlhttpRequest(obj);
} else {
obj['responseType'] = 'arraybuffer';
try {
$xhr(obj);
} catch(e) {
Fn(null);
}
}
}
function preloadImages(post) {
if(!Cfg['preLoadImgs'] && !Cfg['openImgs'] && !isPreImg) {
return;
}
var lnk, url, iType, nExp, el, i, len, els, queue, mReqs = post ? 1 : 4, cImg = 1,
rjf = (isPreImg || Cfg['findImgFile']) && new workerQueue(mReqs, detectImgFile, function(e) {
console.error("FILE DETECTOR ERROR, line: " + e.lineno + " - " + e.message);
});
if(isPreImg || Cfg['preLoadImgs']) {
queue = new $queue(mReqs, function(qIdx, num, dat) {
downloadImgData(dat[0], function(idx, data) {
if(data) {
var a = this[1],
fName = this[0].substring(this[0].lastIndexOf("/") + 1),
aEl = $q(aib.qImgLink, aib.getImgWrap(a));
aEl.setAttribute('download', fName);
a.href = window.URL.createObjectURL(new Blob([data], {'type': this[2]}));
a.setAttribute('de-name', fName);
if(this[3]) {
this[3].src = a.href;
}
if(rjf) {
rjf.run(data.buffer, [data.buffer], addImgFileIcon.bind(aEl, fName));
}
}
queue.end(idx);
if(Images_.progressId) {
$alert(Lng.loadImage[lang] + cImg + '/' + len, Images_.progressId, true);
}
cImg++;
}.bind(dat, qIdx));
}, function() {
Images_.preloading = false
if(Images_.afterpreload) {
Images_.afterpreload();
Images_.afterpreload = Images_.progressId = null;
}
rjf && rjf.clear();
rjf = queue = cImg = len = null;
});
Images_.preloading = true;
}
for(i = 0, els = getImages(post || dForm), len = els.length; i < len; i++) {
if(lnk = getAncestor(el = els[i], 'A')) {
url = lnk.href;
nExp = !!Cfg['openImgs'];
if(/\.gif$/i.test(url)) {
iType = 'image/gif';
} else {
if(/\.jpe?g$/i.test(url)) {
iType = 'image/jpeg';
} else if(/\.png$/i.test(url)) {
iType = 'image/png';
} else {
continue;
}
nExp &= !Cfg['openGIFs'];
}
if(queue) {
queue.run([url, lnk, iType, nExp && el]);
} else if(nExp) {
el.src = url;
}
}
}
queue && queue.complete();
}
function getDataFromImg(img) {
var cnv = Images_.canvas || (Images_.canvas = doc.createElement('canvas'));
cnv.width = img.width;
cnv.height = img.height;
cnv.getContext('2d').drawImage(img, 0, 0);
return new Uint8Array(atob(cnv.toDataURL("image/png").split(',')[1]).split('').map(function(a) {
return a.charCodeAt();
}));
}
function loadDocFiles(imgOnly) {
var els, files, progress, counter, count = 0,
current = 1,
warnings = '',
tar = new $tar(),
dc = imgOnly ? doc : doc.documentElement.cloneNode(true);
Images_.queue = new $queue(4, function(qIdx, num, dat) {
downloadImgData(dat[0], function(idx, data) {
var name = this[1].replace(/[\\\/:*?"<>|]/g, '_'), el = this[2];
progress.value = current;
counter.innerHTML = current;
current++;
if(this[3]) {
if(!data) {
warnings += '<br>' + Lng.cantLoad[lang] + '<a href="' + this[0] + '">' +
this[0] + '</a><br>' + Lng.willSavePview[lang];
$alert(Lng.loadErrors[lang] + warnings, 'floadwarn', false);
name = 'thumb-' + name.replace(/\.[a-z]+$/, '.png');
data = getDataFromImg(this[2]);
}
if(!imgOnly) {
el.classList.add('de-thumb');
el.src = this[3].href = $q(aib.qImgLink, aib.getImgWrap(this[3])).href =
name = 'images/' + name;
}
tar.addFile(name, data);
} else if(data && data.length > 0) {
tar.addFile(el.href = el.src = 'data/' + name, data);
} else {
$del(el);
}
Images_.queue.end(idx);
}.bind(dat, qIdx));
}, function() {
var u, a, dt;
if(!imgOnly) {
dt = doc.doctype;
$t('head', dc).insertAdjacentHTML('beforeend',
'<script type="text/javascript" src="data/dollscript.js"></script>');
tar.addString('data/dollscript.js', '(' + String(de_main_func) + ')(null, true);');
tar.addString(
TNum + '.html', '<!DOCTYPE ' + dt.name +
(dt.publicId ? ' PUBLIC "' + dt.publicId + '"' : dt.systemId ? ' SYSTEM' : '') +
(dt.systemId ? ' "' + dt.systemId + '"' : '') + '>' + dc.outerHTML
);
}
u = window.URL.createObjectURL(tar.get());
a = $new('a', {'href': u, 'download': aib.dm + '-' + brd.replace(/[\\\/:*?"<>|]/g, '') +
'-t' + TNum + (imgOnly ? '-images.tar' : '.tar')}, null);
doc.body.appendChild(a);
a.click();
setTimeout(function(el, url) {
window.URL.revokeObjectURL(url);
$del(el);
}, 0, a, u);
$del($id('de-alert-filesload'));
Images_.queue = tar = warnings = count = current = imgOnly = progress = counter = null;
});
els = aProto.slice.call(getImages($q('[de-form]', dc)));
count += els.length;
els.forEach(function(el) {
var lnk, url;
if(lnk = getAncestor(el, 'A')) {
url = lnk.href;
Images_.queue.run([url, lnk.getAttribute('de-name') ||
url.substring(url.lastIndexOf("/") + 1), el, lnk]);
}
});
if(!imgOnly) {
files = [];
$each($Q('script, link[rel="alternate stylesheet"], span[class^="de-btn-"],' +
' #de-main > div, .de-parea, #de-qarea, ' + aib.qPostForm, dc), $del);
$each($T('a', dc), function(el) {
var num, tc = el.textContent;
if(tc[0] === '>' && tc[1] === '>' && (num = +tc.substr(2)) && (num in pByNum)) {
el.href = aib.anchor + num;
} else {
el.href = getAbsLink(el.href);
}
if(!el.classList.contains('de-preflink')) {
el.className = 'de-preflink ' + el.className;
}
});
$each($Q('.' + aib.cRPost, dc), function(post, i) {
post.setAttribute('de-num', i === 0 ? TNum : aib.getPNum(post));
});
$each($Q('link, *[src]', dc), function(el) {
if(els.indexOf(el) !== -1) {
return;
}
var temp, i, ext, name, url = el.tagName === 'LINK' ? el.href : el.src;
if(!this.test(url)) {
$del(el);
return;
}
name = url.substring(url.lastIndexOf("/") + 1).replace(/[\\\/:*?"<>|]/g, '_')
.toLowerCase();
if(files.indexOf(name) !== -1) {
temp = url.lastIndexOf('.');
ext = url.substring(temp);
url = url.substring(0, temp);
name = name.substring(0, name.lastIndexOf('.'));
for(i = 0; ; ++i) {
temp = name + '(' + i + ')' + ext;
if(files.indexOf(temp) === -1) {
break;
}
}
name = temp;
}
files.push(name);
Images_.queue.run([url, name, el, null]);
count++;
}.bind(new RegExp('^\\/\\/?|^https?:\\/\\/([^\\/]*\.)?' + regQuote(aib.dm) + '\\/', 'i')));
}
$alert((imgOnly ? Lng.loadImage[lang] : Lng.loadFile[lang]) +
'<br><progress id="de-loadprogress" value="0" max="' + count + '"></progress> <span>1</span>/' +
count, 'filesload', true);
progress = $id('de-loadprogress');
counter = progress.nextElementSibling;
Images_.queue.complete();
els = null;
}
//============================================================================================================
// TIME CORRECTION
//============================================================================================================
function dateTime(pattern, rPattern, diff, dtLang, onRPat) {
if(dateTime.checkPattern(pattern)) {
this.disabled = true;
return;
}
this.regex = pattern
.replace(/(?:[sihdny]\?){2,}/g, function() {
return '(?:' + arguments[0].replace(/\?/g, '') + ')?';
})
.replace(/\-/g, '[^<]')
.replace(/\+/g, '[^0-9]')
.replace(/([sihdny]+)/g, '($1)')
.replace(/[sihdny]/g, '\\d')
.replace(/m|w/g, '([a-zA-Zа-яА-Я]+)');
this.pattern = pattern.replace(/[\?\-\+]+/g, '').replace(/([a-z])\1+/g, '$1');
this.diff = parseInt(diff, 10);
this.sDiff = (this.diff < 0 ? '' : '+') + this.diff;
this.arrW = Lng.week[dtLang];
this.arrM = Lng.month[dtLang];
this.arrFM = Lng.fullMonth[dtLang];
this.rPattern = rPattern;
this.onRPat = onRPat;
}
dateTime.toggleSettings = function(el) {
if(el.checked && (!/^[+-]\d{1,2}$/.test(Cfg['timeOffset']) || dateTime.checkPattern(Cfg['timePattern']))) {
$alert(Lng.cTimeError[lang], 'err-correcttime', false);
saveCfg('correctTime', 0);
el.checked = false;
}
};
dateTime.checkPattern = function(val) {
return !val.contains('i') || !val.contains('h') || !val.contains('d') || !val.contains('y') ||
!(val.contains('n') || val.contains('m')) ||
/[^\?\-\+sihdmwny]|mm|ww|\?\?|([ihdny]\?)\1+/.test(val);
};
dateTime.prototype = {
getRPattern: function(txt) {
var k, p, a, str, i = 1,
j = 0,
m = txt.match(new RegExp(this.regex));
if(!m) {
this.disabled = true;
return false;
}
this.rPattern = '';
str = m[0];
while(a = m[i++]) {
p = this.pattern[i - 2];
if((p === 'm' || p === 'y') && a.length > 3) {
p = p.toUpperCase();
}
k = str.indexOf(a, j);
this.rPattern += str.substring(j, k) + '_' + p;
j = k + a.length;
}
this.onRPat && this.onRPat(this.rPattern);
return true;
},
pad2: function(num) {
return num < 10 ? '0' + num : num;
},
fix: function(txt) {
if(this.disabled || (!this.rPattern && !this.getRPattern(txt))) {
return txt;
}
return txt.replace(new RegExp(this.regex, 'g'), function() {
var i, a, t, second, minute, hour, day, month, year, dtime;
for(i = 1; i < 8; i++) {
a = arguments[i];
t = this.pattern[i - 1];
t === 's' ? second = a :
t === 'i' ? minute = a :
t === 'h' ? hour = a :
t === 'd' ? day = a :
t === 'n' ? month = a - 1 :
t === 'y' ? year = a :
t === 'm' && (
month =
/^янв|^jan/i.test(a) ? 0 :
/^фев|^feb/i.test(a) ? 1 :
/^мар|^mar/i.test(a) ? 2 :
/^апр|^apr/i.test(a) ? 3 :
/^май|^may/i.test(a) ? 4 :
/^июн|^jun/i.test(a) ? 5 :
/^июл|^jul/i.test(a) ? 6 :
/^авг|^aug/i.test(a) ? 7 :
/^сен|^sep/i.test(a) ? 8 :
/^окт|^oct/i.test(a) ? 9 :
/^ноя|^nov/i.test(a) ? 10 :
/^дек|^dec/i.test(a) && 11
);
}
dtime = new Date(year.length === 2 ? '20' + year : year, month, day, hour, minute, second || 0);
dtime.setHours(dtime.getHours() + this.diff);
return this.rPattern
.replace('_o', this.sDiff)
.replace('_s', this.pad2(dtime.getSeconds()))
.replace('_i', this.pad2(dtime.getMinutes()))
.replace('_h', this.pad2(dtime.getHours()))
.replace('_d', this.pad2(dtime.getDate()))
.replace('_w', this.arrW[dtime.getDay()])
.replace('_n', this.pad2(dtime.getMonth() + 1))
.replace('_m', this.arrM[dtime.getMonth()])
.replace('_M', this.arrFM[dtime.getMonth()])
.replace('_y', ('' + dtime.getFullYear()).substring(2))
.replace('_Y', dtime.getFullYear());
}.bind(this));
}
};
//============================================================================================================
// PLAYERS
//============================================================================================================
function initYouTube(embedType, videoType, width, height, isHD, loadTitles) {
var vData, vimReg = /^https?:\/\/(?:www\.)?vimeo\.com\/(?:[^\?]+\?clip_id=)?(\d+).*?$/,
ytReg = /^https?:\/\/(?:www\.|m\.)?youtu(?:be\.com\/(?:watch\?.*?v=|v\/|embed\/)|\.be\/)([^&#?]+).*?(?:t(?:ime)?=(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?)?$/;
function addThumb(el, m, isYtube) {
var wh = ' width="' + width + '" height="' + height + '"></a>';
if(isYtube) {
el.innerHTML = '<a href="https://www.youtube.com/watch?v=' + m[1] + '" target="_blank">' +
'<img class="de-video-thumb de-ytube" src="https://i.ytimg.com/vi/' + m[1] +
'/0.jpg"' + wh;
} else {
el.innerHTML = '<a href="https://vimeo.com/' + m[1] + '" target="_blank">' +
'<img class="de-video-thumb de-vimeo" src=""' + wh;
GM_xmlhttpRequest({
'method': 'GET',
'url': 'http://vimeo.com/api/v2/video/' + m[1] + '.json',
'onload': function(xhr){
this.setAttribute('src', JSON.parse(xhr.responseText)[0]['thumbnail_large']);
}.bind(el.firstChild.firstChild)
});
}
}
function addPlayer(el, m, isYtube) {
var time, id = m[1],
wh = ' width="' + width + '" height="' + height + '">';
if(isYtube) {
time = (m[2] ? m[2] * 3600 : 0) + (m[3] ? m[3] * 60 : 0) + (m[4] ? +m[4] : 0);
el.innerHTML = videoType === 1 ?
'<iframe type="text/html" src="https://www.youtube.com/embed/' + id +
(isHD ? '?hd=1&' : '?') + 'start=' + time + '&html5=1&rel=0" frameborder="0"' + wh :
'<embed type="application/x-shockwave-flash" src="https://www.youtube.com/v/' + id +
(isHD ? '?hd=1&' : '?') + 'start=' + time + '" allowfullscreen="true" wmode="transparent"' + wh;
} else {
el.innerHTML = videoType === 1 ?
'<iframe src="//player.vimeo.com/video/' + id +
'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen' + wh :
'<embed type="application/x-shockwave-flash" src="http://vimeo.com/moogaloop.swf?clip_id=' + id +
'&server=vimeo.com&color=00adef&fullscreen=1" ' +
'allowscriptaccess="always" allowfullscreen="true"' + wh;
}
}
function addLink(post, m, loader, link, isYtube) {
var msg, src, time, dataObj;
post.hasYTube = true;
if(post.ytInfo === null) {
if(youTube.embedType === 2) {
youTube.addPlayer(post.ytObj, post.ytInfo = m, isYtube);
} else if(youTube.embedType > 2) {
youTube.addThumb(post.ytObj, post.ytInfo = m, isYtube);
}
} else if(!link && $q('.de-video-link[href*="' + m[1] + '"]', post.msg)) {
return;
}
if(loader && (dataObj = youTube.vData[m[1]])) {
post.ytData.push(dataObj);
}
if(m[4] || m[3] || m[2]) {
if(m[4] >= 60) {
m[3] = (m[3] || 0) + Math.floor(m[4] / 60);
m[4] %= 60;
}
if(m[3] >= 60) {
m[2] = (m[2] || 0) + Math.floor(m[3] / 60);
m[3] %= 60;
}
time = (m[2] ? m[2] + 'h' : '') + (m[3] ? m[3] + 'm' : '') + (m[4] ? m[4] + 's' : '');
}
if(link) {
link.href = link.href.replace(/^http:/, 'https:');
if(time) {
link.setAttribute('de-time', time);
}
if(dataObj) {
link.textContent = dataObj[0];
link.className = 'de-video-link de-ytube de-video-title';
link.setAttribute('de-author', dataObj[1]);
} else {
link.className = 'de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo');
}
} else {
src = isYtube ? 'https://www.youtube.com/watch?v=' + m[1] + (time ? '#t=' + time : '')
: 'https://vimeo.com/' + m[1];
post.msg.insertAdjacentHTML('beforeend',
'<p class="de-video-ext"><a ' + (dataObj ? 'de-author="' + dataObj[1] + '" ' : '') +
(time ? 'de-time="' + time + '" ' : '') +
'class="de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo') +
(dataObj ? ' de-video-title' : '') +
'" href="' + src + '">' + (dataObj ? dataObj[0] : src) + '</a></p>');
link = post.msg.lastChild.firstChild;
}
if(!post.ytInfo || post.ytInfo === m) {
post.ytLink = link;
}
link.ytInfo = m;
if(loader && !dataObj) {
post.ytLinksLoading++;
loader.run([post, link, m[1]]);
}
}
function getYtubeTitleLoader() {
var queueEnd, queue = new $queue(4, function(qIdx, num, data) {
if(num % 30 === 0) {
queue.pause();
setTimeout(queue.continue.bind(queue), 3e3);
}
GM_xmlhttpRequest({
'method': 'GET',
'url': 'https://gdata.youtube.com/feeds/api/videos/' + data[2] +
'?alt=json&fields=title/text(),author/name',
'onreadystatechange': function(idx, xhr) {
if(xhr.readyState !== 4) {
return;
}
var entry, title, author, data, post = this[0], link = this[1];
try {
if(xhr.status === 200) {
entry = JSON.parse(xhr.responseText)['entry'];
title = entry['title']['$t'];
author = entry['author'][0]['name']['$t'];
}
} finally {
if(title) {
link.textContent = title;
link.setAttribute('de-author', author);
link.classList.add('de-video-title');
vData[this[2]] = data = [title, author];
post.ytData.push(data);
post.ytLinksLoading--;
if(post.ytHideFun !== null) {
post.ytHideFun(data);
}
}
setTimeout(queueEnd, 250, idx);
}
}.bind(data, qIdx)
});
}, function() {
sessionStorage['de-ytube-data'] = JSON.stringify(vData);
queue = queueEnd = null;
});
queueEnd = queue.end.bind(queue);
return queue;
}
function parseLinks(post) {
var i, len, els, el, src, m, embedTube = [],
loader = loadTitles && getYtubeTitleLoader();
for(i = 0, els = $Q('embed, object, iframe', post ? post.el : dForm), len = els.length; i < len; ++i) {
el = els[i];
src = el.src || el.data;
if(m = src.match(ytReg)) {
embedTube.push(post || aib.getPostEl(el).post, m, true);
$del(el);
}
if(Cfg['addVimeo'] && (m = src.match(vimReg))) {
embedTube.push(post || aib.getPostEl(el).post, m, false);
$del(el);
}
}
for(i = 0, els = $Q('a[href*="youtu"]', post ? post.el : dForm), len = els.length; i < len; ++i) {
el = els[i];
if(m = el.href.match(ytReg)) {
addLink(post || aib.getPostEl(el).post, m, loader, el, true);
}
}
if(Cfg['addVimeo']) {
for(i = 0, els = $Q('a[href*="vimeo.com"]', post ? post.el : dForm), len = els.length; i < len; ++i) {
el = els[i];
if(m = el.href.match(vimReg)) {
addLink(post || aib.getPostEl(el).post, m, null, el, false);
}
}
}
for(i = 0, len = embedTube.length; i < len; i += 3) {
addLink(embedTube[i], embedTube[i + 1], loader, null, embedTube[i + 2]);
}
loader && loader.complete();
}
function updatePost(post, oldLinks, newLinks, cloned) {
var i, j, el, link, m, loader = !cloned && loadTitles && getYtubeTitleLoader(),
len = newLinks.length;
for(i = 0, j = 0; i < len; i++) {
el = newLinks[i];
link = oldLinks[j];
if(cloned) {
el.ytInfo = link.ytInfo;
j++;
} else if(m = el.href.match(ytReg)) {
addLink(post, m, loader, el, true);
j++;
}
}
loader && loader.complete();
}
if(embedType === 0) {
return {
parseLinks: emptyFn,
updatePost: emptyFn,
ytReg: ytReg
};
}
if(loadTitles) {
vData = JSON.parse(sessionStorage['de-ytube-data'] || '{}');
}
return {
addThumb: addThumb,
addPlayer: addPlayer,
embedType: embedType,
parseLinks: parseLinks,
updatePost: updatePost,
ytReg: ytReg,
vData: vData
};
}
function embedMP3Links(post) {
var el, link, src, i, els, len;
if(!Cfg['addMP3']) {
return;
}
for(i = 0, els = $Q('a[href*=".mp3"]', post ? post.el : dForm), len = els.length; i < len; ++i) {
link = els[i];
if(link.target !== '_blank' && link.rel !== 'nofollow') {
continue;
}
src = link.href;
el = (post || aib.getPostEl(link).post).mp3Obj;
if(nav.canPlayMP3) {
if(!$q('audio[src="' + src + '"]', el)) {
el.insertAdjacentHTML('beforeend',
'<p><audio src="' + src + '" preload="none" controls></audio></p>');
link = el.lastChild.firstChild;
link.addEventListener('play', updater.addPlayingTag, false);
link.addEventListener('pause', updater.removePlayingTag, false);
}
} else if(!$q('object[FlashVars*="' + src + '"]', el)) {
el.insertAdjacentHTML('beforeend', '<object data="http://junglebook2007.narod.ru/audio/player.swf" type="application/x-shockwave-flash" wmode="transparent" width="220" height="16" FlashVars="playerID=1&bg=0x808080&leftbg=0xB3B3B3&lefticon=0x000000&rightbg=0x808080&rightbghover=0x999999&rightcon=0x000000&righticonhover=0xffffff&text=0xffffff&slider=0x222222&track=0xf5f5dc&border=0x666666&loader=0x7fc7ff&loop=yes&autostart=no&soundFile=' + src + '"><br>');
}
}
}
//============================================================================================================
// AJAX
//============================================================================================================
function ajaxLoad(url, loadForm, Fn, errFn) {
var origXHR = GM_xmlhttpRequest({
'method': 'GET',
'url': nav.fixLink(url),
'onreadystatechange': function(xhr) {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status !== 200) {
if(errFn) {
errFn(xhr.status, xhr.statusText, origXHR);
}
} else if(Fn) {
do {
var el, text = xhr.responseText;
if(/<\/html>[\s\n\r]*$/.test(text)) {
el = $DOM(text);
if(!loadForm || (el = $q(aib.qDForm, el))) {
Fn(el, origXHR);
break;
}
}
if(errFn) {
errFn(0, Lng.errCorruptData[lang], origXHR);
}
} while(false);
}
loadForm = Fn = errFn = origXHR = null;
}
});
return origXHR;
}
function getJsonPosts(url, Fn) {
var origXHR = GM_xmlhttpRequest({
'method': 'GET',
'url': nav.fixLink(url),
'onreadystatechange': function(xhr) {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status === 304) {
closeAlert($id('de-alert-newposts'));
} else {
try {
var json = JSON.parse(xhr.responseText);
} catch(e) {
Fn(1, e.toString(), null, origXHR);
} finally {
if(json) {
Fn(xhr.status, xhr.statusText, json, origXHR);
}
Fn = origXHR = null;
}
}
}
});
}
function loadFavorThread() {
var post, el = this.parentNode.parentNode,
ifrm = $t('iframe', el),
cont = $c('de-content', doc);
$del($id('de-fav-wait'));
if(ifrm) {
$del(ifrm);
cont.style.overflowY = 'auto';
return;
}
if((post = pByNum[el.getAttribute('info').split(';')[2]]) && !post.hidden) {
scrollTo(0, pageYOffset + post.el.getBoundingClientRect().top);
return;
}
$del($id('de-iframe-fav'));
$c('de-content', doc).style.overflowY = 'scroll';
el.insertAdjacentHTML('beforeend', '<iframe name="de-iframe-fav" id="de-iframe-fav" src="' +
$t('a', el).href + '" scrolling="no" style="border: none; width: ' +
(doc.documentElement.clientWidth - 55) + 'px; height: 1px;"><div id="de-fav-wait" ' +
'class="de-wait" style="font-size: 1.1em; text-align: center">' + Lng.loading[lang] + '</div>');
}
function loadPages(count) {
var fun, i = pageNum,
len = Math.min(aib.lastPage + 1, i + count),
pages = [],
loaded = 1;
count = len - i;
function onLoadOrError(idx, eCodeOrForm, eMsgOrXhr, maybeXhr) {
if(typeof eCodeOrForm === 'number') {
pages[idx] = $add('<div><center style="font-size: 2em">' +
getErrorMessage(eCodeOrForm, eMsgOrXhr) + '</center><hr></div>');
} else {
pages[idx] = replacePost(eCodeOrForm);
}
if(loaded === count) {
var el, df, j, parseThrs = Thread.parsed,
threads = parseThrs ? [] : null;
for(j in pages) {
if(j != pageNum) {
dForm.insertAdjacentHTML('beforeend', '<center style="font-size: 2em">' +
Lng.page[lang] + ' ' + j + '</center><hr>');
}
df = pages[j];
if(parseThrs) {
threads = parseThreadNodes(df, threads);
}
while(el = df.firstChild) {
dForm.appendChild(el);
}
}
if(!parseThrs) {
threads = $Q(aib.qThread, dForm);
}
do {
if(threads.length !== 0) {
try {
parseDelform(dForm, threads);
} catch(e) {
$alert(getPrettyErrorMessage(e), 'load-pages', true);
break;
}
initDelformAjax()
readFavorites();
addDelformStuff(false);
readUserPosts();
checkPostsVisib();
saveFavorites();
saveUserPosts();
$each($Q('input[type="password"]', dForm), function(pEl) {
pr.dpass = pEl;
pEl.value = Cfg['passwValue'];
});
if(keyNav) {
keyNav.clear(pageNum + count - 1);
}
}
closeAlert($id('de-alert-load-pages'));
} while(false);
$disp(dForm);
loaded = pages = count = null;
} else {
loaded++;
}
}
$alert(Lng.loading[lang], 'load-pages', true);
$each($Q('a[href^="blob:"]', dForm), function(a) {
window.URL.revokeObjectURL(a.href);
});
Pview.clearCache();
isExpImg = false;
pByNum = Object.create(null);
Thread.tNums = [];
Post.hiddenNums = [];
$disp(dForm);
dForm.innerHTML = '';
if(pr.isQuick) {
if(pr.file) {
pr.delFileUtils(getAncestor(pr.file, aib.trTag), true);
}
pr.txta.value = '';
}
while(i < len) {
fun = onLoadOrError.bind(null, i);
ajaxLoad(aib.getPageUrl(brd, i++), true, fun, fun);
}
}
function infoLoadErrors(eCode, eMsg, newPosts) {
if(eCode === 200) {
closeAlert($id('de-alert-newposts'));
} else if(eCode === 0) {
$alert(eMsg || Lng.noConnect[lang], 'newposts', false);
} else {
$alert(Lng.thrNotFound[lang] + TNum + '): \n' + getErrorMessage(eCode, eMsg), 'newposts', false);
if(newPosts !== -1) {
doc.title = '{' + eCode + '} ' + doc.title;
}
}
}
function getHanaFile(file, id) {
var name, src = file['src'],
thumb = file['thumb'],
thumbW = file['thumb_width'],
thumbH = file['thumb_height'],
size = file['size'],
rating = file['rating'],
maxRating = Cfg['__hanarating'] || 'r-15',
kb = 1024,
mb = 1048576,
gb = 1073741824;
if(brd === 'b' || brd === 'rf') {
name = thumb.substring(thumb.lastIndexOf("/") + 1);
} else {
name = src.substring(src.lastIndexOf("/") + 1);
if(name.length > 17) {
name = name.substring(0, 17) + '...';
}
}
thumb = rating === 'r-18g' && maxRating !== 'r-18g' ? 'images/r-18g.png' :
rating === 'r-18' && (maxRating !== 'r-18g' || maxRating !== 'r-18') ? 'images/r-18.png' :
rating === 'r-15' && maxRating === 'sfw' ? 'images/r-15.png' :
rating === 'illegal' ? 'images/illegal.png' :
file['thumb'];
if(thumb !== file['thumb']) {
thumbW = 200;
thumbH = 200;
}
return '<div class="file"><div class="fileinfo">Файл: <a href="/' + src + '" target="_blank">' +
name + '</a><br><em>' + file['thumb'].substring(file['thumb'].lastIndexOf('.') + 1) + ', ' + (
size < kb ? size + ' B' :
size < mb ? (size / kb).toFixed(2) + ' KB' :
size < gb ? (size / mb).toFixed(2) + ' MB' :
(size / gb).toFixed(2) + ' GB'
) + ', ' + file['metadata']['width'] + 'x' + file['metadata']['height'] +
'</em><br><a class="edit_ icon" href="/utils/image/edit/' + file['file_id'] + '/' + id +
'"><img title="edit" alt="edit" src="/images/blank.png"></a></div><a href="/' + src +
'" target="_blank"><img class="thumb" src="/' + thumb + '" width="' + thumbW + '" height="' +
thumbH + '"></a></div>';
}
function getHanaPost(postJson) {
var i, html, id = postJson['display_id'],
files = postJson['files'],
len = files.length,
wrap = $new('table', {'id': 'post_' + id, 'class': 'replypost post'}, null);
html = '<tbody><tr><td class="doubledash">>></td><td id="reply' + id + '" class="reply">' +
'<a name="i' + id + '"></a><label><a class="delete icon"><input type="checkbox" id="delbox_' +
id + '" class="delete_checkbox" value="' + postJson['thread_id'] + '" name="' + id +
'"></a><span class="replytitle">' + postJson['subject'] + '</span> <span class="postername">' +
postJson['name'] + '</span> ' + aib.hDTFix.fix(postJson['date']) +
' </label><span class="reflink"><a onclick="Highlight(0, ' + id + ')" href="/' + brd +
'/res/' + TNum + '.xhtml#i' + id + '">No.' + id + '</a></span><br>';
for(i = 0; i < len; i++) {
html += getHanaFile(files[i], postJson['post_id']);
}
wrap.innerHTML = html + (len > 1 ? '<div style="clear: both;"></div>' : '') +
'<div class="postbody">' + postJson['message_html'] +
'</div><div class="abbrev"></div></td></tr></tbody>';
return [wrap, wrap.firstChild.firstChild.lastChild];
}
//============================================================================================================
// SPELLS
//============================================================================================================
function Spells(read) {
if(read) {
this._read(true);
} else {
this.disable(false);
}
}
Spells.names = [
'words', 'exp', 'exph', 'imgn', 'ihash', 'subj', 'name', 'trip', 'img', 'sage', 'op', 'tlen',
'all', 'video', 'wipe', 'num', 'vauthor'
];
Spells.needArg = [
/* words */ true, /* exp */ true, /* exph */ true, /* imgn */ true, /* ihash */ true,
/* subj */ false, /* name */ true, /* trip */ false, /* img */ false, /* sage */ false,
/* op */ false, /* tlen */ false, /* all */ false, /* video */ false, /* wipe */ false,
/* num */ true, /* vauthor */ true
];
Spells.checkArr = function(val, num) {
var i, arr;
for(arr = val[0], i = arr.length - 1; i >= 0; --i) {
if(arr[i] === num) {
return true;
}
}
for(arr = val[1], i = arr.length - 1; i >= 0; --i) {
if(num >= arr[i][0] && num <= arr[i][1]) {
return true;
}
}
return false;
};
Spells.YTubeSpell = function spell_youtube(post, val, ctx, cxTail) {
if(!val) {
return !!post.hasYTube;
}
if(!post.hasYTube || !Cfg['YTubeTitles']) {
return false;
}
var i, data, len, isAuthorSpell = typeof val === 'string';
for(i = 0, data = post.ytData, len = data.length; i < len; ++i) {
if(isAuthorSpell ? val === data[i][1] : val.test(data[i][0])) {
return true;
}
}
if(post.ytLinksLoading === 0) {
return false;
}
post.ytHideFun = function(ctx, cxTail, isASpell, val, data) {
if(isASpell ? val === data[1] : val.test(data[0])) {
this.ytHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), true);
} else if(post.ytLinksLoading === 0) {
this.ytHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), false);
}
}.bind(post, ctx, cxTail, isAuthorSpell, val);
return null;
};
Spells.prototype = {
_funcs: [
// 0: #words
function spell_words(post, val) {
return post.text.toLowerCase().contains(val) || post.subj.toLowerCase().contains(val);
},
// 1: #exp
function spell_exp(post, val) {
return val.test(post.text);
},
// 2: #exph
function spell_exph(post, val) {
return val.test(post.html);
},
// 3: #imgn
function spell_imgn(post, val) {
for(var i = 0, imgs = post.images, len = imgs.length; i < len; ++i) {
if(val.test(imgs[i].info)) {
return true;
}
}
return false;
},
// 4: #ihash
function spell_ihash(post, val, ctx, cxTail) {
for(var i = 0, imgs = post.images, len = imgs.length; i < len; ++i) {
if(imgs[i].hash === val) {
return true;
}
}
if(post.hashImgsBusy === 0) {
return false;
}
post.hashHideFun = function(ctx, cxTail, val, hash) {
if(val === hash) {
this.hashHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), true);
} else if(post.hashImgsBusy === 0) {
this.hashHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), false);
}
}.bind(post, ctx, cxTail, val);
return null;
},
// 5: #subj
function spell_subj(post, val) {
var pSubj = post.subj;
return pSubj ? !val || val.test(pSubj) : false;
},
// 6: #name
function spell_name(post, val) {
var pName = post.posterName;
return pName ? !val || pName.contains(val) : false;
},
// 7: #trip
function spell_trip(post, val) {
var pTrip = post.posterTrip;
return pTrip ? !val || pTrip.contains(val) : false;
},
// 8: #img
function spell_img(post, val) {
var temp, w, h, hide, img, i, imgs = post.images,
len = imgs.length;
if(!val) {
return len !== 0;
}
for(i = 0; i < len; ++i) {
img = imgs[i];
if(temp = val[1]) {
w = img.weight;
switch(val[0]) {
case 0: hide = w >= temp[0] && w <= temp[1]; break;
case 1: hide = w < temp[0]; break;
case 2: hide = w > temp[0];
}
if(!hide) {
continue;
} else if(!val[2]) {
return true;
}
}
if(temp = val[2]) {
w = img.width;
h = img.height;
switch(val[0]) {
case 0:
if(w >= temp[0] && w <= temp[1] && h >= temp[2] && h <= temp[3]) {
return true
}
break;
case 1:
if(w < temp[0] && h < temp[3]) {
return true
}
break;
case 2:
if(w > temp[0] && h > temp[3]) {
return true
}
}
}
}
return false;
},
// 9: #sage
function spell_sage(post, val) {
return post.sage;
},
// 10: #op
function spell_op(post, val) {
return post.isOp;
},
// 11: #tlen
function spell_tlen(post, val) {
var text = post.text;
return !val ? !!text : Spells.checkArr(val, text.replace(/\n/g, '').length);
},
// 12: #all
function spell_all(post, val) {
return true;
},
// 13: #video
Spells.YTubeSpell,
// 14: #wipe
function spell_wipe(post, val) {
var arr, len, i, j, n, x, keys, pop, capsw, casew, _txt, txt = post.text;
// (1 << 0): samelines
if(val & 1) {
arr = txt.replace(/>/g, '').split(/\s*\n\s*/);
if((len = arr.length) > 5) {
arr.sort();
for(i = 0, n = len / 4; i < len;) {
x = arr[i];
j = 0;
while(arr[i++] === x) {
j++;
}
if(j > 4 && j > n && x) {
Spells._lastWipeMsg = 'same lines: "' + x.substr(0, 20) + '" x' + (j + 1);
return true;
}
}
}
}
// (1 << 1): samewords
if(val & 2) {
arr = txt.replace(/[\s\.\?\!,>]+/g, ' ').toUpperCase().split(' ');
if((len = arr.length) > 3) {
arr.sort();
for(i = 0, n = len / 4, keys = 0, pop = 0; i < len; keys++) {
x = arr[i];
j = 0;
while(arr[i++] === x) {
j++;
}
if(len > 25) {
if(j > pop && x.length > 2) {
pop = j;
}
if(pop >= n) {
Spells._lastWipeMsg = 'same words: "' + x.substr(0, 20) + '" x' + (pop + 1);
return true;
}
}
}
x = keys / len;
if(x < 0.25) {
Spells._lastWipeMsg = 'uniq words: ' + (x * 100).toFixed(0) + '%';
return true;
}
}
}
// (1 << 2): longwords
if(val & 4) {
arr = txt.replace(/https*:\/\/.*?(\s|$)/g, '').replace(/[\s\.\?!,>:;-]+/g, ' ').split(' ');
if(arr[0].length > 50 || ((len = arr.length) > 1 && arr.join('').length / len > 10)) {
Spells._lastWipeMsg = 'long words';
return true;
}
}
// (1 << 3): symbols
if(val & 8) {
_txt = txt.replace(/\s+/g, '');
if((len = _txt.length) > 30 &&
(x = _txt.replace(/[0-9a-zа-я\.\?!,]/ig, '').length / len) > 0.4)
{
Spells._lastWipeMsg = 'specsymbols: ' + (x * 100).toFixed(0) + '%';
return true;
}
}
// (1 << 4): capslock
if(val & 16) {
arr = txt.replace(/[\s\.\?!;,-]+/g, ' ').trim().split(' ');
if((len = arr.length) > 4) {
for(i = 0, n = 0, capsw = 0, casew = 0; i < len; i++) {
x = arr[i];
if((x.match(/[a-zа-я]/ig) || []).length < 5) {
continue;
}
if((x.match(/[A-ZА-Я]/g) || []).length > 2) {
casew++;
}
if(x === x.toUpperCase()) {
capsw++;
}
n++;
}
if(capsw / n >= 0.3 && n > 4) {
Spells._lastWipeMsg = 'CAPSLOCK: ' + capsw / arr.length * 100 + '%';
return true;
} else if(casew / n >= 0.3 && n > 8) {
Spells._lastWipeMsg = 'cAsE words: ' + casew / arr.length * 100 + '%';
return true;
}
}
}
// (1 << 5): numbers
if(val & 32) {
_txt = txt.replace(/\s+/g, ' ').replace(/>>\d+|https*:\/\/.*?(?: |$)/g, '');
if((len = _txt.length) > 30 && (x = (len - _txt.replace(/\d/g, '').length) / len) > 0.4) {
Spells._lastWipeMsg = 'numbers: ' + Math.round(x * 100) + '%';
return true;
}
}
// (1 << 5): whitespace
if(val & 64) {
if(/(?:\n\s*){5}/i.test(txt)) {
Spells._lastWipeMsg = 'whitespace';
return true;
}
}
return false;
},
// 15: #num
function spell_num(post, val) {
return Spells.checkArr(val, post.count + 1);
},
// 16: #vauthor
Spells.YTubeSpell
],
_optimizeSpells: function(spells) {
var i, len, flags, type, spell, scope, neg, parensSpells, newSpells = [];
for(i = 0, len = spells.length; i < len; ++i) {
spell = spells[i];
flags = spell[0];
type = flags & 0xFF;
neg = (flags & 0x100) !== 0;
if(type === 0xFF) {
parensSpells = this._optimizeSpells(spell[1]);
if(parensSpells) {
if(parensSpells.length === 1) {
newSpells.push([(parensSpells[0][0] | (flags & 0x200)) ^ (flags & 0x100),
parensSpells[0][1]]);
} else {
newSpells.push([flags, parensSpells]);
}
continue;
}
} else {
scope = spell[2];
if(!scope || (scope[0] === brd &&
(scope[1] === -1 ? !TNum : (!scope[1] || scope[1] === TNum))))
{
if(type === 12) {
neg = !neg;
} else {
newSpells.push([flags, spell[1]]);
continue;
}
}
}
if(((flags & 0x200) !== 0) ^ neg) {
return neg ? [[12, '']] : null;
}
}
i = len = newSpells.length - 1;
if(i === -1) {
return neg ? [[12, '']] : null;
} else if(i !== 0) {
if(neg) {
while(i >= 0 && (newSpells[i][0] & 0x200) === 0) {
i--;
}
if(i < 0) {
return [[12, '']];
}
newSpells[i][0] &= 0x1FF;
} else {
while(i >= 0 && (newSpells[i][0] & 0x200) !== 0) {
i--;
}
if(i < 0) {
return null;
}
}
if(i !== len) {
newSpells = newSpells.slice(0, i + 1);
}
}
return newSpells;
},
_initSpells: function(data) {
if(data) {
data.forEach(function initExps(item) {
var val = item[1];
if(val) {
switch(item[0] & 0xFF) {
case 1:
case 2:
case 3:
case 5:
case 13: item[1] = toRegExp(val, true); break;
case 0xFF: val.forEach(initExps);
}
}
});
}
return data;
},
_checkRes: function(flags, val) {
if((flags & 0x100) !== 0) {
val = !val;
}
if((flags & 0x200) !== 0) {
if(!val) {
return false;
}
} else if(val) {
return true;
}
return null;
},
_decompileSpell: function(type, neg, val, scope) {
var temp, temp_, spell = (neg ? '!#' : '#') + Spells.names[type] + (scope ? '[' +
scope[0] + (scope[1] ? ',' + (scope[1] === -1 ? '' : scope[1]) : '') + ']' : '');
if(!val) {
return spell;
}
// #img
if(type === 8) {
return spell + '(' + (val[0] === 2 ? '>' : val[0] === 1 ? '<' : '=') +
(val[1] ? val[1][0] + (val[1][1] === val[1][0] ? '' : '-' + val[1][1]) : '') +
(val[2] ? '@' + val[2][0] + (val[2][0] === val[2][1] ? '' : '-' + val[2][1]) + 'x' +
val[2][2] + (val[2][2] === val[2][3] ? '' : '-' + val[2][3]) : '') + ')';
}
// #wipe
else if(type === 14) {
if(val === 0x3F) {
return spell;
}
temp = [];
(val & 1) && temp.push('samelines');
(val & 2) && temp.push('samewords');
(val & 4) && temp.push('longwords');
(val & 8) && temp.push('symbols');
(val & 16) && temp.push('capslock');
(val & 32) && temp.push('numbers');
(val & 64) && temp.push('whitespace');
return spell + '(' + temp.join(',') + ')';
}
// #num, #tlen
else if(type === 15 || type === 11) {
if((temp = val[1].length - 1) !== -1) {
for(temp_ = []; temp >= 0; temp--) {
temp_.push(val[1][temp][0] + '-' + val[1][temp][1]);
}
temp_.reverse();
}
spell += '(';
if(val[0].length !== 0) {
spell += val[0].join(',') + (temp_ ? ',' : '');
}
if(temp_) {
spell += temp_.join(',');
}
return spell + ')';
}
// #words, #name, #trip, #vauthor
else if(type === 0 || type === 6 || type === 7 || type === 16) {
return spell + '(' + val.replace(/\)/g, '\\)') + ')';
} else {
return spell + '(' + String(val) + ')';
}
},
_decompileScope: function(scope, indent) {
var spell, type, temp, str, dScope = [], hScope = false, i = 0, j = 0, len = scope.length;
for(; i < len; i++, j++) {
spell = scope[i];
type = spell[0] & 0xFF;
if(type === 0xFF) {
hScope = true;
temp = this._decompileScope(spell[1], indent + ' ');
if(temp[1]) {
str = ((spell[0] & 0x100) ? '!(\n' : '(\n') + indent + ' ' +
temp[0].join('\n' + indent + ' ') + '\n' + indent + ')';
if(j === 0) {
dScope[0] = str;
} else {
dScope[--j] += ' ' + str;
}
} else {
dScope[j] = ((spell[0] & 0x100) ? '!(' : '(') + temp[0].join(' ') + ')';
}
} else {
dScope[j] = this._decompileSpell(type, spell[0] & 0x100, spell[1], spell[2]);
}
if(i !== len - 1) {
dScope[j] += (spell[0] & 0x200) ? ' &' : ' |';
}
}
return [dScope, dScope.length > 2 || hScope];
},
_decompileSpells: function() {
var str, reps, oreps, data = this._data;
if(!data) {
this._read(false);
if(!(data = this._data)) {
return this._list = '';
}
}
str = data[1] ? this._decompileScope(data[1], '')[0].join('\n') : '';
reps = data[2];
oreps = data[3];
if(reps || oreps) {
str += '\n\n';
reps && reps.forEach(function(rep) {
str += this._decompileRep(rep, false) + '\n';
}.bind(this));
oreps && oreps.forEach(function(orep) {
str += this._decompileRep(orep, true) + '\n';
}.bind(this));
str = str.substr(0, str.length - 1);
}
this._data = null;
return this._list = str;
},
_getMsg: function(spell) {
var neg = spell[0] & 0x100,
type = spell[0] & 0xFF,
val = spell[1];
if(type === 0xFF) {
return this._getMsg(val[this._lastPSpell]);
}
if(type === 14) {
return (neg ? '!#wipe' : '#wipe') + (Spells._lastWipeMsg ? ': ' + Spells._lastWipeMsg : '');
} else {
return this._decompileSpell(type, neg, val, spell[2]);
}
},
_continueCheck: function(post, ctx, val) {
var temp, rv = this._checkRes(ctx.pop(), val);
if(rv === null) {
if(this._check(post, ctx)) {
return;
}
} else if(rv) {
temp = ctx.pop();
post.spellHide(this._getMsg(ctx.pop()[temp - 1]));
} else if(!post.deleted) {
sVis[post.count] = 1;
}
this._asyncWrk--;
this.end(null);
},
_check: function(post, ctx) {
var rv, type, val, temp, deep = ctx[0],
i = ctx.pop(),
scope = ctx.pop(),
len = ctx.pop();
while(true) {
if(i < len) {
temp = scope[i][0];
type = temp & 0xFF;
switch(type) {
case 0xFF:
ctx.push(len, scope, i);
scope = scope[i][1];
len = scope.length;
i = 0;
deep++;
continue;
case 4: // #ihash
case 13: // #video
case 16: // #vauthor
ctx[0] = deep;
val = this._funcs[type](post, scope[i][1], ctx, [len, scope, i + 1, temp]);
if(val === null) {
this._asyncWrk++;
return 0;
}
break;
case 15: // #num
this.hasNumSpell = true;
default:
val = this._funcs[type](post, scope[i][1]);
}
rv = this._checkRes(temp, val);
if(rv === null) {
i++;
continue;
}
this._lastPSpell = i;
} else {
this._lastPSpell = i -= 1;
rv = false;
}
if(deep !== 0) {
i = ctx.pop();
scope = ctx.pop();
len = ctx.pop();
deep--;
rv = this._checkRes(scope[i][0], rv);
if(rv === null) {
i++;
continue;
}
}
if(rv) {
post.spellHide(this._getMsg(scope[i]));
} else if(!post.deleted) {
sVis[post.count] = 1;
}
return +rv;
}
},
_findReps: function(str) {
var reps = [],
outreps = [];
str = str.replace(
/([^\\]\)|^)?[\n\s]*(#rep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g,
function(exp, preOp, fullExp, b, nt, t, reg, txt) {
reps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]);
return preOp || '';
}
).replace(
/([^\\]\)|^)?[\n\s]*(#outrep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g,
function(exp, preOp, fullExp, b, nt, t, reg, txt) {
outreps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]);
return preOp || '';
}
);
return [str, reps.length === 0 ? false : reps, outreps.length === 0 ? false : outreps];
},
_decompileRep: function(rep, isOrep) {
return (isOrep ? '#outrep' : '#rep') +
(rep[0] ? '[' + rep[0] + (rep[1] ? ',' + (rep[1] === -1 ? '' : rep[1]) : '') + ']' : '') +
'(' + rep[2] + ',' + rep[3].replace(/\)/g, '\\)') + ')';
},
_optimizeReps: function(data) {
if(data) {
var nData = [];
data.forEach(function(temp) {
if(!temp[0] || (temp[0] === brd && (temp[1] === -1 ? !TNum : !temp[1] || temp[1] === TNum))) {
nData.push([temp[2], temp[3]]);
}
});
return nData.length === 0 ? false : nData;
}
return false;
},
_initReps: function(data) {
if(data) {
for(var i = data.length - 1; i >= 0; i--) {
data[i][0] = toRegExp(data[i][0], false);
}
}
return data;
},
_init: function(spells, reps, outreps) {
this._spells = this._initSpells(spells);
this._sLength = spells && spells.length;
this._reps = this._initReps(reps);
this._outreps = this._initReps(outreps);
this.enable = !!this._spells;
this.haveReps = !!reps;
this.haveOutreps = !!outreps;
},
_read: function(init) {
var spells, data;
if(Cfg.hasOwnProperty('spells')) {
try {
spells = JSON.parse(Cfg['spells']);
data = JSON.parse(sessionStorage['de-spells-' + brd + TNum]);
} catch(e) {}
if(data && data[0] === spells[0]) {
this._data = spells;
if(init) {
this.hash = data[0];
this._init(data[1], data[2], data[3]);
}
return;
}
} else {
if(data = getStored('DESU_CSpells_' + aib.dm)) {
delStored('DESU_CSpells_' + aib.dm);
try {
spells = JSON.parse(data);
} catch(e) {}
if(!spells) {
this.disable(false);
return;
}
} else {
spells = this.parseText('#wipe(samelines,samewords,longwords,numbers,whitespace)');
}
saveCfg('spells', data);
}
if(init) {
this.update(spells, false, false);
} else {
this._data = spells;
}
},
_asyncWrk: 0,
_completeFns: [],
_hasComplFns: false,
_data: null,
_list: '',
hash: 0,
hasNumSpell: false,
enable: false,
get list() {
return this._list || this._decompileSpells();
},
addCompleteFunc: function(Fn) {
this._completeFns.push(Fn);
this._hasComplFns = true;
},
parseText: function(str) {
str = String(str).replace(/[\s\n]+$/, '');
var reps = this._findReps(str),
codeGen = new SpellsCodegen(reps[0]),
spells = codeGen.generate();
if(spells) {
if(Cfg['sortSpells']) {
this.sort(spells);
}
return [Date.now(), spells, reps[1], reps[2]];
} else if(codeGen.hasError) {
$alert(Lng.error[lang] + ' ' + codeGen.error, 'help-err-spell', false);
}
return null;
},
sort: function(sp) {
// Wraps AND-spells with brackets for proper sorting
for(var i = 0, len = sp.length-1; i < len; i++) {
if(sp[i][0] > 0x200) {
var temp = [0xFF, []];
do {
temp[1].push(sp.splice(i, 1)[0]);
len--;
} while (sp[i][0] > 0x200);
temp[1].push(sp.splice(i, 1)[0]);
sp.splice(i, 0, temp);
}
}
sp = sp.sort();
for(var i = 0, len = sp.length-1; i < len; i++) {
// Removes duplicates and weaker spells
if(sp[i][0] == sp[i+1][0] && sp[i][1] <= sp[i+1][1] && sp[i][1] >= sp[i+1][1] &&
(sp[i][2] === null || // Stronger spell with 3 parameters
sp[i][2] === undefined || // Equal spells with 2 parameters
(sp[i][2] <= sp[i+1][2] && sp[i][2] >= sp[i+1][2])))
{ // Equal spells with 3 parameters
sp.splice(i+1, 1);
i--;
len--;
// Moves brackets to the end of the list
} else if(sp[i][0] == 0xFF) {
sp.push(sp.splice(i, 1)[0]);
i--;
len--;
}
}
},
update: function(data, sync, isHide) {
var spells = data[1] ? this._optimizeSpells(data[1]) : false,
reps = this._optimizeReps(data[2]),
outreps = this._optimizeReps(data[3]);
saveCfg('spells', JSON.stringify(data));
sessionStorage['de-spells-' + brd + TNum] = JSON.stringify([data[0], spells, reps, outreps]);
this._data = data;
this._list = '';
this.hash = data[0];
if(sync) {
localStorage['__de-spells'] = JSON.stringify({
'hide': (!!this.list && !!isHide),
'data': data
});
localStorage.removeItem('__de-spells');
}
this._init(spells, reps, outreps);
},
setSpells: function(spells, sync) {
this.update(spells, sync, Cfg['hideBySpell']);
if(Cfg['hideBySpell']) {
for(var post = firstThr.op; post; post = post.next) {
this.check(post);
}
this.end(savePosts);
} else {
this.enable = false;
}
},
disable: function(sync) {
this.enable = false;
this._list = '';
this._data = null;
this.haveReps = this.haveOutreps = false;
saveCfg('hideBySpell', false);
},
end: function(Fn) {
if(this._asyncWrk === 0) {
Fn && Fn();
if(this._hasComplFns) {
for(var i = 0, len = this._completeFns.length; i < len; ++i) {
this._completeFns[i]();
}
this._completeFns = [];
this._hasComplFns = false;
}
} else if(Fn) {
this.addCompleteFunc(Fn);
}
},
check: function(post) {
if(this.enable) {
return this._check(post, [0, this._sLength, this._spells, 0]);
}
return 0;
},
replace: function(txt) {
for(var i = 0, len = this._reps.length; i < len; i++) {
txt = txt.replace(this._reps[i][0], this._reps[i][1]);
}
return txt;
},
outReplace: function(txt) {
for(var i = 0, len = this._outreps.length; i < len; i++) {
txt = txt.replace(this._outreps[i][0], this._outreps[i][1]);
}
return txt;
},
addSpell: function(type, arg, scope, isNeg, spells) {
if(!spells) {
if(!this._data) {
this._read(false);
}
spells = this._data || [Date.now(), [], false, false];
}
var idx, sScope = String(scope),
sArg = String(arg);
if(spells[1]) {
spells[1].some(scope && isNeg ? function(spell, i) {
var data;
if(spell[0] === 0xFF && ((data = spell[1]) instanceof Array) && data.length === 2 &&
data[0][0] === 0x20C && data[1][0] === type && data[1][2] == null &&
String(data[1][1]) === sArg && String(data[0][2]) === sScope)
{
idx = i;
return true;
}
return (spell[0] & 0x200) !== 0;
} : function(spell, i) {
if(spell[0] === type && String(spell[1]) === sArg && String(spell[2]) === sScope) {
idx = i;
return true;
}
return (spell[0] & 0x200) !== 0;
});
} else {
spells[1] = [];
}
if(typeof idx !== 'undefined') {
spells[1].splice(idx, 1);
} else if(scope && isNeg) {
spells[1].splice(0, 0, [0xFF, [[0x20C, '', scope], [type, arg, void 0]], void 0]);
} else {
spells[1].splice(0, 0, [type, arg, scope]);
}
this.update(spells, true, true);
idx = null;
}
};
function SpellsCodegen(sList) {
this._line = 1;
this._col = 1;
this._sList = sList;
this.hasError = false;
}
SpellsCodegen.prototype = {
TYPE_UNKNOWN: 0,
TYPE_ANDOR: 1,
TYPE_NOT: 2,
TYPE_SPELL: 3,
TYPE_PARENTHESES: 4,
generate: function() {
return this._sList ? this._generate(this._sList, false) : null;
},
get error() {
if(!this.hasError) {
return '';
}
return (this._errMsgArg ? this._errMsg.replace('%s', this._errMsgArg) : this._errMsg) +
Lng.seRow[lang] + this._line + Lng.seCol[lang] + this._col + ')';
},
_errMsg: '',
_errMsgArg: null,
_generate: function(sList, inParens) {
var res, name, i = 0,
len = sList.length,
data = [],
lastType = this.TYPE_UNKNOWN;
for(; i < len; i++, this._col++) {
switch(sList[i]) {
case '\n':
this._line++;
this._col = 0;
case '\r':
case ' ': continue;
case '#':
if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) {
this._setError(Lng.seMissOp[lang], null);
return null;
}
name = '';
i++;
this._col++;
while((sList[i] >= 'a' && sList[i] <= 'z') || (sList[i] >= 'A' && sList[i] <= 'Z')) {
name += sList[i].toLowerCase();
i++;
this._col++;
}
res = this._doSpell(name, sList.substr(i), lastType === this.TYPE_NOT)
if(!res) {
return null;
}
i += res[0] - 1;
this._col += res[0] - 1;
data.push(res[1]);
lastType = this.TYPE_SPELL;
break;
case '(':
if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) {
this._setError(Lng.seMissOp[lang], null);
return null;
}
res = this._generate(sList.substr(i + 1), true);
if(!res) {
return null;
}
i += res[0] + 1;
data.push([lastType === this.TYPE_NOT ? 0x1FF : 0xFF, res[1]]);
lastType = this.TYPE_PARENTHESES;
break;
case '|':
case '&':
if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) {
this._setError(Lng.seMissSpell[lang], null);
return null;
}
if(sList[i] === '&') {
data[data.length - 1][0] |= 0x200;
}
lastType = this.TYPE_ANDOR;
break;
case '!':
if(lastType !== this.TYPE_ANDOR && lastType !== this.TYPE_UNKNOWN) {
this._setError(Lng.seMissOp[lang], null);
return null;
}
lastType = this.TYPE_NOT;
break;
case ')':
if(lastType === this.TYPE_ANDOR || lastType === this.TYPE_NOT) {
this._setError(Lng.seMissSpell[lang], null);
return null;
}
if(inParens) {
return [i, data];
}
default:
this._setError(Lng.seUnexpChar[lang], sList[i]);
return null;
}
}
if(inParens) {
this._setError(Lng.seMissClBkt[lang], null);
return null;
}
if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) {
this._setError(Lng.seMissSpell[lang], null);
return null;
}
return data;
},
_doSpell: function(name, str, isNeg) {
var scope, m, spellType, val, i = 0,
spellIdx = Spells.names.indexOf(name);
if(spellIdx === -1) {
this._setError(Lng.seUnknown[lang], name);
return null;
}
spellType = isNeg ? spellIdx | 0x100 : spellIdx;
m = str.match(/^\[([a-z0-9\/]+)(?:(,)|,(\s*[0-9]+))?\]/);
if(m) {
i = m[0].length;
str = str.substring(i);
scope = [m[1], m[3] ? m[3] : m[2] ? -1 : false];
} else {
scope = null;
}
if(str[0] !== '(' || str[1] === ')') {
if(Spells.needArg[spellIdx]) {
this._setError(Lng.seMissArg[lang], name);
return null;
}
return [str[0] === '(' ? i + 2 : i, [spellType, spellIdx === 14 ? 0x3F : '', scope]];
}
switch(spellIdx) {
// #ihash
case 4:
m = str.match(/^\((\d+)\)/);
if(+m[1] === +m[1]) {
return [i + m[0].length, [spellType, +m[1], scope]];
}
break;
// #img
case 8:
m = str.match(/^\(([><=])(?:(\d+(?:\.\d+)?)(?:-(\d+(?:\.\d+)?))?)?(?:@(\d+)(?:-(\d+))?x(\d+)(?:-(\d+))?)?\)/);
if(m && (m[2] || m[4])) {
return [i + m[0].length, [spellType, [
m[1] === '=' ? 0 : m[1] === '<' ? 1 : 2,
m[2] && [+m[2], m[3] ? +m[3] : +m[2]],
m[4] && [+m[4], m[5] ? +m[5] : +m[4], +m[6], m[7] ? +m[7] : +m[6]]
], scope]];
}
break;
// #wipe
case 14:
m = str.match(/^\(([a-z, ]+)\)/);
if(m) {
val = m[1].split(/, */).reduce(function(val, str) {
switch(str) {
case 'samelines': return val |= 1;
case 'samewords': return val |= 2;
case 'longwords': return val |= 4;
case 'symbols': return val |= 8;
case 'capslock': return val |= 16;
case 'numbers': return val |= 32;
case 'whitespace': return val |= 64;
default: return -1;
}
}, 0);
if(val !== -1) {
return [i + m[0].length, [spellType, val, scope]];
}
}
break;
// #tlen, #num
case 11:
case 15:
m = str.match(/^\(([\d-, ]+)\)/);
if(m) {
m[1].split(/, */).forEach(function(v) {
if(v.contains('-')) {
var nums = v.split('-');
nums[0] = +nums[0];
nums[1] = +nums[1];
this[1].push(nums);
} else {
this[0].push(+v);
}
}, val = [[], []]);
return [i + m[0].length, [spellType, val, scope]];
}
break;
// #exp, #exph, #imgn, #subj, #video
case 1:
case 2:
case 3:
case 5:
case 13:
m = str.match(/^\((\/.*?[^\\]\/[igm]*)\)/);
if(m) {
val = m[1];
try {
toRegExp(val, true);
} catch(e) {
this._setError(Lng.seErrRegex[lang], val);
return null;
}
return [i + m[0].length, [spellType, val, scope]];
}
break;
// #sage, #op, #all, #trip, #name, #words, #vauthor
default:
m = str.match(/^\((.*?[^\\])\)/);
if(m) {
val = m[1].replace(/\\\)/g, ')');
return [i + m[0].length, [spellType, spellIdx === 0 ? val.toLowerCase() : val, scope]];
}
}
this._setError(Lng.seSyntaxErr[lang], name);
return null;
},
_setError: function(msg, arg) {
this.hasError = true;
this._errMsg = msg;
this._errMsgArg = arg;
}
};
function disableSpells() {
closeAlert($id('de-alert-help-err-spell'));
if(spells.enable) {
sVis = TNum ? '1'.repeat(firstThr.pcount).split('') : [];
for(var post = firstThr.op; post; post = post.next) {
if(post.spellHidden && !post.userToggled) {
post.spellUnhide();
}
}
}
}
function toggleSpells() {
var temp, fld = $id('de-spell-edit'),
val = fld.value;
if(val && (temp = spells.parseText(val))) {
disableSpells();
spells.setSpells(temp, true);
fld.value = spells.list;
} else {
if(val) {
localStorage['__de-spells'] = '{"hide": false, "data": null}';
} else {
disableSpells();
spells.disable();
saveCfg('spells', '');
localStorage['__de-spells'] = '{"hide": false, "data": ""}';
}
localStorage.removeItem('__de-spells');
$q('input[info="hideBySpell"]', doc).checked = spells.enable = false;
}
}
function addSpell(type, arg, isNeg) {
var temp, fld = $id('de-spell-edit'),
val = fld && fld.value,
chk = $q('input[info="hideBySpell"]', doc);
if(!val || (temp = spells.parseText(val))) {
disableSpells();
spells.addSpell(type, arg, TNum ? [brd, TNum] : null, isNeg, temp);
val = spells.list;
saveCfg('hideBySpell', !!val);
if(val) {
for(var post = firstThr.op; post; post = post.next) {
spells.check(post);
}
spells.end(savePosts);
} else {
saveCfg('spells', '');
spells.enable = false;
}
if(fld) {
chk.checked = !!(fld.value = val);
}
return;
}
spells.enable = false;
if(chk) {
chk.checked = false;
}
}
function checkPostsVisib() {
for(var vis, num, date = Date.now(), post = firstThr.op; post; post = post.next) {
num = post.num;
if(num in uVis) {
if(post.isOp) {
uVis[num][0] = +!(num in hThr[brd]);
}
if(uVis[num][0] === 0) {
post.setUserVisib(true, date, false);
} else {
uVis[num][1] = date;
post.btns.firstChild.className = 'de-btn-hide-user';
post.userToggled = true;
}
} else {
vis = sVis[post.count];
if(post.isOp) {
if(num in hThr[brd]) {
vis = '0';
} else if(vis === '0') {
vis = null;
}
}
if(vis === '0') {
post.setVisib(true);
post.spellHidden = true;
} else if(vis !== '1') {
spells.check(post);
}
}
}
spells.end(savePosts);
}
//============================================================================================================
// STYLES
//============================================================================================================
function getThemeLang() {
return !Cfg['scriptStyle'] ? 'fr' :
Cfg['scriptStyle'] === 1 ? 'en' :
'de';
}
function scriptCSS() {
var p, x = '';
function cont(id, src) {
return id + ':before { content: ""; padding: 0 16px 0 0; margin: 0 4px; background: url(' + src + ') no-repeat center; }';
}
function gif(id, src) {
return id + ' { background: url(data:image/gif;base64,' + src + ') no-repeat center !important; }';
}
// Settings window
x += '.de-block { display: block; }\
#de-content-cfg > div { border-radius: 10px 10px 0 0; width: auto; min-width: 0; padding: 0; margin: 5px 20px; overflow: hidden; }\
#de-cfg-head { padding: 4px; border-radius: 10px 10px 0 0; color: #fff; text-align: center; font: bold 14px arial; cursor: default; }\
#de-cfg-head:lang(en), #de-panel:lang(en) { background: linear-gradient(to bottom, #4b90df, #3d77be 5px, #376cb0 7px, #295591 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #183d77 13px, #1f4485 18px, #264c90 20px, #325f9e 25px); }\
#de-cfg-head:lang(fr), #de-panel:lang(fr) { background: linear-gradient(to bottom, #7b849b, #616b86 2px, #3a414f 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #121212 13px, #1f2740 25px); }\
#de-cfg-head:lang(de), #de-panel:lang(de) { background: #777; }\
.de-cfg-body { min-height: 288px; min-width: 371px; padding: 11px 7px 7px; margin-top: -1px; font: 13px sans-serif; }\
.de-cfg-body input[type="text"], .de-cfg-body select { width: auto; padding: 0 !important; margin: 0 !important; }\
.de-cfg-body, #de-cfg-btns { border: 1px solid #183d77; border-top: none; }\
.de-cfg-body:lang(de), #de-cfg-btns:lang(de) { border-color: #444; }\
#de-cfg-btns { padding: 7px 2px 2px; }\
#de-cfg-bar { width: 100%; display: table; background-color: #1f2740; margin: 0; padding: 0; }\
#de-cfg-bar:lang(en) { background-color: #325f9e; }\
#de-cfg-bar:lang(de) { background-color: #777; }\
.de-cfg-depend { padding-left: 25px; }\
.de-cfg-tab { padding: 4px 5px; border-radius: 4px 4px 0 0; font: bold 12px arial; text-align: center; cursor: default; }\
.de-cfg-tab-back { display: table-cell !important; float: none !important; min-width: 0 !important; padding: 0 !important; box-shadow: none !important; border: 1px solid #183d77 !important; border-radius: 4px 4px 0 0; opacity: 1; }\
.de-cfg-tab-back:lang(de) { border-color: #444 !important; }\
.de-cfg-tab-back:lang(fr) { border-color: #121421 !important; }\
.de-cfg-tab-back[selected="true"] { border-bottom: none !important; }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab { background-color: rgba(0,0,0,.2); }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(fr) { background: linear-gradient(to bottom, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover { background-color: rgba(99,99,99,.2); }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(fr) { background: linear-gradient(to top, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\
.de-cfg-tab::' + (nav.Firefox ? '-moz-' : '') + 'selection { background: transparent; }\
.de-cfg-unvis { display: none; }\
#de-cfg-updresult { padding: 3px 0; font-size: 1.1em; text-align: center; }\
#de-spell-panel { float: right; }\
#de-spell-panel > a { padding: 0 4px; }\
#de-spell-div { display: table; }\
#de-spell-div > div { display: table-cell; vertical-align: top; }\
#de-spell-edit { padding: 2px !important; width: 340px; height: 180px; border: none !important; outline: none !important; }\
#de-spell-rowmeter { padding: 2px 3px 0 0; margin: 2px 0; overflow: hidden; width: 2em; height: 182px; text-align: right; color: #fff; font: 12px courier new; }\
#de-spell-rowmeter:lang(en), #de-spell-rowmeter:lang(fr) { background-color: #616b86; }\
#de-spell-rowmeter:lang(de) { background-color: #777; }';
// Main panel
x += '#de-btn-logo { margin-right: 3px; cursor: pointer; }\
#de-panel { height: 25px; z-index: 9999; border-radius: 15px 0 0 0; cursor: default;}\
#de-panel-btns { display: inline-block; padding: 0 0 0 2px; margin: 0; height: 25px; border-left: 1px solid #8fbbed; }\
#de-panel-btns:lang(de), #de-panel-info:lang(de) { border-color: #ccc; }\
#de-panel-btns:lang(fr), #de-panel-info:lang(fr) { border-color: #616b86; }\
#de-panel-btns > li { margin: 0 1px; padding: 0; }\
#de-panel-btns > li, #de-panel-btns > li > a, #de-btn-logo { display: inline-block; width: 25px; height: 25px; }\
#de-panel-btns:lang(en) > li, #de-panel-btns:lang(fr) > li { transition: all 0.3s ease; }\
#de-panel-btns:lang(en) > li:hover, #de-panel-btns:lang(fr) > li:hover { background-color: rgba(255,255,255,.15); box-shadow: 0 0 3px rgba(143,187,237,.5); }\
#de-panel-btns:lang(de) > li > a { border-radius: 5px; }\
#de-panel-btns:lang(de) > li > a:hover { width: 21px; height: 21px; border: 2px solid #444; }\
#de-panel-info { display: inline-block; vertical-align: 6px; padding: 0 6px; margin: 0 0 0 2px; height: 25px; border-left: 1px solid #8fbbed; color: #fff; font: 18px serif; }';
p = 'R0lGODlhGQAZAIAAAPDw8P///yH5BAEAAAEALAAAAAAZABkAQA';
x += gif('#de-btn-logo', p + 'I5jI+pywEPWoIIRomz3tN6K30ixZXM+HCgtjpk1rbmTNc0erHvLOt4vvj1KqnD8FQ0HIPCpbIJtB0KADs=');
x += gif('#de-btn-settings', p + 'JAjI+pa+API0Mv1Ymz3hYuiQHHFYjcOZmlM3Jkw4aeAn7R/aL6zuu5VpH8aMJaKtZR2ZBEZnMJLM5kIqnP2csUAAA7');
x += gif('#de-btn-hidden', p + 'I5jI+pa+CeHmRHgmCp3rxvO3WhMnomUqIXl2UmuLJSNJ/2jed4Tad96JLBbsEXLPbhFRc8lU8HTRQAADs=');
x += gif('#de-btn-favor', p + 'IzjI+py+AMjZs02ovzobzb1wDaeIkkwp3dpLEoeMbynJmzG6fYysNh3+IFWbqPb3OkKRUFADs=');
x += gif('#de-btn-refresh', p + 'JAjI+pe+AfHmRGLkuz3rzN+1HS2JWbhWlpVIXJ+roxSpr2jedOBIu0rKjxhEFgawcCqJBFZlPJIA6d0ZH01MtRCgA7');
x += gif('#de-btn-goback', p + 'IrjI+pmwAMm4u02gud3lzjD4biJgbd6VVPybbua61lGqIoY98ZPcvwD4QUAAA7');
x += gif('#de-btn-gonext', p + 'IrjI+pywjQonuy2iuf3lzjD4Zis0Xd6YnQyLbua61tSqJnbXcqHVLwD0QUAAA7');
x += gif('#de-btn-goup', p + 'IsjI+pm+DvmDRw2ouzrbq9DmKcBpVfN4ZpyLYuCbgmaK7iydpw1OqZf+O9LgUAOw==');
x += gif('#de-btn-godown', p + 'ItjI+pu+DA4ps02osznrq9DnZceIxkYILUd7bue6WhrLInLdokHq96tnI5YJoCADs=');
x += gif('#de-btn-expimg', p + 'I9jI+pGwDn4GPL2Wep3rxXFEFel42mBE6kcYXqFqYnVc72jTPtS/KNr5OJOJMdq4diAXWvS065NNVwseehAAA7');
x += gif('#de-btn-preimg', p + 'JFjI+pGwCcHJPGWdoe3Lz7qh1WFJLXiX4qgrbXVEIYadLLnMX4yve+7ErBYorRjXiEeXagGguZAbWaSdHLOow4j8Hrj1EAADs=');
x += gif('#de-btn-maskimg', p + 'JQjI+pGwD3TGxtJgezrKz7DzLYRlKj4qTqmoYuysbtgk02ZCG1Rkk53gvafq+i8QiSxTozIY7IcZJOl9PNBx1de1Sdldeslq7dJ9gsUq6QnwIAOw==');
x += gif('#de-btn-imgload', p + 'JFjI+pG+CQnHlwSYYu3rz7RoVipWib+aVUVD3YysAledKZHePpzvecPGnpDkBQEEV03Y7DkRMZ9ECNnemUlZMOQc+iT1EAADs=')
x += gif('#de-btn-catalog', p + 'I2jI+pa+DhAHyRNYpltbz7j1Rixo0aCaaJOZ2SxbIwKTMxqub6zuu32wP9WsHPcFMs0XDJ5qEAADs=');
x += gif('#de-btn-audio-off', p + 'I7jI+pq+DO1psvQHOj3rxTik1dCIzmSZqfmGXIWlkiB6L2jedhPqOfCitVYolgKcUwyoQuSe3WwzV1kQIAOw==');
x += gif('#de-btn-audio-on', p + 'JHjI+pq+AewJHs2WdoZLz7X11WRkEgNoHqimadOG7uAqOm+Y6atvb+D0TgfjHS6RIp8YQ1pbHRfA4n0eSTI7JqP8Wtahr0FAAAOw==');
p = 'Dw8P///wAAACH5BAEAAAIALAAAAAAZABkAQAJElI+pe2EBoxOTNYmr3bz7OwHiCDzQh6bq06QSCUhcZMCmNrfrzvf+XsF1MpjhCSainBg0AbKkFCJko6g0MSGyftwuowAAOw==';
x += gif('#de-btn-upd-on', 'R0lGODlhGQAZAJEAADL/Mv' + p);
x += gif('#de-btn-upd-off', 'R0lGODlhGQAZAJEAAP8yMv' + p);
x += gif('#de-btn-upd-warn', 'R0lGODlhGQAZAJEAAP/0Qf' + p);
// Post panel
x += '.de-ppanel { margin-left: 4px; }\
.de-thread-note { font-style: italic; }\
.de-post-note { color: inherit; margin: 0 4px; vertical-align: 1px; font: italic bold 12px serif; }\
.de-btn-hide, .de-btn-hide-user, .de-btn-rep, .de-btn-fav, .de-btn-fav-sel, .de-btn-src, .de-btn-expthr, .de-btn-sage { display: inline-block; margin: 0 4px -2px 0 !important; cursor: pointer; ';
if(Cfg['postBtnsCSS'] === 0) {
x += 'color: #4F7942; font-size: 14px; }\
.de-btn-hide:after { content: "\u2716"; }\
.de-post-hid .de-btn-hide:after { content: "\u271a"; }\
.de-btn-hide-user:after { content: "\u2716"; color: red !important; }\
.de-post-hid .de-btn-hide-user:after { content: "\u271a"; }\
.de-btn-rep:after { content: "\u25b6"; }\
.de-btn-expthr:after { content: "\u21d5"; }\
.de-btn-fav:after { content: "\u2605"; }\
.de-btn-fav-sel:after { content: "[\u2605]"; }\
.de-btn-sage:after { content: "\u274e"; }\
.de-btn-src:after { content: "[S]"; }';
} else if(Cfg['postBtnsCSS'] === 1) {
x += 'padding: 0 14px 14px 0; }';
x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAKIAAL//v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM8SLLcS2MNQGsUMYi6uB5BKI5hFgojel5YBbDDNcmvpJLkcgLq1jcuSgPmgkUmlJgFAyqNmoEBJEatxggJADs=');
x += gif('.de-post-hid .de-btn-hide-user', 'R0lGODlhDgAOAKIAAP+/v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM5SLLcS2ONCcCMIoYdRBVcN4Qkp4ULmWVV20ZTM1SYBJbqvXmA3jk8IMzlgtVYFtkoNCENIJdolJAAADs=');
p = 'R0lGODlhDgAOAKIAAPDw8KCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM';
x += gif('.de-btn-hide', p + '8SLLcS2MNQGsUMYi6uB5BKI5hFgojel5YBbDDNcmvpJLkcgLq1jcuSgPmgkUmlJgFAyqNmoEBJEatxggJADs=');
x += gif('.de-post-hid .de-btn-hide', p + '5SLLcS2ONCcCMIoYdRBVcN4Qkp4ULmWVV20ZTM1SYBJbqvXmA3jk8IMzlgtVYFtkoNCENIJdolJAAADs=');
x += gif('.de-btn-rep', p + '4SLLcS2MNQGsUMQRRwdLbAI5kpn1kKHUWdk3AcDFmOqKcJ5AOq0srX0QWpBAlIo3MNoDInlAZIQEAOw==');
x += gif('.de-btn-expthr', p + '7SLLcS6MNACKLIQjKgcjCkI2DOAbYuHlnKFHWUl5dnKpfm2vd7iyUXywEk1gmnYrMlEEyUZCSdFoiJAAAOw==');
x += gif('.de-btn-fav', p + '5SLLcS2MNQGsUl1XgRvhg+EWhQAllNG0WplLXqqIlDS7lWZvsJkm92Au2Aqg8gQFyhBxAlNCokpAAADs=');
x += gif('.de-btn-fav-sel', 'R0lGODlhDgAOAKIAAP/hAKCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM5SLLcS2MNQGsUl1XgRvhg+EWhQAllNG0WplLXqqIlDS7lWZvsJkm92Au2Aqg8gQFyhBxAlNCokpAAADs=');
x += gif('.de-btn-sage', 'R0lGODlhDgAOAJEAAPDw8EtLS////wAAACH5BAEAAAIALAAAAAAOAA4AQAIZVI55duDvFIKy2vluoJfrD4Yi5lWRwmhCAQA7');
x += gif('.de-btn-src', p + '9SLLcS0MMQMesUoQg6PKbtFnDaI0a53VAml2ARcVSFC0WY6ecyy+hFajnWDVssyQtB5NhTs1mYAAhWa2EBAA7');
} else {
x += 'padding: 0 14px 14px 0; }';
x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAJEAAL//v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw==');
x += gif('.de-post-hid .de-btn-hide-user', 'R0lGODlhDgAOAJEAAP+/v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7 ');
p = 'R0lGODlhDgAOAJEAAPDw8IyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAI';
x += gif('.de-btn-hide', p + 'dVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw==');
x += gif('.de-post-hid .de-btn-hide', p + 'ZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7');
x += gif('.de-btn-rep', p + 'aVI55pu2vAIBISmrty7rx63FbN1LmiTCUUAAAOw==');
x += gif('.de-btn-expthr', p + 'bVI55pu0BwEMxzlonlHp331kXxjlYWH4KowkFADs=');
x += gif('.de-btn-fav', p + 'dVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw==');
x += gif('.de-btn-fav-sel','R0lGODlhDgAOAJEAAP/hAIyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw==');
x += gif('.de-btn-sage','R0lGODlhDgAOAJEAAPDw8FBQUP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu0AgZs0SoqTzdnu5l1P1ImcwmBCAQA7');
x += gif('.de-btn-src', p + 'fVI55pt0ADnRh1uispfvpLkEieGGiZ5IUGmJrw7xCAQA7');
}
if(!pr.form && !pr.oeForm) {
x += '.de-btn-rep { display: none; }';
}
// Search images buttons
x += cont('.de-src-google', 'http://google.com/favicon.ico');
x += cont('.de-src-tineye', 'http://tineye.com/favicon.ico');
x += cont('.de-src-iqdb', 'http://iqdb.org/favicon.ico');
x += cont('.de-src-saucenao', 'http://saucenao.com/favicon.ico');
// Posts counter
x += '.de-ppanel-cnt:after { counter-increment: de-cnt 1; content: counter(de-cnt); margin-right: 4px; vertical-align: 1px; color: #4f7942; font: bold 11px tahoma; cursor: default; }\
.de-ppanel-del:after { content: "' + Lng.deleted[lang] + '"; margin-right: 4px; vertical-align: 1px; color: #727579; font: bold 11px tahoma; cursor: default; }';
// Text format buttons
x += '#de-txt-panel { display: block; height: 23px; font-weight: bold; cursor: pointer; }\
#de-txt-panel > span:empty { display: inline-block; width: 27px; height: 23px; }';
p = 'R0lGODlhFwAWAJEAAPDw8GRkZAAAAP///yH5BAEAAAMALAAAAAAXABYAQAJ';
x += gif('#de-btn-bold:empty', p + 'T3IKpq4YAoZgR0KqqnfzipIUikFWc6ZHBwbQtG4zyonW2Vkb2iYOo8Ps8ZLOV69gYEkU5yQ7YUzqhzmgsOLXWnlRIc9PleX06rnbJ/KITDqTLUAAAOw==');
x += gif('#de-btn-italic:empty', p + 'K3IKpq4YAYxRCSmUhzTfx3z3c9iEHg6JnAJYYSFpvRlXcLNUg3srBmgr+RL0MzxILsYpGzyepfEIjR43t5kResUQmtdpKOIQpQwEAOw==');
x += gif('#de-btn-under:empty', p + 'V3IKpq4YAoRARzAoV3hzoDnoJNlGSWSEHw7JrEHILiVp1NlZXtKe5XiptPrFh4NVKHh9FI5NX60WIJ6ATZoVeaVnf8xSU4r7NMRYcFk6pzYRD2TIUAAA7');
x += gif('#de-btn-strike:empty', p + 'S3IKpq4YAoRBR0qqqnVeD7IUaKHIecjCqmgbiu3jcfCbAjOfTZ0fmVnu8YIHW6lgUDkOkCo7Z8+2AmCiVqHTSgi6pZlrN3nJQ8TISO4cdyJWhAAA7');
x += gif('#de-btn-spoil:empty', 'R0lGODlhFwAWAJEAAPDw8GRkZP///wAAACH5BAEAAAIALAAAAAAXABYAQAJBlIKpq4YAmHwxwYtzVrprXk0LhBziGZiBx44hur4kTIGsZ99fSk+mjrMAd7XerEg7xnpLIVM5JMaiFxc14WBiBQUAOw==');
x += gif('#de-btn-code:empty', p + 'O3IKpq4YAoZgR0KpqnFxokH2iFm7eGCEHw7JrgI6L2F1YotloKek6iIvJAq+WkfgQinjKVLBS45CePSXzt6RaTjHmNjpNNm9aq6p4XBgKADs=');
x += gif('#de-btn-sup:empty', p + 'Q3IKpq4YAgZiSQhGByrzn7YURGFGWhxzMuqqBGC7wRUNkeU7nnWNoMosFXKzi8BHs3EQnDRAHLY2e0BxnWfEJkRdT80NNTrliG3aWcBhZhgIAOw==');
x += gif('#de-btn-sub:empty', p + 'R3IKpq4YAgZiSxquujtOCvIUayAkVZEoRcjCu2wbivMw2WaYi7vVYYqMFYq/i8BEM4ZIrYOmpdD49m2VFd2oiUZTORWcNYT9SpnZrTjiML0MBADs=');
x += gif('#de-btn-quote:empty', p + 'L3IKpq4YAYxRUSKguvRzkDkZfWFlicDCqmgYhuGjVO74zlnQlnL98uwqiHr5ODbDxHSE7Y490wxF90eUkepoysRxrMVaUJBzClaEAADs=');
// Show/close animation
if(nav.Anim) {
x += '@keyframes de-open {\
0% { transform: translateY(-1500px); }\
40% { transform: translateY(30px); }\
70% { transform: translateY(-10px); }\
100% { transform: translateY(0); }\
}\
@keyframes de-close {\
0% { transform: translateY(0); }\
20% { transform: translateY(20px); }\
100% { transform: translateY(-4000px); }\
}\
@keyframes de-blink {\
0%, 100% { transform: translateX(0); }\
10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }\
20%, 40%, 60%, 80% { transform: translateX(10px); }\
}\
@keyframes de-cfg-open { from { transform: translate(0,50%) scaleY(0); opacity: 0; } }\
@keyframes de-cfg-close { to { transform: translate(0,50%) scaleY(0); opacity: 0; } }\
@keyframes de-post-open-tl { from { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-open-bl { from { transform: translate(-50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-open-tr { from { transform: translate(50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-open-br { from { transform: translate(50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-tl { to { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-bl { to { transform: translate(-50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-tr { to { transform: translate(50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-br { to { transform: translate(50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-new { from { transform: translate(0,-50%) scaleY(0); opacity: 0; } }\
.de-pview-anim { animation-duration: .2s; animation-timing-function: ease-in-out; animation-fill-mode: both; }\
.de-open { animation: de-open .7s ease-out both; }\
.de-close { animation: de-close .7s ease-in both; }\
.de-blink { animation: de-blink .7s ease-in-out both; }\
.de-cfg-open { animation: de-cfg-open .2s ease-out backwards; }\
.de-cfg-close { animation: de-cfg-close .2s ease-in both; }\
.de-post-new { animation: de-post-new .2s ease-out both; }';
}
// Embedders
x += cont('.de-video-link.de-ytube', 'https://youtube.com/favicon.ico');
x += cont('.de-video-link.de-vimeo', 'https://vimeo.com/favicon.ico');
x += cont('.de-img-arch', 'data:image/gif;base64,R0lGODlhEAAQALMAAF82SsxdwQMEP6+zzRA872NmZQesBylPHYBBHP///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAAAQABAAQARTMMlJaxqjiL2L51sGjCOCkGiBGWyLtC0KmPIoqUOg78i+ZwOCUOgpDIW3g3KJWC4t0ElBRqtdMr6AKRsA1qYy3JGgMR4xGpAAoRYkVDDWKx6NRgAAOw==');
x += cont('.de-img-audio', 'data:image/gif;base64,R0lGODlhEAAQAKIAAGya4wFLukKG4oq3802i7Bqy9P///wAAACH5BAEAAAYALAAAAAAQABAAQANBaLrcHsMN4QQYhE01OoCcQIyOYQGooKpV1GwNuAwAa9RkqTPpWqGj0YTSELg0RIYM+TjOkgba0sOaAEbGBW7HTQAAOw==');
x += '.de-current:after { content: "\u25c4"; }\
.de-img-arch, .de-img-audio { color: inherit; text-decoration: none; font-weight: bold; }\
.de-img-pre, .de-img-full { display: block; border: none; outline: none; cursor: pointer; }\
.de-img-pre { max-width: 200px; max-height: 200px; }\
.de-img-full { float: left; }\
.de-img-center { position: fixed; margin: 0 !important; z-index: 9999; background-color: #ccc; border: 1px solid black !important; }\
#de-img-btn-next > div, #de-img-btn-prev > div { height: 36px; width: 36px; }' +
gif('#de-img-btn-next > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJPjI8JkO1vlpzS0YvzhUdX/nigR2ZgSJ6IqY5Uy5UwJK/l/eI6A9etP1N8grQhUbg5RlLKAJD4DAJ3uCX1isU4s6xZ9PR1iY7j5nZibixgBQA7') +
gif('#de-img-btn-prev > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJOjI8JkO24ooxPzYvzfJrWf3Rg2JUYVI4qea1g6zZmPLvmDeM6Y4mxU/v1eEKOpziUIA1BW+rXXEVVu6o1dQ1mNcnTckp7In3LAKyMchUAADs=') +
'#de-img-btns { position: fixed; z-index: 10000; cursor: pointer; }\
#de-img-btn-next, #de-img-btn-prev { position: fixed; top: 50%; margin-top: -8px; background-color: black; }\
#de-img-btn-next { right: 0; border-radius: 10px 0 0 10px; }\
#de-img-btn-prev { left: 0; border-radius: 0 10px 10px 0; }\
.de-mp3, .de-video-obj { margin: 5px 20px; }\
.de-video-title[de-time]:after { content: " [" attr(de-time) "]"; color: red; }\
td > a + .de-video-obj { display: inline-block; }\
video { background: black; }';
// Other
x += cont('.de-wait', 'data:image/gif;base64,R0lGODlhEAAQALMMAKqooJGOhp2bk7e1rZ2bkre1rJCPhqqon8PBudDOxXd1bISCef///wAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAMACwAAAAAEAAQAAAET5DJyYyhmAZ7sxQEs1nMsmACGJKmSaVEOLXnK1PuBADepCiMg/DQ+/2GRI8RKOxJfpTCIJNIYArS6aRajWYZCASDa41Ow+Fx2YMWOyfpTAQAIfkEBQAADAAsAAAAABAAEAAABE6QyckEoZgKe7MEQMUxhoEd6FFdQWlOqTq15SlT9VQM3rQsjMKO5/n9hANixgjc9SQ/CgKRUSgw0ynFapVmGYkEg3v1gsPibg8tfk7CnggAIfkEBQAADAAsAAAAABAAEAAABE2QycnOoZjaA/IsRWV1goCBoMiUJTW8A0XMBPZmM4Ug3hQEjN2uZygahDyP0RBMEpmTRCKzWGCkUkq1SsFOFQrG1tr9gsPc3jnco4A9EQAh+QQFAAAMACwAAAAAEAAQAAAETpDJyUqhmFqbJ0LMIA7McWDfF5LmAVApOLUvLFMmlSTdJAiM3a73+wl5HYKSEET2lBSFIhMIYKRSimFriGIZiwWD2/WCw+Jt7xxeU9qZCAAh+QQFAAAMACwAAAAAEAAQAAAETZDJyRCimFqbZ0rVxgwF9n3hSJbeSQ2rCWIkpSjddBzMfee7nQ/XCfJ+OQYAQFksMgQBxumkEKLSCfVpMDCugqyW2w18xZmuwZycdDsRACH5BAUAAAwALAAAAAAQABAAAARNkMnJUqKYWpunUtXGIAj2feFIlt5JrWybkdSydNNQMLaND7pC79YBFnY+HENHMRgyhwPGaQhQotGm00oQMLBSLYPQ9QIASrLAq5x0OxEAIfkEBQAADAAsAAAAABAAEAAABE2QycmUopham+da1cYkCfZ94UiW3kmtbJuRlGF0E4Iwto3rut6tA9wFAjiJjkIgZAYDTLNJgUIpgqyAcTgwCuACJssAdL3gpLmbpLAzEQA7');
x += '.de-abtn { text-decoration: none !important; outline: none; }\
.de-after-fimg { clear: left; }\
#de-alert { position: fixed; right: 0; top: 0; z-index: 9999; font: 14px arial; cursor: default; }\
#de-alert > div { float: right; clear: both; width: auto; min-width: 0pt; padding: 10px; margin: 1px; border: 1px solid grey; white-space: pre-wrap; }\
.de-alert-btn { display: inline-block; vertical-align: top; color: green; cursor: pointer; }\
.de-alert-btn:not(.de-wait) + div { margin-top: .15em; }\
.de-alert-msg { display: inline-block; }\
.de-content textarea { display: block; margin: 2px 0; font: 12px courier new; ' + (nav.Opera ? '' : 'resize: none !important; ') + '}\
.de-content-block > a { color: inherit; font-weight: bold; }\
#de-content-fav, #de-content-hid { font-size: 16px; padding: 10px; border: 1px solid gray; }\
.de-editor { display: block; font: 12px courier new; width: 619px; height: 337px; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; }\
.de-entry { margin: 2px 0; ' + (nav.Opera ? 'white-space: nowrap; ' : '') + '}\
.de-entry > :first-child { float: none !important; }\
.de-entry > div > a { text-decoration: none; }\
.de-fav-inf-posts, .de-fav-inf-page { float: right; margin-right: 5px; font: bold 16px serif; }\
.de-fav-inf-old { color: #4f7942; }\
.de-fav-inf-new { color: blue; }\
.de-fav-title { margin-right: 15px; }\
.de-menu { padding: 0 !important; margin: 0 !important; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important;}\
.de-menu-item { display: block; padding: 3px 10px; color: inherit; text-decoration: none; font: 13px arial; white-space: nowrap; cursor: pointer; }\
.de-menu-item:hover { background-color: #222; color: #fff; }\
.de-new-post { ' + (nav.Opera ? 'border-left: 4px solid blue; border-right: 4px solid blue; }' : 'box-shadow: 6px 0 2px -2px blue, -6px 0 2px -2px blue; }') + '\
.de-omitted { color: grey; font-style: italic; }\
.de-omitted:before { content: "' + Lng.postsOmitted[lang] + '"; }\
.de-opref::after { content: " [OP]"; }\
.de-parea { text-align: center;}\
.de-parea-btn-close:after { content: "' + Lng.hideForm[lang] + '" }\
.de-parea-btn-thrd:after { content: "' + Lng.makeThrd[lang] + '" }\
.de-parea-btn-reply:after { content: "' + Lng.makeReply[lang] + '" }\
.de-pview { position: absolute; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important; margin: 0 !important; display: block !important; }\
.de-pview-info { padding: 3px 6px !important; }\
.de-pview-link { font-weight: bold; }\
.de-ref-hid { text-decoration: line-through !important; }\
.de-refmap { margin: 10px 4px 4px 4px; font-size: 70%; font-style: italic; }\
.de-refmap:before { content: "' + Lng.replies[lang] + ' "; }\
.de-reflink { text-decoration: none; }\
.de-refcomma:last-child { display: none; }\
#de-sagebtn { margin-right: 7px; cursor: pointer; }\
.de-selected, .de-error-key { ' + (nav.Opera ? 'border-left: 4px solid red; border-right: 4px solid red; }' : 'box-shadow: 6px 0 2px -2px red, -6px 0 2px -2px red; }') + '\
#de-txt-resizer { display: inline-block !important; float: none !important; padding: 6px; margin: -2px -12px; vertical-align: bottom; border-bottom: 2px solid #555; border-right: 2px solid #444; cursor: se-resize; }\
#de-updater-btn:after { content: "' + Lng.getNewPosts[lang] + '" }\
#de-updater-div { margin-top: 10px; }\
.de-viewed { color: #888 !important; }\
.de-hidden, small[id^="rfmap"], body > hr, .theader, .postarea, .thumbnailmsg { display: none !important; }\
form > hr { clear: both }\
' + aib.css + aib.cssEn + aib.cssHide + ' { display: none !important; }';
if(!nav.Firefox) {
x = x.replace(/(transition|keyframes|transform|animation|linear-gradient)/g, nav.cssFix + '$1');
if(!nav.Opera) {
x = x.replace(/\(to bottom/g, '(top').replace(/\(to top/g, '(bottom');
}
}
$css(x).id = 'de-css';
$css('').id = 'de-css-dynamic';
$css('').id = 'de-css-user';
updateCSS();
}
function updateCSS() {
var x;
if(Cfg['attachPanel']) {
x = '.de-content { position: fixed; right: 0; bottom: 25px; z-index: 9999; max-height: 95%; overflow-x: visible; overflow-y: auto; }\
#de-panel { position: fixed; right: 0; bottom: 0; }'
} else {
x = '.de-content { clear: both; float: right; }\
#de-panel { float: right; clear: both; }'
}
if(Cfg['addPostForm'] === 3) {
x += '#de-qarea { position: fixed; right: 0; bottom: 25px; z-index: 9990; padding: 3px; border: 1px solid gray; }\
#de-qarea-target { font-weight: bold; }\
#de-qarea-close { float: right; color: green; font: bold 20px arial; cursor: pointer; }';
} else {
x += '#de-qarea { float: none; clear: left; width: 100%; padding: 3px 0 3px 3px; margin: 2px 0; }';
}
if(!Cfg['panelCounter']) {
x += '#de-panel-info { display: none; }';
}
if(Cfg['maskImgs']) {
x += '.de-img-pre, .de-video-obj, .thumb, .ca_thumb, img[src*="spoiler"], img[src*="thumb"], img[src^="blob"] { opacity: 0.07 !important; }\
.de-img-pre:hover, .de-video-obj:hover, img[src*="spoiler"]:hover, img[src*="thumb"]:hover, img[src^="blob"]:hover { opacity: 1 !important; }';
}
if(Cfg['expandImgs'] === 1 && !(aib.fch || aib.dobr || aib.krau)) {
x += '.de-img-full { margin: 2px 10px; }';
}
if(Cfg['delHiddPost']) {
x += '.de-thr-hid, .de-thr-hid + div + br, .de-thr-hid + div + br + hr { display: none; }';
}
if(Cfg['noPostNames']) {
x += aib.qName + ', .' + aib.cTrip + ' { display: none; }';
}
if(Cfg['noSpoilers']) {
x += '.spoiler' + (aib.fch ? ', s' : '') + ' { background: #888 !important; color: #ccc !important; }';
}
if(Cfg['noPostScrl']) {
x += 'blockquote, blockquote > p, .code_part { max-height: 100% !important; overflow: visible !important; }';
}
if(Cfg['noBoardRule']) {
x += (aib.futa ? '.chui' : '.rules, #rules, #rules_row') + ' { display: none; }';
}
if(aib.abu) {
if(Cfg['addYouTube']) {
x += 'div[id^="post_video"] { display: none !important; }';
}
}
$id('de-css-dynamic').textContent = x;
$id('de-css-user').textContent = Cfg['userCSS'] ? Cfg['userCSSTxt'] : '';
}
//============================================================================================================
// SCRIPT UPDATING
//============================================================================================================
function checkForUpdates(isForce, Fn) {
var day, temp = Cfg['scrUpdIntrv'];
if(!isForce) {
day = 2 * 1000 * 60 * 60 * 24;
switch(temp) {
case 0: temp = day; break;
case 1: temp = day * 2; break;
case 2: temp = day * 7; break;
case 3: temp = day * 14; break;
default: temp = day * 30;
}
if(Date.now() - +comCfg['lastUpd'] < temp) {
return;
}
}
GM_xmlhttpRequest({
'method': 'GET',
'url': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js',
'headers': {'Content-Type': 'text/plain'},
'onreadystatechange': function(xhr) {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status === 200) {
var dVer = xhr.responseText.match(/@version\s+([0-9.]+)/)[1].split('.'),
cVer = version.split('.'),
len = cVer.length > dVer.length ? cVer.length : dVer.length,
i = 0,
isUpd = false;
if(!dVer) {
if(isForce) {
Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>');
}
return;
}
saveComCfg('lastUpd', Date.now());
while(i < len) {
if((+dVer[i] || 0) > (+cVer[i] || 0)) {
isUpd = true;
break;
} else if((+dVer[i] || 0) < (+cVer[i] || 0)) {
break;
}
i++;
}
if(isUpd) {
Fn('<a style="color: blue; font-weight: bold;" href="' +
'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/' +
'Dollchan_Extension_Tools.user.js">' + Lng.updAvail[lang] + '</a>');
} else if(isForce) {
Fn(Lng.haveLatest[lang]);
}
} else if(isForce) {
Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>');
}
}
});
}
//============================================================================================================
// POSTFORM
//============================================================================================================
function PostForm(form, ignoreForm, init) {
this.oeForm = $q('form[name="oeform"], form[action*="paint"]', doc);
if(aib.abu && ($c('locked', form) || this.oeForm)) {
this.form = null;
if(this.oeForm) {
this._init();
}
return;
}
if(!ignoreForm && !form) {
if(this.oeForm) {
ajaxLoad(aib.getThrdUrl(brd, aib.getTNum(dForm)), false, function(dc, xhr) {
pr = new PostForm($q(aib.qPostForm, dc), true, init);
}, function(eCode, eMsg, xhr) {
pr = new PostForm(null, true, init);
});
} else {
this.form = null;
}
return;
}
function $x(path, root) {
return doc.evaluate(path, root, null, 8, null).singleNodeValue;
}
var tr = aib.trTag,
p = './/' + tr + '[not(contains(@style,"none"))]//input[not(@type="hidden") and ';
this.tNum = TNum;
this.form = form;
this.cap = $q('input[type="text"][name*="aptcha"], div[id*="captcha"]', form);
this.txta = $q(tr + ':not([style*="none"]) textarea:not([style*="display:none"])', form);
this.subm = $q(tr + ' input[type="submit"]', form);
this.file = $q(tr + ' input[type="file"]', form);
this.passw = $q(tr + ' input[type="password"]', form);
this.dpass = $q('input[type="password"], input[name="password"]', dForm);
this.gothr = $x('.//tr[@id="trgetback"]|.//input[@type="radio" or @name="gotothread"]/ancestor::tr[1]', form);
this.name = $x(p + '(@name="field1" or @name="name" or @name="internal_n" or @name="nya1" or @name="akane")]', form);
this.mail = $x(p + (
aib._410 ? '@name="sage"]' :
'(@name="field2" or @name="em" or @name="sage" or @name="email" or @name="nabiki" or @name="dont_bump")]'
), form);
this.subj = $x(p + '(@name="field3" or @name="sub" or @name="subject" or @name="internal_s" or @name="nya3" or @name="kasumi")]', form);
this.video = $q(tr + ' input[name="video"], ' + tr + ' input[name="embed"]', form);
if(init) {
this._init();
}
}
PostForm.setUserName = function() {
var el = $q('input[info="nameValue"]', doc);
if(el) {
saveCfg('nameValue', el.value);
}
pr.name.value = Cfg['userName'] ? Cfg['nameValue'] : '';
};
PostForm.setUserPassw = function() {
var el = $q('input[info="passwValue"]', doc);
if(el) {
saveCfg('passwValue', el.value);
}
(pr.dpass || {}).value = pr.passw.value = Cfg['passwValue'];
};
PostForm.eventFiles = function(tr) {
$each($Q('input[type="file"]', tr), function(el) {
el.addEventListener('change', PostForm.processInput, false);
});
};
PostForm.processInput = function() {
if(!this.haveBtns) {
this.haveBtns = true;
var delBtn = $new('button', {
'class': 'de-file-util de-file-del',
'text': Lng.clear[lang],
'type': 'button'}, {
'click': function(e) {
$pd(e);
if(aib.krau && this.parentNode.nextSibling) {
var current = $q('input[type="file"]', this.parentNode).name.match(/\d/)[0];
$each($Q('input[type="file"]', getAncestor(this, aib.trTag)), function(input, index) {
if(index > current)
input.name = "file_" + (index-1);
});
$del(this.parentNode);
if($q('input[type="file"]', $id('files_parent').lastElementChild).value) {
setTimeout(function(){PostForm.eventFiles($id('files_parent'));}, 100);
}
} else {
pr.delFileUtils(this.parentNode, false);
pr.file.addEventListener('change', PostForm.processInput, false);
}
}
});
if(aib.krau) {
delBtn.addEventListener('focus', function() {
if(this.parentNode.nextSibling) {
this.setAttribute('onclick', 'window.fileCounter -= 1;' + ($q('input[type="file"]', $id('files_parent').lastElementChild).value ? 'updateFileFields();' : ''));
}
}, false);
}
$after(this, delBtn);
} else if(this.imgFile) {
this.imgFile = null;
$del(this.nextSibling);
}
$del($c('de-file-rar', this.parentNode));
PostForm.eventFiles(getAncestor(this, aib.trTag));
if(nav.noBlob || !/^image\/(?:png|jpeg)$/.test(this.files[0].type)) {
return;
}
$after(this, $new('button', {
'class': 'de-file-util de-file-rar',
'text': Lng.addFile[lang],
'title': Lng.helpAddFile[lang],
'type': 'button'}, {
'click': function(e) {
$pd(e);
var el = $id('de-input-rar') || doc.body.appendChild($new('input', {
'id': 'de-input-rar',
'type': 'file',
'style': 'display: none;'
}, null));
el.onchange = function(inp, e) {
$del(this);
var file = e.target.files[0],
fr = new FileReader();
inp.insertAdjacentHTML('afterend', '<span class="de-file-util" style="margin: 0 5px;">' +
'<span class="de-wait"></span>' + Lng.wait[lang] + '</span>');
fr.onload = function(input, node, e) {
if(input.nextSibling === node) {
node.style.cssText = 'font-weight: bold; margin: 0 5px; cursor: default;';
node.title = input.files[0].name + ' + ' + this.name;
node.textContent = input.files[0].name.replace(/^.+\./, '') + ' + ' +
this.name.replace(/^.+\./, '')
input.imgFile = e.target.result;
}
}.bind(file, inp, inp.nextSibling);
fr.readAsArrayBuffer(file);
}.bind(this, $q('input[type="file"]', this.parentNode));
el.click();
}
}));
};
PostForm.prototype = {
isHidden: false,
isQuick: false,
isTopForm: false,
lastQuickPNum: -1,
pForm: null,
pArea: [],
qArea: null,
addTextPanel: function() {
var i, len, tag, html, btns, tPanel = $id('de-txt-panel');
if(!Cfg['addTextBtns']) {
$del(tPanel);
return;
}
if(!tPanel) {
tPanel = $new('span', {'id': 'de-txt-panel'}, {
'click': this,
'mouseover': this
});
}
tPanel.style.cssFloat = Cfg['txtBtnsLoc'] ? 'none' : 'right';
$after(Cfg['txtBtnsLoc'] ? $id('de-txt-resizer') || this.txta :
aib._420 ? $c('popup', this.form) : this.subm, tPanel);
for(html = '', i = 0, btns = aib.formButtons, len = btns['id'].length; i < len; ++i) {
tag = btns['tag'][i];
if(tag === '') {
continue;
}
html += '<span id="de-btn-' + btns['id'][i] + '" de-title="' + Lng.txtBtn[i][lang] +
'" de-tag="' + tag + '"' + (btns['bb'][i] ? 'de-bb' : '') + '>' + (
Cfg['addTextBtns'] === 2 ?
(i === 0 ? '[ ' : '') + '<a class="de-abtn" href="#">' + btns['val'][i] +
'</a>' + (i === len - 1 ? ' ]' : ' / ') :
Cfg['addTextBtns'] === 3 ?
'<input type="button" value="' + btns['val'][i] + '" style="font-weight: bold;">' : ''
) + '</span>';
}
tPanel.innerHTML = html;
},
delFileUtils: function(el, eventFiles) {
$each($Q('.de-file-util', el), $del);
$each($Q('input[type="file"]', el), function(node) {
node.imgFile = null;
});
this._clearFileInput(el, eventFiles);
},
handleEvent: function(e) {
var x, start, end, scrtop, title, id, el = e.target;
if(el.tagName !== 'SPAN') {
el = el.parentNode;
}
id = el.id;
if(id.startsWith('de-btn')) {
if(e.type === 'mouseover') {
if(id === 'de-btn-quote') {
quotetxt = $txtSelect();
}
x = -1;
if(keyNav) {
switch(id.substr(7)) {
case 'bold': x = 12; break;
case 'italic': x = 13; break;
case 'strike': x = 14; break;
case 'spoil': x = 15; break;
case 'code': x = 16; break;
}
}
el.title = el.getAttribute('de-title') + (x === -1 ? '' : ' [' +
KeyEditListener.getStrKey(keyNav.gKeys[x]) + ']');
return;
}
x = pr.txta;
start = x.selectionStart;
end = x.selectionEnd;
if(id === 'de-btn-quote') {
$txtInsert(x, '> ' + (start === end ? quotetxt : x.value.substring(start, end))
.replace(/\n/gm, '\n> '));
} else {
scrtop = x.scrollTop;
txt = this._wrapText(el.hasAttribute('de-bb'), el.getAttribute('de-tag'),
x.value.substring(start, end));
len = start + txt.length;
x.value = x.value.substr(0, start) + txt + x.value.substr(end);
x.setSelectionRange(len, len);
x.focus();
x.scrollTop = scrtop;
}
$pd(e);
e.stopPropagation();
}
},
showQuickReply: function(post, pNum, closeReply) {
var el, tNum = post.tNum;
if(!this.isQuick) {
this.isQuick = true;
this.setReply(true, false);
$t('a', this._pBtn[+this.isTopForm]).className =
'de-abtn de-parea-btn-' + (TNum ? 'reply' : 'thrd');
if(!TNum && !aib.kus && !aib.dobr) {
if(this.oeForm) {
$del($q('input[name="oek_parent"]', this.oeForm));
this.oeForm.insertAdjacentHTML('afterbegin', '<input type="hidden" value="' +
tNum + '" name="oek_parent">');
}
if(this.form) {
$del($q('#thr_id, input[name="parent"]', this.form));
this.form.insertAdjacentHTML('afterbegin',
'<input type="hidden" id="thr_id" value="' + tNum + '" name="' + (
aib.fch || aib.futa ? 'resto' :
aib.tiny ? 'thread' :
'parent'
) + '">'
);
}
}
} else if(closeReply && !quotetxt && post.wrap.nextElementSibling === this.qArea) {
this.closeQReply();
return;
}
$after(post.wrap, this.qArea);
if(!TNum) {
this._toggleQuickReply(tNum);
}
if(!this.form) {
return;
}
if(this._lastCapUpdate && ((!TNum && this.tNum !== tNum) || (Date.now() - this._lastCapUpdate > 3e5))) {
this.tNum = tNum;
this.refreshCapImg(false);
}
this.tNum = tNum;
if(aib._420 && this.txta.value === 'Comment') {
this.txta.value = '';
}
$txtInsert(this.txta, (this.txta.value === '' || this.txta.value.slice(-1) === '\n' ? '' : '\n') +
(this.lastQuickPNum === pNum && this.txta.value.contains('>>' + pNum) ? '' : '>>' + pNum + '\n') +
(quotetxt ? quotetxt.replace(/^\n|\n$/g, '').replace(/(^|\n)(.)/gm, '$1> $2') + '\n': ''));
if(Cfg['addPostForm'] === 3) {
el = $t('a', this.qArea.firstChild);
el.href = aib.getThrdUrl(brd, tNum);
el.textContent = '#' + tNum;
}
this.lastQuickPNum = pNum;
},
showMainReply: function(isTop, evt) {
this.closeQReply();
if(this.isTopForm === isTop) {
this.pForm.style.display = this.isHidden ? '' : 'none';
this.isHidden = !this.isHidden;
this.updatePAreaBtns();
} else {
this.isTopForm = isTop;
this.setReply(false, false);
}
if(evt) {
$pd(evt);
}
},
closeQReply: function() {
if(this.isQuick) {
this.isQuick = false;
this.lastQuickPNum = -1;
if(!TNum) {
this._toggleQuickReply(0);
$del($id('thr_id'));
}
this.setReply(false, !TNum || Cfg['addPostForm'] > 1);
}
},
refreshCapImg: function(focus) {
var src, img;
if(aib.abu && (img = $id('captcha_div')) && img.hasAttribute('onclick')) {
img.dispatchEvent(new CustomEvent('click', {
'bubbles': true,
'cancelable': true,
'detail': {'isCustom': true, 'focus': focus}
}));
return;
}
if(!this.cap || (aib.krau && !$q('input[name="captcha_name"]', this.form).hasAttribute('value'))) {
return;
}
img = this.recap ? $id('recaptcha_image') : $t('img', this.capTr);
if(aib.dobr || aib.krau || this.recap) {
img.click();
} else if(img) {
src = img.getAttribute('src');
if(aib.kus || aib.tinyIb) {
src = src.replace(/\?[^?]+$|$/, (aib._410 ? '?board=' + brd + '&' : '?') + Math.random());
} else {
src = src.replace(/pl$/, 'pl?key=mainpage&dummy=')
.replace(/dummy=[\d\.]*/, 'dummy=' + Math.random());
src = this.tNum ? src.replace(/mainpage|res\d+/, 'res' + this.tNum) :
src.replace(/res\d+/, 'mainpage');
}
img.src = '';
img.src = src;
}
this.cap.value = '';
if(focus) {
this.cap.focus();
}
if(this._lastCapUpdate) {
this._lastCapUpdate = Date.now();
}
},
setReply: function(quick, hide) {
if(quick) {
this.qArea.appendChild(this.pForm);
} else {
$after(this.pArea[+this.isTopForm], this.qArea);
$after(this._pBtn[+this.isTopForm], this.pForm);
}
this.isHidden = hide;
this.qArea.style.display = quick ? '' : 'none';
this.pForm.style.display = hide ? 'none' : '';
this.updatePAreaBtns();
},
updatePAreaBtns: function() {
var txt = 'de-abtn de-parea-btn-',
rep = TNum ? 'reply' : 'thrd';
$t('a', this._pBtn[+this.isTopForm]).className = txt + (this.pForm.style.display === '' ? 'close' : rep);
$t('a', this._pBtn[+!this.isTopForm]).className = txt + rep;
},
_lastCapUpdate: 0,
_pBtn: [],
_clearFileInput: function(el, eventFiles) {
var cln = el.cloneNode(false);
cln.innerHTML = el.innerHTML;
el.parentNode.replaceChild(cln, el);
if(eventFiles) {
PostForm.eventFiles(cln);
}
this.file = $q('input[type="file"]', cln);
},
_init: function() {
this.pForm = $New('div', {'id': 'de-pform'}, [this.form, this.oeForm]);
var btn = $New('div', {'class': 'de-' + (TNum ? 'make-reply' : 'create-thread')}, [
$txt('['),
$new('a', {'href': '#'}, null),
$txt(']')
]);
$before(dForm, this.pArea[0] = $New('div', {'class': 'de-parea'}, [btn, doc.createElement('hr')]));
this._pBtn[0] = btn;
btn.firstElementChild.addEventListener('click', this.showMainReply.bind(this, false), true);
btn = btn.cloneNode(true);
btn.firstElementChild.addEventListener('click', this.showMainReply.bind(this, true), true);
$after(aib.fch ? $c('board', dForm) : dForm, this.pArea[1] =
$New('div', {'class': 'de-parea'}, [btn, doc.createElement('hr')]));
this._pBtn[1] = btn;
this.qArea = $add('<div id="de-qarea" class="' + aib.cReply + '" style="display: none;"></div>');
this.isTopForm = Cfg['addPostForm'] !== 0;
this.setReply(false, !TNum || Cfg['addPostForm'] > 1);
if(Cfg['addPostForm'] === 3) {
$append(this.qArea, [
$add('<span id="de-qarea-target">' + Lng.replyTo[lang] + ' <a class="de-abtn"></a></span>'),
$new('span', {'id': 'de-qarea-close', 'text': '\u2716'}, {'click': this.closeQReply.bind(this)})
]);
}
if(aib.tire) {
$each($Q('input[type="hidden"]', dForm), $del);
dForm.appendChild($c('userdelete', doc.body));
this.dpass = $q('input[type="password"]', dForm);
}
if(!this.form) {
return;
}
this.form.style.display = 'inline-block';
this.form.style.textAlign = 'left';
if(nav.Firefox) {
this.txta.addEventListener('mouseup', function() {
saveCfg('textaWidth', parseInt(this.style.width, 10));
saveCfg('textaHeight', parseInt(this.style.height, 10));
}, false);
} else {
this.txta.insertAdjacentHTML('afterend', '<div id="de-txt-resizer"></div>');
this.txta.nextSibling.addEventListener('mousedown', {
el: this.txta,
elStyle: this.txta.style,
handleEvent: function(e) {
switch(e.type) {
case 'mousedown':
doc.body.addEventListener('mousemove', this, false);
doc.body.addEventListener('mouseup', this, false);
$pd(e);
return;
case 'mousemove':
var cr = this.el.getBoundingClientRect();
this.elStyle.width = (e.pageX - cr.left - window.pageXOffset) + 'px';
this.elStyle.height = (e.pageY - cr.top - window.pageYOffset) + 'px';
return;
default: // mouseup
doc.body.removeEventListener('mousemove', this, false);
doc.body.removeEventListener('mouseup', this, false);
saveCfg('textaWidth', parseInt(this.elStyle.width, 10));
saveCfg('textaHeight', parseInt(this.elStyle.height, 10));
}
}
}, false);
}
if(aib.kus) {
while(this.subm.nextSibling) {
$del(this.subm.nextSibling);
}
}
if(Cfg['addSageBtn'] && this.mail) {
btn = $new('span', {'id': 'de-sagebtn'}, {'click': function(e) {
e.stopPropagation();
$pd(e);
toggleCfg('sageReply');
this._setSage();
}.bind(this)});
el = getAncestor(this.mail, 'LABEL') || this.mail;
if(el.nextElementSibling || el.previousElementSibling) {
$disp(el);
$after(el, btn);
} else {
$disp(getAncestor(this.mail, aib.trTag));
$after(this.name || this.subm, btn);
}
this._setSage();
if(aib.urup || aib._2chru) {
while(btn.nextSibling) {
$del(btn.nextSibling);
}
}
}
this.addTextPanel();
this.txta.style.cssText = 'padding: 0; resize: both; width: ' +
Cfg['textaWidth'] + 'px; height: ' + Cfg['textaHeight'] + 'px;';
this.txta.addEventListener('keypress', function(e) {
var code = e.charCode || e.keyCode;
if((code === 33 || code === 34) && e.which === 0) {
e.target.blur();
window.focus();
}
}, false);
if(!aib.tiny && !aib.nul) {
this.subm.value = Lng.reply[lang];
}
this.subm.addEventListener('click', function(e) {
var temp, val = this.txta.value,
sVal = Cfg['signatValue'];
if(aib._2chru && !aib.reqCaptcha) {
GM_xmlhttpRequest({
'method': 'GET',
'url': '/' + brd + '/api/requires-captcha',
'onreadystatechange': function(xhr) {
if(xhr.readyState === 4 && xhr.status === 200) {
aib.reqCaptcha = true;
if(JSON.parse(xhr.responseText)['requires-captcha'] === '1') {
$id('captcha_tr').style.display = 'table-row';
$after(this.cap, $new('span', {
'class': 'shortened',
'style': 'margin: 0px 0.5em;',
'text': 'проверить капчу'}, {
'click': function() {
GM_xmlhttpRequest({
'method': 'POST',
'url': '/' + brd + '/api/validate-captcha',
'onreadystatechange': function(str) {
if(str.readyState === 4 && str.status === 200) {
if(JSON.parse(str.responseText)['status'] === 'ok') {
this.innerHTML = 'можно постить';
} else {
this.innerHTML = 'неверная капча';
setTimeout(function() {
this.innerHTML = 'проверить капчу';
}.bind(this), 1000);
}
}
}.bind(this)
})
}
}))
} else {
this.subm.click();
}
}
}.bind(this)
});
$pd(e);
return;
}
if(Cfg['warnSubjTrip'] && this.subj && /#.|##./.test(this.subj.value)) {
$pd(e);
$alert(Lng.subjHasTrip[lang], 'upload', false);
return;
}
if(spells.haveOutreps) {
val = spells.outReplace(val);
}
if(Cfg['userSignat'] && sVal) {
val += '\n' + sVal;
}
if(this.tNum && pByNum[this.tNum].subj === 'Dollchan Extension Tools') {
temp = '\n\n' + this._wrapText(aib.formButtons.bb[5], aib.formButtons.tag[5],
'-'.repeat(50) + '\n' + nav.ua + '\nv' + version);
if(!val.contains(temp)) {
val += temp;
}
}
this.txta.value = val;
if(Cfg['ajaxReply']) {
$alert(Lng.checking[lang], 'upload', true);
}
if(Cfg['favOnReply'] && this.tNum) {
toggleFavorites(pByNum[this.tNum], $c('de-btn-fav', pByNum[this.tNum].btns));
}
if(this.video && (val = this.video.value) && (val = val.match(youTube.ytReg))) {
this.video.value = aib.nul ? val[1] : 'http://www.youtube.com/watch?v=' + val[1];
}
if(this.isQuick) {
$disp(this.pForm);
$disp(this.qArea);
$after(this._pBtn[+this.isTopForm], this.pForm);
}
}.bind(this), false);
$each($Q('input[type="text"], input[type="file"]', this.form), function(node) {
node.size = 30;
});
if(Cfg['noGoto'] && this.gothr) {
$disp(this.gothr);
}
if(Cfg['noPassword'] && this.passw) {
$disp(getAncestor(this.passw, aib.trTag));
}
window.addEventListener('load', function() {
if(Cfg['userName'] && this.name) {
setTimeout(PostForm.setUserName, 1e3);
}
if(this.passw) {
setTimeout(PostForm.setUserPassw, 1e3);
}
}.bind(this), false);
if(this.cap) {
this.capTr = getAncestor(this.cap, aib.trTag);
this.txta.addEventListener('focus', this._captchaInit.bind(this, this.capTr.innerHTML), false);
if(this.file) {
this.file.addEventListener('click', this._captchaInit.bind(this, this.capTr.innerHTML), false);
}
if(!aib.krau) {
$disp(this.capTr);
}
this.capTr.innerHTML = '';
this.cap = null;
}
if(Cfg['ajaxReply'] === 2) {
if(aib.krau) {
this.form.removeAttribute('onsubmit');
}
this.form.onsubmit = function(e) {
$pd(e);
if(aib.krau) {
aib.addProgressTrack.click();
}
new html5Submit(this.form, this.subm, checkUpload);
}.bind(this);
} else if(Cfg['ajaxReply'] === 1) {
this.form.target = 'de-iframe-pform';
this.form.onsubmit = null;
}
if(this.file) {
if('files' in this.file && this.file.files.length > 0) {
this._clearFileInput(getAncestor(this.file, aib.trTag), true);
} else {
PostForm.eventFiles(getAncestor(this.file, aib.trTag));
}
}
},
_setSage: function() {
var c = Cfg['sageReply'];
$id('de-sagebtn').innerHTML = ' ' + (
c ? '<span class="de-btn-sage"></span><b style="color: red;">SAGE</b>' : '<i>(no sage)</i>'
);
if(this.mail.type === 'text') {
this.mail.value = c ? 'sage' : aib.fch ? 'noko' : '';
} else {
this.mail.checked = c;
}
},
_toggleQuickReply: function(tNum) {
if(this.oeForm) {
$q('input[name="oek_parent"], input[name="replyto"]', this.oeForm).value = tNum;
}
if(this.form) {
$q('#thr_id, input[name*="thread"]', this.form).value = tNum;
if(aib.pony) {
$q('input[name="quickreply"]', this.form).value = tNum || '';
}
}
},
_captchaInit: function(html) {
if(this.capInited) {
return
}
this.capTr.innerHTML = html;
this.cap = $q('input[type="text"][name*="aptcha"]:not([name="recaptcha_challenge_field"])', this.capTr);
if(aib.iich || aib.abu) {
$t('td', this.capTr).textContent = 'Капча';
}
if(aib.fch) {
$script('loadRecaptcha()');
}
if(aib.tire) {
$script('show_captcha()');
}
if(aib.krau) {
aib.initCaptcha.click();
$id('captcha_image').setAttribute('onclick', 'requestCaptcha(true);');
}
setTimeout(this._captchaUpd.bind(this), 100);
},
_captchaUpd: function() {
var img, a;
if((this.recap = $id('recaptcha_response_field')) && (img = $id('recaptcha_image'))) {
this.cap = this.recap;
img.setAttribute('onclick', 'Recaptcha.reload()');
img.style.cssText = 'width: 300px; cursor: pointer;';
} else if(aib.fch) {
setTimeout(this._captchaUpd.bind(this), 100);
return;
}
this.capInited = true;
this.cap.autocomplete = 'off';
this.cap.onkeypress = (function() {
var ru = 'йцукенгшщзхъфывапролджэячсмитьбюё',
en = 'qwertyuiop[]asdfghjkl;\'zxcvbnm,.`';
return function(e) {
if(!Cfg['captchaLang'] || e.which === 0) {
return;
}
var i, code = e.charCode || e.keyCode,
chr = String.fromCharCode(code).toLowerCase();
if(Cfg['captchaLang'] === 1) {
if(code < 0x0410 || code > 0x04FF || (i = ru.indexOf(chr)) === -1) {
return;
}
chr = en[i];
} else {
if(code < 0x0021 || code > 0x007A || (i = en.indexOf(chr)) === -1) {
return;
}
chr = ru[i];
}
$pd(e);
$txtInsert(e.target, chr);
};
})();
if(aib.krau) {
return;
}
if(aib.abu || aib.dobr || this.recap || !(img = $q('img', this.capTr))) {
$disp(this.capTr);
return;
}
if(!aib.kus && !aib.tinyIb) {
this._lastCapUpdate = Date.now();
this.cap.onfocus = function() {
if(this._lastCapUpdate && (Date.now() - this._lastCapUpdate > 3e5)) {
this.refreshCapImg(false);
}
}.bind(this);
if(!TNum && this.isQuick) {
this.refreshCapImg(false);
}
}
img.title = Lng.refresh[lang];
img.alt = Lng.loading[lang];
img.style.cssText = 'display: block; border: none; cursor: pointer;';
img.onclick = this.refreshCapImg.bind(this, true);
if((a = img.parentNode).tagName === 'A') {
$after(a, img);
$del(a);
}
$disp(this.capTr);
},
_wrapText: function(isBB, tag, text) {
var m;
if(isBB) {
if(text.contains('\n')) {
return '[' + tag + ']' + text + '[/' + tag + ']';
}
m = text.match(/^(\s*)(.*?)(\s*)$/);
return m[1] + '[' + tag + ']' + m[2] + '[/' + tag + ']' + m[3];
}
for(var rv = '', i = 0, arr = text.split('\n'), len = arr.length; i < len; ++i) {
m = arr[i].match(/^(\s*)(.*?)(\s*)$/);
rv += '\n' + m[1] + (tag === '^H' ? m[2] + '^H'.repeat(m[2].length) :
tag + m[2] + tag) + m[3];
}
return rv.slice(1);
}
}
//============================================================================================================
// IMAGES
//============================================================================================================
function genImgHash(data) {
var i, j, l, c, t, u, g, buf = new Uint8Array(data[0]),
oldw = data[1],
oldh = data[2],
tmp = oldw * oldh,
newh = 8,
neww = 8,
levels = 3,
areas = 256 / levels,
values = 256 / (levels - 1),
hash = 0;
for(i = 0, j = 0; i < tmp; i++, j += 4) {
buf[i] = buf[j] * 0.3 + buf[j + 1] * 0.59 + buf[j + 2] * 0.11;
}
for(i = 0; i < newh; i++) {
for(j = 0; j < neww; j++) {
tmp = i / (newh - 1) * (oldh - 1);
l = Math.min(tmp | 0, oldh - 2);
u = tmp - l;
tmp = j / (neww - 1) * (oldw - 1);
c = Math.min(tmp | 0, oldw - 2);
t = tmp - c;
hash = (hash << 4) + Math.min(values * (((buf[l * oldw + c] * ((1 - t) * (1 - u)) +
buf[l * oldw + c + 1] * (t * (1 - u)) +
buf[(l + 1) * oldw + c + 1] * (t * u) +
buf[(l + 1) * oldw + c] * ((1 - t) * u)) / areas) | 0), 255);
if(g = hash & 0xF0000000) {
hash ^= g >>> 24;
}
hash &= ~g;
}
}
return {hash: hash};
}
function ImageData(post, el, idx) {
this.el = el;
this.idx = idx;
this.post = post;
}
ImageData.prototype = {
expanded: false,
getAdjacentImage: function(toUp) {
var post = this.post,
imgs = post.images;
if(toUp ? this.idx === 0 : this.idx + 1 === imgs.length) {
do {
post = post.getAdjacentVisPost(toUp);
if(!post) {
post = toUp ? lastThr.last : firstThr.op;
if(post.hidden || post.thr.hidden) {
post = post.getAdjacentVisPost(toUp);
}
}
imgs = post.images;
} while(imgs.length === 0);
return imgs[toUp ? imgs.length - 1 : 0];
}
return imgs[toUp ? this.idx - 1 : this.idx + 1];
},
get data() {
var img = this.el,
cnv = this._glob.canvas,
w = cnv.width = img.naturalWidth,
h = cnv.height = img.naturalHeight,
ctx = cnv.getContext('2d');
ctx.drawImage(img, 0, 0);
return [ctx.getImageData(0, 0, w, h).data.buffer, w, h];
},
getHash: function(Fn) {
if(this.hasOwnProperty('hash')) {
Fn(this.hash);
} else {
this.callback = Fn;
if(!this._processing) {
var hash = this._maybeGetHash();
if(hash !== null) {
Fn(hash);
}
}
}
},
get hash() {
var hash;
if(this._processing) {
this._needToHide = true;
} else if(aib.fch || this.el.complete) {
hash = this._maybeGetHash(null);
if(hash !== null) {
return hash;
}
} else {
this.el.onload = this.el.onerror = this._onload.bind(this);
}
this.post.hashImgsBusy++;
return null;
},
get height() {
var dat = aib.getImgSize(this.info);
Object.defineProperties(this, {
'width': { value: dat[0] },
'height': { value: dat[1] }
});
return dat[1];
},
get info() {
var el = $c(aib.cFileInfo, this.wrap),
val = el ? el.textContent : '';
Object.defineProperty(this, 'info', { value: val });
return val;
},
get isImage() {
var val = /\.jpe?g|\.png|\.gif|^blob:/i.test(this.src);
Object.defineProperty(this, 'isImage', { value: val });
return val;
},
get fullSrc() {
var val = aib.getImgLink(this.el).href;
Object.defineProperty(this, 'fullSrc', { value: val });
return val;
},
get src() {
var val = aib.getImgSrc(this.el);
Object.defineProperty(this, 'src', { value: val });
return val;
},
get weight() {
var val = aib.getImgWeight(this.info);
Object.defineProperty(this, 'weight', { value: val });
return val;
},
get width() {
var dat = aib.getImgSize(this.info);
Object.defineProperties(this, {
'width': { value: dat[0] },
'height': { value: dat[1] }
});
return dat[0];
},
get wrap() {
var val = aib.getImgWrap(this.el.parentNode);
Object.defineProperty(this, 'wrap', { value: val });
return val;
},
_glob: {
get canvas() {
var val = doc.createElement('canvas');
Object.defineProperty(this, 'canvas', { value: val });
return val;
},
get storage() {
try {
var val = JSON.parse(sessionStorage['de-imageshash']);
} finally {
if(!val) {
val = {};
}
spells.addCompleteFunc(this._saveStorage.bind(this));
Object.defineProperty(this, 'storage', { value: val });
return val;
}
},
get workers() {
var val = new workerQueue(4, genImgHash, function(e) {});
spells.addCompleteFunc(this._clearWorkers.bind(this));
Object.defineProperty(this, 'workers', { value: val, configurable: true });
return val;
},
_saveStorage: function() {
sessionStorage['de-imageshash'] = JSON.stringify(this.storage);
},
_clearWorkers: function() {
this.workers.clear();
delete this.workers;
},
},
_callback: null,
_processing: false,
_needToHide: false,
_endLoad: function(hash) {
this.post.hashImgsBusy--;
if(this.post.hashHideFun !== null) {
this.post.hashHideFun(hash);
}
},
_maybeGetHash: function() {
var data, val;
if(this.src in this._glob.storage) {
val = this._glob.storage[this.src];
} else if(aib.fch) {
downloadImgData(this.el.src, this._onload4chan.bind(this));
this._callback = null;
return null;
} else if(this.el.naturalWidth + this.el.naturalHeight === 0) {
val = -1;
} else {
data = this.data;
this._glob.workers.run(data, [data[0]], this._wrkEnd.bind(this));
this._callback = null;
return null;
}
Object.defineProperty(this, 'hash', { value: val });
return val;
},
_onload: function() {
var hash = this._maybeGetHash(null);
if(hash !== null) {
this._endLoad(hash);
}
},
_onload4chan: function(maybeData) {
if(maybeData === null) {
Object.defineProperty(this, 'hash', { value: -1 });
this._endLoad(-1);
} else {
var buffer = maybeData.buffer,
data = [buffer, this.el.naturalWidth, this.el.naturalHeight];
this._glob.workers.run(data, [buffer], this._wrkEnd.bind(this));
}
},
_wrkEnd: function(data) {
var hash = data.hash;
Object.defineProperty(this, 'hash', { value: hash });
this._endLoad(hash);
if(this.callback) {
this.callback(hash);
this.callback = null;
}
this._glob.storage[this.src] = hash;
}
}
function ImageMover(img) {
this.el = img;
this.elStyle = img.style;
img.addEventListener(nav.Firefox ? 'DOMMouseScroll' : 'mousewheel', this, false);
img.addEventListener('mousedown', this, false);
}
ImageMover.prototype = {
curX: 0,
curY: 0,
moved: false,
handleEvent: function(e) {
switch(e.type) {
case 'mousedown':
this.curX = e.clientX - parseInt(this.elStyle.left, 10);
this.curY = e.clientY - parseInt(this.elStyle.top, 10);
doc.body.addEventListener('mousemove', this, false);
doc.body.addEventListener('mouseup', this, false);
break;
case 'mousemove':
this.elStyle.left = e.clientX - this.curX + 'px';
this.elStyle.top = e.clientY - this.curY + 'px';
this.moved = true;
return;
case 'mouseup':
doc.body.removeEventListener('mousemove', this, false);
doc.body.removeEventListener('mouseup', this, false);
return;
default: // wheel event
var curX = e.clientX,
curY = e.clientY,
oldL = parseInt(this.elStyle.left, 10),
oldT = parseInt(this.elStyle.top, 10),
oldW = parseFloat(this.elStyle.width || this.el.width),
oldH = parseFloat(this.elStyle.height || this.el.height),
d = nav.Firefox ? -e.detail : e.wheelDelta,
newW = oldW * (d > 0 ? 1.25 : 0.8),
newH = oldH * (d > 0 ? 1.25 : 0.8);
this.elStyle.width = newW + 'px';
this.elStyle.height = newH + 'px';
this.elStyle.left = parseInt(curX - (newW/oldW) * (curX - oldL), 10) + 'px';
this.elStyle.top = parseInt(curY - (newH/oldH) * (curY - oldT), 10) + 'px';
}
$pd(e);
}
};
function addImagesSearch(el) {
for(var link, i = 0, els = $Q(aib.qImgLink, el), len = els.length; i < len; i++) {
link = els[i];
if(/google\.|tineye\.com|iqdb\.org/.test(link.href)) {
$del(link);
continue;
}
if(link.firstElementChild) {
continue;
}
link.insertAdjacentHTML('beforebegin', '<span class="de-btn-src"></span>');
}
}
function embedImagesLinks(el) {
for(var a, link, i = 0, els = $Q(aib.qMsgImgLink, el); link = els[i++];) {
if(link.parentNode.tagName === 'SMALL') {
return;
}
a = link.cloneNode(false);
a.target = '_blank';
a.innerHTML = '<img class="de-img-pre" src="' + a.href + '">';
$before(link, a);
}
}
//============================================================================================================
// POST
//============================================================================================================
function Post(el, thr, num, count, isOp, prev) {
var h, ref, html;
this.count = count;
this.el = el;
this.isOp = isOp;
this.num = num;
this._pref = ref = $q(aib.qRef, el);
this.prev = prev;
this.thr = thr;
if(prev) {
prev.next = this;
}
el.post = this;
html = '<span class="de-ppanel ' + (isOp ? '' : 'de-ppanel-cnt') +
'"><span class="de-btn-hide"></span><span class="de-btn-rep"></span>';
if(isOp) {
if(!TNum && !aib.arch) {
html += '<span class="de-btn-expthr"></span>';
}
h = aib.host;
if(Favor[h] && Favor[h][brd] && Favor[h][brd][num]) {
html += '<span class="de-btn-fav-sel"></span>';
Favor[h][brd][num]['cnt'] = thr.pcount;
} else {
html += '<span class="de-btn-fav"></span>';
}
}
ref.insertAdjacentHTML('afterend', html + (
this.sage ? '<span class="de-btn-sage" title="SAGE"></span>' : ''
) + '</span>');
this.btns = ref.nextSibling;
if(Cfg['expandPosts'] === 1 && this.trunc) {
this._getFull(this.trunc, true);
}
el.addEventListener('click', this, true);
el.addEventListener('mouseover', this, true);
el.addEventListener('mouseout', this, true);
}
Post.hiddenNums = [];
Post.getWrds = function(text) {
return text.replace(/\s+/g, ' ').replace(/[^a-zа-яё ]/ig, '').substring(0, 800).split(' ');
};
Post.findSameText = function(oNum, oHid, oWords, date, post) {
var j, words = Post.getWrds(post.text),
len = words.length,
i = oWords.length,
olen = i,
_olen = i,
n = 0;
if(len < olen * 0.4 || len > olen * 3) {
return;
}
while(i--) {
if(olen > 6 && oWords[i].length < 3) {
_olen--;
continue;
}
j = len;
while(j--) {
if(words[j] === oWords[i] || oWords[i].match(/>>\d+/) && words[j].match(/>>\d+/)) {
n++;
}
}
}
if(n < _olen * 0.4 || len > _olen * 3) {
return;
}
if(oHid) {
post.note = '';
if(!post.spellHidden) {
post.setVisib(false);
}
if(post.userToggled) {
delete uVis[post.num];
post.userToggled = false;
}
} else {
post.setUserVisib(true, date, true);
post.note = 'similar to >>' + oNum;
}
return false;
};
Post.sizing = {
get wHeight() {
var val = window.innerHeight;
if(!this._enabled) {
window.addEventListener('resize', this, false);
this._enabled = true;
}
Object.defineProperty(this, 'wHeight', { writable: true, value: val });
return val;
},
get wWidth() {
var val = doc.documentElement.clientWidth;
if(!this._enabled) {
window.addEventListener('resize', this, false);
this._enabled = true;
}
Object.defineProperty(this, 'wWidth', { writable: true, value: val });
return val;
},
getOffset: function(el) {
return el.getBoundingClientRect().left + window.pageXOffset;
},
getCachedOffset: function(pCount, el) {
if(pCount === 0) {
return this._opOffset === -1 ? this._opOffset = this.getOffset(el) : this._opOffset;
}
if(pCount > 4) {
return this._pOffset === -1 ? this._pOffset = this.getOffset(el) : this._pOffset;
}
return this.getOffset(el);
},
handleEvent: function() {
this.wHeight = window.innerHeight;
this.wWidth = doc.documentElement.clientWidth;
},
_enabled: false,
_opOffset: -1,
_pOffset: -1
};
Post.prototype = {
banned: false,
deleted: false,
hasRef: false,
hasYTube: false,
hidden: false,
hashHideFun: null,
hashImgsBusy: 0,
imagesExpanded: false,
inited: true,
kid: null,
next: null,
omitted: false,
parent: null,
prev: null,
spellHidden: false,
userToggled: false,
viewed: false,
ytHideFun: null,
ytInfo: null,
ytLinksLoading: 0,
addFuncs: function() {
updRefMap(this, true);
embedMP3Links(this);
if(Cfg['addImgs']) {
embedImagesLinks(this.el);
}
if(isExpImg) {
this.toggleImages(true);
}
},
handleEvent: function(e) {
var temp, el = e.target,
type = e.type;
if(type === 'click') {
if(e.button !== 0) {
return;
}
switch(el.tagName) {
case 'IMG':
if(el.classList.contains('de-video-thumb')) {
if(Cfg['addYouTube'] === 3) {
this.ytLink.classList.add('de-current');
youTube.addPlayer(this.ytObj, this.ytInfo, el.classList.contains('de-ytube'));
$pd(e);
}
} else if(Cfg['expandImgs'] !== 0) {
this._clickImage(el, e);
}
return;
case 'A':
if(el.classList.contains('de-video-link')) {
var m = el.ytInfo;
if(this.ytInfo === m) {
if(Cfg['addYouTube'] === 3) {
if($c('de-video-thumb', this.ytObj)) {
el.classList.add('de-current');
youTube.addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
} else {
el.classList.remove('de-current');
youTube.addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
}
} else {
el.classList.remove('de-current');
this.ytObj.innerHTML = '';
this.ytInfo = null;
}
} else if(Cfg['addYouTube'] > 2) {
this.ytLink.classList.remove('de-current');
this.ytLink = el;
youTube.addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
} else {
this.ytLink.classList.remove('de-current');
this.ytLink = el;
el.classList.add('de-current');
youTube.addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
}
$pd(e);
} else {
temp = el.parentNode;
if(temp === this.trunc) {
this._getFull(temp, false);
$pd(e);
e.stopPropagation();
} else if(Cfg['insertNum'] && pr.form && temp === this._pref &&
!/Reply|Ответ/.test(el.textContent))
{
if(TNum && Cfg['addPostForm'] > 1 && !pr.isQuick) {
pr.showQuickReply(this, this.num, true);
} else {
if(aib._420 && pr.txta.value === 'Comment') {
pr.txta.value = '';
}
$txtInsert(pr.txta, '>>' + this.num);
}
$pd(e);
e.stopPropagation();
}
}
return;
}
switch(el.className) {
case 'de-btn-expthr':
this.thr.load(1, false, null);
$del(this._menu);
this._menu = null;
return;
case 'de-btn-fav':
case 'de-btn-fav-sel':
toggleFavorites(this, el);
return;
case 'de-btn-hide':
case 'de-btn-hide-user':
if(this._isPview) {
pByNum[this.num].toggleUserVisib();
this.btns.firstChild.className = 'de-btn-hide-user';
if(pByNum[this.num].hidden) {
this.btns.classList.add('de-post-hid');
} else {
this.btns.classList.remove('de-post-hid');
}
} else {
this.toggleUserVisib();
}
$del(this._menu);
this._menu = null;
return;
case 'de-btn-rep':
pr.showQuickReply(this._isPview ? this.getTopParent() : this, this.num, !this._isPview);
return;
case 'de-btn-sage':
addSpell(9, '', false);
return;
}
if(el.classList[0] === 'de-menu-item') {
this._clickMenu(el);
}
return;
}
switch(el.classList[0]) {
case 'de-reflink':
case 'de-preflink':
if(Cfg['linksNavig']) {
if(type === 'mouseover') {
clearTimeout(Pview.delTO);
this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']);
} else {
this._eventRefLinkOut(e);
}
$pd(e);
e.stopPropagation();
}
return;
case 'de-btn-hide':
case 'de-btn-hide-user':
if(type === 'mouseover') {
this._menuDelay = setTimeout(this._addMenu.bind(this, el, 'hide'), Cfg['linksOver']);
} else {
this._closeMenu(e.relatedTarget);
}
return;
case 'de-btn-rep':
if(type === 'mouseover') {
quotetxt = $txtSelect();
}
return;
case 'de-btn-expthr':
if(type === 'mouseover') {
this._menuDelay = setTimeout(this._addMenu.bind(this, el, 'expand'), Cfg['linksOver']);
} else {
this._closeMenu(e.relatedTarget);
}
return;
case 'de-btn-src':
if(type === 'mouseover') {
this._menuDelay = setTimeout(this._addMenu.bind(this, el, 'imgsrc'), Cfg['linksOver']);
} else {
this._closeMenu(e.relatedTarget);
}
break;
case 'de-menu':
case 'de-menu-item':
if(type === 'mouseover') {
clearTimeout(this._menuDelay);
} else {
this._closeMenu(e.relatedTarget);
}
return;
}
if(Cfg['linksNavig'] && el.tagName === 'A' && !el.lchecked) {
if(el.textContent.startsWith('>>')) {
el.className = 'de-preflink ' + el.className;
clearTimeout(Pview.delTO);
this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']);
$pd(e);
e.stopPropagation();
} else {
el.lchecked = true;
}
return;
}
if(this._isPview) {
if(type === 'mouseout') {
temp = e.relatedTarget;
if(Pview.top && (!temp || (!Pview.getPview(temp) && !temp.classList.contains('de-imgmenu')))) {
Pview.top.markToDel();
}
} else {
temp = Pview.getPview(e.relatedTarget);
if(!temp || temp.post !== this) {
if(this.kid) {
this.kid.markToDel();
} else {
clearTimeout(Pview.delTO);
}
}
}
}
},
hideRefs: function() {
if(!Cfg['hideRefPsts'] || !this.hasRef) {
return;
}
this.ref.forEach(function(num) {
var pst = pByNum[num];
if(pst && !pst.userToggled) {
pst.setVisib(true);
pst.note = 'reference to >>' + this.num;
pst.hideRefs();
}
}, this);
},
getAdjacentVisPost: function(toUp) {
var post = toUp ? this.prev : this.next;
while(post) {
if(post.thr.hidden) {
post = toUp ? post.thr.op.prev : post.thr.last.next;
} else if(post.hidden || post.omitted) {
post = toUp ? post.prev : post.next
} else {
return post;
}
}
return null;
},
get html() {
var val = this.el.innerHTML;
Object.defineProperty(this, 'html', { configurable: true, value: val });
return val;
},
get images() {
var i, len, el, els = getImages(this.el),
imgs = [];
for(i = 0, len = els.length; i < len; i++) {
el = els[i];
el.imgIdx = i;
imgs[i] = new ImageData(this, el, i);
}
Object.defineProperty(this, 'images', { value: imgs });
return imgs;
},
get mp3Obj() {
var val = $new('div', {'class': 'de-mp3'}, null);
$before(this.msg, val);
Object.defineProperty(this, 'mp3Obj', { value: val });
return val;
},
get msg() {
var val = $q(aib.qMsg, this.el);
Object.defineProperty(this, 'msg', { configurable: true, value: val });
return val;
},
get nextInThread() {
var post = this.next;
return !post || post.count === 0 ? null : post;
},
get nextNotDeleted() {
var post = this.nextInThread;
while(post && post.deleted) {
post = post.nextInThread;
}
return post;
},
set note(val) {
if(this.isOp) {
this.noteEl.textContent = val ? '(autohide: ' + val + ')' : '(' + this.title + ')';
} else if(!Cfg['delHiddPost']) {
this.noteEl.textContent = val ? 'autohide: ' + val : '';
}
},
get noteEl() {
var val;
if(this.isOp) {
val = this.thr.el.previousElementSibling.lastChild;
} else {
this.btns.insertAdjacentHTML('beforeend', '<span class="de-post-note"></span>');
val = this.btns.lastChild;
}
Object.defineProperty(this, 'noteEl', { value: val });
return val;
},
get posterName() {
var pName = $q(aib.qName, this.el), val = pName ? pName.textContent : '';
Object.defineProperty(this, 'posterName', { value: val });
return val;
},
get posterTrip() {
var pTrip = $c(aib.cTrip, this.el), val = pTrip ? pTrip.textContent : '';
Object.defineProperty(this, 'posterTrip', { value: val });
return val;
},
get ref() {
var val = [];
Object.defineProperty(this, 'ref', { configurable: true, value: val });
return val;
},
get sage() {
var val = aib.getSage(this.el);
Object.defineProperty(this, 'sage', { value: val });
return val;
},
select: function() {
if(this.isOp) {
if(this.hidden) {
this.thr.el.previousElementSibling.classList.add('de-selected');
}
this.thr.el.classList.add('de-selected');
} else {
this.el.classList.add('de-selected');
}
},
setUserVisib: function(hide, date, sync) {
this.setVisib(hide);
this.btns.firstChild.className = 'de-btn-hide-user';
this.userToggled = true;
if(hide) {
this.note = '';
this.hideRefs();
} else {
this.unhideRefs();
}
uVis[this.num] = [+!hide, date];
if(sync) {
localStorage['__de-post'] = JSON.stringify({
'brd': brd,
'date': date,
'isOp': this.isOp,
'num': this.num,
'hide': hide,
'title': this.isOp ? this.title : ''
});
localStorage.removeItem('__de-post');
}
},
setVisib: function(hide) {
var el, tEl;
if(this.hidden === hide) {
return;
}
if(this.isOp) {
this.hidden = this.thr.hidden = hide;
tEl = this.thr.el;
tEl.style.display = hide ? 'none' : '';
el = $id('de-thr-hid-' + this.num);
if(el) {
el.style.display = hide ? '' : 'none';
} else {
tEl.insertAdjacentHTML('beforebegin', '<div class="' + aib.cReply +
' de-thr-hid" id="de-thr-hid-' + this.num + '">' + Lng.hiddenThrd[lang] +
' <a href="#">№' + this.num + '</a> <span class="de-thread-note"></span></div>');
el = $t('a', tEl.previousSibling);
el.onclick = el.onmouseover = el.onmouseout = function(e) {
switch(e.type) {
case 'click':
this.toggleUserVisib();
$pd(e);
return;
case 'mouseover': this.thr.el.style.display = ''; return;
default: // mouseout
if(this.hidden) {
this.thr.el.style.display = 'none';
}
}
}.bind(this);
}
return;
}
if(Cfg['delHiddPost']) {
if(hide) {
this.wrap.classList.add('de-hidden');
this.wrap.insertAdjacentHTML('beforebegin',
'<span style="counter-increment: de-cnt 1;"></span>');
} else if(this.hidden) {
this.wrap.classList.remove('de-hidden');
$del(this.wrap.previousSibling);
}
} else {
if(!hide) {
this.note = '';
}
this._pref.onmouseover = this._pref.onmouseout = hide && function(e) {
this.toggleContent(e.type === 'mouseout');
}.bind(this);
}
this.hidden = hide;
this.toggleContent(hide);
if(Cfg['strikeHidd']) {
setTimeout(this._strikePostNum.bind(this, hide), 50);
}
},
spellHide: function(note) {
this.spellHidden = true;
if(!this.userToggled) {
if(TNum && !this.deleted) {
sVis[this.count] = 0;
}
if(!this.hidden) {
this.hideRefs();
}
this.setVisib(true);
this.note = note;
}
},
spellUnhide: function() {
this.spellHidden = false;
if(!this.userToggled) {
if(TNum && !this.deleted) {
sVis[this.count] = 1;
}
this.setVisib(false);
this.unhideRefs();
}
},
get subj() {
var subj = $c(aib.cSubj, this.el), val = subj ? subj.textContent : '';
Object.defineProperty(this, 'subj', { value: val });
return val;
},
get text() {
var val = this.msg.innerHTML
.replace(/<\/?(?:br|p|li)[^>]*?>/gi,'\n')
.replace(/<[^>]+?>/g,'')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/ /g, '\u00A0')
.trim();
Object.defineProperty(this, 'text', { configurable: true, value: val });
return val;
},
get title() {
var val = this.subj || this.text.substring(0, 70).replace(/\s+/g, ' ')
Object.defineProperty(this, 'title', { value: val });
return val;
},
get tNum() {
return this.thr.num;
},
toggleContent: function(hide) {
if(hide) {
this.el.classList.add('de-post-hid');
} else {
this.el.classList.remove('de-post-hid');
}
},
toggleImages: function(expand) {
var i, dat;
for(var dat, i = 0, imgs = this.images, len = imgs.length; i < len; ++i) {
dat = imgs[i];
if(dat.isImage && (dat.expanded ^ expand)) {
if(expand) {
this._addFullImage(dat.el, dat, true);
} else {
this._removeFullImage(null, dat.el.nextSibling, dat.el, dat);
}
}
}
this.imagesExpanded = expand;
},
toggleUserVisib: function() {
var isOp = this.isOp,
hide = !this.hidden,
date = Date.now();
this.setUserVisib(hide, date, true);
if(isOp) {
if(hide) {
hThr[brd][this.num] = this.title;
} else {
delete hThr[brd][this.num];
}
saveHiddenThreads(false);
}
saveUserPosts();
},
get topCoord() {
var el = this.isOp && this.hidden ? this.thr.el.previousElementSibling : this.el;
return el.getBoundingClientRect().top;
},
get trunc() {
var el = $q(aib.qTrunc, this.el), val = null;
if(el && /long|full comment|gekürzt|слишком|длинн|мног|полная версия/i.test(el.textContent)) {
val = el;
}
Object.defineProperty(this, 'trunc', { configurable: true, value: val });
return val;
},
unhideRefs: function() {
if(!Cfg['hideRefPsts'] || !this.hasRef) {
return;
}
this.ref.forEach(function(num) {
var pst = pByNum[num];
if(pst && pst.hidden && !pst.userToggled && !pst.spellHidden) {
pst.setVisib(false);
pst.unhideRefs();
}
});
},
unselect: function() {
if(this.isOp) {
var el = $id('de-thr-hid-' + this.num);
if(el) {
el.classList.remove('de-selected');
}
this.thr.el.classList.remove('de-selected');
} else {
this.el.classList.remove('de-selected');
}
},
updateMsg: function(newMsg) {
var origMsg = aib.dobr ? this.msg.firstElementChild : this.msg,
ytExt = $c('de-video-ext', origMsg),
ytLinks = $Q(':not(.de-video-ext) > .de-video-link', origMsg);
origMsg.parentNode.replaceChild(newMsg, origMsg);
Object.defineProperties(this, {
'msg': { configurable: true, value: newMsg },
'trunc': { configurable: true, value: null }
});
delete this.html;
delete this.text;
youTube.updatePost(this, ytLinks, $Q('a[href*="youtu"]', newMsg), false);
if(ytExt) {
newMsg.appendChild(ytExt);
}
this.addFuncs();
spells.check(this);
closeAlert($id('de-alert-load-fullmsg'));
},
get wrap() {
var val = aib.getWrap(this.el, this.isOp);
Object.defineProperty(this, 'wrap', { value: val });
return val;
},
get ytData() {
var val = [];
Object.defineProperty(this, 'ytData', { value: val });
return val;
},
get ytObj() {
var msg, prev, val = $new('div', {'class': 'de-video-obj'}, null);
if(aib.krau) {
msg = this.msg.parentNode;
prev = msg.previousElementSibling;
$before(prev.hasAttribute('style') ? prev : msg, val);
} else {
$before(this.msg, val);
}
Object.defineProperty(this, 'ytObj', { value: val });
return val;
},
_isPview: false,
_linkDelay: 0,
_menu: null,
_menuDelay: 0,
_pref: null,
_selRange: null,
_selText: '',
_addFullImage: function(el, data, inPost) {
var elMove, elStop, newW, newH, scrH, img, scrW = Post.sizing.wWidth;
if(inPost) {
(aib.hasPicWrap ? data.wrap : el.parentNode).insertAdjacentHTML('afterend',
'<div class="de-after-fimg"></div>');
scrW -= this._isPview ? Post.sizing.getOffset(el) : Post.sizing.getCachedOffset(this.count, el);
el.style.display = 'none';
} else {
$del($c('de-img-center', doc));
}
newW = !Cfg['resizeImgs'] || data.width < scrW ? data.width : scrW - 5;
newH = newW * data.height / data.width;
if(inPost) {
data.expanded = true;
} else {
scrH = Post.sizing.wHeight;
if(Cfg['resizeImgs'] && newH > scrH) {
newH = scrH - 2;
newW = newH * data.width / data.height;
}
}
img = $add('<img class="de-img-full" src="' + data.fullSrc + '" alt="' + data.fullSrc +
'" width="' + newW + '" height="' + newH + '">');
img.onload = img.onerror = function(e) {
if(this.naturalHeight + this.naturalWidth === 0 && !this.onceLoaded) {
this.src = this.src;
this.onceLoaded = true;
}
};
$after(el, img);
if(!inPost) {
img.classList.add('de-img-center');
img.style.cssText = 'left: ' + ((scrW - newW) / 2 - 1) +
'px; top: ' + ((scrH - newH) / 2 - 1) + 'px;';
img.mover = new ImageMover(img);
if(this._isPview) {
$id('de-img-btns').style.display = 'none';
} else {
$id('de-img-btn-next').onclick = this._navigateImages.bind(this, true);
$id('de-img-btn-prev').onclick = this._navigateImages.bind(this, false);
if ($id('de-img-btns').style.display) {
var btns = $id('de-img-btns');
btns.style.display = '';
btns.style.opacity = 0;
_setFadeOutDelay = function() {
clearTimeout(btns._fadeOutDelay);
btns._fadeOutDelay = setTimeout(function() {
clearInterval(btns._fadeOut);
btns._fadeOut = setInterval(function() {
if(+btns.style.opacity > 0) {
btns.style.opacity = +btns.style.opacity - 0.05;
} else {
clearInterval(btns._fadeOut);
}
}, 25);
}, 2000);
}
window.addEventListener('mousemove', btns._imgBtnsFade = function() {
if(!btns._fadeIn && !btns._isOverBtns) {
clearTimeout(btns._fadeOutDelay);
clearInterval(btns._fadeOut);
btns._fadeIn = setInterval(function() {
if(+btns.style.opacity < 1) {
btns.style.opacity =+ btns.style.opacity + 0.05;
} else {
clearInterval(btns._fadeIn); btns._fadeIn = 0;
_setFadeOutDelay();
}
}, 25);
}
}, false);
btns.addEventListener('mouseover', btns._imgBtnsOverCheck = function() {
if(!btns._overChecker) {
this.style.opacity = 1;
btns._overChecker = setInterval(function() {
if(btns.parentElement.querySelector(':hover') === btns) {
clearTimeout(btns._fadeOutDelay);
btns._isOverBtns = true;
} else {
clearInterval(btns._overChecker); btns._overChecker = 0;
btns._isOverBtns = false;
_setFadeOutDelay();
}
}, 100);
}
}, false)
}
}
}
},
_addMenu: function(el, type) {
var html, cr = el.getBoundingClientRect(),
isLeft = false,
className = 'de-menu ' + aib.cReply,
xOffset = window.pageXOffset;
switch(type) {
case 'hide':
if(!Cfg['menuHiddBtn']) {
return;
}
html = this._addMenuHide();
break;
case 'expand':
html = '<span class="de-menu-item" info="thr-exp">' + Lng.selExpandThrd[lang]
.join('</span><span class="de-menu-item" info="thr-exp">') + '</span>';
break;
case 'imgsrc':
isLeft = true;
className += ' de-imgmenu';
html = this._addMenuImgSrc(el);
break;
}
doc.body.insertAdjacentHTML('beforeend', '<div class="' + className +
'" style="position: absolute; ' + (
isLeft ? 'left: ' + (cr.left + xOffset) :
'right: ' + (doc.documentElement.clientWidth - cr.right - xOffset)
) + 'px; top: ' + (window.pageYOffset + cr.bottom) + 'px;">' + html + '</div>');
if(this._menu) {
clearTimeout(this._menuDelay);
$del(this._menu);
}
this._menu = doc.body.lastChild;
this._menu.addEventListener('click', this, false);
this._menu.addEventListener('mouseover', this, false);
this._menu.addEventListener('mouseout', this, false);
},
_addMenuHide: function() {
var sel, ssel, str = '', addItem = function(name) {
str += '<span info="spell-' + name + '" class="de-menu-item">' +
Lng.selHiderMenu[name][lang] + '</span>';
};
sel = nav.Opera ? doc.getSelection() : window.getSelection();
if(ssel = sel.toString()) {
this._selText = ssel;
this._selRange = sel.getRangeAt(0);
addItem('sel');
}
if(this.posterName) {
addItem('name');
}
if(this.posterTrip) {
addItem('trip');
}
if(this.images.length === 0) {
addItem('noimg');
} else {
addItem('img');
addItem('ihash');
}
if(this.text) {
addItem('text');
} else {
addItem('notext');
}
return str;
},
_addMenuImgSrc: function(el) {
var p = el.nextSibling.href + '" target="_blank">' + Lng.search[lang],
c = doc.body.getAttribute('de-image-search'),
str = '';
if(c) {
c = c.split(';');
c.forEach(function(el) {
var info = el.split(',');
str += '<a class="de-src' + info[0] + (!info[1] ?
'" onclick="de_isearch(event, \'' + info[0] + '\')" de-url="' :
'" href="' + info[1]
) + p + info[0] + '</a>';
});
}
return '<a class="de-menu-item de-imgmenu de-src-iqdb" href="http://iqdb.org/?url=' + p + 'IQDB</a>' +
'<a class="de-menu-item de-imgmenu de-src-tineye" href="http://tineye.com/search/?url=' + p + 'TinEye</a>' +
'<a class="de-menu-item de-imgmenu de-src-google" href="http://google.com/searchbyimage?image_url=' + p + 'Google</a>' +
'<a class="de-menu-item de-imgmenu de-src-saucenao" href="http://saucenao.com/search.php?url=' + p + 'SauceNAO</a>' + str;
},
_addPview: function(link) {
var tNum = (link.pathname.match(/.+?\/[^\d]*(\d+)/) || [,0])[1],
pNum = (link.textContent.trim().match(/\d+$/) || [tNum])[0],
pv = this._isPview ? this.kid : Pview.top;
if(pv && pv.num === pNum) {
Pview.del(pv.kid);
setPviewPosition(link, pv.el, Cfg['animation'] && animPVMove);
if(pv.parent.num !== this.num) {
$each($C('de-pview-link', pv.el), function(el) {
el.classList.remove('de-pview-link');
});
pv._markLink(this.num);
}
this.kid = pv;
pv.parent = this;
} else {
this.kid = new Pview(this, link, tNum, pNum);
}
},
_clickImage: function(el, e) {
var data, iEl, mover, inPost = (Cfg['expandImgs'] === 1) ^ e.ctrlKey;
var clearBtns = function() {
var btns = $id('de-img-btns');
btns.style.display = 'none';
window.removeEventListener('mousemove', btns._imgBtnsFade, false);
btns.removeEventListener('mouseover', btns._imgBtnsOverCheck, false);
clearInterval(btns._fadeIn); btns._fadeIn = 0;
clearInterval(btns._fadeOut);
clearTimeout(btns._fadeOutDelay);
clearInterval(btns._overChecker); btns._overChecker = 0;
}
switch(el.className) {
case 'de-img-full de-img-center':
mover = el.mover;
if(mover.moved) {
mover.moved = false;
break;
}
el.mover = null;
case 'de-img-full':
iEl = el.previousSibling;
this._removeFullImage(e, el, iEl, this.images[iEl.imgIdx] || iEl.data);
clearBtns();
break;
case 'de-img-pre':
if(!(data = el.data)) {
iEl = new Image();
iEl.src = el.src;
data = el.data = {
expanded: false,
isImage: true,
width: iEl.width,
height: iEl.height,
fullSrc: el.src
};
}
break;
case 'thumb':
case 'ca_thumb':
data = this.images[el.imgIdx];
break;
default:
if(!/thumb|\/spoiler|^blob:/i.test(el.src)) {
return;
}
data = this.images[el.imgIdx];
}
if(data && data.isImage) {
if(!inPost && (iEl = $c('de-img-center', el.parentNode))) {
$del(iEl);
clearBtns();
} else {
this._addFullImage(el, data, inPost);
}
}
$pd(e);
e.stopPropagation();
return;
},
_clickMenu: function(el) {
$del(this._menu);
this._menu = null;
switch(el.getAttribute('info')) {
case 'spell-sel':
var start = this._selRange.startContainer,
end = this._selRange.endContainer;
if(start.nodeType === 3) {
start = start.parentNode;
}
if(end.nodeType === 3) {
end = end.parentNode;
}
if((nav.matchesSelector(start, aib.qMsg + ' *') && nav.matchesSelector(end, aib.qMsg + ' *')) ||
(nav.matchesSelector(start, '.' + aib.cSubj) && nav.matchesSelector(end, '.' + aib.cSubj))
) {
if(this._selText.contains('\n')) {
addSpell(1 /* #exp */, '/' +
regQuote(this._selText).replace(/\r?\n/g, '\\n') + '/', false);
} else {
addSpell(0 /* #words */, this._selText.replace(/\)/g, '\\)').toLowerCase(), false);
}
} else {
dummy.innerHTML = '';
dummy.appendChild(this._selRange.cloneContents());
addSpell(2 /* #exph */, '/' +
regQuote(dummy.innerHTML.replace(/^<[^>]+>|<[^>]+>$/g, '')) + '/', false);
}
return;
case 'spell-name': addSpell(6 /* #name */, this.posterName.replace(/\)/g, '\\)'), false); return;
case 'spell-trip': addSpell(7 /* #trip */, this.posterTrip.replace(/\)/g, '\\)'), false); return;
case 'spell-img':
var img = this.images[0],
w = img.weight,
wi = img.width,
h = img.height;
addSpell(8 /* #img */, [0, [w, w], [wi, wi, h, h]], false);
return;
case 'spell-ihash':
this.images[0].getHash(function(hash) {
addSpell(4 /* #ihash */, hash, false);
});
return;
case 'spell-noimg': addSpell(0x108 /* (#all & !#img) */, '', true); return;
case 'spell-text':
var num = this.num,
hidden = this.hidden,
wrds = Post.getWrds(this.text),
time = Date.now();
for(var post = firstThr.op; post; post = post.next) {
Post.findSameText(num, hidden, wrds, time, post);
}
saveUserPosts();
return;
case 'spell-notext': addSpell(0x10B /* (#all & !#tlen) */, '', true); return;
case 'thr-exp': this.thr.load(parseInt(el.textContent, 10), false, null); return;
}
},
_closeMenu: function(rt) {
clearTimeout(this._menuDelay);
if(this._menu && (!rt || rt.className !== 'de-menu-item')) {
this._menuDelay = setTimeout(function() {
$del(this._menu);
this._menu = null;
}.bind(this), 75);
}
},
_eventRefLinkOut: function(e) {
var rt = e.relatedTarget,
pv = Pview.getPview(rt);
clearTimeout(this._linkDelay);
if(!rt || !pv) {
if(Pview.top) {
Pview.top.markToDel();
}
} else if(pv.post === this && this.kid && rt.className !== 'de-reflink') {
this.kid.markToDel();
}
},
_getFull: function(node, isInit) {
if(aib.dobr) {
$del(node.nextSibling);
$del(node.previousSibling);
$del(node);
if(isInit) {
this.msg.replaceChild($q('.alternate > div', this.el), this.msg.firstElementChild);
} else {
this.updateMsg($q('.alternate > div', this.el));
}
return;
}
if(!isInit) {
$alert(Lng.loading[lang], 'load-fullmsg', true);
}
ajaxLoad(aib.getThrdUrl(brd, this.tNum), true, function(node, form, xhr) {
if(this.isOp) {
this.updateMsg(replacePost($q(aib.qMsg, form)));
$del(node);
} else {
for(var i = 0, els = aib.getPosts(form), len = els.length; i < len; i++) {
if(this.num === aib.getPNum(els[i])) {
this.updateMsg(replacePost($q(aib.qMsg, els[i])));
$del(node);
return;
}
}
}
}.bind(this, node), null);
},
_markLink: function(pNum) {
$each($Q('a[href*="' + pNum + '"]', this.el), function(num, el) {
if(el.textContent === '>>' + num) {
el.classList.add('de-pview-link');
}
}.bind(null, pNum));
},
_navigateImages: function(isNext) {
var el = $c('de-img-full', doc),
iEl = el.previousSibling,
data = this.images[iEl.imgIdx];
this._removeFullImage(null, el, iEl, data);
data = data.getAdjacentImage(!isNext);
data.post._addFullImage(data.el, data, false);
},
_removeFullImage: function(e, full, thumb, data) {
var pv, cr, x, y, inPost = data.expanded;
data.expanded = false;
if(nav.Firefox && this._isPview) {
cr = this.el.getBoundingClientRect();
x = e.pageX;
y = e.pageY;
if(!inPost) {
pv = this;
while(x > cr.right || x < cr.left || y > cr.bottom || y < cr.top) {
if(pv = pv.parent) {
cr = pv.el.getBoundingClientRect();
} else {
if(Pview.top) {
Pview.top.markToDel();
}
$del(full);
return;
}
}
if(pv.kid) {
pv.kid.markToDel();
}
} else if(x > cr.right || y > cr.bottom && Pview.top) {
Pview.top.markToDel();
}
}
$del(full);
if(inPost) {
thumb.style.display = '';
$del((aib.hasPicWrap ? data.wrap : thumb.parentNode).nextSibling);
}
},
_strikePostNum: function(isHide) {
var idx, num = this.num;
if(isHide) {
Post.hiddenNums.push(+num);
} else {
idx = Post.hiddenNums.indexOf(+num);
if(idx !== -1) {
Post.hiddenNums.splice(idx, 1);
}
}
$each($Q('a[href*="#' + num + '"]', dForm), isHide ? function(el) {
el.classList.add('de-ref-hid');
} : function(el) {
el.classList.remove('de-ref-hid');
});
}
}
//============================================================================================================
// PREVIEW
//============================================================================================================
function Pview(parent, link, tNum, pNum) {
var b, post = pByNum[pNum];
if(Cfg['noNavigHidd'] && post && post.hidden) {
return;
}
this.parent = parent;
this._link = link;
this.num = pNum;
Object.defineProperty(this, 'tNum', { value: tNum });
if(post && (!post.isOp || !parent._isPview || !parent._loaded)) {
this._showPost(post);
return;
}
b = link.pathname.match(/^\/?(.+\/)/)[1].replace(aib.res, '').replace(/\/$/, '');
if(post = this._cache && this._cache[b + tNum] && this._cache[b + tNum].getPost(pNum)) {
this._loaded = true;
this._showPost(post);
} else {
this._showText('<span class="de-wait">' + Lng.loading[lang] + '</span>');
ajaxLoad(aib.getThrdUrl(b, tNum), true, this._onload.bind(this, b), this._onerror.bind(this));
}
}
Pview.clearCache = function() {
Pview.prototype._cache = {};
};
Pview.del = function(pv) {
var el;
if(!pv) {
return;
}
pv.parent.kid = null;
if(!pv.parent._isPview) {
Pview.top = null;
}
do {
clearTimeout(pv._readDelay);
el = pv.el;
if(Cfg['animation']) {
nav.animEvent(el, $del);
el.classList.add('de-pview-anim');
el.style[nav.animName] = 'de-post-close-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r');
} else {
$del(el);
}
} while(pv = pv.kid);
};
Pview.getPview = function(el) {
while(el && !el.classList.contains('de-pview')) {
el = el.parentElement;
}
return el;
};
Pview.delTO = 0;
Pview.top = null;
Pview.prototype = Object.create(Post.prototype, {
getTopParent: { value: function pvGetBoardParent() {
var post = this.parent;
while(post._isPview) {
post = post.parent;
}
return post;
} },
markToDel: { value: function pvMarkToDel() {
clearTimeout(Pview.delTO);
Pview.delTO = setTimeout(Pview.del, Cfg['linksOut'], this);
} },
_isPview: { value: true },
_loaded: { value: false, writable: true },
_cache: { value: {}, writable: true },
_readDelay: { value: 0, writable: true },
_onerror: { value: function(eCode, eMsg, xhr) {
Pview.del(this);
this._showText(eCode === 404 ? Lng.postNotFound[lang] : getErrorMessage(eCode, eMsg));
} },
_onload: { value: function pvOnload(b, form, xhr) {
var rm, parent = this.parent,
parentNum = parent.num,
cache = this._cache[b + this.tNum] = new PviewsCache(form, b, this.tNum),
post = cache.getPost(this.num);
if(post && (brd !== b || !post.hasRef || post.ref.indexOf(parentNum) === -1)) {
if(post.hasRef) {
rm = $c('de-refmap', post.el)
} else {
post.msg.insertAdjacentHTML('afterend', '<div class="de-refmap"></div>');
rm = post.msg.nextSibling;
}
rm.insertAdjacentHTML('afterbegin', '<a class="de-reflink" href="' +
aib.getThrdUrl(b, parent._isPview ? parent.tNum : parent.tNum) + aib.anchor +
parentNum + '">>>' + (brd === b ? '' : '/' + brd + '/') + parentNum +
'</a><span class="de-refcomma">, </span>');
}
if(parent.kid === this) {
Pview.del(this);
if(post) {
this._loaded = true;
this._showPost(post);
} else {
this._showText(Lng.postNotFound[lang]);
}
}
} },
_showPost: { value: function pvShowPost(post) {
var btns, el = this.el = post.el.cloneNode(true),
pText = '<span class="de-btn-rep"></span>' +
(post.sage ? '<span class="de-btn-sage" title="SAGE"></span>' : '') +
(post.deleted ? '' : '<span style="margin-right: 4px; vertical-align: 1px; color: #4f7942; ' +
'font: bold 11px tahoma; cursor: default;">' + (post.isOp ? 'OP' : post.count + 1) + '</span>');
el.post = this;
el.className = aib.cReply + ' de-pview' + (post.viewed ? ' de-viewed' : '');
el.style.display = '';
if(aib._7ch) {
el.firstElementChild.style.cssText = 'max-width: 100%; margin: 0;';
$del($c('doubledash', el));
}
if(Cfg['linksNavig'] === 2) {
this._markLink(this.parent.num);
}
this._pref = $q(aib.qRef, el);
if(post.inited) {
this.btns = btns = $c('de-ppanel', el);
this.isOp = post.isOp;
btns.classList.remove('de-ppanel-cnt');
if(post.hidden) {
btns.classList.add('de-post-hid');
}
btns.innerHTML = '<span class="de-btn-hide' +
(post.userToggled ? '-user' : '') + '"></span>' + pText;
$each($Q((!TNum && post.isOp ? aib.qOmitted + ', ' : '') +
'.de-img-full, .de-after-fimg', el), $del);
$each(getImages(el), function(el) {
el.style.display = '';
});
if(post.hasYTube) {
if(post.ytInfo !== null) {
Object.defineProperty(this, 'ytObj', { value: $c('de-video-obj', el) });
this.ytInfo = post.ytInfo;
}
youTube.updatePost(this, $C('de-video-link', post.el), $C('de-video-link', el), true);
}
if(Cfg['addImgs']) {
$each($C('de-img-pre', el), function(el) {
el.style.display = '';
});
}
if(Cfg['markViewed']) {
this._readDelay = setTimeout(function(pst) {
if(!pst.viewed) {
pst.el.classList.add('de-viewed');
pst.viewed = true;
}
var arr = (sessionStorage['de-viewed'] || '').split(',');
arr.push(pst.num);
sessionStorage['de-viewed'] = arr;
}, 2e3, post);
}
} else {
this._pref.insertAdjacentHTML('afterend', '<span class="de-ppanel">' + pText + '</span');
embedMP3Links(this);
youTube.parseLinks(this);
if(Cfg['addImgs']) {
embedImagesLinks(el);
}
if(Cfg['imgSrcBtns']) {
addImagesSearch(el);
}
}
el.addEventListener('click', this, true);
this._showPview(el);
} },
_showPview: { value: function pvShowPview(el, id) {
if(this.parent._isPview) {
Pview.del(this.parent.kid);
} else {
Pview.del(Pview.top);
Pview.top = this;
}
this.parent.kid = this;
el.addEventListener('mouseover', this, true);
el.addEventListener('mouseout', this, true);
(aib.arch ? doc.body : dForm).appendChild(el);
setPviewPosition(this._link, el, false);
if(Cfg['animation']) {
nav.animEvent(el, function(node) {
node.classList.remove('de-pview-anim');
node.style[nav.animName] = '';
});
el.classList.add('de-pview-anim');
el.style[nav.animName] = 'de-post-open-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r');
}
} },
_showText: { value: function pvShowText(txt) {
this._showPview(this.el = $add('<div class="' + aib.cReply + ' de-pview-info de-pview">' +
txt + '</div>'));
} },
});
function PviewsCache(form, b, tNum) {
var i, len, post, pBn = {},
pProto = Post.prototype,
thr = $q(aib.qThread, form) || form,
posts = aib.getPosts(thr);
for(i = 0, len = posts.length; i < len; ++i) {
post = posts[i];
pBn[aib.getPNum(post)] = Object.create(pProto, {
count: { value: i + 1 },
el: { value: post },
inited: { value: false },
pvInited: { value: false, writable: true }
});
}
pBn[tNum] = this._opObj = Object.create(pProto, {
inited: { value: false },
isOp: { value: true },
msg: { value: $q(aib.qMsg, thr), writable: true },
ref: { value: [], writable: true }
});
this._brd = b;
this._thr = thr;
this._tNum = tNum;
this._tUrl = aib.getThrdUrl(b, tNum);
this._posts = pBn;
if(Cfg['linksNavig'] === 2) {
genRefMap(pBn, false, this._tUrl);
}
}
PviewsCache.prototype = {
getPost: function(num) {
if(num === this._tNum) {
return this._op;
}
var pst = this._posts[num];
if(pst && !pst.pvInited) {
pst.el = replacePost(pst.el);
delete pst.msg;
if(pst.hasRef) {
addRefMap(pst, this._tUrl);
}
pst.pvInited = true;
}
return pst;
},
get _op() {
var i, j, len, num, nRef, oRef, rRef, oOp, op = this._opObj;
op.el = replacePost(aib.getOp(this._thr));
op.msg = $q(aib.qMsg, op.el);
if(this._brd === brd && (oOp = pByNum[this._tNum])) {
oRef = op.ref;
rRef = [];
for(i = j = 0, nRef = oOp.ref, len = nRef.length; j < len; ++j) {
num = nRef[j];
if(oRef[i] === num) {
i++;
} else if(oRef.indexOf(num) !== -1) {
continue;
}
rRef.push(num)
}
for(len = oRef.length; i < len; i++) {
rRef.push(oRef[i]);
}
op.ref = rRef;
if(rRef.length !== 0) {
op.hasRef = true;
addRefMap(op, this._tUrl);
}
} else if(op.hasRef) {
addRefMap(op, this._tUrl);
}
Object.defineProperty(this, '_op', { value: op });
return op;
}
};
function PviewMoved() {
if(this.style[nav.animName]) {
this.classList.remove('de-pview-anim');
this.style.cssText = this.newPos;
this.newPos = false;
$each($C('de-css-move', doc.head), $del);
this.removeEventListener(nav.animEnd, PviewMoved, false);
}
}
function animPVMove(pView, lmw, top, oldCSS) {
var uId = 'de-movecss-' + Math.round(Math.random() * 1e3);
$css('@' + nav.cssFix + 'keyframes ' + uId + ' {to { ' + lmw + ' top:' + top + '; }}').className =
'de-css-move';
if(pView.newPos) {
pView.style.cssText = pView.newPos;
pView.removeEventListener(nav.animEnd, PviewMoved, false);
} else {
pView.style.cssText = oldCSS;
}
pView.newPos = lmw + ' top:' + top + ';';
pView.addEventListener(nav.animEnd, PviewMoved, false);
pView.classList.add('de-pview-anim');
pView.style[nav.animName] = uId;
}
function setPviewPosition(link, pView, animFun) {
if(pView.link === link) {
return;
}
pView.link = link;
var isTop, top, oldCSS, cr = link.getBoundingClientRect(),
offX = cr.left + window.pageXOffset + link.offsetWidth / 2,
offY = cr.top + window.pageYOffset,
bWidth = doc.documentElement.clientWidth,
isLeft = offX < bWidth / 2,
tmp = (isLeft ? offX : offX -
Math.min(parseInt(pView.offsetWidth, 10), offX - 10)),
lmw = 'max-width:' + (bWidth - tmp - 10) + 'px; left:' + tmp + 'px;';
if(animFun) {
oldCSS = pView.style.cssText;
pView.style.cssText = 'opacity: 0; ' + lmw;
} else {
pView.style.cssText = lmw;
}
top = pView.offsetHeight;
isTop = top + cr.top + link.offsetHeight < window.innerHeight || cr.top - top < 5;
top = (isTop ? offY + link.offsetHeight : offY - top) + 'px';
pView.aLeft = isLeft;
pView.aTop = isTop;
if(animFun) {
animFun(pView, lmw, top, oldCSS);
} else {
pView.style.top = top;
}
}
function addRefMap(post, tUrl) {
var i, ref, len, bStr = '<a ' + aib.rLinkClick + ' href="' + tUrl + aib.anchor,
str = '<div class="de-refmap">';
for(i = 0, ref = post.ref, len = ref.length; i < len; ++i) {
str += bStr + ref[i] + '" class="de-reflink">>>' + ref[i] +
'</a><span class="de-refcomma">, </span>';
}
post.msg.insertAdjacentHTML('afterend', str + '</div>');
}
function genRefMap(posts, hideRefs, thrURL) {
var tc, lNum, post, ref, i, len, links, url, pNum, opNums = Thread.tNums;
for(pNum in posts) {
for(i = 0, links = $T('a', posts[pNum].msg), len = links.length; i < len; ++i) {
tc = links[i].textContent;
if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in posts)) {
post = posts[lNum];
ref = post.ref;
if(ref.indexOf(pNum) === -1) {
ref.push(pNum);
post.hasRef = true;
if(hideRefs && post.hidden) {
post = posts[pNum];
post.setVisib(true);
post.note = 'reference to >>' + lNum;
post.hideRefs();
}
}
if(opNums.indexOf(lNum) !== -1) {
links[i].classList.add('de-opref');
}
if(thrURL) {
url = links[i].getAttribute('href');
if(url[0] === '#') {
links[i].setAttribute('href', thrURL + url);
}
}
}
}
}
}
function updRefMap(post, add) {
var tc, ref, idx, link, lNum, lPost, i, len, links, pNum = post.num,
strNums = add && Cfg['strikeHidd'] && Post.hiddenNums.length !== 0 ? Post.hiddenNums : null,
opNums = add && Thread.tNums;
for(i = 0, links = $T('a', post.msg), len = links.length; i < len; ++i) {
link = links[i];
tc = link.textContent;
if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in pByNum)) {
lPost = pByNum[lNum];
if(!TNum) {
link.href = '#' + (aib.fch ? 'p' : '') + lNum;
}
if(add) {
if(strNums && strNums.lastIndexOf(lNum) !== -1) {
link.classList.add('de-ref-hid');
}
if(opNums.indexOf(lNum) !== -1) {
link.classList.add('de-opref');
}
if(lPost.ref.indexOf(pNum) === -1) {
lPost.ref.push(pNum);
post.hasRef = true;
if(Cfg['hideRefPsts'] && lPost.hidden) {
if(!post.hidden) {
post.hideRefs();
}
post.setVisib(true);
post.note = 'reference to >>' + lNum;
}
} else {
continue;
}
} else if(lPost.hasRef) {
ref = lPost.ref;
idx = ref.indexOf(pNum);
if(idx === -1) {
continue;
}
ref.splice(idx, 1);
if(ref.length === 0) {
lPost.hasRef = false;
$del($c('de-refmap', lPost.el));
continue;
}
}
$del($c('de-refmap', lPost.el));
addRefMap(lPost, '');
}
}
}
//============================================================================================================
// THREAD
//============================================================================================================
function Thread(el, prev) {
if(aib._420 || aib.tiny) {
$after(el, el.lastChild);
$del($c('clear', el));
}
var i, pEl, lastPost,
els = aib.getPosts(el),
len = els.length,
num = aib.getTNum(el),
omt = TNum ? 1 : this.omitted = aib.getOmitted($q(aib.qOmitted, el), len);
this.num = num;
Thread.tNums.push(+num);
this.pcount = omt + len;
pByNum[num] = lastPost = this.op = el.post = new Post(aib.getOp(el), this, num, 0, true,
prev ? prev.last : null);
for(i = 0; i < len; i++) {
num = aib.getPNum(pEl = els[i]);
pByNum[num] = lastPost = new Post(pEl, this, num, omt + i, false, lastPost);
}
this.last = lastPost;
el.style.counterReset = 'de-cnt ' + omt;
el.removeAttribute('id');
el.setAttribute('de-thread', null);
visPosts = Math.max(visPosts, len);
this.el = el;
this.prev = prev;
if(prev) {
prev.next = this;
}
}
Thread.parsed = false;
Thread.loadNewPosts = function(e) {
if(e) {
$pd(e);
}
$alert(Lng.loading[lang], 'newposts', true);
firstThr.clearPostsMarks();
updater.forceLoad();
};
Thread.tNums = [];
Thread.prototype = {
hasNew: false,
hidden: false,
loadedOnce: false,
next: null,
get lastNotDeleted() {
var post = this.last;
while(post.deleted) {
post = post.prev;
}
return post;
},
get nextNotHidden() {
for(var thr = this.next; thr && thr.hidden; thr = thr.next) {}
return thr;
},
get prevNotHidden() {
for(var thr = this.prev; thr && thr.hidden; thr = thr.prev) {}
return thr;
},
clearPostsMarks: function() {
if(this.hasNew) {
this.hasNew = false;
$each($Q('.de-new-post', this.el), function(el) {
el.classList.remove('de-new-post');
});
}
},
load: function(last, smartScroll, Fn) {
if(!Fn) {
$alert(Lng.loading[lang], 'load-thr', true);
}
ajaxLoad(aib.getThrdUrl(brd, this.num), true, function threadOnload(last, smartScroll, Fn, form, xhr) {
var nextCoord, els = aib.getPosts(form),
op = this.op,
thrEl = this.el,
expEl = $c('de-expand', thrEl),
nOmt = last === 1 ? 0 : Math.max(els.length - last, 0);
if(smartScroll) {
if(this.next) {
nextCoord = this.next.topCoord;
} else {
smartScroll = false;
}
}
pr.closeQReply();
$del($q(aib.qOmitted + ', .de-omitted', thrEl));
if(!this.loadedOnce) {
if(op.trunc) {
op.updateMsg(replacePost($q(aib.qMsg, form)));
}
delete op.ref;
this.loadedOnce = true;
}
this._checkBans(op, form);
this._parsePosts(els, nOmt, this.omitted - 1);
this.omitted = nOmt;
thrEl.style.counterReset = 'de-cnt ' + (nOmt + 1);
if(nOmt !== 0) {
op.el.insertAdjacentHTML('afterend', '<div class="de-omitted">' + nOmt + '</div>');
}
if(this.pcount - nOmt - 1 <= visPosts) {
$del(expEl);
} else if(!expEl) {
thrEl.insertAdjacentHTML('beforeend', '<span class="de-expand">[<a href="' +
aib.getThrdUrl(brd, this.num) + aib.anchor + this.last.num + '">' +
Lng['collapseThrd'][lang] + '</a>]</span>');
thrEl.lastChild.onclick = function(e) {
$pd(e);
this.load(visPosts, true, null);
}.bind(this);
} else if(expEl !== thrEl.lastChild) {
thrEl.appendChild(expEl);
}
if(smartScroll) {
scrollTo(pageXOffset, pageYOffset - (nextCoord - this.next.topCoord));
}
closeAlert($id('de-alert-load-thr'));
Fn && Fn();
}.bind(this, last, smartScroll, Fn), function(eCode, eMsg, xhr) {
$alert(getErrorMessage(eCode, eMsg), 'load-thr', false);
if(typeof this === 'function') {
this();
}
}.bind(Fn));
},
loadNew: function(Fn, useAPI) {
if(aib.dobr && useAPI) {
return getJsonPosts('/api/thread/' + brd + '/' + TNum +
'/new.json?message_html&new_format&last_post=' + this.last.num,
function parseNewPosts(status, sText, json, xhr) {
if(status !== 200 || json['error']) {
Fn(status, sText || json['message'], 0, xhr);
} else {
var i, pCount, fragm, last, temp, el = (json['result'] || {})['posts'],
len = el ? el.length : 0,
np = len;
if(len > 0) {
fragm = doc.createDocumentFragment();
pCount = this.pcount;
last = this.last;
for(i = 0; i < len; i++) {
temp = getHanaPost(el[i]);
last = this._addPost(fragm, el[i]['display_id'].toString(),
replacePost(temp[1]), temp[0], pCount + i, last);
np -= spells.check(last)
}
spells.end(savePosts);
this.last = last;
this.el.appendChild(fragm);
this.pcount = pCount + len;
}
Fn(200, '', np, xhr);
Fn = null;
}
}.bind(this)
);
}
return ajaxLoad(aib.getThrdUrl(brd, TNum), true, function parseNewPosts(form, xhr) {
this._checkBans(firstThr.op, form);
var info = this._parsePosts(aib.getPosts(form), 0, 0);
Fn(200, '', info[1], xhr);
if(info[0] !== 0) {
$id('de-panel-info').firstChild.textContent = this.pcount + '/' + getImages(dForm).length;
}
Fn = null;
}.bind(this), function(eCode, eMsg, xhr) {
Fn(eCode, eMsg, 0, xhr);
Fn = null;
});
},
get topCoord() {
return this.op.topCoord;
},
updateHidden: function(data) {
var realHid, date = Date.now(),
thr = this;
do {
realHid = thr.num in data;
if(thr.hidden ^ realHid) {
if(realHid) {
thr.op.setUserVisib(true, date, false);
data[thr.num] = thr.op.title;
} else if(thr.hidden) {
thr.op.setUserVisib(false, date, false);
}
}
} while(thr = thr.next);
},
_addPost: function(parent, num, el, wrap, i, prev) {
var post = new Post(el, this, num, i, false, prev);
pByNum[num] = post;
Object.defineProperty(post, 'wrap', { value: wrap });
parent.appendChild(wrap);
if(TNum && Cfg['animation']) {
nav.animEvent(post.el, function(node) {
node.classList.remove('de-post-new');
});
post.el.classList.add('de-post-new');
}
youTube.parseLinks(post);
if(Cfg['imgSrcBtns']) {
addImagesSearch(el);
}
post.addFuncs();
preloadImages(el);
if(TNum && Cfg['markNewPosts']) {
if(updater.focused) {
this.clearPostsMarks();
} else {
this.hasNew = true;
el.classList.add('de-new-post');
}
}
return post;
},
_checkBans: function(op, thrNode) {
var pEl, bEl, post, i, bEls, len;
if(aib.qBan) {
for(i = 0, banEls = $Q(aib.qBan, thrNode), len = banEls.length; i < len; ++i) {
bEl = banEls[i];
pEl = aib.getPostEl(bEl);
post = pEl ? pByNum[aib.getPNum(pEl)] : op;
if(post && !post.banned) {
if(!$q(aib.qBan, post.el)) {
post.msg.appendChild(bEl);
}
post.banned = true;
}
}
}
},
_parsePosts: function(nPosts, from, omt) {
var i, c, len, el, tPost, fragm, newPosts = 0,
newVisPosts = 0,
firstDelPost = null,
rerunSpells = spells.hasNumSpell,
saveSpells = false,
post = this.op.nextNotDeleted;
for(i = 0, len = nPosts.length; i <= len && post; ) {
if(post.count - 1 === i) {
if(i === len || post.num !== aib.getPNum(nPosts[i])) {
if(!firstDelPost) {
firstDelPost = post;
}
c = 0;
do {
if(TNum) {
post.deleted = true;
post.btns.classList.remove('de-ppanel-cnt');
post.btns.classList.add('de-ppanel-del');
($q('input[type="checkbox"]', post.el) || {}).disabled = true;
} else {
$del(post.wrap);
delete pByNum[post.num];
if(post.hidden) {
post.unhideRefs();
}
updRefMap(post, false);
if(post.prev.next = post.next) {
post.next.prev = post.prev;
}
if(this.last === post) {
this.last = post.prev;
}
}
post = post.nextNotDeleted;
c++;
} while(post && (i === len || post.num !== aib.getPNum(nPosts[i])));
if(!rerunSpells) {
sVis.splice(i + 1, c);
}
for(tPost = post; tPost; tPost = tPost.nextInThread) {
tPost.count -= c;
}
} else {
if(i < from) {
if(i >= omt) {
post.wrap.classList.add('de-hidden');
post.omitted = true;
}
} else if(!TNum) {
if(post.trunc) {
post.updateMsg(replacePost($q(aib.qMsg, nPosts[i])));
}
post.wrap.classList.remove('de-hidden');
post.omitted = false;
updRefMap(post, true);
}
i++;
post = post.nextNotDeleted;
}
} else if(!TNum && i >= from) {
fragm = doc.createDocumentFragment();
tPost = this.op;
for(c = post.count - 1; i < c; i++) {
el = nPosts[i];
tPost = this._addPost(fragm, aib.getPNum(el), replacePost(el),
aib.getWrap(el, false), i + 1, tPost);
spells.check(tPost);
}
$after(this.op.el, fragm);
tPost.next = post;
post.prev = tPost;
} else {
if(TNum) {
console.error('Loaded thread has extra post, num:', aib.getPNum(nPosts[i]),
'count:', i, '. Latest in thread post num:', post.num, 'count:', post.count,
'. Posts count in thread:', this.pcount, 'Posts count loaded:', len + 1);
}
i++;
}
}
this.pcount = len + 1;
if(firstDelPost && rerunSpells) {
disableSpells();
for(post = firstDelPost.nextInThread; post; post = post.nextInThread) {
spells.check(post);
}
saveSpells = true;
}
if(i < len) {
newPosts = newVisPosts = len - i;
post = this.last;
fragm = doc.createDocumentFragment();
do {
el = nPosts[i];
post = this._addPost(fragm, aib.getPNum(el), replacePost(el),
aib.getWrap(el, false), i + 1, post);
newVisPosts -= spells.check(post);
} while(++i < len);
this.el.appendChild(fragm);
this.last = post;
saveSpells = true;
}
if(saveSpells) {
spells.end(savePosts);
}
return [newPosts, newVisPosts];
}
};
//============================================================================================================
// IMAGEBOARD
//============================================================================================================
function getImageBoard(checkDomains, checkOther) {
var ibDomains = {
'02ch.in': [{
css: { value: 'span[id$="_display"] { display: none !important; }' },
isBB: { value: true }
}],
'02ch.net': [{
ru: { value: true },
timePattern: { value: 'yyyy+nn+dd++w++hh+ii+ss' }
}],
'0chan.hk': [{
nul: { value: true },
css: { value: '#captcha_status, .content-background > hr, #postform nobr, .postnode + a, .replieslist, label[for="save"], span[style="float: right;"] { display: none !important; }\
.ui-wrapper { position: static !important; margin: 0 !important; overflow: visible !important; }\
.ui-resizable { display: inline !important; }\
form textarea { resize: both !important; }'
},
ru: { value: true },
timePattern: { value: 'w+yyyy+m+dd+hh+ii+ss' }
}, 'script[src*="kusaba"]'],
get '22chan.net'() { return this['ernstchan.com']; },
get '2ch.hk'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.pm'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.re'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.tf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.wf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.yt'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2-ch.so'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
'2--ch.ru': [{
tire: { value: true },
qPages: { value: 'table[border="1"] tr:first-of-type > td:first-of-type a' },
qTable: { value: 'table:not(.postfiles)' },
_qThread: { value: '.threadz' },
getOmitted: { value: function(el, len) {
var txt;
return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] - len : 1;
} },
docExt: { value: '.html' },
css: { value: 'span[id$="_display"] { display: none !important; }' },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p : 0) + '.memhtml';
} },
hasPicWrap: { value: true },
ru: { value: true },
isBB: { value: true }
}],
get '2-ch.su'() { return this['2--ch.ru']; },
get '2--ch.su'() { return this['2--ch.ru']; },
'2chru.net': [{
_2chru: { value: true }
}],
'410chan.org': [{
_410: { value: true },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['**', '*', '__', '^^', '%%', '`', '', '', 'q'] }
});
} },
getSage: { value: function(post) {
var el = $c('filetitle', post);
return el && el.textContent.contains('\u21E9');
} },
isBB: { value: false },
timePattern: { value: 'dd+nn+yyyy++w++hh+ii+ss' }
}, 'script[src*="kusaba"]'],
'420chan.org': [{
_420: { value: true },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['**', '*', '', '', '%', 'pre', '', '', 'q'] }
});
} },
qBan: { value: '.ban' },
qError: { value: 'pre' },
qPages: { value: '.pagelist > a:last-child' },
qThread: { value: '[id*="thread"]' },
getTNum: { value: function(op) {
return $q('a[id]', op).id.match(/\d+/)[0];
} },
css: { value: '#content > hr, .hidethread, .ignorebtn, .opqrbtn, .qrbtn, noscript { display: none !important; }\
.de-thr-hid { margin: 1em 0; }' },
cssHide: { value: '.de-post-hid > .replyheader ~ *' },
docExt: { value: '.php' },
isBB: { value: true }
}],
'4chan.org': [{
fch: { value: true },
cFileInfo: { value: 'fileText' },
cOPost: { value: 'op' },
cSubj: { value: 'subject' },
cReply: { value: 'post reply' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['**', '*', '__', '^H', 'spoiler', 'code', '', '', 'q'] },
bb: { value: [false, false, false, false, true, true, false, false, false] }
});
} },
qBan: { value: 'strong[style="color: red;"]' },
qDelBut: { value: '.deleteform > input[type="submit"]' },
qError: { value: '#errmsg' },
qName: { value: '.name' },
qOmitted: { value: '.summary.desktop' },
qPages: { value: '.pagelist > .pages:not(.cataloglink) > a:last-of-type' },
qPostForm: { value: 'form[name="post"]' },
qRef: { value: '.postInfo > .postNum' },
qTable: { value: '.replyContainer' },
timePattern: { value: 'nn+dd+yy+w+hh+ii-?s?s?' },
getSage: { value: function(post) {
return !!$q('.id_Heaven, .useremail[href^="mailto:sage"]', post);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
getWrap: { value: function(el, isOp) {
return el.parentNode;
} },
anchor: { value: '#p' },
css: { value: '#mpostform, .navLinks, .postingMode { display: none !important; }' },
cssHide: { value: '.de-post-hid > .postInfo ~ *' },
docExt: { value: '' },
rLinkClick: { value: '' },
rep: { value: true }
}],
'7chan.org': [{
_7ch: { value: true },
cOPost: { value: 'op' },
cFileInfo: { value: 'file_size' },
qMsg: { value: '.message' },
qPages: { value: '#paging > ul > li:nth-last-child(2)' },
qThread: { value: '[id^="thread"]:not(#thread_controls)' },
css: { get: function() {
return '.reply { background-color: ' + $getStyle(doc.body, 'background-color') + '; }'
} },
cssHide: { value: '.de-post-hid > div > .post_header ~ *' },
getImgWrap: { value: function(el) {
return el.parentNode.parentNode;
} },
timePattern: { value: 'yy+dd+nn+w+hh+ii+ss' },
trTag: { value: 'LI' }
}, 'script[src*="kusaba"]'],
'9ch.ru': [{
qRef: { value: '[color="#117743"]' },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : 'index.htm');
} },
getThrdUrl: { value: function(b, tNum) {
return this.prot + '//' + this.host + fixBrd(b) + 'index.php?res=' + tNum;
} }
}, 'form[action*="futaba.php"]'],
'britfa.gs': [{
init: { value: function() { return true; } }
}],
'dfwk.ru': [{
timePattern: { value: 'w+yy+nn+dd+hh+ii' }
}, 'script[src*="kusaba"]'],
'dobrochan.com': [{
dobr: { value: true },
cSubj: { value: 'replytitle' },
cFileInfo: { value: 'fileinfo' },
qDForm: { value: 'form[action*="delete"]' },
qError: { value: '.post-error, h2' },
qOmitted: { value: '.abbrev > span:first-of-type' },
qMsg: { value: '.postbody' },
qPages: { value: '.pages > tbody > tr > td' },
qTrunc: { value: '.abbrev > span:nth-last-child(2)' },
timePattern: { value: 'dd+m+?+?+?+?+?+yyyy++w++hh+ii-?s?s?' },
getImgLink: { value: function(img) {
var el = img.parentNode;
if(el.tagName === 'A') {
return el;
}
return $q('.fileinfo > a', img.previousElementSibling ? el : el.parentNode);
} },
getImgSrc: { value: function(el) {
return this.getImgLink(el).href;
} },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : 'index.xhtml');
} },
getImgWrap: { value: function(el) {
return el.tagName === 'A' ? (el.previousElementSibling ? el : el.parentNode).parentNode :
el.firstElementChild.tagName === 'IMG' ? el.parentNode : el;
} },
getTNum: { value: function(op) {
return $q('a[name]', op).name.match(/\d+/)[0];
} },
css: { value: '.delete > img, .popup, .reply_, .search_google, .search_iqdb { display: none !important; }\
.delete { background: none; }\
.delete_checkbox { position: static !important; }\
.file + .de-video-obj { float: left; margin: 5px 20px 5px 5px; }\
.de-video-obj + div { clear: left; }' },
hasPicWrap: { value: true },
rLinkClick: { value: 'onclick="Highlight(event, this.getAttribute(\'de-num\'))"' },
ru: { value: true },
init: { value: function() {
if(window.location.pathname === '/settings') {
nav = getNavFuncs();
$q('input[type="button"]', doc).addEventListener('click', function() {
readCfg();
saveCfg('__hanarating', $id('rating').value);
}, false);
return true;
}
} }
}],
'ernstchan.com': [{
css: { value: '.content > hr, .de-parea > hr { display: none !important }' },
cOPost: { value: 'thread_OP' },
cReply: { value: 'post' },
cRPost: { value: 'thread_reply' },
qError: { value: '.error' },
qMsg: { value: '.text' }
}, 'link[href$="phutaba.css"]'],
'hiddenchan.i2p': [{
hid: { value: true }
}, 'script[src*="kusaba"]'],
'iichan.hk': [{
iich: { value: true }
}],
'inach.org': [{
css: { value: '#postform > table > tbody > tr:first-child { display: none !important; }' },
isBB: { value: true }
}],
'krautchan.net': [{
krau: { value: true },
cFileInfo: { value: 'fileinfo' },
cReply: { value: 'postreply' },
cRPost: { value: 'postreply' },
cSubj: { value: 'postsubject' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'aa', '', '', 'q'] },
});
} },
qBan: { value: '.ban_mark' },
qDForm: { value: 'form[action*="delete"]' },
qError: { value: '.message_text' },
qImgLink: { value: '.filename > a' },
qOmitted: { value: '.omittedinfo' },
qPages: { value: 'table[border="1"] > tbody > tr > td > a:nth-last-child(2) + a' },
qRef: { value: '.postnumber' },
qThread: { value: '.thread_body' },
qTrunc: { value: 'p[id^="post_truncated"]' },
timePattern: { value: 'yyyy+nn+dd+hh+ii+ss+--?-?-?-?-?' },
getImgWrap: { value: function(el) {
return el.parentNode;
} },
getSage: { value: function(post) {
return !!$c('sage', post);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
css: { value: 'img[id^="translate_button"], img[src$="button-expand.gif"], img[src$="button-close.gif"], body > center > hr, form > div:first-of-type > hr, h2 { display: none !important; }\
div[id^="Wz"] { z-index: 10000 !important; }\
.de-thr-hid { margin-bottom: ' + (!TNum ? '7' : '2') + 'px; float: none !important; }\
.file_reply + .de-video-obj, .file_thread + .de-video-obj { margin: 5px 20px 5px 5px; float: left; }\
.de-video-obj + div { clear: left; }' },
cssHide: { value: '.de-post-hid > div:not(.postheader)' },
hasPicWrap: { value: true },
isBB: { value: true },
rLinkClick: { value: 'onclick="highlightPost(this.textContent.substr(2)))"' },
rep: { value: true },
res: { value: 'thread-' },
init: { value: function() {
doc.body.insertAdjacentHTML('beforeend', '<div style="display: none;">' +
'<div onclick="window.lastUpdateTime = 0;"></div>' +
'<div onclick="window.fileCounter = 1;"></div>' +
'<div onclick="if(boardRequiresCaptcha) { requestCaptcha(true); }"></div>' +
'<div onclick="setupProgressTracking();"></div>' +
'</div>');
var els = doc.body.lastChild.children;
this.btnZeroLUTime = els[0];
this.btnSetFCntToOne = els[1];
this.initCaptcha = els[2];
this.addProgressTrack = els[3];
} }
}],
'lambdadelta.net': [{
css: { value: '.content > hr { display: none !important }' },
cssHide: { value: '.de-post-hid > .de-ppanel ~ *' }
}, 'link[href$="phutaba.css"]'],
'mlpg.co': [{
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', '-', 'spoiler', 'c', '', '', 'q'] },
});
} },
getWrap: { value: function(el, isOp) {
return el.parentNode;
} },
css: { value: '.image-hover, form > div[style="text-align: center;"], form > div[style="text-align: center;"] + hr { display: none !important; }' },
isBB: { value: true }
}, 'form[name*="postcontrols"]'],
'nido.org': [{
qPages: { value: '.pagenavi > tbody > tr > td:nth-child(2) > a:last-of-type' },
getSage: { value: function(post) {
return !!$q('a[href="mailto:cejas"]', post);
} },
init: { value: function() {
for(var src, el, i = 0, els = $Q('span[id^="pv-"]', doc.body), len = els.length; i < len; ++i) {
el = els[i];
src = 'https://www.youtube.com/watch?v=' + el.id.substring(3);
el.parentNode.insertAdjacentHTML('beforeend',
'<p class="de-video-ext"><a href="' + src + '">' + src + '</a></p>');
$del(el);
}
} }
}, 'script[src*="kusaba"]'],
'ponychan.net': [{
pony: { value: true },
cOPost: { value: 'op' },
qPages: { value: 'table[border="0"] > tbody > tr > td:nth-child(2) > a:last-of-type' },
css: { value: '#bodywrap3 > hr { display: none !important; }' }
}, 'script[src*="kusaba"]'],
'syn-ch.ru': [{
css: { value: '.fa-sort, .image_id { display: none !important; }\
time:after { content: none; }' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sub', 'sup', 'q'] },
});
} },
init: { value: function() {
$script('$ = function(){};');
$each($Q('.mentioned', doc), $del);
} },
isBB: { value: true }
}, 'form[name*="postcontrols"]'],
'urupchan.ru': [{
urup: { value: true },
init: { value: function() {
for(var src, el, i = 0, els = $Q('blockquote > span[style="float: left;"]', doc.body), len = els.length; i < len; ++i) {
el = els[i];
src = $t('a', el).href;
el.parentNode.insertAdjacentHTML('beforeend',
'<p class="de-video-ext"><a href="' + src + '">' + src + '</a></p>');
$del(el);
}
} },
css: { value: '#captchaimage, .replybacklinks, .messagehelperC { display: none !important }' }
}, 'script[src*="kusaba"]']
};
var ibEngines = {
'#ABU_css, #ShowLakeSettings': {
abu: { value: true },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sup', 'sub', 'q'] }
});
} },
qBan: { value: 'font[color="#C12267"]' },
qDForm: { value: '#posts_form, #delform' },
qOmitted: { value: '.mess_post, .omittedposts' },
getSage: { writable: true, value: function(post) {
if($c('postertripid', dForm)) {
this.getSage = function(post) {
return !$c('postertripid', post);
};
} else {
this.getSage = Object.getPrototypeOf(this).getSage;
}
return this.getSage(post);
} },
cssEn: { value: '#ABU_alert_wait, .ABU_refmap, #captcha_div + font, #CommentToolbar, .postpanel, #usrFlds + tbody > tr:first-child, body > center { display: none !important; }\
.de-abtn { transition: none; }\
#de-txt-panel { font-size: 16px !important; }\
.reflink:before { content: none !important; }' },
isBB: { value: true },
init: { value: function() {
var cd = $id('captcha_div'),
img = cd && $t('img', cd);
if(img) {
cd.setAttribute('onclick', ['var el, i = 4,',
'isCustom = (typeof event.detail === "object") && event.detail.isCustom;',
"if(!isCustom && event.target.tagName !== 'IMG') {",
'return;',
'}',
'do {', img.getAttribute('onclick'), '} while(--i > 0 && !/<img|не нужно/i.test(this.innerHTML));',
"if(el = this.getElementsByTagName('img')[0]) {",
"el.removeAttribute('onclick');",
"if((!isCustom || event.detail.focus) && (el = this.querySelector('input[type=\\'text\\']'))) {",
'el.focus();',
'}',
'}'
].join(''));
img.removeAttribute('onclick');
}
} }
},
'form[action*="futaba.php"]': {
futa: { value: true },
qDForm: { value: 'form:not([enctype])' },
qImgLink: { value: 'a[href$=".jpg"]:nth-of-type(1), a[href$=".png"]:nth-of-type(1), a[href$=".gif"]:nth-of-type(1)' },
qOmitted: { value: 'font[color="#707070"]' },
qPostForm: { value: 'form:nth-of-type(1)' },
qRef: { value: '.del' },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : 'futaba.htm');
} },
getPNum: { value: function(post) {
return $t('input', post).name;
} },
getPostEl: { value: function(el) {
while(el && el.tagName !== 'TD' && !el.hasAttribute('de-thread')) {
el = el.parentElement;
}
return el;
} },
getPosts: { value: function(thr) {
return $Q('td:nth-child(2)', thr);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
cssEn: { value: '.de-cfg-body, .de-content { font-family: arial; }\
.ftbl { width: auto; margin: 0; }\
.reply { background: #f0e0d6; }\
span { font-size: inherit; }' },
docExt: { value: '.htm' }
},
'form[action*="imgboard.php?delete"]': {
tinyIb: { value: true },
ru: { value: true }
},
'form[name*="postcontrols"]': {
tiny: { value: true },
cFileInfo: { value: 'fileinfo' },
cOPost: { value: 'op' },
cReply: { value: 'post reply' },
cSubj: { value: 'subject' },
cTrip: { value: 'trip' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ["'''", "''", '__', '^H', '**', '`', '', '', 'q'] },
});
} },
qDForm: { value: 'form[name="postcontrols"]' },
qMsg: { value: '.body' },
qName: { value: '.name' },
qOmitted: { value: '.omitted' },
qPages: { value: '.pages > a:nth-last-of-type(2)' },
qPostForm: { value: 'form[name="post"]' },
qRef: { value: '.post_no:nth-of-type(2)' },
qTrunc: { value: '.toolong' },
firstPage: { value: 1 },
timePattern: { value: 'nn+dd+yy++w++hh+ii+ss' },
getPageUrl: { value: function(b, p) {
return p > 1 ? fixBrd(b) + p + this.docExt : fixBrd(b);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
cssEn: { get: function() {
return '.banner, .mentioned, .post-hover' + (TNum ? '' : ', .de-btn-rep') + ' { display: none !important; }\
form, form table { margin: 0; }';
} },
cssHide: { value: '.de-post-hid > .intro ~ *'}
},
'script[src*="kusaba"]': {
kus: { value: true },
cOPost: { value: 'postnode' },
qError: { value: 'h1, h2, div[style*="1.25em"]' },
cssEn: { value: '.extrabtns, #newposts_get, .replymode, .ui-resizable-handle, blockquote + a { display: none !important; }\
.ui-wrapper { display: inline-block; width: auto !important; height: auto !important; padding: 0 !important; }' },
isBB: { value: true },
rLinkClick: { value: 'onclick="highlight(this.textContent.substr(2), true)"' }
},
'link[href$="phutaba.css"]': {
phut: { value: true },
cSubj: { value: 'subject' },
cTrip: { value: 'tripcode' },
qPages: { value: '.pagelist > li:nth-last-child(2)' },
getImgWrap: { value: function(el) {
return el.parentNode.parentNode;
} },
getSage: { value: function(post) {
return !!$q('.sage', post);
} },
cssHide: { value: '.de-post-hid > .post > .post_body' },
docExt: { value: '' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] },
});
} },
isBB: { value: true },
res: { value: 'thread/' }
}
};
var ibBase = {
cFileInfo: 'filesize',
cOPost: 'oppost',
cReply: 'reply',
cRPost: 'reply',
cSubj: 'filetitle',
cTrip: 'postertrip',
get _formButtons() {
var bb = this.isBB;
return {
id: ['bold', 'italic', 'under', 'strike', 'spoil', 'code', 'sup', 'sub', 'quote'],
val: ['B', 'i', 'U', 'S', '%', 'C', 'v', '^', '>'],
tag: bb ? ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] :
['**', '*', '', '^H', '%%', '`', '', '', 'q'],
bb: [bb, bb, bb, bb, bb, bb, bb, bb, bb]
};
},
get formButtons() {
return this._formButtons;
},
qBan: '',
qDelBut: 'input[type="submit"]',
qDForm: '#delform, form[name="delform"]',
qError: 'h1, h2, font[size="5"]',
get qImgLink() {
var val = '.' + this.cFileInfo + ' a[href$=".jpg"]:nth-of-type(1), ' +
'.' + this.cFileInfo + ' a[href$=".png"]:nth-of-type(1), ' +
'.' + this.cFileInfo + ' a[href$=".gif"]:nth-of-type(1)';
Object.defineProperty(this, 'qImgLink', { value: val });
return val;
},
qMsg: 'blockquote',
get qMsgImgLink() {
var val = this.qMsg + ' a[href*=".jpg"], ' +
this.qMsg + ' a[href*=".png"], ' +
this.qMsg + ' a[href*=".gif"], ' +
this.qMsg + ' a[href*=".jpeg"]';
Object.defineProperty(this, 'qMsgImgLink', { value: val });
return val;
},
qName: '.postername, .commentpostername',
qOmitted: '.omittedposts',
qPages: 'table[border="1"] > tbody > tr > td:nth-child(2) > a:last-of-type',
qPostForm: '#postform',
qRef: '.reflink',
qTable: 'form > table, div > table',
timePattern: 'w+dd+m+yyyy+hh+ii+ss',
get qThread() {
var val = $c('thread', doc) ? '.thread' :
$q('div[id*="_info"][style*="float"]', doc) ? 'div[id^="t"]:not([style])' :
'[id^="thread"]';
Object.defineProperty(this, 'qThread', { value: val });
return val;
},
qTrunc: '.abbrev, .abbr, .shortened',
getImgLink: function(img) {
var el = img.parentNode;
return el.tagName === 'SPAN' ? el.parentNode : el;
},
getImgSrc: function(el) {
return el.getAttribute('src');
},
getImgSize: function(info) {
if(info) {
var sz = info.match(/(\d+)\s?[x×]\s?(\d+)/);
return [sz[1], sz[2]];
}
return [-1, -1];
},
getImgWeight: function(info) {
var w = info.match(/(\d+(?:[\.,]\d+)?)\s*([mkк])?i?[bб]/i);
return w[2] === 'M' ? (w[1] * 1e3) | 0 : !w[2] ? Math.round(w[1] / 1e3) : w[1];
},
getImgWrap: function(el) {
var node = (el.tagName === 'SPAN' ? el.parentNode : el).parentNode;
return node.tagName === 'SPAN' ? node.parentNode : node;
},
getOmitted: function(el, len) {
var txt;
return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] + 1 : 1;
},
getOp: function(thr) {
var el, op, opEnd;
if(op = $c(this.cOPost, thr)) {
return op;
}
op = thr.ownerDocument.createElement('div'),
opEnd = $q(this.qTable + ', div[id^="repl"]', thr);
while((el = thr.firstChild) !== opEnd) {
op.appendChild(el);
}
if(thr.hasChildNodes()) {
thr.insertBefore(op, thr.firstChild);
} else {
thr.appendChild(op);
}
return op;
},
getPNum: function(post) {
return post.id.match(/\d+/)[0];
},
getPageUrl: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : '');
},
getPostEl: function(el) {
while(el && !el.classList.contains(this.cRPost) && !el.hasAttribute('de-thread')) {
el = el.parentElement;
}
return el;
},
getPosts: function(thr) {
return $Q('.' + this.cRPost, thr);
},
getSage: function(post) {
var a = $q('a[href^="mailto:"], a[href="sage"]', post);
return !!a && /sage/i.test(a.href);
},
getThrdUrl: function(b, tNum) {
return this.prot + '//' + this.host + fixBrd(b) + this.res + tNum + this.docExt;
},
getTNum: function(op) {
return $q('input[type="checkbox"]', op).value;
},
getWrap: function(el, isOp) {
if(isOp) {
return el;
}
if(el.tagName === 'TD') {
Object.defineProperty(this, 'getWrap', { value: function(el, isOp) {
return isOp ? el : getAncestor(el, 'TABLE');
}});
} else {
Object.defineProperty(this, 'getWrap', { value: function(el, isOp) {
return el;
}});
}
return this.getWrap(el, isOp);
},
css: '',
cssEn: '',
cssHide: '.de-post-hid > .de-ppanel ~ *',
init: null,
isBB: false,
get lastPage() {
var el = $q(this.qPages, doc),
val = el && +aProto.pop.call(el.textContent.match(/\d+/g) || []) || 0;
if(pageNum === val + 1) {
val++;
}
Object.defineProperty(this, 'pagesCount', { value: val });
return val;
},
get reCrossLinks() {
var val = new RegExp('>https?:\\/\\/[^\\/]*' + this.dm + '\\/([a-z0-9]+)\\/' +
regQuote(this.res) + '(\\d+)(?:[^#<]+)?(?:#i?(\\d+))?<', 'g');
Object.defineProperty(this, 'reCrossLinks', { value: val });
return val;
},
rLinkClick: 'onclick="highlight(this.textContent.substr(2))"',
anchor: '#',
docExt: '.html',
dm: '',
firstPage: 0,
host: window.location.hostname,
hasPicWrap: false,
prot: window.location.protocol,
get rep() {
var val = dTime || spells.haveReps || Cfg['crossLinks'];
Object.defineProperty(this, 'rep', { value: val });
return val;
},
res: 'res/',
ru: false,
trTag: 'TR'
};
var i, ibObj = null, dm = window.location.hostname
.match(/(?:(?:[^.]+\.)(?=org\.|net\.|com\.))?[^.]+\.[^.]+$|^\d+\.\d+\.\d+\.\d+$|localhost/)[0];
if(checkDomains) {
if(dm in ibDomains) {
ibObj = (function createBoard(info) {
return Object.create(
info[2] ? createBoard(ibDomains[info[2]]) :
info[1] ? Object.create(ibBase, ibEngines[info[1]]) :
ibBase, info[0]
);
})(ibDomains[dm]);
checkOther = false;
}
}
if(checkOther) {
for(i in ibEngines) {
if($q(i, doc)) {
ibObj = Object.create(ibBase, ibEngines[i]);
break;
}
}
if(!ibObj) {
ibObj = ibBase;
}
}
if(ibObj) {
ibObj.dm = dm;
}
return ibObj;
};
//============================================================================================================
// BROWSER
//============================================================================================================
function getNavFuncs() {
if(!('contains' in String.prototype)) {
String.prototype.contains = function(s) {
return this.indexOf(s) !== -1;
};
String.prototype.startsWith = function(s) {
return this.indexOf(s) === 0;
};
}
if(!('repeat' in String.prototype)) {
String.prototype.repeat = function(nTimes) {
return new Array(nTimes + 1).join(this.valueOf());
};
}
if('toJSON' in aProto) {
delete aProto.toJSON;
}
if(!('URL' in window)) {
window.URL = window.webkitURL;
}
var ua = window.navigator.userAgent,
opera = window.opera ? +window.opera.version() : 0,
isOldOpera = opera ? opera < 12.1 : false,
webkit = ua.contains('WebKit/'),
chrome = webkit && ua.contains('Chrome/'),
safari = webkit && !chrome,
isGM = typeof GM_setValue === 'function' &&
(!chrome || !GM_setValue.toString().contains('not supported')),
isScriptStorage = !!scriptStorage && !ua.contains('Opera Mobi');
if(!window.GM_xmlhttpRequest) {
window.GM_xmlhttpRequest = $xhr;
}
return {
get ua() {
return navigator.userAgent + (this.Firefox ? ' [' + navigator.buildID + ']' : '');
},
Firefox: ua.contains('Gecko/'),
Opera: !!opera,
oldOpera: isOldOpera,
WebKit: webkit,
Chrome: chrome,
Safari: safari,
isGM: isGM,
isGlobal: isGM || isScriptStorage,
isSStorage: isScriptStorage,
cssFix: webkit ? '-webkit-' : isOldOpera ? '-o-' : '',
Anim: !isOldOpera,
animName: webkit ? 'webkitAnimationName' : isOldOpera ? 'OAnimationName' : 'animationName',
animEnd: webkit ? 'webkitAnimationEnd' : isOldOpera ? 'oAnimationEnd' : 'animationend',
animEvent: function(el, Fn) {
el.addEventListener(this.animEnd, function aEvent() {
this.removeEventListener(nav.animEnd, aEvent, false);
Fn(this);
Fn = null;
}, false);
},
noBlob: isOldOpera,
fixLink: safari ? getAbsLink : function fixLink(url) {
return url;
},
get hasWorker() {
var val = 'Worker' in (this.Firefox ? unsafeWindow : Window);
Object.defineProperty(this, 'hasWorker', { value: val });
return val;
},
get canPlayMP3() {
var val = !!new Audio().canPlayType('audio/mp3; codecs="mp3"');
Object.defineProperty(this, 'canPlayMP3', { value: val });
return val;
},
get matchesSelector() {
var dE = doc.documentElement,
fun = dE.matchesSelector || dE.mozMatchesSelector ||
dE.webkitMatchesSelector || dE.oMatchesSelector,
val = Function.prototype.call.bind(fun);
Object.defineProperty(this, 'matchesSelector', { value: val });
return val;
}
};
}
//============================================================================================================
// INITIALIZATION
//============================================================================================================
function Initialization(checkDomains) {
if(/^(?:about|chrome|opera|res)/i.test(window.location)) {
return false;
}
if(!(window.localStorage && typeof localStorage === 'object' && window.sessionStorage)) {
GM_log('WEBSTORAGE ERROR: please, enable webstorage!');
return false;
}
var intrv, url;
if(!aib) {
aib = getImageBoard(checkDomains, true);
}
if(aib.init && aib.init()) {
return false;
}
switch(window.name) {
case '': break;
case 'de-iframe-pform':
case 'de-iframe-dform':
$script((
'window.top.postMessage("A' + window.name + '$#$' +
getSubmitResponse(doc, true).join('$#$') + '", "*");'
).replace(/\n|\r/g, '\\n'));
return false;
case 'de-iframe-fav':
intrv = setInterval(function() {
$script('window.top.postMessage("B' + (doc.body.offsetHeight + 5) + '", "*");');
}, 1500);
window.addEventListener('load', setTimeout.bind(window, clearInterval, 3e4, intrv), false);
liteMode = true;
pr = {};
}
dForm = $q(aib.qDForm, doc);
if(!dForm || $id('de-panel')) {
return false;
}
nav = getNavFuncs();
window.addEventListener('storage', function(e) {
var data, temp, post, val = e.newValue;
if(!val) {
return;
}
switch(e.key) {
case '__de-post': {
try {
data = JSON.parse(val);
} catch(e) {
return;
}
temp = data['hide'];
if(data['brd'] === brd && (post = pByNum[data['num']]) && (post.hidden ^ temp)) {
post.setUserVisib(temp, data['date'], false);
} else {
if(!(data['brd'] in bUVis)) {
bUVis[data['brd']] = {};
}
bUVis[data['brd']][data['num']] = [+!temp, data['date']];
}
if(data['isOp']) {
if(!(data['brd'] in hThr)) {
if(temp) {
hThr[data['brd']] = {};
} else {
break;
}
}
if(temp) {
hThr[data['brd']][data['num']] = data['title'];
} else {
delete hThr[data['brd']][data['num']];
}
}
break;
}
case '__de-threads': {
try {
hThr = JSON.parse(val);
} catch(e) {
return;
}
if(!(brd in hThr)) {
hThr[brd] = {};
}
firstThr.updateHidden(hThr[brd]);
break;
}
case '__de-spells': {
try {
data = JSON.parse(val);
} catch(e) {
return;
}
Cfg['hideBySpell'] = data['hide'];
if(temp = $q('input[info="hideBySpell"]', doc)) {
temp.checked = data['hide'];
}
doc.body.style.display = 'none';
disableSpells();
if(data['data']) {
spells.setSpells(data['data'], false);
if(temp = $id('de-spell-edit')) {
temp.value = spells.list;
}
} else {
if(data['data'] === '') {
spells.disable();
if(temp = $id('de-spell-edit')) {
temp.value = '';
}
saveCfg('spells', '');
}
spells.enable = false;
}
doc.body.style.display = '';
}
default: return;
}
toggleContent('hid', true);
}, false);
url = (window.location.pathname || '').match(new RegExp(
'^(?:\\/?([^\\.]*?)\\/?)?' + '(' + regQuote(aib.res) + ')?' +
'(\\d+|index|wakaba|futaba)?' + '(\\.(?:[a-z]+))?$'
));
brd = url[1];
TNum = url[2] ? url[3] :
aib.futa ? +(window.location.search.match(/\d+/) || [false])[0] :
false;
pageNum = url[3] && !TNum ? +url[3] || aib.firstPage : aib.firstPage;
if(!aib.hasOwnProperty('docExt') && url[4]) {
aib.docExt = url[4];
}
dummy = doc.createElement('div');
return true;
}
function parseThreadNodes(form, threads) {
var el, i, len, node, fNodes = aProto.slice.call(form.childNodes),
cThr = doc.createElement('div');
for(i = 0, len = fNodes.length - 1; i < len; ++i) {
node = fNodes[i];
if(node.tagName === 'HR') {
form.insertBefore(cThr, node);
form.insertBefore(cThr.lastElementChild, node);
el = cThr.lastElementChild;
if(el.tagName === 'BR') {
form.insertBefore(el, node);
}
threads.push(cThr);
cThr = doc.createElement('div');
} else {
cThr.appendChild(node);
}
}
cThr.appendChild(fNodes[i]);
form.appendChild(cThr);
return threads;
}
function parseDelform(node, thrds) {
var i, lThr, len = thrds.length;
$each($T('script', node), $del);
if(len === 0) {
Thread.parsed = true;
thrds = parseThreadNodes(dForm, []);
len = thrds.length;
}
if(len) {
firstThr = lThr = new Thread(thrds[0], null);
}
for(i = 1; i < len; i++) {
lThr = new Thread(thrds[i], lThr);
}
lastThr = lThr;
node.setAttribute('de-form', '');
node.removeAttribute('id');
if(aib.abu && TNum) {
lThr = firstThr.el;
while((node = lThr.nextSibling) && node.tagName !== 'HR') {
$del(node);
}
}
}
function replaceString(txt) {
if(dTime) {
txt = dTime.fix(txt);
}
if(aib.fch || aib.krau) {
if(aib.fch) {
txt = txt.replace(/<wbr>/g, '');
}
txt = txt.replace(/(^|>|\s|>)(https*:\/\/.*?)(<\/a>)?(?=$|<|\s)/ig, function(x, a, b, c) {
return c ? x : a + '<a href="' + b + '">' + b + '</a>';
});
}
if(spells.haveReps) {
txt = spells.replace(txt);
}
if(Cfg['crossLinks']) {
txt = txt.replace(aib.reCrossLinks, function(str, b, tNum, pNum) {
return '>>>/' + b + '/' + (pNum || tNum) + '<';
});
}
return txt;
}
function replacePost(el) {
if(aib.rep) {
el.innerHTML = replaceString(el.innerHTML);
}
return el;
}
function replaceDelform() {
if(liteMode) {
doc.body.insertAdjacentHTML('afterbegin', dForm.outerHTML);
dForm = doc.body.firstChild;
window.addEventListener('load', function() {
while(dForm.nextSibling) {
$del(dForm.nextSibling);
}
}, false);
} else if(aib.rep) {
dForm.insertAdjacentHTML('beforebegin', replaceString(dForm.outerHTML));
dForm.style.display = 'none';
dForm.id = 'de-dform-old';
dForm = dForm.previousSibling;
window.addEventListener('load', function() {
$del($id('de-dform-old'));
}, false);
}
}
function initDelformAjax() {
var btn;
if(Cfg['ajaxReply'] === 2) {
dForm.onsubmit = $pd;
if(btn = $q(aib.qDelBut, dForm)) {
btn.onclick = function(e) {
$pd(e);
pr.closeQReply();
$alert(Lng.deleting[lang], 'deleting', true);
new html5Submit(dForm, e.target, checkDelete);
};
}
} else if(Cfg['ajaxReply'] === 1) {
dForm.insertAdjacentHTML('beforeend',
'<iframe name="de-iframe-pform" src="about:blank" style="display: none;"></iframe>' +
'<iframe name="de-iframe-dform" src="about:blank" style="display: none;"></iframe>'
);
dForm.target = 'de-iframe-dform';
dForm.onsubmit = function() {
pr.closeQReply();
$alert(Lng.deleting[lang], 'deleting', true);
};
}
}
function initThreadUpdater(title, enableUpdate) {
var delay, checked404, loadTO, audioRep, currentXHR, audioEl, stateButton, hasAudio,
initDelay, favIntrv, favNorm, favHref, enabled = false,
inited = false,
lastECode = 200,
newPosts = 0,
aPlayers = 0,
focused = true;
if(enableUpdate) {
init();
}
if(focused && Cfg['desktNotif'] && ('permission' in Notification)) {
switch(Notification.permission.toLowerCase()) {
case 'default': requestNotifPermission(); break;
case 'denied': saveCfg('desktNotif', 0);
}
}
function init() {
audioEl = null;
stateButton = null;
hasAudio = false;
initDelay = Cfg['updThrDelay'] * 1e3;
favIntrv = 0;
favNorm = notifGranted = inited = true;
favHref = ($q('head link[rel="shortcut icon"]', doc) || {}).href;
if(('hidden' in doc) || ('webkitHidden' in doc)) {
focused = !(doc.hidden || doc.webkitHidden);
doc.addEventListener((nav.WebKit ? 'webkit' : '') + 'visibilitychange', function() {
if(doc.hidden || doc.webkitHidden) {
onBlur();
} else {
onVis();
}
}, false);
} else {
focused = false;
window.addEventListener('focus', onVis, false);
window.addEventListener('blur', onBlur, false);
window.addEventListener('mousemove', function mouseMove() {
window.removeEventListener('mousemove', mouseMove, false);
onVis();
}, false);
}
enable();
}
function enable() {
if(!enabled) {
enabled = true;
checked404 = false;
newPosts = 0;
delay = initDelay;
loadTO = setTimeout(loadPostsFun, delay);
}
}
function disable() {
if(enabled) {
clearTimeout(loadTO);
enabled = hasAudio = false;
setState('off');
var btn = $id('de-btn-audio-on');
if(btn) {
btn.id = 'de-btn-audio-off';
}
}
}
function toggleAudio(aRep) {
if(!audioEl) {
audioEl = $new('audio', {
'preload': 'auto',
'src': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/signal.ogg'
}, null);
}
audioRep = aRep;
return hasAudio = !hasAudio;
}
function audioNotif() {
if(focused) {
hasAudio = false;
} else {
audioEl.play()
setTimeout(audioNotif, audioRep);
hasAudio = true;
}
}
function requestNotifPermission() {
notifGranted = false;
Notification.requestPermission(function(state) {
if(state.toLowerCase() === 'denied') {
saveCfg('desktNotif', 0);
} else {
notifGranted = true;
}
});
}
function loadPostsFun() {
currentXHR = firstThr.loadNew(onLoaded, true);
}
function forceLoadPosts() {
if(currentXHR) {
currentXHR.abort();
}
clearTimeout(loadTO);
delay = initDelay;
loadPostsFun();
}
function onLoaded(eCode, eMsg, lPosts, xhr) {
if(currentXHR !== xhr && eCode === 0) { // Loading aborted
return;
}
currentXHR = null;
infoLoadErrors(eCode, eMsg, -1);
if(eCode !== 200) {
lastECode = eCode;
if(!Cfg['noErrInTitle']) {
updateTitle();
}
if(eCode !== 0 && Math.floor(eCode / 500) === 0) {
if(eCode === 404 && !checked404) {
checked404 = true;
} else {
updateTitle();
disable();
return;
}
}
setState('warn');
if(enabled) {
loadTO = setTimeout(loadPostsFun, delay);
}
return;
}
if(lastECode !== 200) {
lastECode = 200;
setState('on');
checked404 = false;
if((focused || lPosts === 0) && !Cfg['noErrInTitle']) {
updateTitle();
}
}
if(!focused) {
if(lPosts !== 0) {
if(Cfg['favIcoBlink'] && favHref && newPosts === 0) {
favIntrv = setInterval(function() {
$del($q('link[rel="shortcut icon"]', doc.head));
doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' +
(!favNorm ? favHref : 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAA' +
'AQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVR' +
'Ix2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII=') + '">');
favNorm = !favNorm;
}, 800);
}
newPosts += lPosts;
updateTitle();
if(Cfg['desktNotif'] && notifGranted) {
var post = firstThr.last,
imgs = post.images,
notif = new Notification(aib.dm + '/' + brd + '/' + TNum + ': ' + newPosts +
Lng.newPost[lang][lang !== 0 ? +(newPosts !== 1) : (newPosts % 10) > 4 ||
(newPosts % 10) === 0 || (((newPosts % 100) / 10) | 0) === 1 ? 2 :
(newPosts % 10) === 1 ? 0 : 1] + Lng.newPost[lang][3],
{
'body': post.text.substring(0, 250).replace(/\s+/g, ' '),
'tag': aib.dm + brd + TNum,
'icon': imgs.length === 0 ? favHref : imgs[0].src
});
notif.onshow = function() {
setTimeout(this.close.bind(this), 12e3);
};
notif.onclick = function() {
window.focus();
};
notif.onerror = function() {
window.focus();
requestNotifPermission();
};
}
if(hasAudio) {
if(audioRep) {
audioNotif();
} else {
audioEl.play()
}
}
delay = initDelay;
} else if(delay !== 12e4) {
delay = Math.min(delay + initDelay, 12e4);
}
}
if(enabled) {
loadTO = setTimeout(loadPostsFun, delay);
}
}
function setState(state) {
var btn = stateButton || (stateButton = $q('a[id^="de-btn-upd"]', doc));
btn.id = 'de-btn-upd-' + state;
btn.title = Lng.panelBtn['upd-' + (state === 'off' ? 'off' : 'on')][lang];
}
function onBlur() {
focused = false;
firstThr.clearPostsMarks();
}
function onVis() {
if(Cfg['favIcoBlink'] && favHref) {
clearInterval(favIntrv);
favNorm = true;
$del($q('link[rel="shortcut icon"]', doc.head));
doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' + favHref + '">');
}
focused = true;
newPosts = 0;
setTimeout(function() {
updateTitle();
if(enabled) {
forceLoadPosts();
}
}, 200);
}
function updateTitle() {
doc.title = (aPlayers === 0 ? '' : '♫ ') +
(lastECode === 200 ? '' : '{' + lastECode + '} ') +
(newPosts === 0 ? '' : '[' + newPosts + '] ') + title;
}
function addPlayingTag() {
aPlayers++;
if(aPlayers === 1) {
updateTitle();
}
}
function removePlayingTag() {
aPlayers = Math.max(aPlayers - 1, 0);
if(aPlayers === 0) {
updateTitle();
}
}
return {
get enabled() {
return enabled;
},
get focused() {
return focused;
},
forceLoad: forceLoadPosts,
enable: function() {
if(!inited) {
init();
} else if(!enabled) {
enable();
} else {
return;
}
setState('on');
},
disable: disable,
toggleAudio: toggleAudio,
addPlayingTag: addPlayingTag,
removePlayingTag: removePlayingTag
};
}
function initPage() {
if(Cfg['updScript']) {
checkForUpdates(false, function(html) {
$alert(html, 'updavail', false);
});
}
if(TNum) {
if(Cfg['rePageTitle']) {
if(aib.abu) {
window.addEventListener('load', function() {
doc.title = '/' + brd + ' - ' + pByNum[TNum].title;
}, false);
}
doc.title = '/' + brd + ' - ' + pByNum[TNum].title;
}
firstThr.el.insertAdjacentHTML('afterend',
'<div id="de-updater-div">>> [<a class="de-abtn" id="de-updater-btn" href="#"></a>]</div>');
firstThr.el.nextSibling.addEventListener('click', Thread.loadNewPosts, false);
} else if(needScroll) {
setTimeout(window.scrollTo, 20, 0, 0);
}
updater = initThreadUpdater(doc.title, TNum && Cfg['ajaxUpdThr']);
}
//============================================================================================================
// MAIN
//============================================================================================================
function addDelformStuff(isLog) {
var pNum, post;
preloadImages(null);
isLog && (Cfg['preLoadImgs'] || Cfg['openImgs']) && $log('Preload images');
embedMP3Links(null);
isLog && Cfg['addMP3'] && $log('MP3 links');
youTube.parseLinks(null);
isLog && Cfg['addYouTube'] && $log('YouTube links');
if(Cfg['addImgs']) {
embedImagesLinks(dForm);
isLog && $log('Image links');
}
if(Cfg['imgSrcBtns']) {
addImagesSearch(dForm);
isLog && $log('Sauce buttons');
}
if(Cfg['linksNavig'] === 2) {
genRefMap(pByNum, !!Cfg['hideRefPsts'], '');
for(pNum in pByNum) {
post = pByNum[pNum];
if(post.hasRef) {
addRefMap(post, '');
}
}
isLog && $log('Reflinks map');
}
}
function doScript(checkDomains) {
var initTime = oldTime = Date.now();
if(!Initialization(checkDomains)) {
return;
}
$log('Init');
readCfg();
spells = new Spells(!!Cfg['hideBySpell']);
youTube = initYouTube(Cfg['addYouTube'], Cfg['YTubeType'], Cfg['YTubeWidth'], Cfg['YTubeHeigh'],
Cfg['YTubeHD'], Cfg['YTubeTitles']);
readFavorites();
$log('Read config');
$disp(doc.body);
replaceDelform();
$log('Replace delform');
pr = new PostForm($q(aib.qPostForm, doc), false, !liteMode);
pByNum = Object.create(null);
try {
parseDelform(dForm, $Q(aib.qThread, dForm));
} catch(e) {
GM_log('DELFORM ERROR:\n' + getPrettyErrorMessage(e));
$disp(doc.body);
return;
}
initDelformAjax();
readViewedPosts();
saveFavorites();
$log('Parse delform');
if(Cfg['keybNavig']) {
keyNav = new KeyNavigation();
$log('Init keybinds');
}
if(!liteMode) {
initPage();
$log('Init page');
addPanel();
$log('Add panel');
}
initMessageFunctions();
addDelformStuff(true);
scriptCSS();
$disp(doc.body);
$log('Apply CSS');
readPosts();
readUserPosts();
checkPostsVisib();
saveUserPosts();
$log('Apply spells');
timeLog.push(Lng.total[lang] + (Date.now() - initTime) + 'ms');
}
if(doc.readyState === 'interactive' || doc.readyState === 'complete') {
needScroll = false;
doScript(true);
} else {
aib = getImageBoard(true, false);
needScroll = true;
doc.addEventListener(doc.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll", function wheelFunc(e) {
needScroll = false;
doc.removeEventListener(e.type, wheelFunc, false);
}, false);
doc.addEventListener('DOMContentLoaded', doScript.bind(null, false), false);
}
})(window.opera && window.opera.scriptStorage);
| Dollchan_Extension_Tools.user.js | // ==UserScript==
// @name Dollchan Extension Tools
// @version 14.2.17.0
// @namespace http://www.freedollchan.org/scripts/*
// @author Sthephan Shinkufag @ FreeDollChan
// @copyright (C)2084, Bender Bending Rodriguez
// @description Doing some profit for imageboards
// @icon https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Icon.png
// @updateURL https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js
// @run-at document-start
// @include http://*
// @include https://*
// ==/UserScript==
(function de_main_func(scriptStorage) {
var version = '14.2.17.0',
defaultCfg = {
'language': 0, // script language [0=ru, 1=en]
'hideBySpell': 1, // hide posts by spells
'spells': '', // user defined spells
'sortSpells': 0, // sort spells when applying
'menuHiddBtn': 1, // menu on hide button
'hideRefPsts': 0, // hide post with references to hidden posts
'delHiddPost': 0, // delete hidden posts
'ajaxUpdThr': 1, // auto update threads
'updThrDelay': 60, // threads update interval in sec
'noErrInTitle': 0, // don't show error number in title except 404
'favIcoBlink': 1, // favicon blinking, if new posts detected
'markNewPosts': 1, // new posts marking on page focus
'desktNotif': 0, // desktop notifications, if new posts detected
'expandPosts': 2, // expand shorted posts [0=off, 1=auto, 2=on click]
'postBtnsCSS': 2, // post buttons style [0=text, 1=classic, 2=solid grey]
'noSpoilers': 1, // open spoilers
'noPostNames': 0, // hide post names
'noPostScrl': 1, // no scroll in posts
'correctTime': 0, // correct time in posts
'timeOffset': '+0', // offset in hours
'timePattern': '', // find pattern
'timeRPattern': '', // replace pattern
'expandImgs': 2, // expand images by click [0=off, 1=in post, 2=by center]
'resizeImgs': 1, // resize large images
'maskImgs': 0, // mask images
'preLoadImgs': 0, // pre-load images
'findImgFile': 0, // detect built-in files in images
'openImgs': 0, // open images in posts
'openGIFs': 0, // open only GIFs in posts
'imgSrcBtns': 1, // add image search buttons
'linksNavig': 2, // navigation by >>links [0=off, 1=no map, 2=+refmap]
'linksOver': 100, // delay appearance in ms
'linksOut': 1500, // delay disappearance in ms
'markViewed': 0, // mark viewed posts
'strikeHidd': 0, // strike >>links to hidden posts
'noNavigHidd': 0, // don't show previews for hidden posts
'crossLinks': 0, // replace http: to >>/b/links
'insertNum': 1, // insert >>link on postnumber click
'addMP3': 1, // embed mp3 links
'addImgs': 0, // embed links to images
'addYouTube': 3, // embed YouTube links [0=off, 1=onclick, 2=player, 3=preview+player, 4=only preview]
'YTubeType': 0, // player type [0=flash, 1=HTML5]
'YTubeWidth': 360, // player width
'YTubeHeigh': 270, // player height
'YTubeHD': 0, // hd video quality
'YTubeTitles': 0, // convert links to titles
'addVimeo': 1, // embed vimeo links
'ajaxReply': 2, // posting with AJAX (0=no, 1=iframe, 2=HTML5)
'postSameImg': 1, // ability to post same images
'removeEXIF': 1, // remove EXIF data from JPEGs
'removeFName': 0, // remove file name
'addPostForm': 2, // postform displayed [0=at top, 1=at bottom, 2=hidden, 3=hanging]
'scrAfterRep': 0, // scroll to the bottom after reply
'favOnReply': 1, // add thread to favorites on reply
'addSageBtn': 1, // email field -> sage btn
'saveSage': 1, // remember sage
'sageReply': 0, // reply with sage
'warnSubjTrip': 0, // warn if subject field contains tripcode
'captchaLang': 1, // language input in captcha [0=off, 1=en, 2=ru]
'addTextBtns': 1, // text format buttons [0=off, 1=graphics, 2=text, 3=usual]
'txtBtnsLoc': 0, // located at [0=top, 1=bottom]
'passwValue': '', // user password value
'userName': 0, // user name
'nameValue': '', // value
'userSignat': 0, // user signature
'signatValue': '', // value
'noBoardRule': 1, // hide board rules
'noGoto': 1, // hide goto field
'noPassword': 1, // hide password field
'scriptStyle': 0, // script style [0=glass black, 1=glass blue, 2=solid grey]
'userCSS': 0, // user style
'userCSSTxt': '', // css text
'expandPanel': 0, // show full main panel
'attachPanel': 1, // attach main panel
'panelCounter': 1, // posts/images counter in script panel
'rePageTitle': 1, // replace page title in threads
'animation': 1, // animation in script
'closePopups': 0, // auto-close popups
'keybNavig': 1, // keyboard navigation
'loadPages': 1, // number of pages that are loaded on F5
'updScript': 1, // check for script's update
'scrUpdIntrv': 1, // check interval in days (every val+1 day)
'textaWidth': 500, // textarea width
'textaHeight': 160 // textarea height
},
Lng = {
cfg: {
'hideBySpell': ['Заклинания: ', 'Magic spells: '],
'sortSpells': ['Сортировать спеллы и удалять дубликаты', 'Sort spells and delete duplicates'],
'menuHiddBtn': ['Дополнительное меню кнопок скрытия ', 'Additional menu of hide buttons'],
'hideRefPsts': ['Скрывать ответы на скрытые посты*', 'Hide replies to hidden posts*'],
'delHiddPost': ['Удалять скрытые посты', 'Delete hidden posts'],
'ajaxUpdThr': ['AJAX обновление треда ', 'AJAX thread update '],
'updThrDelay': [' (сек)', ' (sec)'],
'noErrInTitle': ['Не показывать номер ошибки в заголовке', 'Don\'t show error number in title'],
'favIcoBlink': ['Мигать фавиконом при новых постах', 'Favicon blinking on new posts'],
'markNewPosts': ['Выделять новые посты при переключении на тред', 'Mark new posts on page focus'],
'desktNotif': ['Уведомления на рабочем столе', 'Desktop notifications'],
'expandPosts': {
sel: [['Откл.', 'Авто', 'По клику'], ['Disable', 'Auto', 'On click']],
txt: ['AJAX загрузка сокращенных постов*', 'AJAX upload of shorted posts*']
},
'postBtnsCSS': {
sel: [['Text', 'Classic', 'Solid grey'], ['Text', 'Classic', 'Solid grey']],
txt: ['Стиль кнопок постов*', 'Post buttons style*']
},
'noSpoilers': ['Открывать текстовые спойлеры', 'Open text spoilers'],
'noPostNames': ['Скрывать имена в постах', 'Hide names in posts'],
'noPostScrl': ['Без скролла в постах', 'No scroll in posts'],
'keybNavig': ['Навигация с помощью клавиатуры ', 'Navigation with keyboard '],
'loadPages': [' Количество страниц, загружаемых по F5', ' Number of pages that are loaded on F5 '],
'correctTime': ['Корректировать время в постах* ', 'Correct time in posts* '],
'timeOffset': [' Разница во времени', ' Time difference'],
'timePattern': [' Шаблон поиска', ' Find pattern'],
'timeRPattern': [' Шаблон замены', ' Replace pattern'],
'expandImgs': {
sel: [['Откл.', 'В посте', 'По центру'], ['Disable', 'In post', 'By center']],
txt: ['раскрывать изображения по клику', 'expand images on click']
},
'resizeImgs': ['Уменьшать в экран большие изображения', 'Resize large images to fit screen'],
'preLoadImgs': ['Предварительно загружать изображения*', 'Pre-load images*'],
'findImgFile': ['Распознавать встроенные файлы в изображениях*', 'Detect built-in files in images*'],
'openImgs': ['Скачивать полные версии изображений*', 'Download full version of images*'],
'openGIFs': ['Скачивать только GIFы*', 'Download GIFs only*'],
'imgSrcBtns': ['Добавлять кнопки для поиска изображений*', 'Add image search buttons*'],
'linksNavig': {
sel: [['Откл.', 'Без карты', 'С картой'], ['Disable', 'No map', 'With map']],
txt: ['навигация по >>ссылкам* ', 'navigation by >>links* ']
},
'linksOver': [' задержка появления (мс)', ' delay appearance (ms)'],
'linksOut': [' задержка пропадания (мс)', ' delay disappearance (ms)'],
'markViewed': ['Отмечать просмотренные посты*', 'Mark viewed posts*'],
'strikeHidd': ['Зачеркивать >>ссылки на скрытые посты', 'Strike >>links to hidden posts'],
'noNavigHidd': ['Не отображать превью для скрытых постов', 'Don\'t show previews for hidden posts'],
'crossLinks': ['Преобразовывать http:// в >>/b/ссылки*', 'Replace http:// with >>/b/links*'],
'insertNum': ['Вставлять >>ссылку по клику на №поста*', 'Insert >>link on №postnumber click*'],
'addMP3': ['Добавлять плейер к mp3 ссылкам* ', 'Add player to mp3 links* '],
'addVimeo': ['Добавлять плейер к Vimeo ссылкам* ', 'Add player to Vimeo links* '],
'addImgs': ['Загружать изображения к .jpg-, .png-, .gif-ссылкам*', 'Load images to .jpg-, .png-, .gif-links*'],
'addYouTube': {
sel: [['Ничего', 'Плейер по клику', 'Авто плейер', 'Превью+плейер', 'Только превью'], ['Nothing', 'On click player', 'Auto player', 'Preview+player', 'Only preview']],
txt: ['к YouTube-ссылкам* ', 'to YouTube-links* ']
},
'YTubeType': {
sel: [['Flash', 'HTML5'], ['Flash', 'HTML5']],
txt: ['', '']
},
'YTubeHD': ['HD ', 'HD '],
'YTubeTitles': ['Загружать названия к YouTube-ссылкам*', 'Load titles into YouTube-links*'],
'ajaxReply': {
sel: [['Откл.', 'Iframe', 'HTML5'], ['Disable', 'Iframe', 'HTML5']],
txt: ['AJAX отправка постов*', 'posting with AJAX*']
},
'postSameImg': ['Возможность отправки одинаковых изображений', 'Ability to post same images'],
'removeEXIF': ['Удалять EXIF из отправляемых JPEG-изображений', 'Remove EXIF from uploaded JPEG-images'],
'removeFName': ['Удалять имя из отправляемых файлов', 'Remove names from uploaded files'],
'addPostForm': {
sel: [['Сверху', 'Внизу', 'Скрытая', 'Отдельная'], ['At top', 'At bottom', 'Hidden', 'Hanging']],
txt: ['форма ответа в треде* ', 'reply form in thread* ']
},
'scrAfterRep': ['Перемещаться в конец треда после отправки', 'Scroll to the bottom after reply'],
'favOnReply': ['Добавлять тред в избранное при ответе', 'Add thread to favorites on reply'],
'addSageBtn': ['Sage вместо поля E-mail* ', 'Sage button instead of E-mail field* '],
'warnSubjTrip': ['Предупреждать при наличии трип-кода в поле тема', 'Warn if field subject contains trip-code'],
'saveSage': ['запоминать сажу', 'remember sage'],
'captchaLang': {
sel: [['Откл.', 'Eng', 'Rus'], ['Disable', 'Eng', 'Rus']],
txt: ['язык ввода капчи', 'language input in captcha']
},
'addTextBtns': {
sel: [['Откл.', 'Графич.', 'Упрощ.', 'Стандарт.'], ['Disable', 'As images', 'As text', 'Standard']],
txt: ['кнопки форматирования текста ', 'text format buttons ']
},
'txtBtnsLoc': ['внизу', 'at bottom'],
'userPassw': [' Постоянный пароль ', ' Fixed password '],
'userName': ['Постоянное имя', 'Fixed name'],
'userSignat': ['Постоянная подпись', 'Fixed signature'],
'noBoardRule': ['правила ', 'rules '],
'noGoto': ['поле goto ', 'goto field '],
'noPassword': ['пароль', 'password'],
'scriptStyle': {
sel: [['Glass black', 'Glass blue', 'Solid grey'], ['Glass black', 'Glass blue', 'Solid grey']],
txt: ['стиль скрипта', 'script style']
},
'userCSS': ['Пользовательский CSS ', 'User CSS '],
'attachPanel': ['Прикрепить главную панель', 'Attach main panel'],
'panelCounter': ['Счетчик постов/изображений на главной панели', 'Counter of posts/images on main panel'],
'rePageTitle': ['Название треда в заголовке вкладки*', 'Thread title in page tab*'],
'animation': ['CSS3 анимация в скрипте', 'CSS3 animation in script'],
'closePopups': ['Автоматически закрывать уведомления', 'Close popups automatically'],
'updScript': ['Автоматически проверять обновления скрипта', 'Check for script update automatically'],
'scrUpdIntrv': {
sel: [['Каждый день', 'Каждые 2 дня', 'Каждую неделю', 'Каждые 2 недели', 'Каждый месяц'], ['Every day', 'Every 2 days', 'Every week', 'Every 2 week', 'Every month']],
txt: ['', '']
},
'language': {
sel: [['Ru', 'En'], ['Ru', 'En']],
txt: ['', '']
}
},
txtBtn: [
['Жирный', 'Bold'],
['Наклонный', 'Italic'],
['Подчеркнутый', 'Underlined'],
['Зачеркнутый', 'Strike'],
['Спойлер', 'Spoiler'],
['Код', 'Code'],
['Верхний индекс', 'Superscript'],
['Нижний индекс', 'Subscript'],
['Цитировать выделенное', 'Quote selected']
],
cfgTab: {
'filters': ['Фильтры', 'Filters'],
'posts': ['Посты', 'Posts'],
'images': ['Картинки', 'Images'],
'links': ['Ссылки', 'Links'],
'form': ['Форма', 'Form'],
'common': ['Общее', 'Common'],
'info': ['Инфо', 'Info']
},
panelBtn: {
'attach': ['Прикрепить/Открепить', 'Attach/Detach'],
'settings': ['Настройки', 'Settings'],
'hidden': ['Скрытое', 'Hidden'],
'favor': ['Избранное', 'Favorites'],
'refresh': ['Обновить', 'Refresh'],
'goback': ['Назад', 'Go back'],
'gonext': ['Следующая', 'Next'],
'goup': ['Наверх', 'To the top'],
'godown': ['В конец', 'To the bottom'],
'expimg': ['Раскрыть картинки', 'Expand images'],
'preimg': ['Предзагрузка картинок', 'Preload images'],
'maskimg': ['Маскировать картинки', 'Mask images'],
'upd-on': ['Выключить автообновление треда', 'Disable thread autoupdate'],
'upd-off': ['Включить автообновление треда', 'Enable thread autoupdate'],
'audio-off':['Звуковое оповещение о новых постах', 'Sound notification about new posts'],
'catalog': ['Каталог', 'Catalog'],
'counter': ['Постов/Изображений в треде', 'Posts/Images in thread'],
'imgload': ['Сохранить изображения из треда', 'Save images from thread']
},
selHiderMenu: {
'sel': ['Скрывать выделенное', 'Hide selected text'],
'name': ['Скрывать имя', 'Hide name'],
'trip': ['Скрывать трип-код', 'Hide with trip-code'],
'img': ['Скрывать изображение', 'Hide with image'],
'ihash': ['Скрывать схожие изобр.', 'Hide similar images'],
'text': ['Скрыть схожий текст', 'Hide similar text'],
'noimg': ['Скрывать без изображений', 'Hide without images'],
'notext': ['Скрывать без текста', 'Hide without text']
},
selExpandThrd: [
['5 постов', '15 постов', '30 постов', '50 постов', '100 постов'],
['5 posts', '15 posts', '30 posts', '50 posts', '100 posts']
],
selAjaxPages: [
['1 страница', '2 страницы', '3 страницы', '4 страницы', '5 страниц'],
['1 page', '2 pages', '3 pages', '4 pages', '5 pages']
],
selAudioNotif: [
['Каждые 30 сек.', 'Каждую минуту', 'Каждые 2 мин.', 'Каждые 5 мин.'],
['Every 30 sec.', 'Every minute', 'Every 2 min.', 'Every 5 min.']
],
keyNavEdit: [
'%l%i24 – предыдущая страница%/l' +
'%l%i33 – следующая страница%/l' +
'%l%i23 – скрыть текущий пост/тред%/l' +
'%l%i34 – раскрыть текущий тред%/l' +
'%l%i22 – быстрый ответ или создать тред%/l' +
'%l%i25t – отправить пост%/l' +
'%l%i21 – тред (на доске)/пост (в треде) ниже%/l' +
'%l%i20 – тред (на доске)/пост (в треде) выше%/l' +
'%l%i31 – пост (на доске) ниже%/l' +
'%l%i30 – пост (на доске) выше%/l' +
'%l%i32 – открыть тред%/l' +
'%l%i210 – открыть/закрыть настройки%/l' +
'%l%i26 – открыть/закрыть избранное%/l' +
'%l%i27 – открыть/закрыть скрытые посты%/l' +
'%l%i28 – открыть/закрыть панель%/l' +
'%l%i29 – включить/выключить маскировку изображений%/l' +
'%l%i40 – обновить тред%/l' +
'%l%i211 – раскрыть изображение текущего поста%/l' +
'%l%i212t – жирный%/l' +
'%l%i213t – курсив%/l' +
'%l%i214t – зачеркнутый%/l' +
'%l%i215t – спойлер%/l' +
'%l%i216t – код%/l',
'%l%i24 – previous page%/l' +
'%l%i33 – next page%/l' +
'%l%i23 – hide current post/thread%/l' +
'%l%i34 – expand current thread%/l' +
'%l%i22 – quick reply or create thread%/l' +
'%l%i25t – send post%/l' +
'%l%i21 – thread (on board) / post (in thread) below%/l' +
'%l%i20 – thread (on board) / post (in thread) above%/l' +
'%l%i31 – on board post below%/l' +
'%l%i30 – on board post above%/l' +
'%l%i32 – open thread%/l' +
'%l%i210 – open/close Settings%/l' +
'%l%i26 – open/close Favorites%/l' +
'%l%i27 – open/close Hidden Posts Table%/l' +
'%l%i28 – open/close the main panel%/l' +
'%l%i29 – turn on/off masking images%/l' +
'%l%i40 – update thread%/l' +
'%l%i211 – expand current post\'s images%/l' +
'%l%i212t – bold%/l' +
'%l%i213t – italic%/l' +
'%l%i214t – strike%/l' +
'%l%i215t – spoiler%/l' +
'%l%i216t – code%/l'
],
month: [
['янв', 'фев', 'мар', 'апр', 'мая', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек'],
['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
],
fullMonth: [
['января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'],
['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
],
week: [
['Вск', 'Пнд', 'Втр', 'Срд', 'Чтв', 'Птн', 'Сбт'],
['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat']
],
editor: {
cfg: ['Редактирование настроек:', 'Edit settings:'],
hidden: ['Редактирование скрытых тредов:', 'Edit hidden threads:'],
favor: ['Редактирование избранного:', 'Edit favorites:'],
css: ['Редактирование CSS', 'Edit CSS']
},
newPost: [
[' новый пост', ' новых поста', ' новых постов', '. Последний:'],
[' new post', ' new posts', ' new posts', '. Latest: ']
],
add: ['Добавить', 'Add'],
apply: ['Применить', 'Apply'],
clear: ['Очистить', 'Clear'],
refresh: ['Обновить', 'Refresh'],
load: ['Загрузить', 'Load'],
save: ['Сохранить', 'Save'],
edit: ['Правка', 'Edit'],
reset: ['Сброс', 'Reset'],
remove: ['Удалить', 'Remove'],
info: ['Инфо', 'Info'],
undo: ['Отмена', 'Undo'],
change: ['Сменить', 'Change'],
reply: ['Ответ', 'Reply'],
loading: ['Загрузка...', 'Loading...'],
checking: ['Проверка...', 'Checking...'],
deleting: ['Удаление...', 'Deleting...'],
error: ['Ошибка:', 'Error:'],
noConnect: ['Ошибка подключения', 'Connection failed'],
thrNotFound: ['Тред недоступен (№', 'Thread is unavailable (№'],
succDeleted: ['Успешно удалено!', 'Succesfully deleted!'],
errDelete: ['Не могу удалить:\n', 'Can\'t delete:\n'],
cTimeError: ['Неправильные настройки времени', 'Invalid time settings'],
noGlobalCfg: ['Глобальные настройки не найдены', 'Global config not found'],
postNotFound: ['Пост не найден', 'Post not found'],
dontShow: ['Не отображать: ', 'Do not show: '],
checkNow: ['Проверить сейчас', 'Check now'],
updAvail: ['Доступно обновление!', 'Update available!'],
haveLatest: ['У вас стоит самая последняя версия!', 'You have latest version!'],
storage: ['Хранение: ', 'Storage: '],
thrViewed: ['Тредов просмотрено: ', 'Threads viewed: '],
thrCreated: ['Тредов создано: ', 'Threads created: '],
thrHidden: ['Тредов скрыто: ', 'Threads hidden: '],
postsSent: ['Постов отправлено: ', 'Posts sent: '],
total: ['Всего: ', 'Total: '],
debug: ['Отладка', 'Debug'],
infoDebug: ['Информация для отладки', 'Information for debugging'],
loadGlobal: ['Загрузить глобальные настройки', 'Load global settings'],
saveGlobal: ['Сохранить настройки как глобальные', 'Save settings as global'],
editInTxt: ['Правка в текстовом формате', 'Edit in text format'],
resetCfg: ['Сбросить в настройки по умолчанию', 'Reset settings to defaults'],
conReset: ['Данное действие удалит все ваши настройки и закладки. Продолжить?', 'This will delete all your preferences and favourites. Continue?'],
clrSelected: ['Удалить выделенные записи', 'Remove selected notes'],
saveChanges: ['Сохранить внесенные изменения', 'Save your changes'],
infoCount: ['Обновить счетчики постов', 'Refresh posts counters'],
infoPage: ['Проверить актуальность тредов (до 5 страницы)', 'Check for threads actuality (up to 5 page)'],
clrDeleted: ['Очистить записи недоступных тредов', 'Clear notes of inaccessible threads'],
hiddenPosts: ['Скрытые посты на странице', 'Hidden posts on page'],
hiddenThrds: ['Скрытые треды', 'Hidden threads'],
noHidPosts: ['На этой странице нет скрытых постов...', 'No hidden posts on this page...'],
noHidThrds: ['Нет скрытых тредов...', 'No hidden threads...'],
expandAll: ['Раскрыть все', 'Expand all'],
invalidData: ['Некорректный формат данных', 'Incorrect data format'],
favThrds: ['Избранные треды:', 'Favorite threads:'],
noFavThrds: ['Нет избранных тредов...', 'Favorites is empty...'],
reply: ['Ответ', 'Reply'],
replyTo: ['Ответ в', 'Reply to'],
replies: ['Ответы:', 'Replies:'],
postsOmitted: ['Пропущено ответов: ', 'Posts omitted: '],
collapseThrd: ['Свернуть тред', 'Collapse thread'],
deleted: ['удалён', 'deleted'],
getNewPosts: ['Получить новые посты', 'Get new posts'],
page: ['Страница', 'Page'],
hiddenThrd: ['Скрытый тред:', 'Hidden thread:'],
makeThrd: ['Создать тред', 'Create thread'],
makeReply: ['Ответить', 'Make reply'],
hideForm: ['Закрыть форму', 'Hide form'],
search: ['Искать в ', 'Search in '],
wait: ['Ждите', 'Wait'],
addFile: ['+ файл', '+ file'],
helpAddFile: ['Добавить .ogg, .rar, .zip, или .7z к картинке', 'Add .ogg, .rar, .zip, or .7z to image '],
downloadFile: ['Скачать содержащийся в картинке файл', 'Download existing file from image'],
fileCorrupt: ['Файл повреждён: ', 'File is corrupted: '],
subjHasTrip: ['Поле "Тема" содержит трипкод', '"Subject" field contains tripcode'],
loadImage: ['Загружаются изображения: ', 'Loading images: '],
loadFile: ['Загружаются файлы: ', 'Loading files: '],
cantLoad: ['Не могу загрузить ', 'Can\'t load '],
willSavePview: ['Будет сохранено превью', 'Thumb will be saved'],
loadErrors: ['Во время загрузки произошли ошибки:', 'Warning:'],
errCorruptData: ['Ошибка: сервер отправил повреждённые данные', 'Error: server sent corrupted data'],
nextImg: ['Следующее изображение', 'Next image'],
prevImg: ['Предыдущее изображение', 'Previous image'],
seSyntaxErr: ['синтаксическая ошибка в аргументе спелла: %s', 'syntax error in argument of spell: %s'],
seUnknown: ['неизвестный спелл: %s', 'unknown spell: %s'],
seMissOp: ['пропущен оператор', 'missing operator'],
seMissArg: ['пропущен аргумент спелла: %s', 'missing argument of spell: %s'],
seMissSpell: ['пропущен спелл', 'missing spell'],
seErrRegex: ['синтаксическая ошибка в регулярном выражении: %s', 'syntax error in regular expression: %s'],
seUnexpChar: ['неожиданный символ: %s', 'unexpected character: %s'],
seMissClBkt: ['пропущена закрывающаяся скобка', 'missing ) in parenthetical'],
seRow: [' (строка ', ' (row '],
seCol: [', столбец ', ', column ']
},
doc = window.document, aProto = Array.prototype,
Cfg, comCfg, hThr, Favor, pByNum, sVis, bUVis, uVis, needScroll,
aib, nav, brd, TNum, pageNum, updater, youTube, keyNav, firstThr, lastThr, visPosts = 2,
pr, dForm, dummy, spells,
Images_ = {preloading: false, afterpreload: null, progressId: null, canvas: null},
oldTime, timeLog = [], dTime,
ajaxInterval, lang, quotetxt = '', liteMode, isExpImg, isPreImg,
$each = Function.prototype.call.bind(aProto.forEach),
emptyFn = function() {};
//============================================================================================================
// UTILITIES
//============================================================================================================
function $Q(path, root) {
return root.querySelectorAll(path);
}
function $q(path, root) {
return root.querySelector(path);
}
function $C(id, root) {
return root.getElementsByClassName(id);
}
function $c(id, root) {
return root.getElementsByClassName(id)[0];
}
function $id(id) {
return doc.getElementById(id);
}
function $T(id, root) {
return root.getElementsByTagName(id);
}
function $t(id, root) {
return root.getElementsByTagName(id)[0];
}
function $append(el, nodes) {
for(var i = 0, len = nodes.length; i < len; i++) {
if(nodes[i]) {
el.appendChild(nodes[i]);
}
}
}
function $before(el, node) {
el.parentNode.insertBefore(node, el);
}
function $after(el, node) {
el.parentNode.insertBefore(node, el.nextSibling);
}
function $add(html) {
dummy.innerHTML = html;
return dummy.firstChild;
}
function $new(tag, attr, events) {
var el = doc.createElement(tag);
if(attr) {
for(var key in attr) {
key === 'text' ? el.textContent = attr[key] :
key === 'value' ? el.value = attr[key] :
el.setAttribute(key, attr[key]);
}
}
if(events) {
for(var key in events) {
el.addEventListener(key, events[key], false);
}
}
return el;
}
function $New(tag, attr, nodes) {
var el = $new(tag, attr, null);
$append(el, nodes);
return el;
}
function $txt(el) {
return doc.createTextNode(el);
}
function $btn(val, ttl, Fn) {
return $new('input', {'type': 'button', 'value': val, 'title': ttl}, {'click': Fn});
}
function $script(text) {
$del(doc.head.appendChild($new('script', {'type': 'text/javascript', 'text': text}, null)));
}
function $css(text) {
return doc.head.appendChild($new('style', {'type': 'text/css', 'text': text}, null));
}
function $if(cond, el) {
return cond ? el : null;
}
function $disp(el) {
el.style.display = el.style.display === 'none' ? '' : 'none';
}
function $del(el) {
if(el) {
el.parentNode.removeChild(el);
}
}
function $DOM(html) {
var myDoc = doc.implementation.createHTMLDocument('');
myDoc.documentElement.innerHTML = html;
return myDoc;
}
function $getStyle(el, prop) {
return getComputedStyle(el).getPropertyValue(prop);
}
function $pd(e) {
e.preventDefault();
}
function $txtInsert(el, txt) {
var scrtop = el.scrollTop,
start = el.selectionStart;
el.value = el.value.substr(0, start) + txt + el.value.substr(el.selectionEnd);
el.setSelectionRange(start + txt.length, start + txt.length);
el.focus();
el.scrollTop = scrtop;
}
function $txtSelect() {
return (nav.Opera ? doc.getSelection() : window.getSelection()).toString();
}
function $isEmpty(obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
return false;
}
}
return true;
}
function $log(txt) {
var newTime = Date.now(),
time = newTime - oldTime;
if(time > 1) {
timeLog.push(txt + ': ' + time + 'ms');
oldTime = newTime;
}
}
function $xhr(obj) {
var h, xhr = new window.XMLHttpRequest();
if(obj['onreadystatechange']) {
xhr.onreadystatechange = obj['onreadystatechange'].bind(window, xhr);
}
if(obj['onload']) {
xhr.onload = obj['onload'].bind(window, xhr);
}
xhr.open(obj['method'], obj['url'], true);
if(obj['responseType']) {
xhr.responseType = obj['responseType'];
}
for(h in obj['headers']) {
xhr.setRequestHeader(h, obj['headers'][h]);
}
xhr.send(obj['data'] || null);
return xhr;
}
function $queue(maxNum, Fn, endFn) {
this.array = [];
this.length = this.index = this.running = 0;
this.num = 1;
this.fn = Fn;
this.endFn = endFn;
this.max = maxNum;
this.freeSlots = [];
while(maxNum--) {
this.freeSlots.push(maxNum);
}
this.completed = this.paused = false;
}
$queue.prototype = {
run: function(data) {
if(this.paused || this.running === this.max) {
this.array.push(data);
this.length++;
} else {
this.fn(this.freeSlots.pop(), this.num++, data);
this.running++;
}
},
end: function(qIdx) {
if(!this.paused && this.index < this.length) {
this.fn(qIdx, this.num++, this.array[this.index++]);
return;
}
this.running--;
this.freeSlots.push(qIdx);
if(!this.paused && this.completed && this.running === 0) {
this.endFn();
}
},
complete: function() {
if(this.index >= this.length && this.running === 0) {
this.endFn();
} else {
this.completed = true;
}
},
pause: function() {
this.paused = true;
},
'continue': function() {
this.paused = false;
if(this.index >= this.length) {
if(this.completed) {
this.endFn();
}
return;
}
while(this.index < this.length && this.running !== this.max) {
this.fn(this.freeSlots.pop(), this.num++, this.array[this.index++]);
this.running++;
}
}
};
function $tar() {
this._data = [];
}
$tar.prototype = {
addFile: function(filepath, input) {
var i, checksum, nameLen, fileSize = input.length,
header = new Uint8Array(512);
for(i = 0, nameLen = Math.min(filepath.length, 100); i < nameLen; ++i) {
header[i] = filepath.charCodeAt(i) & 0xFF;
}
this._padSet(header, 100, '100777', 8); // fileMode
this._padSet(header, 108, '0', 8); // uid
this._padSet(header, 116, '0', 8); // gid
this._padSet(header, 124, fileSize.toString(8), 13); // fileSize
this._padSet(header, 136, Math.floor(Date.now() / 1000).toString(8), 12); // mtime
this._padSet(header, 148, ' ', 8); // checksum
header[156] = 0x30; // type ('0')
for(i = checksum = 0; i < 157; i++) {
checksum += header[i];
}
this._padSet(header, 148, checksum.toString(8), 8); // checksum
this._data.push(header);
this._data.push(input);
if((i = Math.ceil(fileSize / 512) * 512 - fileSize) !== 0) {
this._data.push(new Uint8Array(i));
}
},
addString: function(filepath, str) {
var i, len, data, sDat = unescape(encodeURIComponent(str));
for(i = 0, len = sDat.length, data = new Uint8Array(len); i < len; ++i) {
data[i] = sDat.charCodeAt(i) & 0xFF;
}
this.addFile(filepath, data);
},
get: function() {
this._data.push(new Uint8Array(1024));
return new Blob(this._data, {'type': 'application/x-tar'});
},
_padSet: function(data, offset, num, len) {
var i = 0, nLen = num.length;
len -= 2;
while(nLen < len) {
data[offset++] = 0x20; // ' '
len--;
}
while(i < nLen) {
data[offset++] = num.charCodeAt(i++);
}
data[offset] = 0x20; // ' '
}
};
function $workers(source, count) {
var i, wrk, wUrl;
if(nav.Firefox) {
wUrl = 'data:text/javascript,' + source;
wrk = unsafeWindow.Worker;
} else {
wUrl = window.URL.createObjectURL(new Blob([source], {'type': 'text/javascript'}));
this.url = wUrl;
wrk = Worker;
}
for(i = 0; i < count; ++i) {
this[i] = new wrk(wUrl);
}
}
$workers.prototype = {
url: null,
clear: function() {
if(this.url !== null) {
window.URL.revokeObjectURL(this.url);
}
}
};
function regQuote(str) {
return (str + '').replace(/([.?*+^$[\]\\(){}|\-])/g, '\\$1');
}
function getImages(el) {
return el.querySelectorAll('.thumb, .de-thumb, .ca_thumb, ' +
'img[src*="thumb"], img[src*="/spoiler"], img[src^="blob:"]');
}
function fixBrd(b) {
return '/' + b + (b ? '/' : '');
}
function getAbsLink(url) {
return url[1] === '/' ? aib.prot + url :
url[0] === '/' ? aib.prot + '//' + aib.host + url : url;
}
function getErrorMessage(eCode, eMsg) {
return eCode === 0 ? eMsg || Lng.noConnect[lang] : 'HTTP [' + eCode + '] ' + eMsg;
}
function getAncestor(el, tagName) {
do {
el = el.parentElement;
} while(el && el.tagName !== tagName);
return el;
}
function getPrettyErrorMessage(e) {
return e.stack ? (nav.WebKit ? e.stack :
e.name + ': ' + e.message + '\n' +
(nav.Firefox ? e.stack.replace(/^([^@]*).*\/(.+)$/gm, function(str, fName, line) {
return ' at ' + (fName ? fName + ' (' + line + ')' : line);
}) : e.stack)
) : e.name + ': ' + e.message;
}
function toRegExp(str, noG) {
var l = str.lastIndexOf('/'),
flags = str.substr(l + 1);
return new RegExp(str.substr(1, l - 1), noG ? flags.replace('g', '') : flags);
}
//============================================================================================================
// STORAGE & CONFIG
//============================================================================================================
function getStored(id) {
return nav.isGM ? GM_getValue(id) :
nav.isSStorage ? scriptStorage.getItem(id) :
localStorage.getItem(id);
}
function setStored(id, value) {
if(nav.isGM) {
GM_setValue(id, value);
} else if(nav.isSStorage) {
scriptStorage.setItem(id, value);
} else {
localStorage.setItem(id, value);
}
}
function delStored(id) {
if(nav.isGM) {
GM_deleteValue(id);
} else if(nav.isSStorage) {
scriptStorage.removeItem(id);
} else {
localStorage.removeItem(id);
}
}
function getStoredObj(id) {
try {
var data = JSON.parse(getStored(id));
} finally {
return data || {};
}
}
function saveComCfg(dm, obj) {
comCfg = getStoredObj('DESU_Config');
if(obj) {
comCfg[dm] = obj;
} else {
delete comCfg[dm];
}
setStored('DESU_Config', JSON.stringify(comCfg) || '');
}
function saveCfg(id, val) {
if(Cfg[id] !== val) {
Cfg[id] = val;
saveComCfg(aib.dm, Cfg);
}
}
function readCfg() {
comCfg = getStoredObj('DESU_Config');
if(!(aib.dm in comCfg) || $isEmpty(Cfg = comCfg[aib.dm])) {
Cfg = {};
if(nav.isGlobal) {
for(var i in comCfg['global']) {
Cfg[i] = comCfg['global'][i];
}
}
Cfg['captchaLang'] = aib.ru ? 2 : 1;
Cfg['correctTime'] = 0;
}
Cfg.__proto__ = defaultCfg;
if(!Cfg['timeOffset']) {
Cfg['timeOffset'] = '+0';
}
if(!Cfg['timePattern']) {
Cfg['timePattern'] = aib.timePattern;
}
if(nav.noBlob) {
Cfg['preLoadImgs'] = 0;
if(Cfg['ajaxReply'] === 2) {
Cfg['ajaxReply'] = 1;
}
}
if(aib.tiny && Cfg['ajaxReply'] === 2) {
Cfg['ajaxReply'] = 1;
}
if(!nav.Firefox) {
defaultCfg['favIcoBlink'] = 0;
}
if(!('Notification' in window)) {
Cfg['desktNotif'] = 0;
}
if(nav.Opera) {
if(nav.oldOpera) {
if(!nav.isGM) {
Cfg['YTubeTitles'] = 0;
}
Cfg['animation'] = 0;
}
if(Cfg['YTubeType'] === 2) {
Cfg['YTubeType'] = 1;
}
Cfg['preLoadImgs'] = 0;
Cfg['findImgFile'] = 0;
if(!nav.isGM) {
Cfg['updScript'] = 0;
}
}
if(Cfg['updThrDelay'] < 10) {
Cfg['updThrDelay'] = 10;
}
if(!Cfg['saveSage']) {
Cfg['sageReply'] = 0;
}
if(!Cfg['passwValue']) {
Cfg['passwValue'] = Math.round(Math.random() * 1e15).toString(32);
}
if(!Cfg['stats']) {
Cfg['stats'] = {'view': 0, 'op': 0, 'reply': 0};
}
if(TNum) {
Cfg['stats']['view']++;
}
saveComCfg(aib.dm, Cfg);
lang = Cfg['language'];
if(Cfg['correctTime']) {
dTime = new dateTime(Cfg['timePattern'], Cfg['timeRPattern'], Cfg['timeOffset'], lang, function(rp) {
saveCfg('timeRPattern', rp);
});
}
if(aib.dobr) {
aib.hDTFix = new dateTime(
'yyyy-nn-dd-hh-ii-ss',
'_d _M _y (_w) _h:_i ',
Cfg['timeOffset'] || 0,
Cfg['correctTime'] ? lang : 1,
null
);
}
}
function toggleCfg(id) {
saveCfg(id, +!Cfg[id]);
}
function readPosts() {
var data, str = TNum ? sessionStorage['de-hidden-' + brd + TNum] : null;
if(typeof str === 'string') {
data = str.split(',');
if(data.length === 4 && +data[0] === (Cfg['hideBySpell'] ? spells.hash : 0) &&
(data[1] in pByNum) && pByNum[data[1]].count === +data[2])
{
sVis = data[3].split('');
return;
}
}
sVis = [];
}
function readUserPosts() {
bUVis = getStoredObj('DESU_Posts_' + aib.dm);
uVis = bUVis[brd];
if(!uVis) {
bUVis[brd] = uVis = getStoredObj('DESU_Posts_' + aib.dm + '_' + brd);
delStored('DESU_Posts_' + aib.dm + '_' + brd);
}
hThr = getStoredObj('DESU_Threads_' + aib.dm);
if(!(brd in hThr)) {
hThr[brd] = {};
}
}
function savePosts() {
if(TNum) {
var lPost = firstThr.lastNotDeleted;
sessionStorage['de-hidden-' + brd + TNum] = (Cfg['hideBySpell'] ? spells.hash : '0') +
',' + lPost.num + ',' + lPost.count + ',' + sVis.join('');
}
saveHiddenThreads(false);
toggleContent('hid', true);
}
function saveUserPosts() {
var minDate, b, vis, key, str = JSON.stringify(bUVis);
if(str.length > 1e6) {
minDate = Date.now() - 5 * 24 * 3600 * 1000;
for(b in bUVis) {
if(bUVis.hasOwnProperty(b)) {
vis = bUVis[b];
for(key in vis) {
if(vis.hasOwnProperty(key) && vis[key][1] < minDate) {
delete vis[key];
}
}
}
}
str = JSON.stringify(bUVis);
}
setStored('DESU_Posts_' + aib.dm, str);
toggleContent('hid', true);
}
function saveHiddenThreads(updContent) {
setStored('DESU_Threads_' + aib.dm, JSON.stringify(hThr));
if(updContent) {
toggleContent('hid', true);
}
}
function readFavorites() {
Favor = getStoredObj('DESU_Favorites');
}
function saveFavorites() {
setStored('DESU_Favorites', JSON.stringify(Favor));
toggleContent('fav', true);
}
function removeFavorites(h, b, tNum) {
delete Favor[h][b][tNum];
if($isEmpty(Favor[h][b])) {
delete Favor[h][b];
}
if($isEmpty(Favor[h])) {
delete Favor[h];
}
if(pByNum[tNum]) {
($c('de-btn-fav-sel', pByNum[tNum].btns) || {}).className = 'de-btn-fav';
}
}
function toggleFavorites(post, btn) {
var h = aib.host,
b = brd,
tNum = post.num;
if(!btn) {
return;
}
readFavorites();
if(Favor[h] && Favor[h][b] && Favor[h][b][tNum]) {
removeFavorites(h, b, tNum);
saveFavorites();
return;
}
if(!Favor[h]) {
Favor[h] = {};
}
if(!Favor[h][b]) {
Favor[h][b] = {};
}
Favor[h][b][tNum] = {
'cnt': post.thr.pcount,
'txt': post.title,
'url': aib.getThrdUrl(brd, tNum)
};
btn.className = 'de-btn-fav-sel';
saveFavorites();
}
function readViewedPosts() {
if(Cfg['markViewed']) {
var data = sessionStorage['de-viewed'];
if(data) {
data.split(',').forEach(function(pNum) {
var post = pByNum[pNum];
if(post) {
post.el.classList.add('de-viewed');
post.viewed = true;
}
});
}
}
}
//============================================================================================================
// MAIN PANEL
//============================================================================================================
function pButton(id, href, hasHotkey) {
return '<li><a id="de-btn-' + id + '" class="de-abtn" ' + (hasHotkey ? 'de-' : '') + 'title="' +
Lng.panelBtn[id][lang] +'" href="' + href + '"></a></li>';
}
function addPanel() {
var panel, evtObject, imgLen = getImages(dForm).length;
(pr.pArea[0] || dForm).insertAdjacentHTML('beforebegin',
'<div id="de-main" lang="' + getThemeLang() + '">' +
'<div class="de-content"></div>' +
'<div id="de-panel">' +
'<span id="de-btn-logo" title="' + Lng.panelBtn['attach'][lang] + '"></span>' +
'<ul id="de-panel-btns"' + (Cfg['expandPanel'] ? '>' : ' style="display: none">') +
pButton('settings', '#', true) +
pButton('hidden', '#', true) +
pButton('favor', '#', true) +
(aib.arch ? '' :
pButton('refresh', '#', false) +
(!TNum && (pageNum === aib.firstPage) ? '' :
pButton('goback', aib.getPageUrl(brd, pageNum - 1), true)) +
(TNum || pageNum === aib.lastPage ? '' :
pButton('gonext', aib.getPageUrl(brd, pageNum + 1), true))
) + pButton('goup', '#', false) +
pButton('godown', '#', false) +
(imgLen === 0 ? '' :
pButton('expimg', '#', false) +
(Cfg['preLoadImgs'] || nav.Opera || nav.noBlob ? '' : pButton('preimg', '#', false)) +
pButton('maskimg', '#', true)) +
(!TNum ? '' :
pButton(Cfg['ajaxUpdThr'] ? 'upd-on' : 'upd-off', '#', false) +
(nav.Safari ? '' : pButton('audio-off', '#', false))) +
(!aib.nul && !aib.abu && (!aib.fch || aib.arch) ? '' :
pButton('catalog', '//' + aib.host + '/' + (aib.abu ?
'makaba/makaba.fcgi?task=catalog&board=' + brd : brd + '/catalog.html'), false)) +
(!TNum && !aib.arch? '' :
(nav.Opera || nav.noBlob ? '' : pButton('imgload', '#', false)) +
'<div id="de-panel-info"><span title="' + Lng.panelBtn['counter'][lang] +
'">' + firstThr.pcount + '/' + imgLen + '</span></div>') +
'</ul>' +
'</div>' +
'<div id="de-img-btns" style="display: none">' +
'<div id="de-img-btn-next" title="' + Lng.nextImg[lang] + '"><div></div></div>' +
'<div id="de-img-btn-prev" title="' + Lng.prevImg[lang] + '"><div></div></div></div>' +
'<div id="de-alert"></div>' +
'<hr style="clear: both;">' +
'</div>'
);
panel = $id('de-panel');
evtObject = {
attach: false,
odelay: 0,
panel: panel,
setTitleWithKey: function(el, isGlob, idx) {
var title = el.getAttribute('de-title');
if(keyNav) {
title += ' [' + KeyEditListener.getStrKey(isGlob ? keyNav.gKeys[idx] : keyNav.ntKeys[idx]) + ']';
}
el.title = title;
},
handleEvent: function(e) {
switch(e.type) {
case 'click':
switch(e.target.id) {
case 'de-btn-logo':
if(Cfg['expandPanel']) {
this.panel.lastChild.style.display = 'none';
this.attach = false;
} else {
this.attach = true;
}
toggleCfg('expandPanel');
return;
case 'de-btn-settings': this.attach = toggleContent('cfg', false); break;
case 'de-btn-hidden': this.attach = toggleContent('hid', false); break;
case 'de-btn-favor': this.attach = toggleContent('fav', false); break;
case 'de-btn-refresh': window.location.reload(); break;
case 'de-btn-goup': scrollTo(0, 0); break;
case 'de-btn-godown': scrollTo(0, doc.body.scrollHeight || doc.body.offsetHeight); break;
case 'de-btn-expimg':
isExpImg = !isExpImg;
$del($c('de-img-center', doc));
for(var post = firstThr.op; post; post = post.next) {
post.toggleImages(isExpImg);
}
break;
case 'de-btn-preimg':
isPreImg = !isPreImg;
preloadImages(null);
break;
case 'de-btn-maskimg':
toggleCfg('maskImgs');
updateCSS();
break;
case 'de-btn-upd-on':
case 'de-btn-upd-off':
case 'de-btn-upd-warn':
if(updater.enabled) {
updater.disable();
} else {
updater.enable();
}
break;
case 'de-btn-audio-on':
case 'de-btn-audio-off':
if(updater.toggleAudio(0)) {
updater.enable();
e.target.id = 'de-btn-audio-on';
} else {
e.target.id = 'de-btn-audio-off';
}
$del($c('de-menu', doc));
break;
case 'de-btn-imgload':
if($id('de-alert-imgload')) {
break;
}
if(Images_.preloading) {
$alert(Lng.loading[lang], 'imgload', true);
Images_.afterpreload = loadDocFiles.bind(null, true);
Images_.progressId = 'imgload';
} else {
loadDocFiles(true);
}
break;
default: return;
}
$pd(e);
return;
case 'mouseover':
if(!Cfg['expandPanel']) {
clearTimeout(this.odelay);
this.panel.lastChild.style.display = '';
}
switch(e.target.id) {
case 'de-btn-settings': this.setTitleWithKey(e.target, true, 10); break;
case 'de-btn-hidden': this.setTitleWithKey(e.target, true, 7); break;
case 'de-btn-favor': this.setTitleWithKey(e.target, true, 6); break;
case 'de-btn-goback': this.setTitleWithKey(e.target, true, 4); break;
case 'de-btn-gonext': this.setTitleWithKey(e.target, false, 3); break;
case 'de-btn-maskimg': this.setTitleWithKey(e.target, true, 9); break;
case 'de-btn-refresh':
if(TNum) {
return;
}
case 'de-btn-audio-off': addMenu(e);
}
return;
default: // mouseout
if(!Cfg['expandPanel'] && !this.attach) {
this.odelay = setTimeout(function(obj) {
obj.panel.lastChild.style.display = 'none';
obj.attach = false;
}, 500, this);
}
switch(e.target.id) {
case 'de-btn-refresh':
case 'de-btn-audio-off': removeMenu(e); break;
}
}
}
};
panel.addEventListener('click', evtObject, true);
panel.addEventListener('mouseover', evtObject, false);
panel.addEventListener('mouseout', evtObject, false);
}
function toggleContent(name, isUpd) {
if(liteMode) {
return false;
}
var remove, el = $c('de-content', doc),
id = 'de-content-' + name;
if(!el) {
return false;
}
if(isUpd && el.id !== id) {
return true;
}
remove = !isUpd && el.id === id;
if(el.hasChildNodes() && Cfg['animation']) {
nav.animEvent(el, function(node) {
showContent(node, id, name, remove);
id = name = remove = null;
});
el.className = 'de-content de-cfg-close';
return !remove;
} else {
showContent(el, id, name, remove);
return !remove;
}
}
function addContentBlock(parent, title) {
return parent.appendChild($New('div', {'class': 'de-content-block'}, [
$new('input', {'type': 'checkbox'}, {'click': function() {
var el, res = this.checked, i = 0, els = $Q('.de-entry > div > input', this.parentNode);
for(; el = els[i++];) {
el.checked = res;
}
}}),
$new('b', {'text': title}, null)
]));
}
function showContent(cont, id, name, remove) {
var h, b, tNum, i, els, post, cln, block;
cont.innerHTML = cont.style.backgroundColor = '';
if(remove) {
cont.removeAttribute('id');
return;
}
cont.id = id;
if(name === 'cfg') {
addSettings(cont);
} else if(Cfg['attachPanel']) {
cont.style.backgroundColor = $getStyle(doc.body, 'background-color');
}
if(name === 'hid') {
for(i = 0, els = $C('de-post-hid', dForm); post = els[i++];) {
if(post.isOp) {
continue;
}
(cln = post.cloneNode(true)).removeAttribute('id');
cln.style.display = '';
if(cln.classList.contains(aib.cRPost)) {
cln.classList.add('de-cloned-post');
} else {
cln.className = aib.cReply + ' de-cloned-post';
}
cln.post = Object.create(cln.clone = post.post);
cln.post.el = cln;
cln.btn = $q('.de-btn-hide, .de-btn-hide-user', cln);
cln.btn.parentNode.className = 'de-ppanel';
cln.btn.onclick = function() {
this.toggleContent(this.hidden = !this.hidden);
}.bind(cln);
(block || (block = cont.appendChild(
$add('<div class="de-content-block"><b>' + Lng.hiddenPosts[lang] + ':</b></div>')
))).appendChild($New('div', {'class': 'de-entry'}, [cln]));
}
if(block) {
$append(cont, [
$btn(Lng.expandAll[lang], '', function() {
$each($Q('.de-cloned-post', this.parentNode), function(el) {
var post = el.post;
post.toggleContent(post.hidden = !post.hidden);
});
this.value = this.value === Lng.undo[lang] ? Lng.expandAll[lang] : Lng.undo[lang];
}),
$btn(Lng.save[lang], '', function() {
$each($Q('.de-cloned-post', this.parentNode), function(date, el) {
if(!el.post.hidden) {
el.clone.setUserVisib(false, date, true);
}
}.bind(null, Date.now()));
saveUserPosts();
})
]);
} else {
cont.appendChild($new('b', {'text': Lng.noHidPosts[lang]}, null));
}
$append(cont, [
doc.createElement('hr'),
$new('b', {'text': ($isEmpty(hThr) ? Lng.noHidThrds[lang] : Lng.hiddenThrds[lang] + ':')}, null)
]);
for(b in hThr) {
if(!$isEmpty(hThr[b])) {
block = addContentBlock(cont, '/' + b);
for(tNum in hThr[b]) {
block.insertAdjacentHTML('beforeend', '<div class="de-entry" info="' + b + ';' +
tNum + '"><div class="' + aib.cReply + '"><input type="checkbox"><a href="' +
aib.getThrdUrl(b, tNum) + '" target="_blank">№' + tNum + '</a> - ' +
hThr[b][tNum] + '</div></div>');
}
}
}
$append(cont, [
doc.createElement('hr'),
addEditButton('hidden', hThr, true, function(data) {
hThr = data;
if(!(brd in hThr)) {
hThr[brd] = {};
}
firstThr.updateHidden(hThr[brd]);
saveHiddenThreads(true);
localStorage['__de-threads'] = JSON.stringify(hThr);
localStorage.removeItem('__de-threads');
}),
$btn(Lng.clear[lang], Lng.clrDeleted[lang], function() {
$each($Q('.de-entry[info]', this.parentNode), function(el) {
var arr = el.getAttribute('info').split(';');
ajaxLoad(aib.getThrdUrl(arr[0], arr[1]), false, null, function(eCode, eMsg, xhr) {
if(eCode === 404) {
delete hThr[this[0]][this[1]];
saveHiddenThreads(true);
}
}.bind(arr));
});
}),
$btn(Lng.remove[lang], Lng.clrSelected[lang], function() {
$each($Q('.de-entry[info]', this.parentNode), function(date, el) {
var post, arr = el.getAttribute('info').split(';');
if($t('input', el).checked) {
if(arr[1] in pByNum) {
pByNum[arr[1]].setUserVisib(false, date, true);
} else {
localStorage['__de-post'] = JSON.stringify({
'brd': arr[0],
'date': date,
'isOp': true,
'num': arr[1],
'hide': false
});
localStorage.removeItem('__de-post');
}
delete hThr[arr[0]][arr[1]];
}
}.bind(null, Date.now()));
saveHiddenThreads(true);
})
]);
}
if(name === 'fav') {
readFavorites();
for(h in Favor) {
for(b in Favor[h]) {
block = addContentBlock(cont, h + '/' + b);
for(tNum in Favor[h][b]) {
i = Favor[h][b][tNum];
if(!i['url'].startsWith('http')) {
i['url'] = (h === aib.host ? aib.prot + '//' : 'http://') + h + i['url'];
}
block.appendChild($New('div', {'class': 'de-entry', 'info': h + ';' + b + ';' + tNum}, [
$New('div', {'class': aib.cReply}, [
$add('<input type="checkbox">'),
$new('span', {'class': 'de-btn-expthr'}, {'click': loadFavorThread}),
$add('<a href="' + i['url'] + '">№' + tNum + '</a>'),
$add('<span class="de-fav-title"> - ' + i['txt'] + '</span>'),
$add('<span class="de-fav-inf-page"></span>'),
$add('<span class="de-fav-inf-posts">[<span class="de-fav-inf-old">' +
i['cnt'] + '</span>]</span>')
])
]));
}
}
}
cont.insertAdjacentHTML('afterbegin', '<b>' + (Lng[block ? 'favThrds' : 'noFavThrds'][lang]) + '</b>');
$append(cont, [
doc.createElement('hr'),
addEditButton('favor', Favor, true, function(data) {
Favor = data;
setStored('DESU_Favorites', JSON.stringify(Favor));
toggleContent('fav', true);
}),
$btn(Lng.info[lang], Lng.infoCount[lang], function() {
$each($C('de-entry', doc), function(el) {
var c, arr = el.getAttribute('info').split(';'),
f = Favor[arr[0]][arr[1]][arr[2]];
if(arr[0] !== aib.host) {
return;
}
c = $c('de-fav-inf-posts', el).firstElementChild;
c.className = 'de-wait';
c.textContent = '';
ajaxLoad(aib.getThrdUrl(arr[1], arr[2]), true, function(form, xhr) {
var cnt = aib.getPosts(form).length + 1;
c.textContent = cnt;
if(cnt > f.cnt) {
c.className = 'de-fav-inf-new';
f.cnt = cnt;
setStored('DESU_Favorites', JSON.stringify(Favor));
} else {
c.className = 'de-fav-inf-old';
}
c = f = null;
}, function(eCode, eMsg, xhr) {
c.textContent = getErrorMessage(eCode, eMsg);
c.className = 'de-fav-inf-old';
c = null;
});
});
}),
$btn(Lng.page[lang], Lng.infoPage[lang], function() {
var i = 6,
loaded = 0;
$alert(Lng.loading[lang], 'load-pages', true);
while(i--) {
ajaxLoad(aib.getPageUrl(brd, i), true, function(idx, form, xhr) {
for(var arr, el, len = this.length, i = 0; i < len; ++i) {
arr = this[i].getAttribute('info').split(';');
if(arr[0] === aib.host && arr[1] === brd) {
el = $c('de-fav-inf-page', this[i]);
if((new RegExp('(?:№|No.|>)\\s*' + arr[2] + '\\s*<'))
.test(form.innerHTML))
{
el.innerHTML = '@' + idx;
} else if(loaded === 5 && !el.textContent.contains('@')) {
el.innerHTML = '@?';
}
}
}
if(loaded === 5) {
closeAlert($id('de-alert-load-pages'));
}
loaded++;
}.bind($C('de-entry', doc), i), function(eCode, eMsg, xhr) {
if(loaded === 5) {
closeAlert($id('de-alert-load-pages'));
}
loaded++;
});
}
}),
$btn(Lng.clear[lang], Lng.clrDeleted[lang], function() {
$each($C('de-entry', doc), function(el) {
var arr = el.getAttribute('info').split(';');
ajaxLoad(Favor[arr[0]][arr[1]][arr[2]]['url'], false, null, function(eCode, eMsg, xhr) {
if(eCode === 404) {
removeFavorites(arr[0], arr[1], arr[2]);
saveFavorites();
arr = null;
}
});
});
}),
$btn(Lng.remove[lang], Lng.clrSelected[lang], function() {
$each($C('de-entry', doc), function(el) {
var arr = el.getAttribute('info').split(';');
if($t('input', el).checked) {
removeFavorites(arr[0], arr[1], arr[2]);
}
});
saveFavorites();
})
]);
}
if(Cfg['animation']) {
cont.className = 'de-content de-cfg-open';
}
}
//============================================================================================================
// SETTINGS WINDOW
//============================================================================================================
function fixSettings() {
function toggleBox(state, arr) {
var i = arr.length,
nState = !state;
while(i--) {
($q(arr[i], doc) || {}).disabled = nState;
}
}
toggleBox(Cfg['ajaxUpdThr'], [
'input[info="noErrInTitle"]',
'input[info="favIcoBlink"]',
'input[info="markNewPosts"]',
'input[info="desktNotif"]'
]);
toggleBox(Cfg['expandImgs'], ['input[info="resizeImgs"]']);
toggleBox(Cfg['preLoadImgs'], ['input[info="findImgFile"]']);
toggleBox(Cfg['openImgs'], ['input[info="openGIFs"]']);
toggleBox(Cfg['linksNavig'], [
'input[info="linksOver"]',
'input[info="linksOut"]',
'input[info="markViewed"]',
'input[info="strikeHidd"]',
'input[info="noNavigHidd"]'
]);
toggleBox(Cfg['addYouTube'] && Cfg['addYouTube'] !== 4, [
'select[info="YTubeType"]', 'input[info="YTubeHD"]', 'input[info="addVimeo"]'
]);
toggleBox(Cfg['addYouTube'], [
'input[info="YTubeWidth"]', 'input[info="YTubeHeigh"]', 'input[info="YTubeTitles"]'
]);
toggleBox(Cfg['ajaxReply'] === 2, [
'input[info="postSameImg"]', 'input[info="removeEXIF"]', 'input[info="removeFName"]'
]);
toggleBox(Cfg['addTextBtns'], ['input[info="txtBtnsLoc"]']);
toggleBox(Cfg['updScript'], ['select[info="scrUpdIntrv"]']);
toggleBox(Cfg['keybNavig'], ['input[info="loadPages"]']);
}
function lBox(id, isBlock, Fn) {
var el = $new('input', {'info': id, 'type': 'checkbox'}, {'click': function() {
toggleCfg(this.getAttribute('info'));
fixSettings();
if(Fn) {
Fn(this);
}
}});
el.checked = Cfg[id];
return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + Lng.cfg[id][lang])]);
}
function inpTxt(id, size, Fn) {
return $new('input', {'info': id, 'type': 'text', 'size': size, 'value': Cfg[id]}, {
'keyup': Fn ? Fn : function() {
saveCfg(this.getAttribute('info'), this.value);
}
});
}
function optSel(id, isBlock, Fn) {
for(var i = 0, x = Lng.cfg[id], len = x.sel[lang].length, el, opt = ''; i < len; i++) {
opt += '<option value="' + i + '">' + x.sel[lang][i] + '</option>';
}
el = $add('<select info="' + id + '">' + opt + '</select>');
el.addEventListener('change', Fn || function() {
saveCfg(this.getAttribute('info'), this.selectedIndex);
fixSettings();
}, false);
el.selectedIndex = Cfg[id];
return $New('label', isBlock ? {'class': 'de-block'} : null, [el, $txt(' ' + x.txt[lang])]);
}
function cfgTab(name) {
return $New('div', {'class': aib.cReply + ' de-cfg-tab-back', 'selected': false}, [$new('div', {
'class': 'de-cfg-tab',
'text': Lng.cfgTab[name][lang],
'info': name}, {
'click': function() {
var el, id, pN = this.parentNode;
if(pN.getAttribute('selected') === 'true') {
return;
}
if(el = $c('de-cfg-body', doc)) {
el.className = 'de-cfg-unvis';
$q('.de-cfg-tab-back[selected="true"]', doc).setAttribute('selected', false);
}
pN.setAttribute('selected', true);
if(!(el = $id('de-cfg-' + (id = this.getAttribute('info'))))) {
$after($id('de-cfg-bar'), el =
id === 'posts' ? getCfgPosts() :
id === 'images' ? getCfgImages() :
id === 'links' ? getCfgLinks() :
id === 'form' ? getCfgForm() :
id === 'common' ? getCfgCommon() :
getCfgInfo()
);
}
el.className = 'de-cfg-body';
if(id === 'filters') {
$id('de-spell-edit').value = spells.list;
}
fixSettings();
}
})]);
}
function updRowMeter() {
var str, top = this.scrollTop,
el = this.parentNode.previousSibling.firstChild,
num = el.numLines || 1,
i = 15;
if(num - i < ((top / 12) | 0 + 1)) {
str = '';
while(i--) {
str += num++ + '<br>';
}
el.insertAdjacentHTML('beforeend', str);
el.numLines = num;
}
el.scrollTop = top;
}
function getCfgFilters() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-filters'}, [
lBox('hideBySpell', false, toggleSpells),
$New('div', {'id': 'de-spell-panel'}, [
$new('a', {
'id': 'de-btn-addspell',
'text': Lng.add[lang],
'href': '#',
'class': 'de-abtn'}, {
'click': $pd,
'mouseover': addMenu,
'mouseout': removeMenu
}),
$new('a', {'text': Lng.apply[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) {
$pd(e);
saveCfg('hideBySpell', 1);
$q('input[info="hideBySpell"]', doc).checked = true;
toggleSpells();
}}),
$new('a', {'text': Lng.clear[lang], 'href': '#', 'class': 'de-abtn'}, {'click': function(e) {
$pd(e);
$id('de-spell-edit').value = '';
toggleSpells();
}}),
$add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Spells-' +
(lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>')
]),
$New('div', {'id': 'de-spell-div'}, [
$add('<div><div id="de-spell-rowmeter"></div></div>'),
$New('div', null, [$new('textarea', {'id': 'de-spell-edit', 'wrap': 'off'}, {
'keydown': updRowMeter,
'scroll': updRowMeter
})])
]),
lBox('sortSpells', true, function() {
if (Cfg['sortSpells']) {
toggleSpells();
}
}),
lBox('menuHiddBtn', true, null),
lBox('hideRefPsts', true, null),
lBox('delHiddPost', true, function() {
$each($C('de-post-hid', dForm), function(el) {
var wrap = el.post.wrap,
hide = !wrap.classList.contains('de-hidden');
if(hide) {
wrap.insertAdjacentHTML('beforebegin',
'<span style="counter-increment: de-cnt 1;"></span>');
} else {
$del(wrap.previousSibling);
}
wrap.classList.toggle('de-hidden');
});
updateCSS();
})
]);
}
function getCfgPosts() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-posts'}, [
lBox('ajaxUpdThr', false, TNum ? function() {
if(Cfg['ajaxUpdThr']) {
updater.enable();
} else {
updater.disable();
}
} : null),
$New('label', null, [
inpTxt('updThrDelay', 4, null),
$txt(Lng.cfg['updThrDelay'][lang])
]),
$New('div', {'class': 'de-cfg-depend'}, [
lBox('noErrInTitle', true, null),
lBox('favIcoBlink', true, null),
lBox('markNewPosts', true, function() {
firstThr.clearPostsMarks();
}),
$if('Notification' in window, lBox('desktNotif', true, function() {
if(Cfg['desktNotif']) {
Notification.requestPermission();
}
}))
]),
optSel('expandPosts', true, null),
optSel('postBtnsCSS', true, null),
lBox('noSpoilers', true, updateCSS),
lBox('noPostNames', true, updateCSS),
lBox('noPostScrl', true, updateCSS),
$New('div', null, [
lBox('correctTime', false, dateTime.toggleSettings),
$add('<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/Settings-time-' +
(lang ? 'en' : 'ru') + '" class="de-abtn" target="_blank">[?]</a>')
]),
$New('div', {'class': 'de-cfg-depend'}, [
$New('div', null, [
inpTxt('timeOffset', 3, null),
$txt(Lng.cfg['timeOffset'][lang])
]),
$New('div', null, [
inpTxt('timePattern', 30, null),
$txt(Lng.cfg['timePattern'][lang])
]),
$New('div', null, [
inpTxt('timeRPattern', 30, null),
$txt(Lng.cfg['timeRPattern'][lang])
])
])
]);
}
function getCfgImages() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-images'}, [
optSel('expandImgs', true, null),
$New('div', {'style': 'padding-left: 25px;'}, [ lBox('resizeImgs', false, null)]),
$if(!nav.noBlob && !nav.Opera, lBox('preLoadImgs', true, null)),
$if(!nav.noBlob && !nav.Opera, $New('div', {'class': 'de-cfg-depend'}, [
lBox('findImgFile', true, null)
])),
lBox('openImgs', true, null),
$New('div', {'class': 'de-cfg-depend'}, [ lBox('openGIFs', false, null)]),
lBox('imgSrcBtns', true, null)
]);
}
function getCfgLinks() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-links'}, [
optSel('linksNavig', true, null),
$New('div', {'class': 'de-cfg-depend'}, [
$New('div', null, [
inpTxt('linksOver', 6, function() {
saveCfg('linksOver', +this.value | 0);
}),
$txt(Lng.cfg['linksOver'][lang])
]),
$New('div', null, [
inpTxt('linksOut', 6, function() {
saveCfg('linksOut', +this.value | 0);
}),
$txt(Lng.cfg['linksOut'][lang])
]),
lBox('markViewed', true, null),
lBox('strikeHidd', true, null),
lBox('noNavigHidd', true, null)
]),
lBox('crossLinks', true, null),
lBox('insertNum', true, null),
lBox('addMP3', true, null),
lBox('addImgs', true, null),
optSel('addYouTube', true, null),
$New('div', {'class': 'de-cfg-depend'}, [
$New('div', null, [
optSel('YTubeType', false, null),
inpTxt('YTubeWidth', 6, null),
$txt('×'),
inpTxt('YTubeHeigh', 6, null),
$txt(' '),
lBox('YTubeHD', false, null)
]),
$if(!nav.oldOpera || nav.isGM, lBox('YTubeTitles', false, null)),
lBox('addVimeo', true, null)
])
]);
}
function getCfgForm() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-form'}, [
optSel('ajaxReply', true, null),
$if(pr.form && !nav.noBlob, $New('div', {'class': 'de-cfg-depend'}, [
lBox('postSameImg', true, null),
lBox('removeEXIF', true, null),
lBox('removeFName', true, null)
])),
$if(pr.form, optSel('addPostForm', true, null)),
$if(pr.form, lBox('scrAfterRep', true, null)),
lBox('favOnReply', true, null),
$if(pr.mail, $New('div', null, [
lBox('addSageBtn', false, null),
lBox('saveSage', false, null)
])),
$if(pr.subj, lBox('warnSubjTrip', false, null)),
$if(pr.capTr, optSel('captchaLang', true, null)),
$if(pr.txta, $New('div', null, [
optSel('addTextBtns', false, function() {
saveCfg('addTextBtns', this.selectedIndex);
pr.addTextPanel();
}),
lBox('txtBtnsLoc', false, pr.addTextPanel.bind(pr))
])),
$if(pr.passw, $New('div', null, [
inpTxt('passwValue', 20, PostForm.setUserPassw),
$txt(Lng.cfg['userPassw'][lang]),
$btn(Lng.change[lang], '', function() {
$q('input[info="passwValue"]', doc).value = Math.round(Math.random() * 1e15).toString(32);
PostForm.setUserPassw();
})
])),
$if(pr.name, $New('div', null, [
inpTxt('nameValue', 20, PostForm.setUserName),
lBox('userName', false, PostForm.setUserName)
])),
$if(pr.txta, $New('div', null, [
inpTxt('signatValue', 20, null),
lBox('userSignat', false, null)
])),
$New('div', null, [
$txt(Lng.dontShow[lang]),
lBox('noBoardRule', false, updateCSS),
$if(pr.gothr, lBox('noGoto', false, function() {
$disp(pr.gothr);
})),
$if(pr.passw, lBox('noPassword', false, function() {
$disp(pr.passw.parentNode.parentNode);
}))
])
]);
}
function getCfgCommon() {
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-common'}, [
optSel('scriptStyle', true, function() {
saveCfg('scriptStyle', this.selectedIndex);
$id('de-main').lang = getThemeLang();
}),
$New('div', null, [
lBox('userCSS', false, updateCSS),
addEditButton('css', Cfg['userCSSTxt'], false, function() {
saveCfg('userCSSTxt', this.value);
updateCSS();
toggleContent('cfg', true);
})
]),
lBox('attachPanel', true, function() {
toggleContent('cfg', false);
updateCSS();
}),
lBox('panelCounter', true, updateCSS),
lBox('rePageTitle', true, null),
$if(nav.Anim, lBox('animation', true, null)),
lBox('closePopups', true, null),
$New('div', null, [
lBox('keybNavig', false, function() {
if(Cfg['keybNavig']) {
if(keyNav) {
keyNav.enable();
} else {
keyNav = new KeyNavigation();
}
} else if(keyNav) {
keyNav.disable();
}
}),
$btn(Lng.edit[lang], '', function(e) {
$pd(e);
if($id('de-alert-edit-keybnavig')) {
return;
}
var aEl, evtListener, keys = KeyNavigation.readKeys(),
temp = KeyEditListener.getEditMarkup(keys);
$alert(temp[1], 'edit-keybnavig', false);
aEl = $id('de-alert-edit-keybnavig');
evtListener = new KeyEditListener(aEl, keys, temp[0]);
aEl.addEventListener('focus', evtListener, true);
aEl.addEventListener('blur', evtListener, true);
aEl.addEventListener('click', evtListener, true);
aEl.addEventListener('keydown', evtListener, true);
aEl.addEventListener('keyup', evtListener, true);
})
]),
$New('div', {'class': 'de-cfg-depend'}, [
inpTxt('loadPages', 4, null),
$txt(Lng.cfg['loadPages'][lang])
]),
$if(!nav.Opera || nav.isGM, $New('div', null, [
lBox('updScript', true, null),
$New('div', {'class': 'de-cfg-depend'}, [
optSel('scrUpdIntrv', false, null),
$btn(Lng.checkNow[lang], '', function() {
var el = $id('de-cfg-updresult');
el.innerHTML = '<span class="de-wait">' + Lng.checking[lang] + '</div>';
checkForUpdates(true, function(html) {
el.innerHTML = html;
});
})
]),
$new('div', {'id': 'de-cfg-updresult'}, null)
]))
]);
}
function getCfgInfo() {
var getHiddenThrCount = function () {
var b, tNum, count = 0;
for(b in hThr) {
for(tNum in hThr[b]) {
count++;
}
}
return count;
}
return $New('div', {'class': 'de-cfg-unvis', 'id': 'de-cfg-info'}, [
$add('<div style="padding-bottom: 10px;">' +
'<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/versions" ' +
'target="_blank">v' + version + '</a> | ' +
'<a href="http://www.freedollchan.org/scripts/" target="_blank">Freedollchan</a> | ' +
'<a href="https://github.com/SthephanShinkufag/Dollchan-Extension-Tools/wiki/' +
(lang ? 'home-en/' : '') + '" target="_blank">Github</a></div>'),
$add('<div><div style="display: inline-block; vertical-align: top; width: 186px; height: 235px;">' +
Lng.thrViewed[lang] + Cfg['stats']['view'] + '<br>' +
Lng.thrCreated[lang] + Cfg['stats']['op'] + '<br>' +
Lng.thrHidden[lang] + getHiddenThrCount() + '<br>' +
Lng.postsSent[lang] + Cfg['stats']['reply'] + '</div>' +
'<div style="display: inline-block; padding-left: 7px; height: 235px; ' +
'border-left: 1px solid grey;">' + timeLog.join('<br>') + '</div></div>'),
$btn(Lng.debug[lang], Lng.infoDebug[lang], function() {
$alert(Lng.infoDebug[lang] +
':<textarea readonly id="de-debug-info" class="de-editor"></textarea>', 'help-debug', false);
$id('de-debug-info').value = JSON.stringify({
'version': version,
'location': String(window.location),
'nav': nav,
'cfg': Cfg,
'sSpells': spells.list.split('\n'),
'oSpells': sessionStorage['de-spells-' + brd + TNum],
'perf': timeLog
}, function(key, value) {
if(key in defaultCfg) {
if(value === defaultCfg[key] || key === 'nameValue' || key === 'passwValue' ||
key === 'signatValue')
{
return void 0;
}
}
return key === 'stats' ? void 0 : value;
}, '\t');
})
]);
}
function addEditButton(name, val, isJSON, Fn) {
return $btn(Lng.edit[lang], Lng.editInTxt[lang], function() {
var ta = $new('textarea', {
'class': 'de-editor',
'value': isJSON ? JSON.stringify(val, null, '\t') : val
}, null);
$alert('', 'edit-' + name, false);
$append($c('de-alert-msg', $id('de-alert-edit-' + name)), [
$txt(Lng.editor[name][lang]),
ta,
$btn(Lng.save[lang], Lng.saveChanges[lang], isJSON ? function(fun, aName) {
var data;
try {
data = JSON.parse(this.value.trim().replace(/[\n\r\t]/g, '') || '{}');
} finally {
if(data) {
fun(data);
closeAlert($id('de-alert-edit-' + aName));
closeAlert($id('de-alert-err-invaliddata'));
} else {
$alert(Lng.invalidData[lang], 'err-invaliddata', false);
}
}
}.bind(ta, Fn, name) : Fn.bind(ta))
]);
});
}
function addSettings(Set) {
Set.appendChild($New('div', {'class': aib.cReply}, [
$new('div', {'id': 'de-cfg-head', 'text': 'Dollchan Extension Tools'}, null),
$New('div', {'id': 'de-cfg-bar'}, [
cfgTab('filters'),
cfgTab('posts'),
cfgTab('images'),
cfgTab('links'),
$if(pr.form || pr.oeForm, cfgTab('form')),
cfgTab('common'),
cfgTab('info')
]),
getCfgFilters(),
$New('div', {'id': 'de-cfg-btns'}, [
optSel('language', false, function() {
saveCfg('language', lang = this.selectedIndex);
$del($id('de-main'));
$del($id('de-css'));
$del($id('de-css-dynamic'));
scriptCSS();
addPanel();
toggleContent('cfg', false);
}),
$New('div', {'style': 'float: right;'}, [
addEditButton('cfg', Cfg, true, function(data) {
saveComCfg(aib.dm, data);
}),
$if(nav.isGlobal, $btn(Lng.load[lang], Lng.loadGlobal[lang], function() {
if(('global' in comCfg) && !$isEmpty(comCfg['global'])) {
saveComCfg(aib.dm, null);
window.location.reload();
} else {
$alert(Lng.noGlobalCfg[lang], 'err-noglobalcfg', false);
}
})),
$if(nav.isGlobal, $btn(Lng.save[lang], Lng.saveGlobal[lang], function() {
var i, obj = {},
com = comCfg[aib.dm];
for(i in com) {
if(com[i] !== defaultCfg[i] && i !== 'stats') {
obj[i] = com[i];
}
}
saveComCfg('global', obj);
toggleContent('cfg', true);
})),
$btn(Lng.reset[lang], Lng.resetCfg[lang], function() {
if(confirm(Lng.conReset[lang])) {
delStored('DESU_Config');
delStored('DESU_Favorites');
delStored('DESU_Threads');
delStored('DESU_keys');
window.location.reload();
}
})
]),
$new('div', {'style': 'clear: both;'}, null)
])
]));
$c('de-cfg-tab', Set).click();
updRowMeter.call($id('de-spell-edit'));
}
//============================================================================================================
// MENUS & POPUPS
//============================================================================================================
function closeAlert(el) {
if(el) {
el.closeTimeout = null;
if(Cfg['animation']) {
nav.animEvent(el, function(node) {
var p = node && node.parentNode;
if(p) {
p.removeChild(node);
}
});
el.classList.add('de-close');
} else {
$del(el);
}
}
}
function $alert(txt, id, wait) {
var node, el = $id('de-alert-' + id),
cBtn = 'de-alert-btn' + (wait ? ' de-wait' : ''),
tBtn = wait ? '' : '\u2716 ';
if(el) {
$t('div', el).innerHTML = txt.trim();
node = $t('span', el);
node.className = cBtn;
node.textContent = tBtn;
clearTimeout(el.closeTimeout);
if(!wait && Cfg['animation']) {
nav.animEvent(el, function(node) {
node.classList.remove('de-blink');
});
el.classList.add('de-blink');
}
} else {
el = $id('de-alert').appendChild($New('div', {'class': aib.cReply, 'id': 'de-alert-' + id}, [
$new('span', {'class': cBtn, 'text': tBtn}, {'click': function() {
closeAlert(this.parentNode);
}}),
$add('<div class="de-alert-msg">' + txt.trim() + '</div>')
]));
if(Cfg['animation']) {
nav.animEvent(el, function(node) {
node.classList.remove('de-open');
});
el.classList.add('de-open');
}
}
if(Cfg['closePopups'] && !wait && !id.contains('help') && !id.contains('edit')) {
el.closeTimeout = setTimeout(closeAlert, 4e3, el);
}
}
function showMenu(el, html, inPanel, onclick) {
var y, pos, menu, cr = el.getBoundingClientRect();
if(Cfg['attachPanel'] && inPanel) {
pos = 'fixed';
y = 'bottom: 25';
} else {
pos = 'absolute';
y = 'top: ' + (window.pageYOffset + cr.bottom);
}
doc.body.insertAdjacentHTML('beforeend', '<div class="' + aib.cReply + ' de-menu" style="position: ' +
pos + '; right: ' + (doc.documentElement.clientWidth - cr.right - window.pageXOffset) +
'px; ' + y + 'px;">' + html + '</div>');
menu = doc.body.lastChild;
menu.addEventListener('mouseover', function(e) {
clearTimeout(e.currentTarget.odelay);
}, true);
menu.addEventListener('mouseout', removeMenu, true);
menu.addEventListener('click', function(e) {
var el = e.target;
if(el.className === 'de-menu-item') {
this(el);
do {
el = el.parentElement;
} while (!el.classList.contains('de-menu'));
$del(el);
}
}.bind(onclick), false);
}
function addMenu(e) {
e.target.odelay = setTimeout(function(el) {
switch(el.id) {
case 'de-btn-addspell': addSpellMenu(el); return;
case 'de-btn-refresh': addAjaxPagesMenu(el); return;
case 'de-btn-audio-off': addAudioNotifMenu(el); return;
}
}, Cfg['linksOver'], e.target);
}
function removeMenu(e) {
var el, rt = e.relatedTarget;
clearTimeout(e.target.odelay);
if(!rt || !nav.matchesSelector(rt, '.de-menu, .de-menu > div, .de-menu-item')) {
if(el = $c('de-menu', doc)) {
el.odelay = setTimeout($del, 75, el);
}
}
}
function addSpellMenu(el) {
showMenu(el, '<div style="display: inline-block; border-right: 1px solid grey;">' +
'<span class="de-menu-item">' + ('#words,#exp,#exph,#imgn,#ihash,#subj,#name,#trip,#img,<br>')
.split(',').join('</span><span class="de-menu-item">') +
'</span></div><div style="display: inline-block;"><span class="de-menu-item">' +
('#sage,#op,#tlen,#all,#video,#vauthor,#num,#wipe,#rep,#outrep')
.split(',').join('</span><span class="de-menu-item">') + '</span></div>', false,
function(el) {
var exp = el.textContent,
idx = Spells.names.indexOf(exp.substr(1));
$txtInsert($id('de-spell-edit'), exp + (
TNum && exp !== '#op' && exp !== '#rep' && exp !== '#outrep' ? '[' + brd + ',' + TNum + ']' : ''
) + (Spells.needArg[idx] ? '(' : ''));
});
}
function addAjaxPagesMenu(el) {
showMenu(el, '<span class="de-menu-item">' +
Lng.selAjaxPages[lang].join('</span><span class="de-menu-item">') + '</span>', true,
function(el) {
loadPages(aProto.indexOf.call(el.parentNode.children, el) + 1);
});
}
function addAudioNotifMenu(el) {
showMenu(el, '<span class="de-menu-item">' +
Lng.selAudioNotif[lang].join('</span><span class="de-menu-item">') + '</span>', true,
function(el) {
var i = aProto.indexOf.call(el.parentNode.children, el);
updater.enable();
updater.toggleAudio(i === 0 ? 3e4 : i === 1 ? 6e4 : i === 2 ? 12e4 : 3e5);
$id('de-btn-audio-off').id = 'de-btn-audio-on';
});
}
//============================================================================================================
// KEYBOARD NAVIGATION
//============================================================================================================
function KeyNavigation() {
var keys = KeyNavigation.readKeys();
this.cPost = null;
this.enabled = true;
this.lastPage = pageNum;
this.lastPageOffset = 0;
this.gKeys = keys[2];
this.ntKeys = keys[3];
this.tKeys = keys[4];
doc.addEventListener('keydown', this, true);
}
KeyNavigation.version = 3;
KeyNavigation.readKeys = function() {
var tKeys, keys, str = getStored('DESU_keys');
if(!str) {
return KeyNavigation.getDefaultKeys();
}
try {
keys = JSON.parse(str);
} finally {
if(!keys) {
return KeyNavigation.getDefaultKeys();
}
if(keys[0] !== KeyNavigation.version) {
tKeys = KeyNavigation.getDefaultKeys();
switch(keys[0]) {
case 1:
keys[2][11] = tKeys[2][11];
keys[4] = tKeys[4];
case 2:
keys[2][12] = tKeys[2][12];
keys[2][13] = tKeys[2][13];
keys[2][14] = tKeys[2][14];
keys[2][15] = tKeys[2][15];
keys[2][16] = tKeys[2][16];
}
keys[0] = KeyNavigation.version;
setStored('DESU_keys', JSON.stringify(keys));
}
if(keys[1] ^ !!nav.Firefox) {
var mapFunc = nav.Firefox ? function mapFuncFF(key) {
switch(key) {
case 189: return 173;
case 187: return 61;
case 186: return 59;
default: return key;
}
} : function mapFuncNonFF(key) {
switch(key) {
case 173: return 189;
case 61: return 187;
case 59: return 186;
default: return key;
}
};
keys[1] = !!nav.Firefox;
keys[2] = keys[2].map(mapFunc);
keys[3] = keys[3].map(mapFunc);
setStored('DESU_keys', JSON.stringify(keys));
}
return keys;
}
};
KeyNavigation.getDefaultKeys = function() {
var isFirefox = !!nav.Firefox;
var globKeys = [
/* One post/thread above */ 0x004B /* = K */,
/* One post/thread below */ 0x004A /* = J */,
/* Reply or create thread */ 0x0052 /* = R */,
/* Hide selected thread/post */ 0x0048 /* = H */,
/* Open previous page */ 0x1025 /* = Ctrl + left arrow */,
/* Send post (txt) */ 0xC00D /* = Alt + Enter */,
/* Open/close favorites posts*/ 0x4046 /* = Alt + F */,
/* Open/close hidden posts */ 0x4048 /* = Alt + H */,
/* Open/close panel */ 0x0050 /* = P */,
/* Mask/unmask images */ 0x0042 /* = B */,
/* Open/close settings */ 0x4053 /* = Alt + S */,
/* Expand current image */ 0x0049 /* = I */,
/* Bold text */ 0xC042 /* = Alt + B */,
/* Italic text */ 0xC049 /* = Alt + I */,
/* Strike text */ 0xC054 /* = Alt + T */,
/* Spoiler text */ 0xC050 /* = Alt + P */,
/* Code text */ 0xC043 /* = Alt + C */
];
var nonThrKeys = [
/* One post above */ 0x004D /* = M */,
/* One post below */ 0x004E /* = N */,
/* Open thread */ 0x0056 /* = V */,
/* Open next page */ 0x1027 /* = Ctrl + right arrow */,
/* Expand thread */ 0x0045 /* = E */
];
var thrKeys = [
/* Update thread */ 0x0055 /* = U */
];
return [KeyNavigation.version, isFirefox, globKeys, nonThrKeys, thrKeys];
};
KeyNavigation.prototype = {
paused: false,
clear: function(lastPage) {
this.cPost = null;
this.lastPage = lastPage;
this.lastPageOffset = 0;
},
disable: function() {
if(this.enabled) {
if(this.cPost) {
this.cPost.unselect();
}
doc.removeEventListener('keydown', this, true);
this.enabled = false;
}
},
enable: function() {
if(!this.enabled) {
this.clear(pageNum);
doc.addEventListener('keydown', this, true);
this.enabled = true;
}
},
handleEvent: function(e) {
if(this.paused) {
return;
}
var temp, post, scrollToThread, globIdx, idx, curTh = e.target.tagName,
kc = e.keyCode | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) |
(e.altKey ? 0x4000 : 0) | (curTh === 'TEXTAREA' ||
(curTh === 'INPUT' && e.target.type === 'text') ? 0x8000 : 0);
if(kc === 0x74 || kc === 0x8074) { // F5
if(TNum) {
return;
}
loadPages(+Cfg['loadPages']);
} else if(kc === 0x1B) { // ESC
if(this.cPost) {
this.cPost.unselect();
this.cPost = null;
}
if(TNum) {
firstThr.clearPostsMarks();
}
this.lastPageOffset = 0;
} else if(kc === 0x801B) { // ESC (txt)
e.target.blur();
} else {
globIdx = this.gKeys.indexOf(kc);
switch(globIdx) {
case 2: // Reply or create thread
if(pr.form) {
if(!this.cPost && TNum && Cfg['addPostForm'] === 3) {
this.cPost = firstThr.op;
}
if(this.cPost) {
pr.showQuickReply(this.cPost, this.cPost.num, true);
} else {
pr.showMainReply(Cfg['addPostForm'] === 1, null);
}
}
break;
case 3: // Hide selected thread/post
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
post.toggleUserVisib();
this._scroll(post, false, post.isOp);
}
break;
case 4: // Open previous page
if(TNum || pageNum !== aib.firstPage) {
window.location.pathname = aib.getPageUrl(brd, TNum ? 0 : pageNum - 1);
}
break;
case 5: // Send post (txt)
if(e.target !== pr.txta && e.target !== pr.cap) {
return;
}
pr.subm.click();
break;
case 6: // Open/close favorites posts
toggleContent('fav', false);
break;
case 7: // Open/close hidden posts
toggleContent('hid', false);
break;
case 8: // Open/close panel
$disp($id('de-panel').lastChild);
break;
case 9: // Mask/unmask images
toggleCfg('maskImgs');
updateCSS();
break;
case 10: // Open/close settings
toggleContent('cfg', false);
break;
case 11: // Expand current image
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
post.toggleImages(!post.imagesExpanded);
}
break;
case 12: // Bold text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-bold').click();
break;
case 13: // Italic text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-italic').click();
break;
case 14: // Strike text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-strike').click();
break;
case 15: // Spoiler text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-spoil').click();
break;
case 16: // Code text (txt)
if(e.target !== pr.txta) {
return;
}
$id('de-btn-code').click();
break;
case -1:
if(TNum) {
idx = this.tKeys.indexOf(kc);
if(idx === 0) { // Update thread
Thread.loadNewPosts(null);
break;
}
return;
}
idx = this.ntKeys.indexOf(kc);
if(idx === -1) {
return;
} else if(idx === 2) { // Open thread
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
if(nav.Firefox) {
GM_openInTab(aib.getThrdUrl(brd, post.tNum), false, true);
} else {
window.open(aib.getThrdUrl(brd, post.tNum), '_blank');
}
}
break;
} else if(idx === 3) { // Open next page
if(this.lastPage !== aib.lastPage) {
window.location.pathname = aib.getPageUrl(brd, this.lastPage + 1);
}
break;
} else if(idx === 4) { // Expand/collapse thread
post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
if(post) {
if(post.thr.loadedOnce && post.thr.omitted === 0) {
temp = post.thr.nextNotHidden;
post.thr.load(visPosts, !!temp, null);
post = (temp || post.thr).op;
} else {
post.thr.load(1, false, null);
post = post.thr.op;
}
scrollTo(0, pageYOffset + post.topCoord);
if(this.cPost && this.cPost !== post) {
this.cPost.unselect();
this.cPost = post;
}
}
break;
}
default:
scrollToThread = !TNum && (globIdx === 0 || globIdx === 1);
this._scroll(this._getFirstVisPost(scrollToThread, false), globIdx === 0 || idx === 0,
scrollToThread);
}
}
e.stopPropagation();
$pd(e);
},
pause: function() {
this.paused = true;
},
resume: function(keys) {
this.gKeys = keys[2];
this.ntKeys = keys[3];
this.tKeys = keys[4];
this.paused = false;
},
_getFirstVisPost: function(getThread, getFull) {
var post, tPost;
if(this.lastPageOffset !== pageYOffset) {
post = getThread ? firstThr : firstThr.op;
while(post.topCoord < 1) {
tPost = post.next;
if(!tPost) {
break;
}
post = tPost;
}
if(this.cPost) {
this.cPost.unselect();
}
this.cPost = getThread ? getFull ? post.op : post.op.prev : getFull ? post : post.prev;
this.lastPageOffset = pageYOffset;
}
return this.cPost;
},
_getNextVisPost: function(cPost, isOp, toUp) {
var thr;
if(isOp) {
thr = cPost ? toUp ? cPost.thr.prevNotHidden : cPost.thr.nextNotHidden :
firstThr.hidden ? firstThr.nextNotHidden : firstThr;
return thr ? thr.op : null;
}
return cPost ? cPost.getAdjacentVisPost(toUp) : firstTht.hidden ||
firstThr.op.hidden ? firstThr.op.getAdjacentVisPost(toUp) : firstThr.op;
},
_scroll: function(post, toUp, toThread) {
var next = this._getNextVisPost(post, toThread, toUp);
if(!next) {
if(!TNum && (toUp ? pageNum > aib.firstPage : this.lastPage < aib.lastPage)) {
window.location.pathname = aib.getPageUrl(brd, toUp ? pageNum - 1 : this.lastPage + 1);
}
return;
}
if(post) {
post.unselect();
}
if(toThread) {
next.el.scrollIntoView();
} else {
scrollTo(0, pageYOffset + next.el.getBoundingClientRect().top -
Post.sizing.wHeight / 2 + next.el.clientHeight / 2);
}
this.lastPageOffset = pageYOffset;
next.select();
this.cPost = next;
}
}
function KeyEditListener(alertEl, keys, allKeys) {
var j, k, i, len, aInputs = aProto.slice.call($C('de-input-key', alertEl));
for(i = 0, len = allKeys.length; i < len; ++i) {
k = allKeys[i];
if(k !== 0) {
for(j = i + 1; j < len; ++j) {
if(k === allKeys[j]) {
aInputs[i].classList.add('de-error-key');
aInputs[j].classList.add('de-error-key');
break;
}
}
}
}
this.aEl = alertEl;
this.keys = keys;
this.initKeys = JSON.parse(JSON.stringify(keys));
this.allKeys = allKeys;
this.allInputs = aInputs;
this.errCount = $C('de-error-key', alertEl).length;
if(this.errCount !== 0) {
this.saveButton.disabled = true;
}
}
// Browsers have different codes for these keys (see KeyNavigation.readKeys):
// Firefox - '-' - 173, '=' - 61, ';' - 59
// Chrome/Opera: '-' - 189, '=' - 187, ';' - 186
KeyEditListener.keyCodes = ['',,,,,,,,'Backspace',/* Tab */,,,,'Enter',,,'Shift','Ctrl','Alt',
/* Pause/Break */,/* Caps Lock */,,,,,,,/* Escape */,,,,,'Space',/* Page Up */,
/* Page Down */,/* End */,/* Home */,'←','↑','→','↓',,,,,/* Insert */,/* Delete */,,'0','1','2',
'3','4','5','6','7','8','9',,';',,'=',,,,'A','B','C','D','E','F','G','H','I','J','K','L','M',
'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',/* Left WIN Key */,/* Right WIN Key */,
/* Select key */,,,'Numpad 0','Numpad 1','Numpad 2','Numpad 3','Numpad 4','Numpad 5','Numpad 6',
'Numpad 7','Numpad 8','Numpad 9','Numpad *','Numpad +',,'Numpad -','Numpad .','Numpad /',
/* F1 */,/* F2 */,/* F3 */,/* F4 */,/* F5 */,/* F6 */,/* F7 */,/* F8 */,/* F9 */,/* F10 */,
/* F11 */,/* F12 */,,,,,,,,,,,,,,,,,,,,,/* Num Lock */,/* Scroll Lock */,,,,,,,,,,,,,,,,,,,,,,,,
,,,,'-',,,,,,,,,,,,,';','=',',','-','.','/','`',,,,,,,,,,,,,,,,,,,,,,,,,,,'[','\\',']','\''
];
KeyEditListener.getStrKey = function(key) {
var str = '';
if(key & 0x1000) {
str += 'Ctrl + ';
}
if(key & 0x2000) {
str += 'Shift + ';
}
if(key & 0x4000) {
str += 'Alt + ';
}
str += KeyEditListener.keyCodes[key & 0xFFF];
return str;
}
KeyEditListener.getEditMarkup = function(keys) {
var allKeys = [];
var html = Lng.keyNavEdit[lang]
.replace(/%l/g, '<label class="de-block">')
.replace(/%\/l/g, '</label>')
.replace(/%i([2-4])([0-9]+)(t)?/g, function(aKeys, all, id1, id2, isText) {
var key = this[+id1][+id2];
aKeys.push(key);
return '<input class="de-input-key" type="text" de-id1="' + id1 + '" de-id2="' + id2 +
'" size="26" value="' + KeyEditListener.getStrKey(key) +
(isText ? '" de-text' : '"' ) + ' readonly></input>';
}.bind(keys, allKeys)) +
'<input type="button" id="de-keys-save" value="' + Lng.save[lang] + '"></input>' +
'<input type="button" id="de-keys-reset" value="' + Lng.reset[lang] + '"></input>';
return [allKeys, html];
};
KeyEditListener.prototype = {
cEl: null,
cKey: -1,
errorInput: false,
get saveButton() {
var val = $id('de-keys-save');
Object.defineProperty(this, 'saveButton', { value: val, configurable: true });
return val;
},
handleEvent: function(e) {
var key, keyStr, keys, str, id, temp, el = e.target;
switch(e.type) {
case 'blur':
if(keyNav && this.errCount === 0) {
keyNav.resume(this.keys);
}
this.cEl = null;
return;
case 'focus':
if(keyNav) {
keyNav.pause();
}
this.cEl = el;
return;
case 'click':
if(el.id === 'de-keys-reset') {
this.keys = KeyNavigation.getDefaultKeys();
this.initKeys = KeyNavigation.getDefaultKeys();
if(keyNav) {
keyNav.resume(this.keys);
}
temp = KeyEditListener.getEditMarkup(this.keys);
this.allKeys = temp[0];
$c('de-alert-msg', this.aEl).innerHTML = temp[1];
this.allInputs = aProto.slice.call($C('de-input-key', this.aEl));
this.errCount = 0;
delete this.saveButton;
break;
} else if(el.id === 'de-keys-save') {
keys = this.keys;
setStored('DESU_keys', JSON.stringify(keys));
} else if(el.className === 'de-alert-btn') {
keys = this.initKeys;
} else {
return;
}
if(keyNav) {
keyNav.resume(keys);
}
closeAlert($id('de-alert-edit-keybnavig'));
break;
case 'keydown':
if(!this.cEl) {
return;
}
key = e.keyCode;
if(key === 0x1B || key === 0x2E) { // ESC, DEL
this.cEl.value = '';
this.cKey = 0;
this.errorInput = false;
break;
}
keyStr = KeyEditListener.keyCodes[key];
if(keyStr == null) {
this.cKey = -1;
return;
}
str = '';
if(e.ctrlKey) {
str += 'Ctrl + ';
}
if(e.shiftKey) {
str += 'Shift + ';
}
if(e.altKey) {
str += 'Alt + ';
}
if(key === 16 || key === 17 || key === 18) {
this.errorInput = true;
} else {
this.cKey = key | (e.ctrlKey ? 0x1000 : 0) | (e.shiftKey ? 0x2000 : 0) |
(e.altKey ? 0x4000 : 0) | (this.cEl.hasAttribute('de-text') ? 0x8000 : 0);
this.errorInput = false;
str += keyStr;
}
this.cEl.value = str;
break;
case 'keyup':
var idx, rIdx, oKey, rEl, isError, el = this.cEl,
key = this.cKey;
if(!el || key === -1) {
return;
}
isError = el.classList.contains('de-error-key');
if(!this.errorInput && key !== -1) {
idx = this.allInputs.indexOf(el);
oKey = this.allKeys[idx];
if(oKey === key) {
this.errorInput = false;
break;
}
rIdx = key === 0 ? -1 : this.allKeys.indexOf(key);
this.allKeys[idx] = key;
if(isError) {
idx = this.allKeys.indexOf(oKey);
if(idx !== -1 && this.allKeys.indexOf(oKey, idx + 1) === -1) {
rEl = this.allInputs[idx];
if(rEl.classList.contains('de-error-key')) {
this.errCount--;
rEl.classList.remove('de-error-key');
}
}
if(rIdx === -1) {
this.errCount--;
el.classList.remove('de-error-key');
}
}
if(rIdx === -1) {
this.keys[+el.getAttribute('de-id1')][+el.getAttribute('de-id2')] = key;
if(this.errCount === 0) {
this.saveButton.disabled = false;
}
this.errorInput = false;
break;
}
rEl = this.allInputs[rIdx];
if(!rEl.classList.contains('de-error-key')) {
this.errCount++;
rEl.classList.add('de-error-key');
}
}
if(!isError) {
this.errCount++;
el.classList.add('de-error-key');
}
if(this.errCount !== 0) {
this.saveButton.disabled = true;
}
}
$pd(e);
}
};
//============================================================================================================
// FORM SUBMIT
//============================================================================================================
function getSubmitResponse(dc, isFrame) {
var i, els, el, err = '', form = $q(aib.qDForm, dc);
if(dc.body.hasChildNodes() && !form) {
for(i = 0, els = $Q(aib.qError, dc); el = els[i++];) {
err += el.innerHTML + '\n';
}
if(!(err = err.replace(/<a [^>]+>Назад.+|<br.+/, ''))) {
err = Lng.error[lang] + '\n' + dc.body.innerHTML;
}
err = /:null|successful|uploaded|updating|обновл|удален[о\.]/i.test(err) ? '' : err.replace(/"/g, "'");
}
return [(isFrame ? window.location : form ? aib.getThrdUrl(brd, aib.getTNum(form)) : ''), err];
}
function checkUpload(response) {
if(aib.krau) {
pr.form.action = pr.form.action.split('?')[0];
$id('postform_row_progress').style.display = 'none';
aib.btnZeroLUTime.click();
}
var err = response[1];
if(err) {
if(pr.isQuick) {
pr.setReply(true, false);
}
if(/captch|капч|подтвер|verifizie/i.test(err)) {
pr.refreshCapImg(true);
}
$alert(err, 'upload', false);
return;
}
pr.txta.value = '';
if(pr.file) {
pr.delFileUtils(getAncestor(pr.file, aib.trTag), true);
if(aib.krau) {
var fileInputs = $Q('input[type="file"]', $id('files_parent'));
if(fileInputs.length > 1) {
$each(fileInputs, function(input, index) {
if(index > 0) {
$del(input.parentNode);
}
});
aib.btnSetFCntToOne.click();
}
}
}
if(pr.video) {
pr.video.value = '';
}
Cfg['stats'][pr.tNum ? 'reply' : 'op']++;
saveComCfg(aib.dm, Cfg);
if(!pr.tNum) {
window.location = response[0];
return;
}
if(TNum) {
firstThr.clearPostsMarks();
firstThr.loadNew(function(eCode, eMsg, np, xhr) {
infoLoadErrors(eCode, eMsg, 0);
closeAlert($id('de-alert-upload'));
if(Cfg['scrAfterRep']) {
scrollTo(0, pageYOffset + firstThr.last.el.getBoundingClientRect().top);
}
}, true);
} else {
pByNum[pr.tNum].thr.load(visPosts, false, closeAlert.bind(window, $id('de-alert-upload')));
}
pr.closeQReply();
pr.refreshCapImg(false);
}
function endDelete() {
var el = $id('de-alert-deleting');
if(el) {
closeAlert(el);
$alert(Lng.succDeleted[lang], 'deleted', false);
}
}
function checkDelete(response) {
if(response[1]) {
$alert(Lng.errDelete[lang] + response[1], 'deleting', false);
return;
}
var el, i, els, len, post, tNums = [],
num = (doc.location.hash.match(/\d+/) || [null])[0];
if(num && (post = pByNum[num])) {
if(!post.isOp) {
post.el.className = aib.cReply;
}
doc.location.hash = '';
}
for(i = 0, els = $Q('.' + aib.cRPost + ' input:checked', dForm), len = els.length; i < len; ++i) {
el = els[i];
el.checked = false;
if(!TNum && tNums.indexOf(num = aib.getPostEl(el).post.tNum) === -1) {
tNums.push(num);
}
}
if(TNum) {
firstThr.clearPostsMarks();
firstThr.loadNew(function(eCode, eMsg, np, xhr) {
infoLoadErrors(eCode, eMsg, 0);
endDelete();
}, false);
} else {
tNums.forEach(function(tNum) {
pByNum[tNum].thr.load(visPosts, false, endDelete);
});
}
}
function html5Submit(form, button, fn) {
this.boundary = '---------------------------' + Math.round(Math.random() * 1e11);
this.data = [];
this.busy = 0;
this.error = false;
this.url = form.action;
this.fn = fn;
$each($Q('input:not([type="submit"]):not([type="button"]), textarea, select', form),
this.append.bind(this));
this.append(button);
this.submit();
}
html5Submit.prototype = {
append: function(el) {
var file, fName, idx, fr,
pre = '--' + this.boundary + '\r\nContent-Disposition: form-data; name="' + el.name + '"';
if(el.type === 'file' && el.files.length > 0) {
file = el.files[0];
fName = file.name;
this.data.push(pre + '; filename="' + (
!Cfg['removeFName'] ? fName : ' ' + fName.substring(fName.lastIndexOf('.'))
) + '"\r\nContent-type: ' + file.type + '\r\n\r\n', null, '\r\n');
idx = this.data.length - 2;
if(!/^image\/(?:png|jpeg)$/.test(file.type)) {
this.data[idx] = file;
return;
}
fr = new FileReader();
fr.onload = function(name, e) {
var dat = this.clearImage(e.target.result, !!el.imgFile);
if(dat) {
if(el.imgFile) {
dat.push(el.imgFile);
}
if(Cfg['postSameImg']) {
dat.push(String(Math.round(Math.random() * 1e6)));
}
this.data[idx] = new Blob(dat);
this.busy--;
this.submit();
} else {
this.error = true;
$alert(Lng.fileCorrupt[lang] + name, 'upload', false);
}
}.bind(this, fName);
fr.readAsArrayBuffer(file);
this.busy++;
} else if(el.type !== 'checkbox' || el.checked) {
this.data.push(pre + '\r\n\r\n' + el.value + '\r\n');
}
},
submit: function() {
if(this.error || this.busy !== 0) {
return;
}
this.data.push('--' + this.boundary + '--\r\n');
$xhr({
'method': 'POST',
'headers': {'Content-type': 'multipart/form-data; boundary=' + this.boundary},
'data': new Blob(this.data),
'url': nav.fixLink(this.url),
'onreadystatechange': function(xhr) {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
this(getSubmitResponse($DOM(xhr.responseText), false));
} else {
$alert(xhr.status === 0 ? Lng.noConnect[lang] :
'HTTP [' + xhr.status + '] ' + xhr.statusText, 'upload', false);
}
}
}.bind(this.fn)
});
},
readExif: function(data, off, len) {
var i, j, dE, tag, tgLen, xRes = 0,
yRes = 0,
resT = 0,
dv = new DataView(data, off),
le = String.fromCharCode(dv.getUint8(0), dv.getUint8(1)) !== 'MM';
if(dv.getUint16(2, le) !== 0x2A) {
return null;
}
i = dv.getUint32(4, le);
if(i > len) {
return null;
}
for(tgLen = dv.getUint16(i, le), j = 0; j < tgLen; j++) {
tag = dv.getUint16(dE = i + 2 + 12 * j, le);
if(tag !== 0x011A && tag !== 0x011B && tag !== 0x0128) {
continue;
}
if(tag === 0x0128) {
resT = dv.getUint16(dE + 8, le) - 1;
} else {
dE = dv.getUint32(dE + 8, le);
if(dE > len) {
return null;
}
if(tag === 0x11A) {
xRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le));
} else {
yRes = Math.round(dv.getUint32(dE, le) / dv.getUint32(dE + 4, le));
}
}
}
xRes = xRes || yRes;
yRes = yRes || xRes;
return new Uint8Array([resT, xRes >> 8, xRes & 0xFF, yRes >> 8, yRes & 0xFF]);
},
clearImage: function(data, delExtraData) {
var tmp, i, len, deep, rv, lIdx, jpgDat, img = new Uint8Array(data),
rExif = !!Cfg['removeEXIF'];
if(!Cfg['postSameImg'] && !rExif && !delExtraData) {
return [img];
}
if(img[0] === 0xFF && img[1] === 0xD8) {
for(i = 2, deep = 1, len = img.length - 1, rv = [null, null], lIdx = 2, jpgDat = null; i < len; ) {
if(img[i] === 0xFF) {
if(rExif) {
if(!jpgDat && deep === 1) {
if(img[i + 1] === 0xE1 && img[i + 4] === 0x45) {
jpgDat = this.readExif(data, i + 10, (img[i + 2] << 8) + img[i + 3]);
} else if(img[i + 1] === 0xE0 && img[i + 7] === 0x46) {
jpgDat = img.subarray(i + 11, i + 16);
}
}
if((img[i + 1] >> 4) === 0xE || img[i + 1] === 0xFE) {
if(lIdx !== i) {
rv.push(img.subarray(lIdx, i));
}
i += 2 + (img[i + 2] << 8) + img[i + 3];
lIdx = i;
continue;
}
} else if(img[i + 1] === 0xD8) {
deep++;
i++;
continue;
}
if(img[i + 1] === 0xD9 && --deep === 0) {
break;
}
}
i++;
}
i += 2;
if(!delExtraData && len - i > 75) {
i = len;
}
if(lIdx === 2) {
return i === len ? [img] : [new Uint8Array(data, 0, i)];
}
rv[0] = new Uint8Array([0xFF, 0xD8, 0xFF, 0xE0, 0, 0x0D, 0x4A, 0x46, 0x49, 0x46, 0, 1, 1]);
rv[1] = jpgDat || new Uint8Array([0, 0, 1, 0, 1]);
rv.push(img.subarray(lIdx, i));
return rv;
}
if(img[0] === 0x89 && img[1] === 0x50) {
for(i = 0, len = img.length - 7; i < len && (img[i] !== 0x49 ||
img[i + 1] !== 0x45 || img[i + 2] !== 0x4E || img[i + 3] !== 0x44); i++) {}
i += 8;
return i === len || (!delExtraData && len - i > 75) ? [img] : [new Uint8Array(data, 0, i)];
}
return null;
}
};
//============================================================================================================
// CONTENT FEATURES
//============================================================================================================
function initMessageFunctions() {
window.addEventListener('message', function(e) {
var temp, data = e.data.substring(1);
switch(e.data[0]) {
case 'A':
temp = data.split('$#$');
if(temp[0] === 'de-iframe-pform') {
checkUpload([temp[1], temp[2]]);
} else {
checkDelete([temp[1], temp[2]]);
}
$q('iframe[name="' + temp[0] + '"]', doc).src = 'about:blank';
return;
case 'B':
$del($id('de-fav-wait'));
$id('de-iframe-fav').style.height = data + 'px';
return;
}
}, false);
}
function detectImgFile(ab) {
var i, j, dat = new Uint8Array(ab),
len = dat.length;
/* JPG [ff d8 ff e0] = [яШяа] */
if(dat[0] === 0xFF && dat[1] === 0xD8) {
for(i = 0, j = 0; i < len - 1; i++) {
if(dat[i] === 0xFF) {
/* Built-in JPG */
if(dat[i + 1] === 0xD8) {
j++;
/* JPG end [ff d9] */
} else if(dat[i + 1] === 0xD9 && --j === 0) {
i += 2;
break;
}
}
}
/* PNG [89 50 4e 47] = [‰PNG] */
} else if(dat[0] === 0x89 && dat[1] === 0x50) {
for(i = 0; i < len - 7; i++) {
/* PNG end [49 45 4e 44 ae 42 60 82] */
if(dat[i] === 0x49 && dat[i + 1] === 0x45 && dat[i + 2] === 0x4E && dat[i + 3] === 0x44) {
i += 8;
break;
}
}
} else {
return {};
}
/* Ignore small files */
if(i !== len && len - i > 60) {
for(len = i + 90; i < len; i++) {
/* 7Z [37 7a bc af] = [7zјЇ] */
if(dat[i] === 0x37 && dat[i + 1] === 0x7A && dat[i + 2] === 0xBC) {
return {'type': 0, 'idx': i, 'data': ab};
/* ZIP [50 4b 03 04] = [PK..] */
} else if(dat[i] === 0x50 && dat[i + 1] === 0x4B && dat[i + 2] === 0x03) {
return {'type': 1, 'idx': i, 'data': ab};
/* RAR [52 61 72 21] = [Rar!] */
} else if(dat[i] === 0x52 && dat[i + 1] === 0x61 && dat[i + 2] === 0x72) {
return {'type': 2, 'idx': i, 'data': ab};
/* OGG [4f 67 67 53] = [OggS] */
} else if(dat[i] === 0x4F && dat[i + 1] === 0x67 && dat[i + 2] === 0x67) {
return {'type': 3, 'idx': i, 'data': ab};
/* MP3 [0x49 0x44 0x33] = [ID3] */
} else if(dat[i] === 0x49 && dat[i + 1] === 0x44 && dat[i + 2] === 0x33) {
return {'type': 4, 'idx': i, 'data': ab};
}
}
}
return {};
}
function workerQueue(mReqs, wrkFn, errFn) {
if(!nav.hasWorker) {
this.run = this._runSync.bind(wrkFn);
return;
}
this.queue = new $queue(mReqs, this._createWrk.bind(this), null);
this.run = this._runWrk;
this.wrks = new $workers('self.onmessage = function(e) {\
var info = (' + String(wrkFn) + ')(e.data[1]);\
if(info.data) {\
self.postMessage([e.data[0], info], [info.data]);\
} else {\
self.postMessage([e.data[0], info]);\
}\
}', mReqs);
this.errFn = errFn;
}
workerQueue.prototype = {
_runSync: function(data, transferObjs, Fn) {
Fn(this(data));
},
onMess: function(Fn, e) {
this.queue.end(e.data[0]);
Fn(e.data[1]);
},
onErr: function(qIdx, e) {
this.queue.end(qIdx);
this.errFn(e);
},
_runWrk: function(data, transObjs, Fn) {
this.queue.run([data, transObjs, this.onMess.bind(this, Fn)]);
},
_createWrk: function(qIdx, num, data) {
var w = this.wrks[qIdx];
w.onmessage = data[2];
w.onerror = this.onErr.bind(this, qIdx);
w.postMessage([qIdx, data[0]], data[1]);
},
clear: function() {
this.wrks.clear();
this.wrks = null;
}
};
function addImgFileIcon(fName, info) {
var app, ext, type = info['type'];
if(typeof type !== 'undefined') {
if(type === 2) {
app = 'application/x-rar-compressed';
ext = 'rar';
} else if(type === 1) {
app = 'application/zip';
ext = 'zip';
} else if(type === 0) {
app = 'application/x-7z-compressed';
ext = '7z';
} else if(type === 3) {
app = 'audio/ogg';
ext = 'ogg';
} else {
app = 'audio/mpeg';
ext = 'mp3';
}
this.insertAdjacentHTML('afterend', '<a href="' + window.URL.createObjectURL(
new Blob([new Uint8Array(info['data']).subarray(info['idx'])], {'type': app})
) + '" class="de-img-' + (type > 2 ? 'audio' : 'arch') + '" title="' + Lng.downloadFile[lang] +
'" download="' + fName.substring(0, fName.lastIndexOf('.')) + '.' + ext + '">.' + ext + '</a>'
);
}
}
function downloadImgData(url, Fn) {
downloadObjInfo({
'method': 'GET',
'url': url,
'onreadystatechange': function onDownloaded(url, e) {
if(e.readyState !== 4) {
return;
}
var isAb = e.responseType === 'arraybuffer';
if(e.status === 0 && isAb) {
Fn(new Uint8Array(e.response));
} else if(e.status !== 200) {
if(e.status === 404 || !url) {
Fn(null);
} else {
downloadObjInfo({
'method': 'GET',
'url': url,
'onreadystatechange': onDownloaded.bind(null, null)
});
}
} else if(isAb) {
Fn(new Uint8Array(e.response));
} else {
for(var len, i = 0, txt = e.responseText, rv = new Uint8Array(len = txt.length); i < len; ++i) {
rv[i] = txt.charCodeAt(i) & 0xFF;
}
Fn(rv);
}
}.bind(null, url)
});
}
function downloadObjInfo(obj) {
if(nav.Firefox && aib.fch && !obj.url.startsWith('blob')) {
obj['overrideMimeType'] = 'text/plain; charset=x-user-defined';
GM_xmlhttpRequest(obj);
} else {
obj['responseType'] = 'arraybuffer';
try {
$xhr(obj);
} catch(e) {
Fn(null);
}
}
}
function preloadImages(post) {
if(!Cfg['preLoadImgs'] && !Cfg['openImgs'] && !isPreImg) {
return;
}
var lnk, url, iType, nExp, el, i, len, els, queue, mReqs = post ? 1 : 4, cImg = 1,
rjf = (isPreImg || Cfg['findImgFile']) && new workerQueue(mReqs, detectImgFile, function(e) {
console.error("FILE DETECTOR ERROR, line: " + e.lineno + " - " + e.message);
});
if(isPreImg || Cfg['preLoadImgs']) {
queue = new $queue(mReqs, function(qIdx, num, dat) {
downloadImgData(dat[0], function(idx, data) {
if(data) {
var a = this[1],
fName = this[0].substring(this[0].lastIndexOf("/") + 1),
aEl = $q(aib.qImgLink, aib.getImgWrap(a));
aEl.setAttribute('download', fName);
a.href = window.URL.createObjectURL(new Blob([data], {'type': this[2]}));
a.setAttribute('de-name', fName);
if(this[3]) {
this[3].src = a.href;
}
if(rjf) {
rjf.run(data.buffer, [data.buffer], addImgFileIcon.bind(aEl, fName));
}
}
queue.end(idx);
if(Images_.progressId) {
$alert(Lng.loadImage[lang] + cImg + '/' + len, Images_.progressId, true);
}
cImg++;
}.bind(dat, qIdx));
}, function() {
Images_.preloading = false
if(Images_.afterpreload) {
Images_.afterpreload();
Images_.afterpreload = Images_.progressId = null;
}
rjf && rjf.clear();
rjf = queue = cImg = len = null;
});
Images_.preloading = true;
}
for(i = 0, els = getImages(post || dForm), len = els.length; i < len; i++) {
if(lnk = getAncestor(el = els[i], 'A')) {
url = lnk.href;
nExp = !!Cfg['openImgs'];
if(/\.gif$/i.test(url)) {
iType = 'image/gif';
} else {
if(/\.jpe?g$/i.test(url)) {
iType = 'image/jpeg';
} else if(/\.png$/i.test(url)) {
iType = 'image/png';
} else {
continue;
}
nExp &= !Cfg['openGIFs'];
}
if(queue) {
queue.run([url, lnk, iType, nExp && el]);
} else if(nExp) {
el.src = url;
}
}
}
queue && queue.complete();
}
function getDataFromImg(img) {
var cnv = Images_.canvas || (Images_.canvas = doc.createElement('canvas'));
cnv.width = img.width;
cnv.height = img.height;
cnv.getContext('2d').drawImage(img, 0, 0);
return new Uint8Array(atob(cnv.toDataURL("image/png").split(',')[1]).split('').map(function(a) {
return a.charCodeAt();
}));
}
function loadDocFiles(imgOnly) {
var els, files, progress, counter, count = 0,
current = 1,
warnings = '',
tar = new $tar(),
dc = imgOnly ? doc : doc.documentElement.cloneNode(true);
Images_.queue = new $queue(4, function(qIdx, num, dat) {
downloadImgData(dat[0], function(idx, data) {
var name = this[1].replace(/[\\\/:*?"<>|]/g, '_'), el = this[2];
progress.value = current;
counter.innerHTML = current;
current++;
if(this[3]) {
if(!data) {
warnings += '<br>' + Lng.cantLoad[lang] + '<a href="' + this[0] + '">' +
this[0] + '</a><br>' + Lng.willSavePview[lang];
$alert(Lng.loadErrors[lang] + warnings, 'floadwarn', false);
name = 'thumb-' + name.replace(/\.[a-z]+$/, '.png');
data = getDataFromImg(this[2]);
}
if(!imgOnly) {
el.classList.add('de-thumb');
el.src = this[3].href = $q(aib.qImgLink, aib.getImgWrap(this[3])).href =
name = 'images/' + name;
}
tar.addFile(name, data);
} else if(data && data.length > 0) {
tar.addFile(el.href = el.src = 'data/' + name, data);
} else {
$del(el);
}
Images_.queue.end(idx);
}.bind(dat, qIdx));
}, function() {
var u, a, dt;
if(!imgOnly) {
dt = doc.doctype;
$t('head', dc).insertAdjacentHTML('beforeend',
'<script type="text/javascript" src="data/dollscript.js"></script>');
tar.addString('data/dollscript.js', '(' + String(de_main_func) + ')(null, true);');
tar.addString(
TNum + '.html', '<!DOCTYPE ' + dt.name +
(dt.publicId ? ' PUBLIC "' + dt.publicId + '"' : dt.systemId ? ' SYSTEM' : '') +
(dt.systemId ? ' "' + dt.systemId + '"' : '') + '>' + dc.outerHTML
);
}
u = window.URL.createObjectURL(tar.get());
a = $new('a', {'href': u, 'download': aib.dm + '-' + brd.replace(/[\\\/:*?"<>|]/g, '') +
'-t' + TNum + (imgOnly ? '-images.tar' : '.tar')}, null);
doc.body.appendChild(a);
a.click();
setTimeout(function(el, url) {
window.URL.revokeObjectURL(url);
$del(el);
}, 0, a, u);
$del($id('de-alert-filesload'));
Images_.queue = tar = warnings = count = current = imgOnly = progress = counter = null;
});
els = aProto.slice.call(getImages($q('[de-form]', dc)));
count += els.length;
els.forEach(function(el) {
var lnk, url;
if(lnk = getAncestor(el, 'A')) {
url = lnk.href;
Images_.queue.run([url, lnk.getAttribute('de-name') ||
url.substring(url.lastIndexOf("/") + 1), el, lnk]);
}
});
if(!imgOnly) {
files = [];
$each($Q('script, link[rel="alternate stylesheet"], span[class^="de-btn-"],' +
' #de-main > div, .de-parea, #de-qarea, ' + aib.qPostForm, dc), $del);
$each($T('a', dc), function(el) {
var num, tc = el.textContent;
if(tc[0] === '>' && tc[1] === '>' && (num = +tc.substr(2)) && (num in pByNum)) {
el.href = aib.anchor + num;
} else {
el.href = getAbsLink(el.href);
}
if(!el.classList.contains('de-preflink')) {
el.className = 'de-preflink ' + el.className;
}
});
$each($Q('.' + aib.cRPost, dc), function(post, i) {
post.setAttribute('de-num', i === 0 ? TNum : aib.getPNum(post));
});
$each($Q('link, *[src]', dc), function(el) {
if(els.indexOf(el) !== -1) {
return;
}
var temp, i, ext, name, url = el.tagName === 'LINK' ? el.href : el.src;
if(!this.test(url)) {
$del(el);
return;
}
name = url.substring(url.lastIndexOf("/") + 1).replace(/[\\\/:*?"<>|]/g, '_')
.toLowerCase();
if(files.indexOf(name) !== -1) {
temp = url.lastIndexOf('.');
ext = url.substring(temp);
url = url.substring(0, temp);
name = name.substring(0, name.lastIndexOf('.'));
for(i = 0; ; ++i) {
temp = name + '(' + i + ')' + ext;
if(files.indexOf(temp) === -1) {
break;
}
}
name = temp;
}
files.push(name);
Images_.queue.run([url, name, el, null]);
count++;
}.bind(new RegExp('^\\/\\/?|^https?:\\/\\/([^\\/]*\.)?' + regQuote(aib.dm) + '\\/', 'i')));
}
$alert((imgOnly ? Lng.loadImage[lang] : Lng.loadFile[lang]) +
'<br><progress id="de-loadprogress" value="0" max="' + count + '"></progress> <span>1</span>/' +
count, 'filesload', true);
progress = $id('de-loadprogress');
counter = progress.nextElementSibling;
Images_.queue.complete();
els = null;
}
//============================================================================================================
// TIME CORRECTION
//============================================================================================================
function dateTime(pattern, rPattern, diff, dtLang, onRPat) {
if(dateTime.checkPattern(pattern)) {
this.disabled = true;
return;
}
this.regex = pattern
.replace(/(?:[sihdny]\?){2,}/g, function() {
return '(?:' + arguments[0].replace(/\?/g, '') + ')?';
})
.replace(/\-/g, '[^<]')
.replace(/\+/g, '[^0-9]')
.replace(/([sihdny]+)/g, '($1)')
.replace(/[sihdny]/g, '\\d')
.replace(/m|w/g, '([a-zA-Zа-яА-Я]+)');
this.pattern = pattern.replace(/[\?\-\+]+/g, '').replace(/([a-z])\1+/g, '$1');
this.diff = parseInt(diff, 10);
this.sDiff = (this.diff < 0 ? '' : '+') + this.diff;
this.arrW = Lng.week[dtLang];
this.arrM = Lng.month[dtLang];
this.arrFM = Lng.fullMonth[dtLang];
this.rPattern = rPattern;
this.onRPat = onRPat;
}
dateTime.toggleSettings = function(el) {
if(el.checked && (!/^[+-]\d{1,2}$/.test(Cfg['timeOffset']) || dateTime.checkPattern(Cfg['timePattern']))) {
$alert(Lng.cTimeError[lang], 'err-correcttime', false);
saveCfg('correctTime', 0);
el.checked = false;
}
};
dateTime.checkPattern = function(val) {
return !val.contains('i') || !val.contains('h') || !val.contains('d') || !val.contains('y') ||
!(val.contains('n') || val.contains('m')) ||
/[^\?\-\+sihdmwny]|mm|ww|\?\?|([ihdny]\?)\1+/.test(val);
};
dateTime.prototype = {
getRPattern: function(txt) {
var k, p, a, str, i = 1,
j = 0,
m = txt.match(new RegExp(this.regex));
if(!m) {
this.disabled = true;
return false;
}
this.rPattern = '';
str = m[0];
while(a = m[i++]) {
p = this.pattern[i - 2];
if((p === 'm' || p === 'y') && a.length > 3) {
p = p.toUpperCase();
}
k = str.indexOf(a, j);
this.rPattern += str.substring(j, k) + '_' + p;
j = k + a.length;
}
this.onRPat && this.onRPat(this.rPattern);
return true;
},
pad2: function(num) {
return num < 10 ? '0' + num : num;
},
fix: function(txt) {
if(this.disabled || (!this.rPattern && !this.getRPattern(txt))) {
return txt;
}
return txt.replace(new RegExp(this.regex, 'g'), function() {
var i, a, t, second, minute, hour, day, month, year, dtime;
for(i = 1; i < 8; i++) {
a = arguments[i];
t = this.pattern[i - 1];
t === 's' ? second = a :
t === 'i' ? minute = a :
t === 'h' ? hour = a :
t === 'd' ? day = a :
t === 'n' ? month = a - 1 :
t === 'y' ? year = a :
t === 'm' && (
month =
/^янв|^jan/i.test(a) ? 0 :
/^фев|^feb/i.test(a) ? 1 :
/^мар|^mar/i.test(a) ? 2 :
/^апр|^apr/i.test(a) ? 3 :
/^май|^may/i.test(a) ? 4 :
/^июн|^jun/i.test(a) ? 5 :
/^июл|^jul/i.test(a) ? 6 :
/^авг|^aug/i.test(a) ? 7 :
/^сен|^sep/i.test(a) ? 8 :
/^окт|^oct/i.test(a) ? 9 :
/^ноя|^nov/i.test(a) ? 10 :
/^дек|^dec/i.test(a) && 11
);
}
dtime = new Date(year.length === 2 ? '20' + year : year, month, day, hour, minute, second || 0);
dtime.setHours(dtime.getHours() + this.diff);
return this.rPattern
.replace('_o', this.sDiff)
.replace('_s', this.pad2(dtime.getSeconds()))
.replace('_i', this.pad2(dtime.getMinutes()))
.replace('_h', this.pad2(dtime.getHours()))
.replace('_d', this.pad2(dtime.getDate()))
.replace('_w', this.arrW[dtime.getDay()])
.replace('_n', this.pad2(dtime.getMonth() + 1))
.replace('_m', this.arrM[dtime.getMonth()])
.replace('_M', this.arrFM[dtime.getMonth()])
.replace('_y', ('' + dtime.getFullYear()).substring(2))
.replace('_Y', dtime.getFullYear());
}.bind(this));
}
};
//============================================================================================================
// PLAYERS
//============================================================================================================
function initYouTube(embedType, videoType, width, height, isHD, loadTitles) {
var vData, vimReg = /^https?:\/\/(?:www\.)?vimeo\.com\/(?:[^\?]+\?clip_id=)?(\d+).*?$/,
ytReg = /^https?:\/\/(?:www\.|m\.)?youtu(?:be\.com\/(?:watch\?.*?v=|v\/|embed\/)|\.be\/)([^&#?]+).*?(?:t(?:ime)?=(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s?)?)?$/;
function addThumb(el, m, isYtube) {
var wh = ' width="' + width + '" height="' + height + '"></a>';
if(isYtube) {
el.innerHTML = '<a href="https://www.youtube.com/watch?v=' + m[1] + '" target="_blank">' +
'<img class="de-video-thumb de-ytube" src="https://i.ytimg.com/vi/' + m[1] +
'/0.jpg"' + wh;
} else {
el.innerHTML = '<a href="https://vimeo.com/' + m[1] + '" target="_blank">' +
'<img class="de-video-thumb de-vimeo" src=""' + wh;
GM_xmlhttpRequest({
'method': 'GET',
'url': 'http://vimeo.com/api/v2/video/' + m[1] + '.json',
'onload': function(xhr){
this.setAttribute('src', JSON.parse(xhr.responseText)[0]['thumbnail_large']);
}.bind(el.firstChild.firstChild)
});
}
}
function addPlayer(el, m, isYtube) {
var time, id = m[1],
wh = ' width="' + width + '" height="' + height + '">';
if(isYtube) {
time = (m[2] ? m[2] * 3600 : 0) + (m[3] ? m[3] * 60 : 0) + (m[4] ? +m[4] : 0);
el.innerHTML = videoType === 1 ?
'<iframe type="text/html" src="https://www.youtube.com/embed/' + id +
(isHD ? '?hd=1&' : '?') + 'start=' + time + '&html5=1&rel=0" frameborder="0"' + wh :
'<embed type="application/x-shockwave-flash" src="https://www.youtube.com/v/' + id +
(isHD ? '?hd=1&' : '?') + 'start=' + time + '" allowfullscreen="true" wmode="transparent"' + wh;
} else {
el.innerHTML = videoType === 1 ?
'<iframe src="//player.vimeo.com/video/' + id +
'" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen' + wh :
'<embed type="application/x-shockwave-flash" src="http://vimeo.com/moogaloop.swf?clip_id=' + id +
'&server=vimeo.com&color=00adef&fullscreen=1" ' +
'allowscriptaccess="always" allowfullscreen="true"' + wh;
}
}
function addLink(post, m, loader, link, isYtube) {
var msg, src, time, dataObj;
post.hasYTube = true;
if(post.ytInfo === null) {
if(youTube.embedType === 2) {
youTube.addPlayer(post.ytObj, post.ytInfo = m, isYtube);
} else if(youTube.embedType > 2) {
youTube.addThumb(post.ytObj, post.ytInfo = m, isYtube);
}
} else if(!link && $q('.de-video-link[href*="' + m[1] + '"]', post.msg)) {
return;
}
if(loader && (dataObj = youTube.vData[m[1]])) {
post.ytData.push(dataObj);
}
if(m[4] || m[3] || m[2]) {
if(m[4] >= 60) {
m[3] = (m[3] || 0) + Math.floor(m[4] / 60);
m[4] %= 60;
}
if(m[3] >= 60) {
m[2] = (m[2] || 0) + Math.floor(m[3] / 60);
m[3] %= 60;
}
time = (m[2] ? m[2] + 'h' : '') + (m[3] ? m[3] + 'm' : '') + (m[4] ? m[4] + 's' : '');
}
if(link) {
link.href = link.href.replace(/^http:/, 'https:');
if(time) {
link.setAttribute('de-time', time);
}
if(dataObj) {
link.textContent = dataObj[0];
link.className = 'de-video-link de-ytube de-video-title';
link.setAttribute('de-author', dataObj[1]);
} else {
link.className = 'de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo');
}
} else {
src = isYtube ? 'https://www.youtube.com/watch?v=' + m[1] + (time ? '#t=' + time : '')
: 'https://vimeo.com/' + m[1];
post.msg.insertAdjacentHTML('beforeend',
'<p class="de-video-ext"><a ' + (dataObj ? 'de-author="' + dataObj[1] + '" ' : '') +
(time ? 'de-time="' + time + '" ' : '') +
'class="de-video-link ' + (isYtube ? 'de-ytube' : 'de-vimeo') +
(dataObj ? ' de-video-title' : '') +
'" href="' + src + '">' + (dataObj ? dataObj[0] : src) + '</a></p>');
link = post.msg.lastChild.firstChild;
}
if(!post.ytInfo || post.ytInfo === m) {
post.ytLink = link;
}
link.ytInfo = m;
if(loader && !dataObj) {
post.ytLinksLoading++;
loader.run([post, link, m[1]]);
}
}
function getYtubeTitleLoader() {
var queueEnd, queue = new $queue(4, function(qIdx, num, data) {
if(num % 30 === 0) {
queue.pause();
setTimeout(queue.continue.bind(queue), 3e3);
}
GM_xmlhttpRequest({
'method': 'GET',
'url': 'https://gdata.youtube.com/feeds/api/videos/' + data[2] +
'?alt=json&fields=title/text(),author/name',
'onreadystatechange': function(idx, xhr) {
if(xhr.readyState !== 4) {
return;
}
var entry, title, author, data, post = this[0], link = this[1];
try {
if(xhr.status === 200) {
entry = JSON.parse(xhr.responseText)['entry'];
title = entry['title']['$t'];
author = entry['author'][0]['name']['$t'];
}
} finally {
if(title) {
link.textContent = title;
link.setAttribute('de-author', author);
link.classList.add('de-video-title');
vData[this[2]] = data = [title, author];
post.ytData.push(data);
post.ytLinksLoading--;
if(post.ytHideFun !== null) {
post.ytHideFun(data);
}
}
setTimeout(queueEnd, 250, idx);
}
}.bind(data, qIdx)
});
}, function() {
sessionStorage['de-ytube-data'] = JSON.stringify(vData);
queue = queueEnd = null;
});
queueEnd = queue.end.bind(queue);
return queue;
}
function parseLinks(post) {
var i, len, els, el, src, m, embedTube = [],
loader = loadTitles && getYtubeTitleLoader();
for(i = 0, els = $Q('embed, object, iframe', post ? post.el : dForm), len = els.length; i < len; ++i) {
el = els[i];
src = el.src || el.data;
if(m = src.match(ytReg)) {
embedTube.push(post || aib.getPostEl(el).post, m, true);
$del(el);
}
if(Cfg['addVimeo'] && (m = src.match(vimReg))) {
embedTube.push(post || aib.getPostEl(el).post, m, false);
$del(el);
}
}
for(i = 0, els = $Q('a[href*="youtu"]', post ? post.el : dForm), len = els.length; i < len; ++i) {
el = els[i];
if(m = el.href.match(ytReg)) {
addLink(post || aib.getPostEl(el).post, m, loader, el, true);
}
}
if(Cfg['addVimeo']) {
for(i = 0, els = $Q('a[href*="vimeo.com"]', post ? post.el : dForm), len = els.length; i < len; ++i) {
el = els[i];
if(m = el.href.match(vimReg)) {
addLink(post || aib.getPostEl(el).post, m, null, el, false);
}
}
}
for(i = 0, len = embedTube.length; i < len; i += 3) {
addLink(embedTube[i], embedTube[i + 1], loader, null, embedTube[i + 2]);
}
loader && loader.complete();
}
function updatePost(post, oldLinks, newLinks, cloned) {
var i, j, el, link, m, loader = !cloned && loadTitles && getYtubeTitleLoader(),
len = newLinks.length;
for(i = 0, j = 0; i < len; i++) {
el = newLinks[i];
link = oldLinks[j];
if(cloned) {
el.ytInfo = link.ytInfo;
j++;
} else if(m = el.href.match(ytReg)) {
addLink(post, m, loader, el, true);
j++;
}
}
loader && loader.complete();
}
if(embedType === 0) {
return {
parseLinks: emptyFn,
updatePost: emptyFn,
ytReg: ytReg
};
}
if(loadTitles) {
vData = JSON.parse(sessionStorage['de-ytube-data'] || '{}');
}
return {
addThumb: addThumb,
addPlayer: addPlayer,
embedType: embedType,
parseLinks: parseLinks,
updatePost: updatePost,
ytReg: ytReg,
vData: vData
};
}
function embedMP3Links(post) {
var el, link, src, i, els, len;
if(!Cfg['addMP3']) {
return;
}
for(i = 0, els = $Q('a[href*=".mp3"]', post ? post.el : dForm), len = els.length; i < len; ++i) {
link = els[i];
if(link.target !== '_blank' && link.rel !== 'nofollow') {
continue;
}
src = link.href;
el = (post || aib.getPostEl(link).post).mp3Obj;
if(nav.canPlayMP3) {
if(!$q('audio[src="' + src + '"]', el)) {
el.insertAdjacentHTML('beforeend',
'<p><audio src="' + src + '" preload="none" controls></audio></p>');
link = el.lastChild.firstChild;
link.addEventListener('play', updater.addPlayingTag, false);
link.addEventListener('pause', updater.removePlayingTag, false);
}
} else if(!$q('object[FlashVars*="' + src + '"]', el)) {
el.insertAdjacentHTML('beforeend', '<object data="http://junglebook2007.narod.ru/audio/player.swf" type="application/x-shockwave-flash" wmode="transparent" width="220" height="16" FlashVars="playerID=1&bg=0x808080&leftbg=0xB3B3B3&lefticon=0x000000&rightbg=0x808080&rightbghover=0x999999&rightcon=0x000000&righticonhover=0xffffff&text=0xffffff&slider=0x222222&track=0xf5f5dc&border=0x666666&loader=0x7fc7ff&loop=yes&autostart=no&soundFile=' + src + '"><br>');
}
}
}
//============================================================================================================
// AJAX
//============================================================================================================
function ajaxLoad(url, loadForm, Fn, errFn) {
var origXHR = GM_xmlhttpRequest({
'method': 'GET',
'url': nav.fixLink(url),
'onreadystatechange': function(xhr) {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status !== 200) {
if(errFn) {
errFn(xhr.status, xhr.statusText, origXHR);
}
} else if(Fn) {
do {
var el, text = xhr.responseText;
if(/<\/html>[\s\n\r]*$/.test(text)) {
el = $DOM(text);
if(!loadForm || (el = $q(aib.qDForm, el))) {
Fn(el, origXHR);
break;
}
}
if(errFn) {
errFn(0, Lng.errCorruptData[lang], origXHR);
}
} while(false);
}
loadForm = Fn = errFn = origXHR = null;
}
});
return origXHR;
}
function getJsonPosts(url, Fn) {
var origXHR = GM_xmlhttpRequest({
'method': 'GET',
'url': nav.fixLink(url),
'onreadystatechange': function(xhr) {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status === 304) {
closeAlert($id('de-alert-newposts'));
} else {
try {
var json = JSON.parse(xhr.responseText);
} catch(e) {
Fn(1, e.toString(), null, origXHR);
} finally {
if(json) {
Fn(xhr.status, xhr.statusText, json, origXHR);
}
Fn = origXHR = null;
}
}
}
});
}
function loadFavorThread() {
var post, el = this.parentNode.parentNode,
ifrm = $t('iframe', el),
cont = $c('de-content', doc);
$del($id('de-fav-wait'));
if(ifrm) {
$del(ifrm);
cont.style.overflowY = 'auto';
return;
}
if((post = pByNum[el.getAttribute('info').split(';')[2]]) && !post.hidden) {
scrollTo(0, pageYOffset + post.el.getBoundingClientRect().top);
return;
}
$del($id('de-iframe-fav'));
$c('de-content', doc).style.overflowY = 'scroll';
el.insertAdjacentHTML('beforeend', '<iframe name="de-iframe-fav" id="de-iframe-fav" src="' +
$t('a', el).href + '" scrolling="no" style="border: none; width: ' +
(doc.documentElement.clientWidth - 55) + 'px; height: 1px;"><div id="de-fav-wait" ' +
'class="de-wait" style="font-size: 1.1em; text-align: center">' + Lng.loading[lang] + '</div>');
}
function loadPages(count) {
var fun, i = pageNum,
len = Math.min(aib.lastPage + 1, i + count),
pages = [],
loaded = 1;
count = len - i;
function onLoadOrError(idx, eCodeOrForm, eMsgOrXhr, maybeXhr) {
if(typeof eCodeOrForm === 'number') {
pages[idx] = $add('<div><center style="font-size: 2em">' +
getErrorMessage(eCodeOrForm, eMsgOrXhr) + '</center><hr></div>');
} else {
pages[idx] = replacePost(eCodeOrForm);
}
if(loaded === count) {
var el, df, j, parseThrs = Thread.parsed,
threads = parseThrs ? [] : null;
for(j in pages) {
if(j != pageNum) {
dForm.insertAdjacentHTML('beforeend', '<center style="font-size: 2em">' +
Lng.page[lang] + ' ' + j + '</center><hr>');
}
df = pages[j];
if(parseThrs) {
threads = parseThreadNodes(df, threads);
}
while(el = df.firstChild) {
dForm.appendChild(el);
}
}
if(!parseThrs) {
threads = $Q(aib.qThread, dForm);
}
do {
if(threads.length !== 0) {
try {
parseDelform(dForm, threads);
} catch(e) {
$alert(getPrettyErrorMessage(e), 'load-pages', true);
break;
}
initDelformAjax()
readFavorites();
addDelformStuff(false);
readUserPosts();
checkPostsVisib();
saveFavorites();
saveUserPosts();
$each($Q('input[type="password"]', dForm), function(pEl) {
pr.dpass = pEl;
pEl.value = Cfg['passwValue'];
});
if(keyNav) {
keyNav.clear(pageNum + count - 1);
}
}
closeAlert($id('de-alert-load-pages'));
} while(false);
$disp(dForm);
loaded = pages = count = null;
} else {
loaded++;
}
}
$alert(Lng.loading[lang], 'load-pages', true);
$each($Q('a[href^="blob:"]', dForm), function(a) {
window.URL.revokeObjectURL(a.href);
});
Pview.clearCache();
isExpImg = false;
pByNum = Object.create(null);
Thread.tNums = [];
Post.hiddenNums = [];
$disp(dForm);
dForm.innerHTML = '';
if(pr.isQuick) {
if(pr.file) {
pr.delFileUtils(getAncestor(pr.file, aib.trTag), true);
}
pr.txta.value = '';
}
while(i < len) {
fun = onLoadOrError.bind(null, i);
ajaxLoad(aib.getPageUrl(brd, i++), true, fun, fun);
}
}
function infoLoadErrors(eCode, eMsg, newPosts) {
if(eCode === 200) {
closeAlert($id('de-alert-newposts'));
} else if(eCode === 0) {
$alert(eMsg || Lng.noConnect[lang], 'newposts', false);
} else {
$alert(Lng.thrNotFound[lang] + TNum + '): \n' + getErrorMessage(eCode, eMsg), 'newposts', false);
if(newPosts !== -1) {
doc.title = '{' + eCode + '} ' + doc.title;
}
}
}
function getHanaFile(file, id) {
var name, src = file['src'],
thumb = file['thumb'],
thumbW = file['thumb_width'],
thumbH = file['thumb_height'],
size = file['size'],
rating = file['rating'],
maxRating = Cfg['__hanarating'] || 'r-15',
kb = 1024,
mb = 1048576,
gb = 1073741824;
if(brd === 'b' || brd === 'rf') {
name = thumb.substring(thumb.lastIndexOf("/") + 1);
} else {
name = src.substring(src.lastIndexOf("/") + 1);
if(name.length > 17) {
name = name.substring(0, 17) + '...';
}
}
thumb = rating === 'r-18g' && maxRating !== 'r-18g' ? 'images/r-18g.png' :
rating === 'r-18' && (maxRating !== 'r-18g' || maxRating !== 'r-18') ? 'images/r-18.png' :
rating === 'r-15' && maxRating === 'sfw' ? 'images/r-15.png' :
rating === 'illegal' ? 'images/illegal.png' :
file['thumb'];
if(thumb !== file['thumb']) {
thumbW = 200;
thumbH = 200;
}
return '<div class="file"><div class="fileinfo">Файл: <a href="/' + src + '" target="_blank">' +
name + '</a><br><em>' + file['thumb'].substring(file['thumb'].lastIndexOf('.') + 1) + ', ' + (
size < kb ? size + ' B' :
size < mb ? (size / kb).toFixed(2) + ' KB' :
size < gb ? (size / mb).toFixed(2) + ' MB' :
(size / gb).toFixed(2) + ' GB'
) + ', ' + file['metadata']['width'] + 'x' + file['metadata']['height'] +
'</em><br><a class="edit_ icon" href="/utils/image/edit/' + file['file_id'] + '/' + id +
'"><img title="edit" alt="edit" src="/images/blank.png"></a></div><a href="/' + src +
'" target="_blank"><img class="thumb" src="/' + thumb + '" width="' + thumbW + '" height="' +
thumbH + '"></a></div>';
}
function getHanaPost(postJson) {
var i, html, id = postJson['display_id'],
files = postJson['files'],
len = files.length,
wrap = $new('table', {'id': 'post_' + id, 'class': 'replypost post'}, null);
html = '<tbody><tr><td class="doubledash">>></td><td id="reply' + id + '" class="reply">' +
'<a name="i' + id + '"></a><label><a class="delete icon"><input type="checkbox" id="delbox_' +
id + '" class="delete_checkbox" value="' + postJson['thread_id'] + '" name="' + id +
'"></a><span class="replytitle">' + postJson['subject'] + '</span> <span class="postername">' +
postJson['name'] + '</span> ' + aib.hDTFix.fix(postJson['date']) +
' </label><span class="reflink"><a onclick="Highlight(0, ' + id + ')" href="/' + brd +
'/res/' + TNum + '.xhtml#i' + id + '">No.' + id + '</a></span><br>';
for(i = 0; i < len; i++) {
html += getHanaFile(files[i], postJson['post_id']);
}
wrap.innerHTML = html + (len > 1 ? '<div style="clear: both;"></div>' : '') +
'<div class="postbody">' + postJson['message_html'] +
'</div><div class="abbrev"></div></td></tr></tbody>';
return [wrap, wrap.firstChild.firstChild.lastChild];
}
//============================================================================================================
// SPELLS
//============================================================================================================
function Spells(read) {
if(read) {
this._read(true);
} else {
this.disable(false);
}
}
Spells.names = [
'words', 'exp', 'exph', 'imgn', 'ihash', 'subj', 'name', 'trip', 'img', 'sage', 'op', 'tlen',
'all', 'video', 'wipe', 'num', 'vauthor'
];
Spells.needArg = [
/* words */ true, /* exp */ true, /* exph */ true, /* imgn */ true, /* ihash */ true,
/* subj */ false, /* name */ true, /* trip */ false, /* img */ false, /* sage */ false,
/* op */ false, /* tlen */ false, /* all */ false, /* video */ false, /* wipe */ false,
/* num */ true, /* vauthor */ true
];
Spells.checkArr = function(val, num) {
var i, arr;
for(arr = val[0], i = arr.length - 1; i >= 0; --i) {
if(arr[i] === num) {
return true;
}
}
for(arr = val[1], i = arr.length - 1; i >= 0; --i) {
if(num >= arr[i][0] && num <= arr[i][1]) {
return true;
}
}
return false;
};
Spells.YTubeSpell = function spell_youtube(post, val, ctx, cxTail) {
if(!val) {
return !!post.hasYTube;
}
if(!post.hasYTube || !Cfg['YTubeTitles']) {
return false;
}
var i, data, len, isAuthorSpell = typeof val === 'string';
for(i = 0, data = post.ytData, len = data.length; i < len; ++i) {
if(isAuthorSpell ? val === data[i][1] : val.test(data[i][0])) {
return true;
}
}
if(post.ytLinksLoading === 0) {
return false;
}
post.ytHideFun = function(ctx, cxTail, isASpell, val, data) {
if(isASpell ? val === data[1] : val.test(data[0])) {
this.ytHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), true);
} else if(post.ytLinksLoading === 0) {
this.ytHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), false);
}
}.bind(post, ctx, cxTail, isAuthorSpell, val);
return null;
};
Spells.prototype = {
_funcs: [
// 0: #words
function spell_words(post, val) {
return post.text.toLowerCase().contains(val) || post.subj.toLowerCase().contains(val);
},
// 1: #exp
function spell_exp(post, val) {
return val.test(post.text);
},
// 2: #exph
function spell_exph(post, val) {
return val.test(post.html);
},
// 3: #imgn
function spell_imgn(post, val) {
for(var i = 0, imgs = post.images, len = imgs.length; i < len; ++i) {
if(val.test(imgs[i].info)) {
return true;
}
}
return false;
},
// 4: #ihash
function spell_ihash(post, val, ctx, cxTail) {
for(var i = 0, imgs = post.images, len = imgs.length; i < len; ++i) {
if(imgs[i].hash === val) {
return true;
}
}
if(post.hashImgsBusy === 0) {
return false;
}
post.hashHideFun = function(ctx, cxTail, val, hash) {
if(val === hash) {
this.hashHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), true);
} else if(post.hashImgsBusy === 0) {
this.hashHideFun = null;
spells._continueCheck(this, ctx.concat(cxTail), false);
}
}.bind(post, ctx, cxTail, val);
return null;
},
// 5: #subj
function spell_subj(post, val) {
var pSubj = post.subj;
return pSubj ? !val || val.test(pSubj) : false;
},
// 6: #name
function spell_name(post, val) {
var pName = post.posterName;
return pName ? !val || pName.contains(val) : false;
},
// 7: #trip
function spell_trip(post, val) {
var pTrip = post.posterTrip;
return pTrip ? !val || pTrip.contains(val) : false;
},
// 8: #img
function spell_img(post, val) {
var temp, w, h, hide, img, i, imgs = post.images,
len = imgs.length;
if(!val) {
return len !== 0;
}
for(i = 0; i < len; ++i) {
img = imgs[i];
if(temp = val[1]) {
w = img.weight;
switch(val[0]) {
case 0: hide = w >= temp[0] && w <= temp[1]; break;
case 1: hide = w < temp[0]; break;
case 2: hide = w > temp[0];
}
if(!hide) {
continue;
} else if(!val[2]) {
return true;
}
}
if(temp = val[2]) {
w = img.width;
h = img.height;
switch(val[0]) {
case 0:
if(w >= temp[0] && w <= temp[1] && h >= temp[2] && h <= temp[3]) {
return true
}
break;
case 1:
if(w < temp[0] && h < temp[3]) {
return true
}
break;
case 2:
if(w > temp[0] && h > temp[3]) {
return true
}
}
}
}
return false;
},
// 9: #sage
function spell_sage(post, val) {
return post.sage;
},
// 10: #op
function spell_op(post, val) {
return post.isOp;
},
// 11: #tlen
function spell_tlen(post, val) {
var text = post.text;
return !val ? !!text : Spells.checkArr(val, text.replace(/\n/g, '').length);
},
// 12: #all
function spell_all(post, val) {
return true;
},
// 13: #video
Spells.YTubeSpell,
// 14: #wipe
function spell_wipe(post, val) {
var arr, len, i, j, n, x, keys, pop, capsw, casew, _txt, txt = post.text;
// (1 << 0): samelines
if(val & 1) {
arr = txt.replace(/>/g, '').split(/\s*\n\s*/);
if((len = arr.length) > 5) {
arr.sort();
for(i = 0, n = len / 4; i < len;) {
x = arr[i];
j = 0;
while(arr[i++] === x) {
j++;
}
if(j > 4 && j > n && x) {
Spells._lastWipeMsg = 'same lines: "' + x.substr(0, 20) + '" x' + (j + 1);
return true;
}
}
}
}
// (1 << 1): samewords
if(val & 2) {
arr = txt.replace(/[\s\.\?\!,>]+/g, ' ').toUpperCase().split(' ');
if((len = arr.length) > 3) {
arr.sort();
for(i = 0, n = len / 4, keys = 0, pop = 0; i < len; keys++) {
x = arr[i];
j = 0;
while(arr[i++] === x) {
j++;
}
if(len > 25) {
if(j > pop && x.length > 2) {
pop = j;
}
if(pop >= n) {
Spells._lastWipeMsg = 'same words: "' + x.substr(0, 20) + '" x' + (pop + 1);
return true;
}
}
}
x = keys / len;
if(x < 0.25) {
Spells._lastWipeMsg = 'uniq words: ' + (x * 100).toFixed(0) + '%';
return true;
}
}
}
// (1 << 2): longwords
if(val & 4) {
arr = txt.replace(/https*:\/\/.*?(\s|$)/g, '').replace(/[\s\.\?!,>:;-]+/g, ' ').split(' ');
if(arr[0].length > 50 || ((len = arr.length) > 1 && arr.join('').length / len > 10)) {
Spells._lastWipeMsg = 'long words';
return true;
}
}
// (1 << 3): symbols
if(val & 8) {
_txt = txt.replace(/\s+/g, '');
if((len = _txt.length) > 30 &&
(x = _txt.replace(/[0-9a-zа-я\.\?!,]/ig, '').length / len) > 0.4)
{
Spells._lastWipeMsg = 'specsymbols: ' + (x * 100).toFixed(0) + '%';
return true;
}
}
// (1 << 4): capslock
if(val & 16) {
arr = txt.replace(/[\s\.\?!;,-]+/g, ' ').trim().split(' ');
if((len = arr.length) > 4) {
for(i = 0, n = 0, capsw = 0, casew = 0; i < len; i++) {
x = arr[i];
if((x.match(/[a-zа-я]/ig) || []).length < 5) {
continue;
}
if((x.match(/[A-ZА-Я]/g) || []).length > 2) {
casew++;
}
if(x === x.toUpperCase()) {
capsw++;
}
n++;
}
if(capsw / n >= 0.3 && n > 4) {
Spells._lastWipeMsg = 'CAPSLOCK: ' + capsw / arr.length * 100 + '%';
return true;
} else if(casew / n >= 0.3 && n > 8) {
Spells._lastWipeMsg = 'cAsE words: ' + casew / arr.length * 100 + '%';
return true;
}
}
}
// (1 << 5): numbers
if(val & 32) {
_txt = txt.replace(/\s+/g, ' ').replace(/>>\d+|https*:\/\/.*?(?: |$)/g, '');
if((len = _txt.length) > 30 && (x = (len - _txt.replace(/\d/g, '').length) / len) > 0.4) {
Spells._lastWipeMsg = 'numbers: ' + Math.round(x * 100) + '%';
return true;
}
}
// (1 << 5): whitespace
if(val & 64) {
if(/(?:\n\s*){5}/i.test(txt)) {
Spells._lastWipeMsg = 'whitespace';
return true;
}
}
return false;
},
// 15: #num
function spell_num(post, val) {
return Spells.checkArr(val, post.count + 1);
},
// 16: #vauthor
Spells.YTubeSpell
],
_optimizeSpells: function(spells) {
var i, len, flags, type, spell, scope, neg, parensSpells, newSpells = [];
for(i = 0, len = spells.length; i < len; ++i) {
spell = spells[i];
flags = spell[0];
type = flags & 0xFF;
neg = (flags & 0x100) !== 0;
if(type === 0xFF) {
parensSpells = this._optimizeSpells(spell[1]);
if(parensSpells) {
if(parensSpells.length === 1) {
newSpells.push([(parensSpells[0][0] | (flags & 0x200)) ^ (flags & 0x100),
parensSpells[0][1]]);
} else {
newSpells.push([flags, parensSpells]);
}
continue;
}
} else {
scope = spell[2];
if(!scope || (scope[0] === brd &&
(scope[1] === -1 ? !TNum : (!scope[1] || scope[1] === TNum))))
{
if(type === 12) {
neg = !neg;
} else {
newSpells.push([flags, spell[1]]);
continue;
}
}
}
if(((flags & 0x200) !== 0) ^ neg) {
return neg ? [[12, '']] : null;
}
}
i = len = newSpells.length - 1;
if(i === -1) {
return neg ? [[12, '']] : null;
} else if(i !== 0) {
if(neg) {
while(i >= 0 && (newSpells[i][0] & 0x200) === 0) {
i--;
}
if(i < 0) {
return [[12, '']];
}
newSpells[i][0] &= 0x1FF;
} else {
while(i >= 0 && (newSpells[i][0] & 0x200) !== 0) {
i--;
}
if(i < 0) {
return null;
}
}
if(i !== len) {
newSpells = newSpells.slice(0, i + 1);
}
}
return newSpells;
},
_initSpells: function(data) {
if(data) {
data.forEach(function initExps(item) {
var val = item[1];
if(val) {
switch(item[0] & 0xFF) {
case 1:
case 2:
case 3:
case 5:
case 13: item[1] = toRegExp(val, true); break;
case 0xFF: val.forEach(initExps);
}
}
});
}
return data;
},
_checkRes: function(flags, val) {
if((flags & 0x100) !== 0) {
val = !val;
}
if((flags & 0x200) !== 0) {
if(!val) {
return false;
}
} else if(val) {
return true;
}
return null;
},
_decompileSpell: function(type, neg, val, scope) {
var temp, temp_, spell = (neg ? '!#' : '#') + Spells.names[type] + (scope ? '[' +
scope[0] + (scope[1] ? ',' + (scope[1] === -1 ? '' : scope[1]) : '') + ']' : '');
if(!val) {
return spell;
}
// #img
if(type === 8) {
return spell + '(' + (val[0] === 2 ? '>' : val[0] === 1 ? '<' : '=') +
(val[1] ? val[1][0] + (val[1][1] === val[1][0] ? '' : '-' + val[1][1]) : '') +
(val[2] ? '@' + val[2][0] + (val[2][0] === val[2][1] ? '' : '-' + val[2][1]) + 'x' +
val[2][2] + (val[2][2] === val[2][3] ? '' : '-' + val[2][3]) : '') + ')';
}
// #wipe
else if(type === 14) {
if(val === 0x3F) {
return spell;
}
temp = [];
(val & 1) && temp.push('samelines');
(val & 2) && temp.push('samewords');
(val & 4) && temp.push('longwords');
(val & 8) && temp.push('symbols');
(val & 16) && temp.push('capslock');
(val & 32) && temp.push('numbers');
(val & 64) && temp.push('whitespace');
return spell + '(' + temp.join(',') + ')';
}
// #num, #tlen
else if(type === 15 || type === 11) {
if((temp = val[1].length - 1) !== -1) {
for(temp_ = []; temp >= 0; temp--) {
temp_.push(val[1][temp][0] + '-' + val[1][temp][1]);
}
temp_.reverse();
}
spell += '(';
if(val[0].length !== 0) {
spell += val[0].join(',') + (temp_ ? ',' : '');
}
if(temp_) {
spell += temp_.join(',');
}
return spell + ')';
}
// #words, #name, #trip, #vauthor
else if(type === 0 || type === 6 || type === 7 || type === 16) {
return spell + '(' + val.replace(/\)/g, '\\)') + ')';
} else {
return spell + '(' + String(val) + ')';
}
},
_decompileScope: function(scope, indent) {
var spell, type, temp, str, dScope = [], hScope = false, i = 0, j = 0, len = scope.length;
for(; i < len; i++, j++) {
spell = scope[i];
type = spell[0] & 0xFF;
if(type === 0xFF) {
hScope = true;
temp = this._decompileScope(spell[1], indent + ' ');
if(temp[1]) {
str = ((spell[0] & 0x100) ? '!(\n' : '(\n') + indent + ' ' +
temp[0].join('\n' + indent + ' ') + '\n' + indent + ')';
if(j === 0) {
dScope[0] = str;
} else {
dScope[--j] += ' ' + str;
}
} else {
dScope[j] = ((spell[0] & 0x100) ? '!(' : '(') + temp[0].join(' ') + ')';
}
} else {
dScope[j] = this._decompileSpell(type, spell[0] & 0x100, spell[1], spell[2]);
}
if(i !== len - 1) {
dScope[j] += (spell[0] & 0x200) ? ' &' : ' |';
}
}
return [dScope, dScope.length > 2 || hScope];
},
_decompileSpells: function() {
var str, reps, oreps, data = this._data;
if(!data) {
this._read(false);
if(!(data = this._data)) {
return this._list = '';
}
}
str = data[1] ? this._decompileScope(data[1], '')[0].join('\n') : '';
reps = data[2];
oreps = data[3];
if(reps || oreps) {
str += '\n\n';
reps && reps.forEach(function(rep) {
str += this._decompileRep(rep, false) + '\n';
}.bind(this));
oreps && oreps.forEach(function(orep) {
str += this._decompileRep(orep, true) + '\n';
}.bind(this));
str = str.substr(0, str.length - 1);
}
this._data = null;
return this._list = str;
},
_getMsg: function(spell) {
var neg = spell[0] & 0x100,
type = spell[0] & 0xFF,
val = spell[1];
if(type === 0xFF) {
return this._getMsg(val[this._lastPSpell]);
}
if(type === 14) {
return (neg ? '!#wipe' : '#wipe') + (Spells._lastWipeMsg ? ': ' + Spells._lastWipeMsg : '');
} else {
return this._decompileSpell(type, neg, val, spell[2]);
}
},
_continueCheck: function(post, ctx, val) {
var temp, rv = this._checkRes(ctx.pop(), val);
if(rv === null) {
if(this._check(post, ctx)) {
return;
}
} else if(rv) {
temp = ctx.pop();
post.spellHide(this._getMsg(ctx.pop()[temp - 1]));
} else if(!post.deleted) {
sVis[post.count] = 1;
}
this._asyncWrk--;
this.end(null);
},
_check: function(post, ctx) {
var rv, type, val, temp, deep = ctx[0],
i = ctx.pop(),
scope = ctx.pop(),
len = ctx.pop();
while(true) {
if(i < len) {
temp = scope[i][0];
type = temp & 0xFF;
switch(type) {
case 0xFF:
ctx.push(len, scope, i);
scope = scope[i][1];
len = scope.length;
i = 0;
deep++;
continue;
case 4: // #ihash
case 13: // #video
case 16: // #vauthor
ctx[0] = deep;
val = this._funcs[type](post, scope[i][1], ctx, [len, scope, i + 1, temp]);
if(val === null) {
this._asyncWrk++;
return 0;
}
break;
case 15: // #num
this.hasNumSpell = true;
default:
val = this._funcs[type](post, scope[i][1]);
}
rv = this._checkRes(temp, val);
if(rv === null) {
i++;
continue;
}
this._lastPSpell = i;
} else {
this._lastPSpell = i -= 1;
rv = false;
}
if(deep !== 0) {
i = ctx.pop();
scope = ctx.pop();
len = ctx.pop();
deep--;
rv = this._checkRes(scope[i][0], rv);
if(rv === null) {
i++;
continue;
}
}
if(rv) {
post.spellHide(this._getMsg(scope[i]));
} else if(!post.deleted) {
sVis[post.count] = 1;
}
return +rv;
}
},
_findReps: function(str) {
var reps = [],
outreps = [];
str = str.replace(
/([^\\]\)|^)?[\n\s]*(#rep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g,
function(exp, preOp, fullExp, b, nt, t, reg, txt) {
reps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]);
return preOp || '';
}
).replace(
/([^\\]\)|^)?[\n\s]*(#outrep(?:\[([a-z0-9]+)(?:(,)|,(\s*[0-9]+))?\])?\((\/.*?[^\\]\/[ig]*)(?:,\)|,(.*?[^\\])?\)))[\n\s]*/g,
function(exp, preOp, fullExp, b, nt, t, reg, txt) {
outreps.push([b, nt ? -1 : t, reg, (txt || '').replace(/\\\)/g, ')')]);
return preOp || '';
}
);
return [str, reps.length === 0 ? false : reps, outreps.length === 0 ? false : outreps];
},
_decompileRep: function(rep, isOrep) {
return (isOrep ? '#outrep' : '#rep') +
(rep[0] ? '[' + rep[0] + (rep[1] ? ',' + (rep[1] === -1 ? '' : rep[1]) : '') + ']' : '') +
'(' + rep[2] + ',' + rep[3].replace(/\)/g, '\\)') + ')';
},
_optimizeReps: function(data) {
if(data) {
var nData = [];
data.forEach(function(temp) {
if(!temp[0] || (temp[0] === brd && (temp[1] === -1 ? !TNum : !temp[1] || temp[1] === TNum))) {
nData.push([temp[2], temp[3]]);
}
});
return nData.length === 0 ? false : nData;
}
return false;
},
_initReps: function(data) {
if(data) {
for(var i = data.length - 1; i >= 0; i--) {
data[i][0] = toRegExp(data[i][0], false);
}
}
return data;
},
_init: function(spells, reps, outreps) {
this._spells = this._initSpells(spells);
this._sLength = spells && spells.length;
this._reps = this._initReps(reps);
this._outreps = this._initReps(outreps);
this.enable = !!this._spells;
this.haveReps = !!reps;
this.haveOutreps = !!outreps;
},
_read: function(init) {
var spells, data;
if(Cfg.hasOwnProperty('spells')) {
try {
spells = JSON.parse(Cfg['spells']);
data = JSON.parse(sessionStorage['de-spells-' + brd + TNum]);
} catch(e) {}
if(data && data[0] === spells[0]) {
this._data = spells;
if(init) {
this.hash = data[0];
this._init(data[1], data[2], data[3]);
}
return;
}
} else {
if(data = getStored('DESU_CSpells_' + aib.dm)) {
delStored('DESU_CSpells_' + aib.dm);
try {
spells = JSON.parse(data);
} catch(e) {}
if(!spells) {
this.disable(false);
return;
}
} else {
spells = this.parseText('#wipe(samelines,samewords,longwords,numbers,whitespace)');
}
saveCfg('spells', data);
}
if(init) {
this.update(spells, false, false);
} else {
this._data = spells;
}
},
_asyncWrk: 0,
_completeFns: [],
_hasComplFns: false,
_data: null,
_list: '',
hash: 0,
hasNumSpell: false,
enable: false,
get list() {
return this._list || this._decompileSpells();
},
addCompleteFunc: function(Fn) {
this._completeFns.push(Fn);
this._hasComplFns = true;
},
parseText: function(str) {
str = String(str).replace(/[\s\n]+$/, '');
var reps = this._findReps(str),
codeGen = new SpellsCodegen(reps[0]),
spells = codeGen.generate();
if(spells) {
if(Cfg['sortSpells']) {
this.sort(spells);
}
return [Date.now(), spells, reps[1], reps[2]];
} else if(codeGen.hasError) {
$alert(Lng.error[lang] + ' ' + codeGen.error, 'help-err-spell', false);
}
return null;
},
sort: function(sp) {
// Wraps AND-spells with brackets for proper sorting
for(var i = 0, len = sp.length-1; i < len; i++) {
if(sp[i][0] > 0x200) {
var temp = [0xFF, []];
do {
temp[1].push(sp.splice(i, 1)[0]);
len--;
} while (sp[i][0] > 0x200);
temp[1].push(sp.splice(i, 1)[0]);
sp.splice(i, 0, temp);
}
}
sp = sp.sort();
for(var i = 0, len = sp.length-1; i < len; i++) {
// Removes duplicates and weaker spells
if(sp[i][0] == sp[i+1][0] && sp[i][1] <= sp[i+1][1] && sp[i][1] >= sp[i+1][1] &&
(sp[i][2] === null || // Stronger spell with 3 parameters
sp[i][2] === undefined || // Equal spells with 2 parameters
(sp[i][2] <= sp[i+1][2] && sp[i][2] >= sp[i+1][2])))
{ // Equal spells with 3 parameters
sp.splice(i+1, 1);
i--;
len--;
// Moves brackets to the end of the list
} else if(sp[i][0] == 0xFF) {
sp.push(sp.splice(i, 1)[0]);
i--;
len--;
}
}
},
update: function(data, sync, isHide) {
var spells = data[1] ? this._optimizeSpells(data[1]) : false,
reps = this._optimizeReps(data[2]),
outreps = this._optimizeReps(data[3]);
saveCfg('spells', JSON.stringify(data));
sessionStorage['de-spells-' + brd + TNum] = JSON.stringify([data[0], spells, reps, outreps]);
this._data = data;
this._list = '';
this.hash = data[0];
if(sync) {
localStorage['__de-spells'] = JSON.stringify({
'hide': (!!this.list && !!isHide),
'data': data
});
localStorage.removeItem('__de-spells');
}
this._init(spells, reps, outreps);
},
setSpells: function(spells, sync) {
this.update(spells, sync, Cfg['hideBySpell']);
if(Cfg['hideBySpell']) {
for(var post = firstThr.op; post; post = post.next) {
this.check(post);
}
this.end(savePosts);
} else {
this.enable = false;
}
},
disable: function(sync) {
this.enable = false;
this._list = '';
this._data = null;
this.haveReps = this.haveOutreps = false;
saveCfg('hideBySpell', false);
},
end: function(Fn) {
if(this._asyncWrk === 0) {
Fn && Fn();
if(this._hasComplFns) {
for(var i = 0, len = this._completeFns.length; i < len; ++i) {
this._completeFns[i]();
}
this._completeFns = [];
this._hasComplFns = false;
}
} else if(Fn) {
this.addCompleteFunc(Fn);
}
},
check: function(post) {
if(this.enable) {
return this._check(post, [0, this._sLength, this._spells, 0]);
}
return 0;
},
replace: function(txt) {
for(var i = 0, len = this._reps.length; i < len; i++) {
txt = txt.replace(this._reps[i][0], this._reps[i][1]);
}
return txt;
},
outReplace: function(txt) {
for(var i = 0, len = this._outreps.length; i < len; i++) {
txt = txt.replace(this._outreps[i][0], this._outreps[i][1]);
}
return txt;
},
addSpell: function(type, arg, scope, isNeg, spells) {
if(!spells) {
if(!this._data) {
this._read(false);
}
spells = this._data || [Date.now(), [], false, false];
}
var idx, sScope = String(scope),
sArg = String(arg);
if(spells[1]) {
spells[1].some(scope && isNeg ? function(spell, i) {
var data;
if(spell[0] === 0xFF && ((data = spell[1]) instanceof Array) && data.length === 2 &&
data[0][0] === 0x20C && data[1][0] === type && data[1][2] == null &&
String(data[1][1]) === sArg && String(data[0][2]) === sScope)
{
idx = i;
return true;
}
return (spell[0] & 0x200) !== 0;
} : function(spell, i) {
if(spell[0] === type && String(spell[1]) === sArg && String(spell[2]) === sScope) {
idx = i;
return true;
}
return (spell[0] & 0x200) !== 0;
});
} else {
spells[1] = [];
}
if(typeof idx !== 'undefined') {
spells[1].splice(idx, 1);
} else if(scope && isNeg) {
spells[1].splice(0, 0, [0xFF, [[0x20C, '', scope], [type, arg, void 0]], void 0]);
} else {
spells[1].splice(0, 0, [type, arg, scope]);
}
this.update(spells, true, true);
idx = null;
}
};
function SpellsCodegen(sList) {
this._line = 1;
this._col = 1;
this._sList = sList;
this.hasError = false;
}
SpellsCodegen.prototype = {
TYPE_UNKNOWN: 0,
TYPE_ANDOR: 1,
TYPE_NOT: 2,
TYPE_SPELL: 3,
TYPE_PARENTHESES: 4,
generate: function() {
return this._sList ? this._generate(this._sList, false) : null;
},
get error() {
if(!this.hasError) {
return '';
}
return (this._errMsgArg ? this._errMsg.replace('%s', this._errMsgArg) : this._errMsg) +
Lng.seRow[lang] + this._line + Lng.seCol[lang] + this._col + ')';
},
_errMsg: '',
_errMsgArg: null,
_generate: function(sList, inParens) {
var res, name, i = 0,
len = sList.length,
data = [],
lastType = this.TYPE_UNKNOWN;
for(; i < len; i++, this._col++) {
switch(sList[i]) {
case '\n':
this._line++;
this._col = 0;
case '\r':
case ' ': continue;
case '#':
if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) {
this._setError(Lng.seMissOp[lang], null);
return null;
}
name = '';
i++;
this._col++;
while((sList[i] >= 'a' && sList[i] <= 'z') || (sList[i] >= 'A' && sList[i] <= 'Z')) {
name += sList[i].toLowerCase();
i++;
this._col++;
}
res = this._doSpell(name, sList.substr(i), lastType === this.TYPE_NOT)
if(!res) {
return null;
}
i += res[0] - 1;
this._col += res[0] - 1;
data.push(res[1]);
lastType = this.TYPE_SPELL;
break;
case '(':
if(lastType === this.TYPE_SPELL || lastType === this.TYPE_PARENTHESES) {
this._setError(Lng.seMissOp[lang], null);
return null;
}
res = this._generate(sList.substr(i + 1), true);
if(!res) {
return null;
}
i += res[0] + 1;
data.push([lastType === this.TYPE_NOT ? 0x1FF : 0xFF, res[1]]);
lastType = this.TYPE_PARENTHESES;
break;
case '|':
case '&':
if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) {
this._setError(Lng.seMissSpell[lang], null);
return null;
}
if(sList[i] === '&') {
data[data.length - 1][0] |= 0x200;
}
lastType = this.TYPE_ANDOR;
break;
case '!':
if(lastType !== this.TYPE_ANDOR && lastType !== this.TYPE_UNKNOWN) {
this._setError(Lng.seMissOp[lang], null);
return null;
}
lastType = this.TYPE_NOT;
break;
case ')':
if(lastType === this.TYPE_ANDOR || lastType === this.TYPE_NOT) {
this._setError(Lng.seMissSpell[lang], null);
return null;
}
if(inParens) {
return [i, data];
}
default:
this._setError(Lng.seUnexpChar[lang], sList[i]);
return null;
}
}
if(inParens) {
this._setError(Lng.seMissClBkt[lang], null);
return null;
}
if(lastType !== this.TYPE_SPELL && lastType !== this.TYPE_PARENTHESES) {
this._setError(Lng.seMissSpell[lang], null);
return null;
}
return data;
},
_doSpell: function(name, str, isNeg) {
var scope, m, spellType, val, i = 0,
spellIdx = Spells.names.indexOf(name);
if(spellIdx === -1) {
this._setError(Lng.seUnknown[lang], name);
return null;
}
spellType = isNeg ? spellIdx | 0x100 : spellIdx;
m = str.match(/^\[([a-z0-9\/]+)(?:(,)|,(\s*[0-9]+))?\]/);
if(m) {
i = m[0].length;
str = str.substring(i);
scope = [m[1], m[3] ? m[3] : m[2] ? -1 : false];
} else {
scope = null;
}
if(str[0] !== '(' || str[1] === ')') {
if(Spells.needArg[spellIdx]) {
this._setError(Lng.seMissArg[lang], name);
return null;
}
return [str[0] === '(' ? i + 2 : i, [spellType, spellIdx === 14 ? 0x3F : '', scope]];
}
switch(spellIdx) {
// #ihash
case 4:
m = str.match(/^\((\d+)\)/);
if(+m[1] === +m[1]) {
return [i + m[0].length, [spellType, +m[1], scope]];
}
break;
// #img
case 8:
m = str.match(/^\(([><=])(?:(\d+(?:\.\d+)?)(?:-(\d+(?:\.\d+)?))?)?(?:@(\d+)(?:-(\d+))?x(\d+)(?:-(\d+))?)?\)/);
if(m && (m[2] || m[4])) {
return [i + m[0].length, [spellType, [
m[1] === '=' ? 0 : m[1] === '<' ? 1 : 2,
m[2] && [+m[2], m[3] ? +m[3] : +m[2]],
m[4] && [+m[4], m[5] ? +m[5] : +m[4], +m[6], m[7] ? +m[7] : +m[6]]
], scope]];
}
break;
// #wipe
case 14:
m = str.match(/^\(([a-z, ]+)\)/);
if(m) {
val = m[1].split(/, */).reduce(function(val, str) {
switch(str) {
case 'samelines': return val |= 1;
case 'samewords': return val |= 2;
case 'longwords': return val |= 4;
case 'symbols': return val |= 8;
case 'capslock': return val |= 16;
case 'numbers': return val |= 32;
case 'whitespace': return val |= 64;
default: return -1;
}
}, 0);
if(val !== -1) {
return [i + m[0].length, [spellType, val, scope]];
}
}
break;
// #tlen, #num
case 11:
case 15:
m = str.match(/^\(([\d-, ]+)\)/);
if(m) {
m[1].split(/, */).forEach(function(v) {
if(v.contains('-')) {
var nums = v.split('-');
nums[0] = +nums[0];
nums[1] = +nums[1];
this[1].push(nums);
} else {
this[0].push(+v);
}
}, val = [[], []]);
return [i + m[0].length, [spellType, val, scope]];
}
break;
// #exp, #exph, #imgn, #subj, #video
case 1:
case 2:
case 3:
case 5:
case 13:
m = str.match(/^\((\/.*?[^\\]\/[igm]*)\)/);
if(m) {
val = m[1];
try {
toRegExp(val, true);
} catch(e) {
this._setError(Lng.seErrRegex[lang], val);
return null;
}
return [i + m[0].length, [spellType, val, scope]];
}
break;
// #sage, #op, #all, #trip, #name, #words, #vauthor
default:
m = str.match(/^\((.*?[^\\])\)/);
if(m) {
val = m[1].replace(/\\\)/g, ')');
return [i + m[0].length, [spellType, spellIdx === 0 ? val.toLowerCase() : val, scope]];
}
}
this._setError(Lng.seSyntaxErr[lang], name);
return null;
},
_setError: function(msg, arg) {
this.hasError = true;
this._errMsg = msg;
this._errMsgArg = arg;
}
};
function disableSpells() {
closeAlert($id('de-alert-help-err-spell'));
if(spells.enable) {
sVis = TNum ? '1'.repeat(firstThr.pcount).split('') : [];
for(var post = firstThr.op; post; post = post.next) {
if(post.spellHidden && !post.userToggled) {
post.spellUnhide();
}
}
}
}
function toggleSpells() {
var temp, fld = $id('de-spell-edit'),
val = fld.value;
if(val && (temp = spells.parseText(val))) {
disableSpells();
spells.setSpells(temp, true);
fld.value = spells.list;
} else {
if(val) {
localStorage['__de-spells'] = '{"hide": false, "data": null}';
} else {
disableSpells();
spells.disable();
saveCfg('spells', '');
localStorage['__de-spells'] = '{"hide": false, "data": ""}';
}
localStorage.removeItem('__de-spells');
$q('input[info="hideBySpell"]', doc).checked = spells.enable = false;
}
}
function addSpell(type, arg, isNeg) {
var temp, fld = $id('de-spell-edit'),
val = fld && fld.value,
chk = $q('input[info="hideBySpell"]', doc);
if(!val || (temp = spells.parseText(val))) {
disableSpells();
spells.addSpell(type, arg, TNum ? [brd, TNum] : null, isNeg, temp);
val = spells.list;
saveCfg('hideBySpell', !!val);
if(val) {
for(var post = firstThr.op; post; post = post.next) {
spells.check(post);
}
spells.end(savePosts);
} else {
saveCfg('spells', '');
spells.enable = false;
}
if(fld) {
chk.checked = !!(fld.value = val);
}
return;
}
spells.enable = false;
if(chk) {
chk.checked = false;
}
}
function checkPostsVisib() {
for(var vis, num, date = Date.now(), post = firstThr.op; post; post = post.next) {
num = post.num;
if(num in uVis) {
if(post.isOp) {
uVis[num][0] = +!(num in hThr[brd]);
}
if(uVis[num][0] === 0) {
post.setUserVisib(true, date, false);
} else {
uVis[num][1] = date;
post.btns.firstChild.className = 'de-btn-hide-user';
post.userToggled = true;
}
} else {
vis = sVis[post.count];
if(post.isOp) {
if(num in hThr[brd]) {
vis = '0';
} else if(vis === '0') {
vis = null;
}
}
if(vis === '0') {
post.setVisib(true);
post.spellHidden = true;
} else if(vis !== '1') {
spells.check(post);
}
}
}
spells.end(savePosts);
}
//============================================================================================================
// STYLES
//============================================================================================================
function getThemeLang() {
return !Cfg['scriptStyle'] ? 'fr' :
Cfg['scriptStyle'] === 1 ? 'en' :
'de';
}
function scriptCSS() {
var p, x = '';
function cont(id, src) {
return id + ':before { content: ""; padding: 0 16px 0 0; margin: 0 4px; background: url(' + src + ') no-repeat center; }';
}
function gif(id, src) {
return id + ' { background: url(data:image/gif;base64,' + src + ') no-repeat center !important; }';
}
// Settings window
x += '.de-block { display: block; }\
#de-content-cfg > div { border-radius: 10px 10px 0 0; width: auto; min-width: 0; padding: 0; margin: 5px 20px; overflow: hidden; }\
#de-cfg-head { padding: 4px; border-radius: 10px 10px 0 0; color: #fff; text-align: center; font: bold 14px arial; cursor: default; }\
#de-cfg-head:lang(en), #de-panel:lang(en) { background: linear-gradient(to bottom, #4b90df, #3d77be 5px, #376cb0 7px, #295591 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #183d77 13px, #1f4485 18px, #264c90 20px, #325f9e 25px); }\
#de-cfg-head:lang(fr), #de-panel:lang(fr) { background: linear-gradient(to bottom, #7b849b, #616b86 2px, #3a414f 13px, rgba(0,0,0,0) 13px), linear-gradient(to bottom, rgba(0,0,0,0) 12px, #121212 13px, #1f2740 25px); }\
#de-cfg-head:lang(de), #de-panel:lang(de) { background: #777; }\
.de-cfg-body { min-height: 288px; min-width: 371px; padding: 11px 7px 7px; margin-top: -1px; font: 13px sans-serif; }\
.de-cfg-body input[type="text"], .de-cfg-body select { width: auto; padding: 0 !important; margin: 0 !important; }\
.de-cfg-body, #de-cfg-btns { border: 1px solid #183d77; border-top: none; }\
.de-cfg-body:lang(de), #de-cfg-btns:lang(de) { border-color: #444; }\
#de-cfg-btns { padding: 7px 2px 2px; }\
#de-cfg-bar { width: 100%; display: table; background-color: #1f2740; margin: 0; padding: 0; }\
#de-cfg-bar:lang(en) { background-color: #325f9e; }\
#de-cfg-bar:lang(de) { background-color: #777; }\
.de-cfg-depend { padding-left: 25px; }\
.de-cfg-tab { padding: 4px 5px; border-radius: 4px 4px 0 0; font: bold 12px arial; text-align: center; cursor: default; }\
.de-cfg-tab-back { display: table-cell !important; float: none !important; min-width: 0 !important; padding: 0 !important; box-shadow: none !important; border: 1px solid #183d77 !important; border-radius: 4px 4px 0 0; opacity: 1; }\
.de-cfg-tab-back:lang(de) { border-color: #444 !important; }\
.de-cfg-tab-back:lang(fr) { border-color: #121421 !important; }\
.de-cfg-tab-back[selected="true"] { border-bottom: none !important; }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab { background-color: rgba(0,0,0,.2); }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:lang(fr) { background: linear-gradient(to bottom, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover { background-color: rgba(99,99,99,.2); }\
.de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(en), .de-cfg-tab-back[selected="false"] > .de-cfg-tab:hover:lang(fr) { background: linear-gradient(to top, rgba(132,132,132,.35) 0%, rgba(79,79,79,.35) 50%, rgba(40,40,40,.35) 50%, rgba(80,80,80,.35) 100%) !important; }\
.de-cfg-tab::' + (nav.Firefox ? '-moz-' : '') + 'selection { background: transparent; }\
.de-cfg-unvis { display: none; }\
#de-cfg-updresult { padding: 3px 0; font-size: 1.1em; text-align: center; }\
#de-spell-panel { float: right; }\
#de-spell-panel > a { padding: 0 4px; }\
#de-spell-div { display: table; }\
#de-spell-div > div { display: table-cell; vertical-align: top; }\
#de-spell-edit { padding: 2px !important; width: 340px; height: 180px; border: none !important; outline: none !important; }\
#de-spell-rowmeter { padding: 2px 3px 0 0; margin: 2px 0; overflow: hidden; width: 2em; height: 182px; text-align: right; color: #fff; font: 12px courier new; }\
#de-spell-rowmeter:lang(en), #de-spell-rowmeter:lang(fr) { background-color: #616b86; }\
#de-spell-rowmeter:lang(de) { background-color: #777; }';
// Main panel
x += '#de-btn-logo { margin-right: 3px; cursor: pointer; }\
#de-panel { height: 25px; z-index: 9999; border-radius: 15px 0 0 0; cursor: default;}\
#de-panel-btns { display: inline-block; padding: 0 0 0 2px; margin: 0; height: 25px; border-left: 1px solid #8fbbed; }\
#de-panel-btns:lang(de), #de-panel-info:lang(de) { border-color: #ccc; }\
#de-panel-btns:lang(fr), #de-panel-info:lang(fr) { border-color: #616b86; }\
#de-panel-btns > li { margin: 0 1px; padding: 0; }\
#de-panel-btns > li, #de-panel-btns > li > a, #de-btn-logo { display: inline-block; width: 25px; height: 25px; }\
#de-panel-btns:lang(en) > li, #de-panel-btns:lang(fr) > li { transition: all 0.3s ease; }\
#de-panel-btns:lang(en) > li:hover, #de-panel-btns:lang(fr) > li:hover { background-color: rgba(255,255,255,.15); box-shadow: 0 0 3px rgba(143,187,237,.5); }\
#de-panel-btns:lang(de) > li > a { border-radius: 5px; }\
#de-panel-btns:lang(de) > li > a:hover { width: 21px; height: 21px; border: 2px solid #444; }\
#de-panel-info { display: inline-block; vertical-align: 6px; padding: 0 6px; margin: 0 0 0 2px; height: 25px; border-left: 1px solid #8fbbed; color: #fff; font: 18px serif; }';
p = 'R0lGODlhGQAZAIAAAPDw8P///yH5BAEAAAEALAAAAAAZABkAQA';
x += gif('#de-btn-logo', p + 'I5jI+pywEPWoIIRomz3tN6K30ixZXM+HCgtjpk1rbmTNc0erHvLOt4vvj1KqnD8FQ0HIPCpbIJtB0KADs=');
x += gif('#de-btn-settings', p + 'JAjI+pa+API0Mv1Ymz3hYuiQHHFYjcOZmlM3Jkw4aeAn7R/aL6zuu5VpH8aMJaKtZR2ZBEZnMJLM5kIqnP2csUAAA7');
x += gif('#de-btn-hidden', p + 'I5jI+pa+CeHmRHgmCp3rxvO3WhMnomUqIXl2UmuLJSNJ/2jed4Tad96JLBbsEXLPbhFRc8lU8HTRQAADs=');
x += gif('#de-btn-favor', p + 'IzjI+py+AMjZs02ovzobzb1wDaeIkkwp3dpLEoeMbynJmzG6fYysNh3+IFWbqPb3OkKRUFADs=');
x += gif('#de-btn-refresh', p + 'JAjI+pe+AfHmRGLkuz3rzN+1HS2JWbhWlpVIXJ+roxSpr2jedOBIu0rKjxhEFgawcCqJBFZlPJIA6d0ZH01MtRCgA7');
x += gif('#de-btn-goback', p + 'IrjI+pmwAMm4u02gud3lzjD4biJgbd6VVPybbua61lGqIoY98ZPcvwD4QUAAA7');
x += gif('#de-btn-gonext', p + 'IrjI+pywjQonuy2iuf3lzjD4Zis0Xd6YnQyLbua61tSqJnbXcqHVLwD0QUAAA7');
x += gif('#de-btn-goup', p + 'IsjI+pm+DvmDRw2ouzrbq9DmKcBpVfN4ZpyLYuCbgmaK7iydpw1OqZf+O9LgUAOw==');
x += gif('#de-btn-godown', p + 'ItjI+pu+DA4ps02osznrq9DnZceIxkYILUd7bue6WhrLInLdokHq96tnI5YJoCADs=');
x += gif('#de-btn-expimg', p + 'I9jI+pGwDn4GPL2Wep3rxXFEFel42mBE6kcYXqFqYnVc72jTPtS/KNr5OJOJMdq4diAXWvS065NNVwseehAAA7');
x += gif('#de-btn-preimg', p + 'JFjI+pGwCcHJPGWdoe3Lz7qh1WFJLXiX4qgrbXVEIYadLLnMX4yve+7ErBYorRjXiEeXagGguZAbWaSdHLOow4j8Hrj1EAADs=');
x += gif('#de-btn-maskimg', p + 'JQjI+pGwD3TGxtJgezrKz7DzLYRlKj4qTqmoYuysbtgk02ZCG1Rkk53gvafq+i8QiSxTozIY7IcZJOl9PNBx1de1Sdldeslq7dJ9gsUq6QnwIAOw==');
x += gif('#de-btn-imgload', p + 'JFjI+pG+CQnHlwSYYu3rz7RoVipWib+aVUVD3YysAledKZHePpzvecPGnpDkBQEEV03Y7DkRMZ9ECNnemUlZMOQc+iT1EAADs=')
x += gif('#de-btn-catalog', p + 'I2jI+pa+DhAHyRNYpltbz7j1Rixo0aCaaJOZ2SxbIwKTMxqub6zuu32wP9WsHPcFMs0XDJ5qEAADs=');
x += gif('#de-btn-audio-off', p + 'I7jI+pq+DO1psvQHOj3rxTik1dCIzmSZqfmGXIWlkiB6L2jedhPqOfCitVYolgKcUwyoQuSe3WwzV1kQIAOw==');
x += gif('#de-btn-audio-on', p + 'JHjI+pq+AewJHs2WdoZLz7X11WRkEgNoHqimadOG7uAqOm+Y6atvb+D0TgfjHS6RIp8YQ1pbHRfA4n0eSTI7JqP8Wtahr0FAAAOw==');
p = 'Dw8P///wAAACH5BAEAAAIALAAAAAAZABkAQAJElI+pe2EBoxOTNYmr3bz7OwHiCDzQh6bq06QSCUhcZMCmNrfrzvf+XsF1MpjhCSainBg0AbKkFCJko6g0MSGyftwuowAAOw==';
x += gif('#de-btn-upd-on', 'R0lGODlhGQAZAJEAADL/Mv' + p);
x += gif('#de-btn-upd-off', 'R0lGODlhGQAZAJEAAP8yMv' + p);
x += gif('#de-btn-upd-warn', 'R0lGODlhGQAZAJEAAP/0Qf' + p);
// Post panel
x += '.de-ppanel { margin-left: 4px; }\
.de-thread-note { font-style: italic; }\
.de-post-note { color: inherit; margin: 0 4px; vertical-align: 1px; font: italic bold 12px serif; }\
.de-btn-hide, .de-btn-hide-user, .de-btn-rep, .de-btn-fav, .de-btn-fav-sel, .de-btn-src, .de-btn-expthr, .de-btn-sage { display: inline-block; margin: 0 4px -2px 0 !important; cursor: pointer; ';
if(Cfg['postBtnsCSS'] === 0) {
x += 'color: #4F7942; font-size: 14px; }\
.de-btn-hide:after { content: "\u2716"; }\
.de-post-hid .de-btn-hide:after { content: "\u271a"; }\
.de-btn-hide-user:after { content: "\u2716"; color: red !important; }\
.de-post-hid .de-btn-hide-user:after { content: "\u271a"; }\
.de-btn-rep:after { content: "\u25b6"; }\
.de-btn-expthr:after { content: "\u21d5"; }\
.de-btn-fav:after { content: "\u2605"; }\
.de-btn-fav-sel:after { content: "[\u2605]"; }\
.de-btn-sage:after { content: "\u274e"; }\
.de-btn-src:after { content: "[S]"; }';
} else if(Cfg['postBtnsCSS'] === 1) {
x += 'padding: 0 14px 14px 0; }';
x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAKIAAL//v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM8SLLcS2MNQGsUMYi6uB5BKI5hFgojel5YBbDDNcmvpJLkcgLq1jcuSgPmgkUmlJgFAyqNmoEBJEatxggJADs=');
x += gif('.de-post-hid .de-btn-hide-user', 'R0lGODlhDgAOAKIAAP+/v6CgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM5SLLcS2ONCcCMIoYdRBVcN4Qkp4ULmWVV20ZTM1SYBJbqvXmA3jk8IMzlgtVYFtkoNCENIJdolJAAADs=');
p = 'R0lGODlhDgAOAKIAAPDw8KCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM';
x += gif('.de-btn-hide', p + '8SLLcS2MNQGsUMYi6uB5BKI5hFgojel5YBbDDNcmvpJLkcgLq1jcuSgPmgkUmlJgFAyqNmoEBJEatxggJADs=');
x += gif('.de-post-hid .de-btn-hide', p + '5SLLcS2ONCcCMIoYdRBVcN4Qkp4ULmWVV20ZTM1SYBJbqvXmA3jk8IMzlgtVYFtkoNCENIJdolJAAADs=');
x += gif('.de-btn-rep', p + '4SLLcS2MNQGsUMQRRwdLbAI5kpn1kKHUWdk3AcDFmOqKcJ5AOq0srX0QWpBAlIo3MNoDInlAZIQEAOw==');
x += gif('.de-btn-expthr', p + '7SLLcS6MNACKLIQjKgcjCkI2DOAbYuHlnKFHWUl5dnKpfm2vd7iyUXywEk1gmnYrMlEEyUZCSdFoiJAAAOw==');
x += gif('.de-btn-fav', p + '5SLLcS2MNQGsUl1XgRvhg+EWhQAllNG0WplLXqqIlDS7lWZvsJkm92Au2Aqg8gQFyhBxAlNCokpAAADs=');
x += gif('.de-btn-fav-sel', 'R0lGODlhDgAOAKIAAP/hAKCgoICAgEtLS////wAAAAAAAAAAACH5BAEAAAQALAAAAAAOAA4AQAM5SLLcS2MNQGsUl1XgRvhg+EWhQAllNG0WplLXqqIlDS7lWZvsJkm92Au2Aqg8gQFyhBxAlNCokpAAADs=');
x += gif('.de-btn-sage', 'R0lGODlhDgAOAJEAAPDw8EtLS////wAAACH5BAEAAAIALAAAAAAOAA4AQAIZVI55duDvFIKy2vluoJfrD4Yi5lWRwmhCAQA7');
x += gif('.de-btn-src', p + '9SLLcS0MMQMesUoQg6PKbtFnDaI0a53VAml2ARcVSFC0WY6ecyy+hFajnWDVssyQtB5NhTs1mYAAhWa2EBAA7');
} else {
x += 'padding: 0 14px 14px 0; }';
x += gif('.de-btn-hide-user', 'R0lGODlhDgAOAJEAAL//v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw==');
x += gif('.de-post-hid .de-btn-hide-user', 'R0lGODlhDgAOAJEAAP+/v4yMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7 ');
p = 'R0lGODlhDgAOAJEAAPDw8IyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAI';
x += gif('.de-btn-hide', p + 'dVI55pu2vQJIN2GNpzPdxGHwep01d5pQlyDoMKBQAOw==');
x += gif('.de-post-hid .de-btn-hide', p + 'ZVI55pu3vAIBI0mOf3LtxDmWUGE7XSTFpAQA7');
x += gif('.de-btn-rep', p + 'aVI55pu2vAIBISmrty7rx63FbN1LmiTCUUAAAOw==');
x += gif('.de-btn-expthr', p + 'bVI55pu0BwEMxzlonlHp331kXxjlYWH4KowkFADs=');
x += gif('.de-btn-fav', p + 'dVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw==');
x += gif('.de-btn-fav-sel','R0lGODlhDgAOAJEAAP/hAIyMjP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIdVI55pu0BwEtxnlgb3ljxrnHP54AgJSGZxT6MJRQAOw==');
x += gif('.de-btn-sage','R0lGODlhDgAOAJEAAPDw8FBQUP///wAAACH5BAEAAAIALAAAAAAOAA4AAAIZVI55pu0AgZs0SoqTzdnu5l1P1ImcwmBCAQA7');
x += gif('.de-btn-src', p + 'fVI55pt0ADnRh1uispfvpLkEieGGiZ5IUGmJrw7xCAQA7');
}
if(!pr.form && !pr.oeForm) {
x += '.de-btn-rep { display: none; }';
}
// Search images buttons
x += cont('.de-src-google', 'http://google.com/favicon.ico');
x += cont('.de-src-tineye', 'http://tineye.com/favicon.ico');
x += cont('.de-src-iqdb', 'http://iqdb.org/favicon.ico');
x += cont('.de-src-saucenao', 'http://saucenao.com/favicon.ico');
// Posts counter
x += '.de-ppanel-cnt:after { counter-increment: de-cnt 1; content: counter(de-cnt); margin-right: 4px; vertical-align: 1px; color: #4f7942; font: bold 11px tahoma; cursor: default; }\
.de-ppanel-del:after { content: "' + Lng.deleted[lang] + '"; margin-right: 4px; vertical-align: 1px; color: #727579; font: bold 11px tahoma; cursor: default; }';
// Text format buttons
x += '#de-txt-panel { display: block; height: 23px; font-weight: bold; cursor: pointer; }\
#de-txt-panel > span:empty { display: inline-block; width: 27px; height: 23px; }';
p = 'R0lGODlhFwAWAJEAAPDw8GRkZAAAAP///yH5BAEAAAMALAAAAAAXABYAQAJ';
x += gif('#de-btn-bold:empty', p + 'T3IKpq4YAoZgR0KqqnfzipIUikFWc6ZHBwbQtG4zyonW2Vkb2iYOo8Ps8ZLOV69gYEkU5yQ7YUzqhzmgsOLXWnlRIc9PleX06rnbJ/KITDqTLUAAAOw==');
x += gif('#de-btn-italic:empty', p + 'K3IKpq4YAYxRCSmUhzTfx3z3c9iEHg6JnAJYYSFpvRlXcLNUg3srBmgr+RL0MzxILsYpGzyepfEIjR43t5kResUQmtdpKOIQpQwEAOw==');
x += gif('#de-btn-under:empty', p + 'V3IKpq4YAoRARzAoV3hzoDnoJNlGSWSEHw7JrEHILiVp1NlZXtKe5XiptPrFh4NVKHh9FI5NX60WIJ6ATZoVeaVnf8xSU4r7NMRYcFk6pzYRD2TIUAAA7');
x += gif('#de-btn-strike:empty', p + 'S3IKpq4YAoRBR0qqqnVeD7IUaKHIecjCqmgbiu3jcfCbAjOfTZ0fmVnu8YIHW6lgUDkOkCo7Z8+2AmCiVqHTSgi6pZlrN3nJQ8TISO4cdyJWhAAA7');
x += gif('#de-btn-spoil:empty', 'R0lGODlhFwAWAJEAAPDw8GRkZP///wAAACH5BAEAAAIALAAAAAAXABYAQAJBlIKpq4YAmHwxwYtzVrprXk0LhBziGZiBx44hur4kTIGsZ99fSk+mjrMAd7XerEg7xnpLIVM5JMaiFxc14WBiBQUAOw==');
x += gif('#de-btn-code:empty', p + 'O3IKpq4YAoZgR0KpqnFxokH2iFm7eGCEHw7JrgI6L2F1YotloKek6iIvJAq+WkfgQinjKVLBS45CePSXzt6RaTjHmNjpNNm9aq6p4XBgKADs=');
x += gif('#de-btn-sup:empty', p + 'Q3IKpq4YAgZiSQhGByrzn7YURGFGWhxzMuqqBGC7wRUNkeU7nnWNoMosFXKzi8BHs3EQnDRAHLY2e0BxnWfEJkRdT80NNTrliG3aWcBhZhgIAOw==');
x += gif('#de-btn-sub:empty', p + 'R3IKpq4YAgZiSxquujtOCvIUayAkVZEoRcjCu2wbivMw2WaYi7vVYYqMFYq/i8BEM4ZIrYOmpdD49m2VFd2oiUZTORWcNYT9SpnZrTjiML0MBADs=');
x += gif('#de-btn-quote:empty', p + 'L3IKpq4YAYxRUSKguvRzkDkZfWFlicDCqmgYhuGjVO74zlnQlnL98uwqiHr5ODbDxHSE7Y490wxF90eUkepoysRxrMVaUJBzClaEAADs=');
// Show/close animation
if(nav.Anim) {
x += '@keyframes de-open {\
0% { transform: translateY(-1500px); }\
40% { transform: translateY(30px); }\
70% { transform: translateY(-10px); }\
100% { transform: translateY(0); }\
}\
@keyframes de-close {\
0% { transform: translateY(0); }\
20% { transform: translateY(20px); }\
100% { transform: translateY(-4000px); }\
}\
@keyframes de-blink {\
0%, 100% { transform: translateX(0); }\
10%, 30%, 50%, 70%, 90% { transform: translateX(-10px); }\
20%, 40%, 60%, 80% { transform: translateX(10px); }\
}\
@keyframes de-cfg-open { from { transform: translate(0,50%) scaleY(0); opacity: 0; } }\
@keyframes de-cfg-close { to { transform: translate(0,50%) scaleY(0); opacity: 0; } }\
@keyframes de-post-open-tl { from { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-open-bl { from { transform: translate(-50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-open-tr { from { transform: translate(50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-open-br { from { transform: translate(50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-tl { to { transform: translate(-50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-bl { to { transform: translate(-50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-tr { to { transform: translate(50%,-50%) scale(0); opacity: 0; } }\
@keyframes de-post-close-br { to { transform: translate(50%,50%) scale(0); opacity: 0; } }\
@keyframes de-post-new { from { transform: translate(0,-50%) scaleY(0); opacity: 0; } }\
.de-pview-anim { animation-duration: .2s; animation-timing-function: ease-in-out; animation-fill-mode: both; }\
.de-open { animation: de-open .7s ease-out both; }\
.de-close { animation: de-close .7s ease-in both; }\
.de-blink { animation: de-blink .7s ease-in-out both; }\
.de-cfg-open { animation: de-cfg-open .2s ease-out backwards; }\
.de-cfg-close { animation: de-cfg-close .2s ease-in both; }\
.de-post-new { animation: de-post-new .2s ease-out both; }';
}
// Embedders
x += cont('.de-video-link.de-ytube', 'https://youtube.com/favicon.ico');
x += cont('.de-video-link.de-vimeo', 'https://vimeo.com/favicon.ico');
x += cont('.de-img-arch', 'data:image/gif;base64,R0lGODlhEAAQALMAAF82SsxdwQMEP6+zzRA872NmZQesBylPHYBBHP///wAAAAAAAAAAAAAAAAAAAAAAACH5BAEAAAkALAAAAAAQABAAQARTMMlJaxqjiL2L51sGjCOCkGiBGWyLtC0KmPIoqUOg78i+ZwOCUOgpDIW3g3KJWC4t0ElBRqtdMr6AKRsA1qYy3JGgMR4xGpAAoRYkVDDWKx6NRgAAOw==');
x += cont('.de-img-audio', 'data:image/gif;base64,R0lGODlhEAAQAKIAAGya4wFLukKG4oq3802i7Bqy9P///wAAACH5BAEAAAYALAAAAAAQABAAQANBaLrcHsMN4QQYhE01OoCcQIyOYQGooKpV1GwNuAwAa9RkqTPpWqGj0YTSELg0RIYM+TjOkgba0sOaAEbGBW7HTQAAOw==');
x += '.de-current:after { content: "\u25c4"; }\
.de-img-arch, .de-img-audio { color: inherit; text-decoration: none; font-weight: bold; }\
.de-img-pre, .de-img-full { display: block; border: none; outline: none; cursor: pointer; }\
.de-img-pre { max-width: 200px; max-height: 200px; }\
.de-img-full { float: left; }\
.de-img-center { position: fixed; margin: 0 !important; z-index: 9999; background-color: #ccc; border: 1px solid black !important; }\
#de-img-btn-next > div, #de-img-btn-prev > div { height: 36px; width: 36px; }' +
gif('#de-img-btn-next > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJPjI8JkO1vlpzS0YvzhUdX/nigR2ZgSJ6IqY5Uy5UwJK/l/eI6A9etP1N8grQhUbg5RlLKAJD4DAJ3uCX1isU4s6xZ9PR1iY7j5nZibixgBQA7') +
gif('#de-img-btn-prev > div', 'R0lGODlhIAAgAIAAAPDw8P///yH5BAEAAAEALAAAAAAgACAAQAJOjI8JkO24ooxPzYvzfJrWf3Rg2JUYVI4qea1g6zZmPLvmDeM6Y4mxU/v1eEKOpziUIA1BW+rXXEVVu6o1dQ1mNcnTckp7In3LAKyMchUAADs=') +
'#de-img-btns { position: fixed; z-index: 10000; cursor: pointer; }\
#de-img-btn-next, #de-img-btn-prev { position: fixed; top: 50%; margin-top: -8px; background-color: black; }\
#de-img-btn-next { right: 0; border-radius: 10px 0 0 10px; }\
#de-img-btn-prev { left: 0; border-radius: 0 10px 10px 0; }\
.de-mp3, .de-video-obj { margin: 5px 20px; }\
.de-video-title[de-time]:after { content: " [" attr(de-time) "]"; color: red; }\
td > a + .de-video-obj { display: inline-block; }\
video { background: black; }';
// Other
x += cont('.de-wait', 'data:image/gif;base64,R0lGODlhEAAQALMMAKqooJGOhp2bk7e1rZ2bkre1rJCPhqqon8PBudDOxXd1bISCef///wAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAAMACwAAAAAEAAQAAAET5DJyYyhmAZ7sxQEs1nMsmACGJKmSaVEOLXnK1PuBADepCiMg/DQ+/2GRI8RKOxJfpTCIJNIYArS6aRajWYZCASDa41Ow+Fx2YMWOyfpTAQAIfkEBQAADAAsAAAAABAAEAAABE6QyckEoZgKe7MEQMUxhoEd6FFdQWlOqTq15SlT9VQM3rQsjMKO5/n9hANixgjc9SQ/CgKRUSgw0ynFapVmGYkEg3v1gsPibg8tfk7CnggAIfkEBQAADAAsAAAAABAAEAAABE2QycnOoZjaA/IsRWV1goCBoMiUJTW8A0XMBPZmM4Ug3hQEjN2uZygahDyP0RBMEpmTRCKzWGCkUkq1SsFOFQrG1tr9gsPc3jnco4A9EQAh+QQFAAAMACwAAAAAEAAQAAAETpDJyUqhmFqbJ0LMIA7McWDfF5LmAVApOLUvLFMmlSTdJAiM3a73+wl5HYKSEET2lBSFIhMIYKRSimFriGIZiwWD2/WCw+Jt7xxeU9qZCAAh+QQFAAAMACwAAAAAEAAQAAAETZDJyRCimFqbZ0rVxgwF9n3hSJbeSQ2rCWIkpSjddBzMfee7nQ/XCfJ+OQYAQFksMgQBxumkEKLSCfVpMDCugqyW2w18xZmuwZycdDsRACH5BAUAAAwALAAAAAAQABAAAARNkMnJUqKYWpunUtXGIAj2feFIlt5JrWybkdSydNNQMLaND7pC79YBFnY+HENHMRgyhwPGaQhQotGm00oQMLBSLYPQ9QIASrLAq5x0OxEAIfkEBQAADAAsAAAAABAAEAAABE2QycmUopham+da1cYkCfZ94UiW3kmtbJuRlGF0E4Iwto3rut6tA9wFAjiJjkIgZAYDTLNJgUIpgqyAcTgwCuACJssAdL3gpLmbpLAzEQA7');
x += '.de-abtn { text-decoration: none !important; outline: none; }\
.de-after-fimg { clear: left; }\
#de-alert { position: fixed; right: 0; top: 0; z-index: 9999; font: 14px arial; cursor: default; }\
#de-alert > div { float: right; clear: both; width: auto; min-width: 0pt; padding: 10px; margin: 1px; border: 1px solid grey; white-space: pre-wrap; }\
.de-alert-btn { display: inline-block; vertical-align: top; color: green; cursor: pointer; }\
.de-alert-btn:not(.de-wait) + div { margin-top: .15em; }\
.de-alert-msg { display: inline-block; }\
.de-content textarea { display: block; margin: 2px 0; font: 12px courier new; ' + (nav.Opera ? '' : 'resize: none !important; ') + '}\
.de-content-block > a { color: inherit; font-weight: bold; }\
#de-content-fav, #de-content-hid { font-size: 16px; padding: 10px; border: 1px solid gray; }\
.de-editor { display: block; font: 12px courier new; width: 619px; height: 337px; tab-size: 4; -moz-tab-size: 4; -o-tab-size: 4; }\
.de-entry { margin: 2px 0; ' + (nav.Opera ? 'white-space: nowrap; ' : '') + '}\
.de-entry > :first-child { float: none !important; }\
.de-entry > div > a { text-decoration: none; }\
.de-fav-inf-posts, .de-fav-inf-page { float: right; margin-right: 5px; font: bold 16px serif; }\
.de-fav-inf-old { color: #4f7942; }\
.de-fav-inf-new { color: blue; }\
.de-fav-title { margin-right: 15px; }\
.de-menu { padding: 0 !important; margin: 0 !important; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important;}\
.de-menu-item { display: block; padding: 3px 10px; color: inherit; text-decoration: none; font: 13px arial; white-space: nowrap; cursor: pointer; }\
.de-menu-item:hover { background-color: #222; color: #fff; }\
.de-new-post { ' + (nav.Opera ? 'border-left: 4px solid blue; border-right: 4px solid blue; }' : 'box-shadow: 6px 0 2px -2px blue, -6px 0 2px -2px blue; }') + '\
.de-omitted { color: grey; font-style: italic; }\
.de-omitted:before { content: "' + Lng.postsOmitted[lang] + '"; }\
.de-opref::after { content: " [OP]"; }\
.de-parea { text-align: center;}\
.de-parea-btn-close:after { content: "' + Lng.hideForm[lang] + '" }\
.de-parea-btn-thrd:after { content: "' + Lng.makeThrd[lang] + '" }\
.de-parea-btn-reply:after { content: "' + Lng.makeReply[lang] + '" }\
.de-pview { position: absolute; width: auto; min-width: 0; z-index: 9999; border: 1px solid grey !important; margin: 0 !important; display: block !important; }\
.de-pview-info { padding: 3px 6px !important; }\
.de-pview-link { font-weight: bold; }\
.de-ref-hid { text-decoration: line-through !important; }\
.de-refmap { margin: 10px 4px 4px 4px; font-size: 70%; font-style: italic; }\
.de-refmap:before { content: "' + Lng.replies[lang] + ' "; }\
.de-reflink { text-decoration: none; }\
.de-refcomma:last-child { display: none; }\
#de-sagebtn { margin-right: 7px; cursor: pointer; }\
.de-selected, .de-error-key { ' + (nav.Opera ? 'border-left: 4px solid red; border-right: 4px solid red; }' : 'box-shadow: 6px 0 2px -2px red, -6px 0 2px -2px red; }') + '\
#de-txt-resizer { display: inline-block !important; float: none !important; padding: 6px; margin: -2px -12px; vertical-align: bottom; border-bottom: 2px solid #555; border-right: 2px solid #444; cursor: se-resize; }\
#de-updater-btn:after { content: "' + Lng.getNewPosts[lang] + '" }\
#de-updater-div { margin-top: 10px; }\
.de-viewed { color: #888 !important; }\
.de-hidden, small[id^="rfmap"], body > hr, .theader, .postarea, .thumbnailmsg { display: none !important; }\
form > hr { clear: both }\
' + aib.css + aib.cssEn + aib.cssHide + ' { display: none !important; }';
if(!nav.Firefox) {
x = x.replace(/(transition|keyframes|transform|animation|linear-gradient)/g, nav.cssFix + '$1');
if(!nav.Opera) {
x = x.replace(/\(to bottom/g, '(top').replace(/\(to top/g, '(bottom');
}
}
$css(x).id = 'de-css';
$css('').id = 'de-css-dynamic';
$css('').id = 'de-css-user';
updateCSS();
}
function updateCSS() {
var x;
if(Cfg['attachPanel']) {
x = '.de-content { position: fixed; right: 0; bottom: 25px; z-index: 9999; max-height: 95%; overflow-x: visible; overflow-y: auto; }\
#de-panel { position: fixed; right: 0; bottom: 0; }'
} else {
x = '.de-content { clear: both; float: right; }\
#de-panel { float: right; clear: both; }'
}
if(Cfg['addPostForm'] === 3) {
x += '#de-qarea { position: fixed; right: 0; bottom: 25px; z-index: 9990; padding: 3px; border: 1px solid gray; }\
#de-qarea-target { font-weight: bold; }\
#de-qarea-close { float: right; color: green; font: bold 20px arial; cursor: pointer; }';
} else {
x += '#de-qarea { float: none; clear: left; width: 100%; padding: 3px 0 3px 3px; margin: 2px 0; }';
}
if(!Cfg['panelCounter']) {
x += '#de-panel-info { display: none; }';
}
if(Cfg['maskImgs']) {
x += '.de-img-pre, .de-video-obj, .thumb, .ca_thumb, img[src*="spoiler"], img[src*="thumb"], img[src^="blob"] { opacity: 0.07 !important; }\
.de-img-pre:hover, .de-video-obj:hover, img[src*="spoiler"]:hover, img[src*="thumb"]:hover, img[src^="blob"]:hover { opacity: 1 !important; }';
}
if(Cfg['expandImgs'] === 1 && !(aib.fch || aib.dobr || aib.krau)) {
x += '.de-img-full { margin: 2px 10px; }';
}
if(Cfg['delHiddPost']) {
x += '.de-thr-hid, .de-thr-hid + div + br, .de-thr-hid + div + br + hr { display: none; }';
}
if(Cfg['noPostNames']) {
x += aib.qName + ', .' + aib.cTrip + ' { display: none; }';
}
if(Cfg['noSpoilers']) {
x += '.spoiler' + (aib.fch ? ', s' : '') + ' { background: #888 !important; color: #ccc !important; }';
}
if(Cfg['noPostScrl']) {
x += 'blockquote, blockquote > p, .code_part { max-height: 100% !important; overflow: visible !important; }';
}
if(Cfg['noBoardRule']) {
x += (aib.futa ? '.chui' : '.rules, #rules, #rules_row') + ' { display: none; }';
}
if(aib.abu) {
if(Cfg['addYouTube']) {
x += 'div[id^="post_video"] { display: none !important; }';
}
}
$id('de-css-dynamic').textContent = x;
$id('de-css-user').textContent = Cfg['userCSS'] ? Cfg['userCSSTxt'] : '';
}
//============================================================================================================
// SCRIPT UPDATING
//============================================================================================================
function checkForUpdates(isForce, Fn) {
var day, temp = Cfg['scrUpdIntrv'];
if(!isForce) {
day = 2 * 1000 * 60 * 60 * 24;
switch(temp) {
case 0: temp = day; break;
case 1: temp = day * 2; break;
case 2: temp = day * 7; break;
case 3: temp = day * 14; break;
default: temp = day * 30;
}
if(Date.now() - +comCfg['lastUpd'] < temp) {
return;
}
}
GM_xmlhttpRequest({
'method': 'GET',
'url': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/Dollchan_Extension_Tools.meta.js',
'headers': {'Content-Type': 'text/plain'},
'onreadystatechange': function(xhr) {
if(xhr.readyState !== 4) {
return;
}
if(xhr.status === 200) {
var dVer = xhr.responseText.match(/@version\s+([0-9.]+)/)[1].split('.'),
cVer = version.split('.'),
len = cVer.length > dVer.length ? cVer.length : dVer.length,
i = 0,
isUpd = false;
if(!dVer) {
if(isForce) {
Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>');
}
return;
}
saveComCfg('lastUpd', Date.now());
while(i < len) {
if((+dVer[i] || 0) > (+cVer[i] || 0)) {
isUpd = true;
break;
} else if((+dVer[i] || 0) < (+cVer[i] || 0)) {
break;
}
i++;
}
if(isUpd) {
Fn('<a style="color: blue; font-weight: bold;" href="' +
'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/' +
'Dollchan_Extension_Tools.user.js">' + Lng.updAvail[lang] + '</a>');
} else if(isForce) {
Fn(Lng.haveLatest[lang]);
}
} else if(isForce) {
Fn('<div style="color: red; font-weigth: bold;">' + Lng.noConnect[lang] + '</div>');
}
}
});
}
//============================================================================================================
// POSTFORM
//============================================================================================================
function PostForm(form, ignoreForm, init) {
this.oeForm = $q('form[name="oeform"], form[action*="paint"]', doc);
if(aib.abu && ($c('locked', form) || this.oeForm)) {
this.form = null;
if(this.oeForm) {
this._init();
}
return;
}
if(!ignoreForm && !form) {
if(this.oeForm) {
ajaxLoad(aib.getThrdUrl(brd, aib.getTNum(dForm)), false, function(dc, xhr) {
pr = new PostForm($q(aib.qPostForm, dc), true, init);
}, function(eCode, eMsg, xhr) {
pr = new PostForm(null, true, init);
});
} else {
this.form = null;
}
return;
}
function $x(path, root) {
return doc.evaluate(path, root, null, 8, null).singleNodeValue;
}
var tr = aib.trTag,
p = './/' + tr + '[not(contains(@style,"none"))]//input[not(@type="hidden") and ';
this.tNum = TNum;
this.form = form;
this.cap = $q('input[type="text"][name*="aptcha"], div[id*="captcha"]', form);
this.txta = $q(tr + ':not([style*="none"]) textarea:not([style*="display:none"])', form);
this.subm = $q(tr + ' input[type="submit"]', form);
this.file = $q(tr + ' input[type="file"]', form);
this.passw = $q(tr + ' input[type="password"]', form);
this.dpass = $q('input[type="password"], input[name="password"]', dForm);
this.gothr = $x('.//tr[@id="trgetback"]|.//input[@type="radio" or @name="gotothread"]/ancestor::tr[1]', form);
this.name = $x(p + '(@name="field1" or @name="name" or @name="internal_n" or @name="nya1" or @name="akane")]', form);
this.mail = $x(p + (
aib._410 ? '@name="sage"]' :
'(@name="field2" or @name="em" or @name="sage" or @name="email" or @name="nabiki" or @name="dont_bump")]'
), form);
this.subj = $x(p + '(@name="field3" or @name="sub" or @name="subject" or @name="internal_s" or @name="nya3" or @name="kasumi")]', form);
this.video = $q(tr + ' input[name="video"], ' + tr + ' input[name="embed"]', form);
if(init) {
this._init();
}
}
PostForm.setUserName = function() {
var el = $q('input[info="nameValue"]', doc);
if(el) {
saveCfg('nameValue', el.value);
}
pr.name.value = Cfg['userName'] ? Cfg['nameValue'] : '';
};
PostForm.setUserPassw = function() {
var el = $q('input[info="passwValue"]', doc);
if(el) {
saveCfg('passwValue', el.value);
}
(pr.dpass || {}).value = pr.passw.value = Cfg['passwValue'];
};
PostForm.eventFiles = function(tr) {
$each($Q('input[type="file"]', tr), function(el) {
el.addEventListener('change', PostForm.processInput, false);
});
};
PostForm.processInput = function() {
if(!this.haveBtns) {
this.haveBtns = true;
var delBtn = $new('button', {
'class': 'de-file-util de-file-del',
'text': Lng.clear[lang],
'type': 'button'}, {
'click': function(e) {
$pd(e);
if(aib.krau && this.parentNode.nextSibling) {
var current = $q('input[type="file"]', this.parentNode).name.match(/\d/)[0];
$each($Q('input[type="file"]', getAncestor(this, aib.trTag)), function(input, index) {
if(index > current)
input.name = "file_" + (index-1);
});
$del(this.parentNode);
if($q('input[type="file"]', $id('files_parent').lastElementChild).value) {
setTimeout(function(){PostForm.eventFiles($id('files_parent'));}, 100);
}
} else {
pr.delFileUtils(this.parentNode, false);
pr.file.addEventListener('change', PostForm.processInput, false);
}
}
});
if(aib.krau) {
delBtn.addEventListener('focus', function() {
if(this.parentNode.nextSibling) {
this.setAttribute('onclick', 'window.fileCounter -= 1;' + ($q('input[type="file"]', $id('files_parent').lastElementChild).value ? 'updateFileFields();' : ''));
}
}, false);
}
$after(this, delBtn);
} else if(this.imgFile) {
this.imgFile = null;
$del(this.nextSibling);
}
$del($c('de-file-rar', this.parentNode));
PostForm.eventFiles(getAncestor(this, aib.trTag));
if(nav.noBlob || !/^image\/(?:png|jpeg)$/.test(this.files[0].type)) {
return;
}
$after(this, $new('button', {
'class': 'de-file-util de-file-rar',
'text': Lng.addFile[lang],
'title': Lng.helpAddFile[lang],
'type': 'button'}, {
'click': function(e) {
$pd(e);
var el = $id('de-input-rar') || doc.body.appendChild($new('input', {
'id': 'de-input-rar',
'type': 'file',
'style': 'display: none;'
}, null));
el.onchange = function(inp, e) {
$del(this);
var file = e.target.files[0],
fr = new FileReader();
inp.insertAdjacentHTML('afterend', '<span class="de-file-util" style="margin: 0 5px;">' +
'<span class="de-wait"></span>' + Lng.wait[lang] + '</span>');
fr.onload = function(input, node, e) {
if(input.nextSibling === node) {
node.style.cssText = 'font-weight: bold; margin: 0 5px; cursor: default;';
node.title = input.files[0].name + ' + ' + this.name;
node.textContent = input.files[0].name.replace(/^.+\./, '') + ' + ' +
this.name.replace(/^.+\./, '')
input.imgFile = e.target.result;
}
}.bind(file, inp, inp.nextSibling);
fr.readAsArrayBuffer(file);
}.bind(this, $q('input[type="file"]', this.parentNode));
el.click();
}
}));
};
PostForm.prototype = {
isHidden: false,
isQuick: false,
isTopForm: false,
lastQuickPNum: -1,
pForm: null,
pArea: [],
qArea: null,
addTextPanel: function() {
var i, len, tag, html, btns, tPanel = $id('de-txt-panel');
if(!Cfg['addTextBtns']) {
$del(tPanel);
return;
}
if(!tPanel) {
tPanel = $new('span', {'id': 'de-txt-panel'}, {
'click': this,
'mouseover': this
});
}
tPanel.style.cssFloat = Cfg['txtBtnsLoc'] ? 'none' : 'right';
$after(Cfg['txtBtnsLoc'] ? $id('de-txt-resizer') || this.txta :
aib._420 ? $c('popup', this.form) : this.subm, tPanel);
for(html = '', i = 0, btns = aib.formButtons, len = btns['id'].length; i < len; ++i) {
tag = btns['tag'][i];
if(tag === '') {
continue;
}
html += '<span id="de-btn-' + btns['id'][i] + '" de-title="' + Lng.txtBtn[i][lang] +
'" de-tag="' + tag + '"' + (btns['bb'][i] ? 'de-bb' : '') + '>' + (
Cfg['addTextBtns'] === 2 ?
(i === 0 ? '[ ' : '') + '<a class="de-abtn" href="#">' + btns['val'][i] +
'</a>' + (i === len - 1 ? ' ]' : ' / ') :
Cfg['addTextBtns'] === 3 ?
'<input type="button" value="' + btns['val'][i] + '" style="font-weight: bold;">' : ''
) + '</span>';
}
tPanel.innerHTML = html;
},
delFileUtils: function(el, eventFiles) {
$each($Q('.de-file-util', el), $del);
$each($Q('input[type="file"]', el), function(node) {
node.imgFile = null;
});
this._clearFileInput(el, eventFiles);
},
handleEvent: function(e) {
var x, start, end, scrtop, title, id, el = e.target;
if(el.tagName !== 'SPAN') {
el = el.parentNode;
}
id = el.id;
if(id.startsWith('de-btn')) {
if(e.type === 'mouseover') {
if(id === 'de-btn-quote') {
quotetxt = $txtSelect();
}
x = -1;
if(keyNav) {
switch(id.substr(7)) {
case 'bold': x = 12; break;
case 'italic': x = 13; break;
case 'strike': x = 14; break;
case 'spoil': x = 15; break;
case 'code': x = 16; break;
}
}
el.title = el.getAttribute('de-title') + (x === -1 ? '' : ' [' +
KeyEditListener.getStrKey(keyNav.gKeys[x]) + ']');
return;
}
x = pr.txta;
start = x.selectionStart;
end = x.selectionEnd;
if(id === 'de-btn-quote') {
$txtInsert(x, '> ' + (start === end ? quotetxt : x.value.substring(start, end))
.replace(/\n/gm, '\n> '));
} else {
scrtop = x.scrollTop;
txt = this._wrapText(el.hasAttribute('de-bb'), el.getAttribute('de-tag'),
x.value.substring(start, end));
len = start + txt.length;
x.value = x.value.substr(0, start) + txt + x.value.substr(end);
x.setSelectionRange(len, len);
x.focus();
x.scrollTop = scrtop;
}
$pd(e);
e.stopPropagation();
}
},
showQuickReply: function(post, pNum, closeReply) {
var el, tNum = post.tNum;
if(!this.isQuick) {
this.isQuick = true;
this.setReply(true, false);
$t('a', this._pBtn[+this.isTopForm]).className =
'de-abtn de-parea-btn-' + (TNum ? 'reply' : 'thrd');
if(!TNum && !aib.kus && !aib.dobr) {
if(this.oeForm) {
$del($q('input[name="oek_parent"]', this.oeForm));
this.oeForm.insertAdjacentHTML('afterbegin', '<input type="hidden" value="' +
tNum + '" name="oek_parent">');
}
if(this.form) {
$del($q('#thr_id, input[name="parent"]', this.form));
this.form.insertAdjacentHTML('afterbegin',
'<input type="hidden" id="thr_id" value="' + tNum + '" name="' + (
aib.fch || aib.futa ? 'resto' :
aib.tiny ? 'thread' :
'parent'
) + '">'
);
}
}
} else if(closeReply && !quotetxt && post.wrap.nextElementSibling === this.qArea) {
this.closeQReply();
return;
}
$after(post.wrap, this.qArea);
if(!TNum) {
this._toggleQuickReply(tNum);
}
if(!this.form) {
return;
}
if(this._lastCapUpdate && ((!TNum && this.tNum !== tNum) || (Date.now() - this._lastCapUpdate > 3e5))) {
this.tNum = tNum;
this.refreshCapImg(false);
}
this.tNum = tNum;
if(aib._420 && this.txta.value === 'Comment') {
this.txta.value = '';
}
$txtInsert(this.txta, (this.txta.value === '' || this.txta.value.slice(-1) === '\n' ? '' : '\n') +
(this.lastQuickPNum === pNum && this.txta.value.contains('>>' + pNum) ? '' : '>>' + pNum + '\n') +
(quotetxt ? quotetxt.replace(/^\n|\n$/g, '').replace(/(^|\n)(.)/gm, '$1> $2') + '\n': ''));
if(Cfg['addPostForm'] === 3) {
el = $t('a', this.qArea.firstChild);
el.href = aib.getThrdUrl(brd, tNum);
el.textContent = '#' + tNum;
}
this.lastQuickPNum = pNum;
},
showMainReply: function(isTop, evt) {
this.closeQReply();
if(this.isTopForm === isTop) {
this.pForm.style.display = this.isHidden ? '' : 'none';
this.isHidden = !this.isHidden;
this.updatePAreaBtns();
} else {
this.isTopForm = isTop;
this.setReply(false, false);
}
if(evt) {
$pd(evt);
}
},
closeQReply: function() {
if(this.isQuick) {
this.isQuick = false;
this.lastQuickPNum = -1;
if(!TNum) {
this._toggleQuickReply(0);
$del($id('thr_id'));
}
this.setReply(false, !TNum || Cfg['addPostForm'] > 1);
}
},
refreshCapImg: function(focus) {
var src, img;
if(aib.abu && (img = $id('captcha_div')) && img.hasAttribute('onclick')) {
img.dispatchEvent(new CustomEvent('click', {
'bubbles': true,
'cancelable': true,
'detail': {'isCustom': true, 'focus': focus}
}));
return;
}
if(!this.cap || (aib.krau && !$q('input[name="captcha_name"]', this.form).hasAttribute('value'))) {
return;
}
img = this.recap ? $id('recaptcha_image') : $t('img', this.capTr);
if(aib.dobr || aib.krau || this.recap) {
img.click();
} else if(img) {
src = img.getAttribute('src');
if(aib.kus || aib.tinyIb) {
src = src.replace(/\?[^?]+$|$/, (aib._410 ? '?board=' + brd + '&' : '?') + Math.random());
} else {
src = src.replace(/pl$/, 'pl?key=mainpage&dummy=')
.replace(/dummy=[\d\.]*/, 'dummy=' + Math.random());
src = this.tNum ? src.replace(/mainpage|res\d+/, 'res' + this.tNum) :
src.replace(/res\d+/, 'mainpage');
}
img.src = '';
img.src = src;
}
this.cap.value = '';
if(focus) {
this.cap.focus();
}
if(this._lastCapUpdate) {
this._lastCapUpdate = Date.now();
}
},
setReply: function(quick, hide) {
if(quick) {
this.qArea.appendChild(this.pForm);
} else {
$after(this.pArea[+this.isTopForm], this.qArea);
$after(this._pBtn[+this.isTopForm], this.pForm);
}
this.isHidden = hide;
this.qArea.style.display = quick ? '' : 'none';
this.pForm.style.display = hide ? 'none' : '';
this.updatePAreaBtns();
},
updatePAreaBtns: function() {
var txt = 'de-abtn de-parea-btn-',
rep = TNum ? 'reply' : 'thrd';
$t('a', this._pBtn[+this.isTopForm]).className = txt + (this.pForm.style.display === '' ? 'close' : rep);
$t('a', this._pBtn[+!this.isTopForm]).className = txt + rep;
},
_lastCapUpdate: 0,
_pBtn: [],
_clearFileInput: function(el, eventFiles) {
var cln = el.cloneNode(false);
cln.innerHTML = el.innerHTML;
el.parentNode.replaceChild(cln, el);
if(eventFiles) {
PostForm.eventFiles(cln);
}
this.file = $q('input[type="file"]', cln);
},
_init: function() {
this.pForm = $New('div', {'id': 'de-pform'}, [this.form, this.oeForm]);
var btn = $New('div', {'class': 'de-' + (TNum ? 'make-reply' : 'create-thread')}, [
$txt('['),
$new('a', {'href': '#'}, null),
$txt(']')
]);
$before(dForm, this.pArea[0] = $New('div', {'class': 'de-parea'}, [btn, doc.createElement('hr')]));
this._pBtn[0] = btn;
btn.firstElementChild.addEventListener('click', this.showMainReply.bind(this, false), true);
btn = btn.cloneNode(true);
btn.firstElementChild.addEventListener('click', this.showMainReply.bind(this, true), true);
$after(aib.fch ? $c('board', dForm) : dForm, this.pArea[1] =
$New('div', {'class': 'de-parea'}, [btn, doc.createElement('hr')]));
this._pBtn[1] = btn;
this.qArea = $add('<div id="de-qarea" class="' + aib.cReply + '" style="display: none;"></div>');
this.isTopForm = Cfg['addPostForm'] !== 0;
this.setReply(false, !TNum || Cfg['addPostForm'] > 1);
if(Cfg['addPostForm'] === 3) {
$append(this.qArea, [
$add('<span id="de-qarea-target">' + Lng.replyTo[lang] + ' <a class="de-abtn"></a></span>'),
$new('span', {'id': 'de-qarea-close', 'text': '\u2716'}, {'click': this.closeQReply.bind(this)})
]);
}
if(aib.tire) {
$each($Q('input[type="hidden"]', dForm), $del);
dForm.appendChild($c('userdelete', doc.body));
this.dpass = $q('input[type="password"]', dForm);
}
if(!this.form) {
return;
}
this.form.style.display = 'inline-block';
this.form.style.textAlign = 'left';
if(nav.Firefox) {
this.txta.addEventListener('mouseup', function() {
saveCfg('textaWidth', parseInt(this.style.width, 10));
saveCfg('textaHeight', parseInt(this.style.height, 10));
}, false);
} else {
this.txta.insertAdjacentHTML('afterend', '<div id="de-txt-resizer"></div>');
this.txta.nextSibling.addEventListener('mousedown', {
el: this.txta,
elStyle: this.txta.style,
handleEvent: function(e) {
switch(e.type) {
case 'mousedown':
doc.body.addEventListener('mousemove', this, false);
doc.body.addEventListener('mouseup', this, false);
$pd(e);
return;
case 'mousemove':
var cr = this.el.getBoundingClientRect();
this.elStyle.width = (e.pageX - cr.left - window.pageXOffset) + 'px';
this.elStyle.height = (e.pageY - cr.top - window.pageYOffset) + 'px';
return;
default: // mouseup
doc.body.removeEventListener('mousemove', this, false);
doc.body.removeEventListener('mouseup', this, false);
saveCfg('textaWidth', parseInt(this.elStyle.width, 10));
saveCfg('textaHeight', parseInt(this.elStyle.height, 10));
}
}
}, false);
}
if(aib.kus) {
while(this.subm.nextSibling) {
$del(this.subm.nextSibling);
}
}
if(Cfg['addSageBtn'] && this.mail) {
btn = $new('span', {'id': 'de-sagebtn'}, {'click': function(e) {
e.stopPropagation();
$pd(e);
toggleCfg('sageReply');
this._setSage();
}.bind(this)});
el = getAncestor(this.mail, 'LABEL') || this.mail;
if(el.nextElementSibling || el.previousElementSibling) {
$disp(el);
$after(el, btn);
} else {
$disp(getAncestor(this.mail, aib.trTag));
$after(this.name || this.subm, btn);
}
this._setSage();
if(aib.urup || aib._2chru) {
while(btn.nextSibling) {
$del(btn.nextSibling);
}
}
}
this.addTextPanel();
this.txta.style.cssText = 'padding: 0; resize: both; width: ' +
Cfg['textaWidth'] + 'px; height: ' + Cfg['textaHeight'] + 'px;';
this.txta.addEventListener('keypress', function(e) {
var code = e.charCode || e.keyCode;
if((code === 33 || code === 34) && e.which === 0) {
e.target.blur();
window.focus();
}
}, false);
if(!aib.tiny && !aib.nul) {
this.subm.value = Lng.reply[lang];
}
this.subm.addEventListener('click', function(e) {
var temp, val = this.txta.value,
sVal = Cfg['signatValue'];
if(aib._2chru && !aib.reqCaptcha) {
GM_xmlhttpRequest({
'method': 'GET',
'url': '/' + brd + '/api/requires-captcha',
'onreadystatechange': function(xhr) {
if(xhr.readyState === 4 && xhr.status === 200) {
aib.reqCaptcha = true;
if(JSON.parse(xhr.responseText)['requires-captcha'] === '1') {
$id('captcha_tr').style.display = 'table-row';
$after(this.cap, $new('span', {
'class': 'shortened',
'style': 'margin: 0px 0.5em;',
'text': 'проверить капчу'}, {
'click': function() {
GM_xmlhttpRequest({
'method': 'POST',
'url': '/' + brd + '/api/validate-captcha',
'onreadystatechange': function(str) {
if(str.readyState === 4 && str.status === 200) {
if(JSON.parse(str.responseText)['status'] === 'ok') {
this.innerHTML = 'можно постить';
} else {
this.innerHTML = 'неверная капча';
setTimeout(function() {
this.innerHTML = 'проверить капчу';
}.bind(this), 1000);
}
}
}.bind(this)
})
}
}))
} else {
this.subm.click();
}
}
}.bind(this)
});
$pd(e);
return;
}
if(Cfg['warnSubjTrip'] && this.subj && /#.|##./.test(this.subj.value)) {
$pd(e);
$alert(Lng.subjHasTrip[lang], 'upload', false);
return;
}
if(spells.haveOutreps) {
val = spells.outReplace(val);
}
if(Cfg['userSignat'] && sVal) {
val += '\n' + sVal;
}
if(this.tNum && pByNum[this.tNum].subj === 'Dollchan Extension Tools') {
temp = '\n\n' + this._wrapText(aib.formButtons.bb[5], aib.formButtons.tag[5],
'-'.repeat(50) + '\n' + nav.ua + '\nv' + version);
if(!val.contains(temp)) {
val += temp;
}
}
this.txta.value = val;
if(Cfg['ajaxReply']) {
$alert(Lng.checking[lang], 'upload', true);
}
if(Cfg['favOnReply'] && this.tNum) {
toggleFavorites(pByNum[this.tNum], $c('de-btn-fav', pByNum[this.tNum].btns));
}
if(this.video && (val = this.video.value) && (val = val.match(youTube.ytReg))) {
this.video.value = aib.nul ? val[1] : 'http://www.youtube.com/watch?v=' + val[1];
}
if(this.isQuick) {
$disp(this.pForm);
$disp(this.qArea);
$after(this._pBtn[+this.isTopForm], this.pForm);
}
}.bind(this), false);
$each($Q('input[type="text"], input[type="file"]', this.form), function(node) {
node.size = 30;
});
if(Cfg['noGoto'] && this.gothr) {
$disp(this.gothr);
}
if(Cfg['noPassword'] && this.passw) {
$disp(getAncestor(this.passw, aib.trTag));
}
window.addEventListener('load', function() {
if(Cfg['userName'] && this.name) {
setTimeout(PostForm.setUserName, 1e3);
}
if(this.passw) {
setTimeout(PostForm.setUserPassw, 1e3);
}
}.bind(this), false);
if(this.cap) {
this.capTr = getAncestor(this.cap, aib.trTag);
this.txta.addEventListener('focus', this._captchaInit.bind(this, this.capTr.innerHTML), false);
if(this.file) {
this.file.addEventListener('click', this._captchaInit.bind(this, this.capTr.innerHTML), false);
}
if(!aib.krau) {
$disp(this.capTr);
}
this.capTr.innerHTML = '';
this.cap = null;
}
if(Cfg['ajaxReply'] === 2) {
if(aib.krau) {
this.form.removeAttribute('onsubmit');
}
this.form.onsubmit = function(e) {
$pd(e);
if(aib.krau) {
aib.addProgressTrack.click();
}
new html5Submit(this.form, this.subm, checkUpload);
}.bind(this);
} else if(Cfg['ajaxReply'] === 1) {
this.form.target = 'de-iframe-pform';
this.form.onsubmit = null;
}
if(this.file) {
if('files' in this.file && this.file.files.length > 0) {
this._clearFileInput(getAncestor(this.file, aib.trTag), true);
} else {
PostForm.eventFiles(getAncestor(this.file, aib.trTag));
}
}
},
_setSage: function() {
var c = Cfg['sageReply'];
$id('de-sagebtn').innerHTML = ' ' + (
c ? '<span class="de-btn-sage"></span><b style="color: red;">SAGE</b>' : '<i>(no sage)</i>'
);
if(this.mail.type === 'text') {
this.mail.value = c ? 'sage' : aib.fch ? 'noko' : '';
} else {
this.mail.checked = c;
}
},
_toggleQuickReply: function(tNum) {
if(this.oeForm) {
$q('input[name="oek_parent"], input[name="replyto"]', this.oeForm).value = tNum;
}
if(this.form) {
$q('#thr_id, input[name*="thread"]', this.form).value = tNum;
if(aib.pony) {
$q('input[name="quickreply"]', this.form).value = tNum || '';
}
}
},
_captchaInit: function(html) {
if(this.capInited) {
return
}
this.capTr.innerHTML = html;
this.cap = $q('input[type="text"][name*="aptcha"]:not([name="recaptcha_challenge_field"])', this.capTr);
if(aib.iich || aib.abu) {
$t('td', this.capTr).textContent = 'Капча';
}
if(aib.fch) {
$script('loadRecaptcha()');
}
if(aib.tire) {
$script('show_captcha()');
}
if(aib.krau) {
aib.initCaptcha.click();
$id('captcha_image').setAttribute('onclick', 'requestCaptcha(true);');
}
setTimeout(this._captchaUpd.bind(this), 100);
},
_captchaUpd: function() {
var img, a;
if((this.recap = $id('recaptcha_response_field')) && (img = $id('recaptcha_image'))) {
this.cap = this.recap;
img.setAttribute('onclick', 'Recaptcha.reload()');
img.style.cssText = 'width: 300px; cursor: pointer;';
} else if(aib.fch) {
setTimeout(this._captchaUpd.bind(this), 100);
return;
}
this.capInited = true;
this.cap.autocomplete = 'off';
this.cap.onkeypress = (function() {
var ru = 'йцукенгшщзхъфывапролджэячсмитьбюё',
en = 'qwertyuiop[]asdfghjkl;\'zxcvbnm,.`';
return function(e) {
if(!Cfg['captchaLang'] || e.which === 0) {
return;
}
var i, code = e.charCode || e.keyCode,
chr = String.fromCharCode(code).toLowerCase();
if(Cfg['captchaLang'] === 1) {
if(code < 0x0410 || code > 0x04FF || (i = ru.indexOf(chr)) === -1) {
return;
}
chr = en[i];
} else {
if(code < 0x0021 || code > 0x007A || (i = en.indexOf(chr)) === -1) {
return;
}
chr = ru[i];
}
$pd(e);
$txtInsert(e.target, chr);
};
})();
if(aib.krau) {
return;
}
if(aib.abu || aib.dobr || this.recap || !(img = $q('img', this.capTr))) {
$disp(this.capTr);
return;
}
if(!aib.kus && !aib.tinyIb) {
this._lastCapUpdate = Date.now();
this.cap.onfocus = function() {
if(this._lastCapUpdate && (Date.now() - this._lastCapUpdate > 3e5)) {
this.refreshCapImg(false);
}
}.bind(this);
if(!TNum && this.isQuick) {
this.refreshCapImg(false);
}
}
img.title = Lng.refresh[lang];
img.alt = Lng.loading[lang];
img.style.cssText = 'display: block; border: none; cursor: pointer;';
img.onclick = this.refreshCapImg.bind(this, true);
if((a = img.parentNode).tagName === 'A') {
$after(a, img);
$del(a);
}
$disp(this.capTr);
},
_wrapText: function(isBB, tag, text) {
var m;
if(isBB) {
if(text.contains('\n')) {
return '[' + tag + ']' + text + '[/' + tag + ']';
}
m = text.match(/^(\s*)(.*?)(\s*)$/);
return m[1] + '[' + tag + ']' + m[2] + '[/' + tag + ']' + m[3];
}
for(var rv = '', i = 0, arr = text.split('\n'), len = arr.length; i < len; ++i) {
m = arr[i].match(/^(\s*)(.*?)(\s*)$/);
rv += '\n' + m[1] + (tag === '^H' ? m[2] + '^H'.repeat(m[2].length) :
tag + m[2] + tag) + m[3];
}
return rv.slice(1);
}
}
//============================================================================================================
// IMAGES
//============================================================================================================
function genImgHash(data) {
var i, j, l, c, t, u, g, buf = new Uint8Array(data[0]),
oldw = data[1],
oldh = data[2],
tmp = oldw * oldh,
newh = 8,
neww = 8,
levels = 3,
areas = 256 / levels,
values = 256 / (levels - 1),
hash = 0;
for(i = 0, j = 0; i < tmp; i++, j += 4) {
buf[i] = buf[j] * 0.3 + buf[j + 1] * 0.59 + buf[j + 2] * 0.11;
}
for(i = 0; i < newh; i++) {
for(j = 0; j < neww; j++) {
tmp = i / (newh - 1) * (oldh - 1);
l = Math.min(tmp | 0, oldh - 2);
u = tmp - l;
tmp = j / (neww - 1) * (oldw - 1);
c = Math.min(tmp | 0, oldw - 2);
t = tmp - c;
hash = (hash << 4) + Math.min(values * (((buf[l * oldw + c] * ((1 - t) * (1 - u)) +
buf[l * oldw + c + 1] * (t * (1 - u)) +
buf[(l + 1) * oldw + c + 1] * (t * u) +
buf[(l + 1) * oldw + c] * ((1 - t) * u)) / areas) | 0), 255);
if(g = hash & 0xF0000000) {
hash ^= g >>> 24;
}
hash &= ~g;
}
}
return {hash: hash};
}
function ImageData(post, el, idx) {
this.el = el;
this.idx = idx;
this.post = post;
}
ImageData.prototype = {
expanded: false,
getAdjacentImage: function(toUp) {
var post = this.post,
imgs = post.images;
if(toUp ? this.idx === 0 : this.idx + 1 === imgs.length) {
do {
post = post.getAdjacentVisPost(toUp);
if(!post) {
post = toUp ? lastThr.last : firstThr.op;
if(post.hidden || post.thr.hidden) {
post = post.getAdjacentVisPost(toUp);
}
}
imgs = post.images;
} while(imgs.length === 0);
return imgs[toUp ? imgs.length - 1 : 0];
}
return imgs[toUp ? this.idx - 1 : this.idx + 1];
},
get data() {
var img = this.el,
cnv = this._glob.canvas,
w = cnv.width = img.naturalWidth,
h = cnv.height = img.naturalHeight,
ctx = cnv.getContext('2d');
ctx.drawImage(img, 0, 0);
return [ctx.getImageData(0, 0, w, h).data.buffer, w, h];
},
getHash: function(Fn) {
if(this.hasOwnProperty('hash')) {
Fn(this.hash);
} else {
this.callback = Fn;
if(!this._processing) {
var hash = this._maybeGetHash();
if(hash !== null) {
Fn(hash);
}
}
}
},
get hash() {
var hash;
if(this._processing) {
this._needToHide = true;
} else if(aib.fch || this.el.complete) {
hash = this._maybeGetHash(null);
if(hash !== null) {
return hash;
}
} else {
this.el.onload = this.el.onerror = this._onload.bind(this);
}
this.post.hashImgsBusy++;
return null;
},
get height() {
var dat = aib.getImgSize(this.info);
Object.defineProperties(this, {
'width': { value: dat[0] },
'height': { value: dat[1] }
});
return dat[1];
},
get info() {
var el = $c(aib.cFileInfo, this.wrap),
val = el ? el.textContent : '';
Object.defineProperty(this, 'info', { value: val });
return val;
},
get isImage() {
var val = /\.jpe?g|\.png|\.gif|^blob:/i.test(this.src);
Object.defineProperty(this, 'isImage', { value: val });
return val;
},
get fullSrc() {
var val = aib.getImgLink(this.el).href;
Object.defineProperty(this, 'fullSrc', { value: val });
return val;
},
get src() {
var val = aib.getImgSrc(this.el);
Object.defineProperty(this, 'src', { value: val });
return val;
},
get weight() {
var val = aib.getImgWeight(this.info);
Object.defineProperty(this, 'weight', { value: val });
return val;
},
get width() {
var dat = aib.getImgSize(this.info);
Object.defineProperties(this, {
'width': { value: dat[0] },
'height': { value: dat[1] }
});
return dat[0];
},
get wrap() {
var val = aib.getImgWrap(this.el.parentNode);
Object.defineProperty(this, 'wrap', { value: val });
return val;
},
_glob: {
get canvas() {
var val = doc.createElement('canvas');
Object.defineProperty(this, 'canvas', { value: val });
return val;
},
get storage() {
try {
var val = JSON.parse(sessionStorage['de-imageshash']);
} finally {
if(!val) {
val = {};
}
spells.addCompleteFunc(this._saveStorage.bind(this));
Object.defineProperty(this, 'storage', { value: val });
return val;
}
},
get workers() {
var val = new workerQueue(4, genImgHash, function(e) {});
spells.addCompleteFunc(this._clearWorkers.bind(this));
Object.defineProperty(this, 'workers', { value: val, configurable: true });
return val;
},
_saveStorage: function() {
sessionStorage['de-imageshash'] = JSON.stringify(this.storage);
},
_clearWorkers: function() {
this.workers.clear();
delete this.workers;
},
},
_callback: null,
_processing: false,
_needToHide: false,
_endLoad: function(hash) {
this.post.hashImgsBusy--;
if(this.post.hashHideFun !== null) {
this.post.hashHideFun(hash);
}
},
_maybeGetHash: function() {
var data, val;
if(this.src in this._glob.storage) {
val = this._glob.storage[this.src];
} else if(aib.fch) {
downloadImgData(this.el.src, this._onload4chan.bind(this));
this._callback = null;
return null;
} else if(this.el.naturalWidth + this.el.naturalHeight === 0) {
val = -1;
} else {
data = this.data;
this._glob.workers.run(data, [data[0]], this._wrkEnd.bind(this));
this._callback = null;
return null;
}
Object.defineProperty(this, 'hash', { value: val });
return val;
},
_onload: function() {
var hash = this._maybeGetHash(null);
if(hash !== null) {
this._endLoad(hash);
}
},
_onload4chan: function(maybeData) {
if(maybeData === null) {
Object.defineProperty(this, 'hash', { value: -1 });
this._endLoad(-1);
} else {
var buffer = maybeData.buffer,
data = [buffer, this.el.naturalWidth, this.el.naturalHeight];
this._glob.workers.run(data, [buffer], this._wrkEnd.bind(this));
}
},
_wrkEnd: function(data) {
var hash = data.hash;
Object.defineProperty(this, 'hash', { value: hash });
this._endLoad(hash);
if(this.callback) {
this.callback(hash);
this.callback = null;
}
this._glob.storage[this.src] = hash;
}
}
function ImageMover(img) {
this.el = img;
this.elStyle = img.style;
img.addEventListener(nav.Firefox ? 'DOMMouseScroll' : 'mousewheel', this, false);
img.addEventListener('mousedown', this, false);
}
ImageMover.prototype = {
curX: 0,
curY: 0,
moved: false,
handleEvent: function(e) {
switch(e.type) {
case 'mousedown':
this.curX = e.clientX - parseInt(this.elStyle.left, 10);
this.curY = e.clientY - parseInt(this.elStyle.top, 10);
doc.body.addEventListener('mousemove', this, false);
doc.body.addEventListener('mouseup', this, false);
break;
case 'mousemove':
this.elStyle.left = e.clientX - this.curX + 'px';
this.elStyle.top = e.clientY - this.curY + 'px';
this.moved = true;
return;
case 'mouseup':
doc.body.removeEventListener('mousemove', this, false);
doc.body.removeEventListener('mouseup', this, false);
return;
default: // wheel event
var curX = e.clientX,
curY = e.clientY,
oldL = parseInt(this.elStyle.left, 10),
oldT = parseInt(this.elStyle.top, 10),
oldW = parseFloat(this.elStyle.width || this.el.width),
oldH = parseFloat(this.elStyle.height || this.el.height),
d = nav.Firefox ? -e.detail : e.wheelDelta,
newW = oldW * (d > 0 ? 1.25 : 0.8),
newH = oldH * (d > 0 ? 1.25 : 0.8);
this.elStyle.width = newW + 'px';
this.elStyle.height = newH + 'px';
this.elStyle.left = parseInt(curX - (newW/oldW) * (curX - oldL), 10) + 'px';
this.elStyle.top = parseInt(curY - (newH/oldH) * (curY - oldT), 10) + 'px';
}
$pd(e);
}
};
function addImagesSearch(el) {
for(var link, i = 0, els = $Q(aib.qImgLink, el), len = els.length; i < len; i++) {
link = els[i];
if(/google\.|tineye\.com|iqdb\.org/.test(link.href)) {
$del(link);
continue;
}
if(link.firstElementChild) {
continue;
}
link.insertAdjacentHTML('beforebegin', '<span class="de-btn-src"></span>');
}
}
function embedImagesLinks(el) {
for(var a, link, i = 0, els = $Q(aib.qMsgImgLink, el); link = els[i++];) {
if(link.parentNode.tagName === 'SMALL') {
return;
}
a = link.cloneNode(false);
a.target = '_blank';
a.innerHTML = '<img class="de-img-pre" src="' + a.href + '">';
$before(link, a);
}
}
//============================================================================================================
// POST
//============================================================================================================
function Post(el, thr, num, count, isOp, prev) {
var h, ref, html;
this.count = count;
this.el = el;
this.isOp = isOp;
this.num = num;
this._pref = ref = $q(aib.qRef, el);
this.prev = prev;
this.thr = thr;
if(prev) {
prev.next = this;
}
el.post = this;
html = '<span class="de-ppanel ' + (isOp ? '' : 'de-ppanel-cnt') +
'"><span class="de-btn-hide"></span><span class="de-btn-rep"></span>';
if(isOp) {
if(!TNum && !aib.arch) {
html += '<span class="de-btn-expthr"></span>';
}
h = aib.host;
if(Favor[h] && Favor[h][brd] && Favor[h][brd][num]) {
html += '<span class="de-btn-fav-sel"></span>';
Favor[h][brd][num]['cnt'] = thr.pcount;
} else {
html += '<span class="de-btn-fav"></span>';
}
}
ref.insertAdjacentHTML('afterend', html + (
this.sage ? '<span class="de-btn-sage" title="SAGE"></span>' : ''
) + '</span>');
this.btns = ref.nextSibling;
if(Cfg['expandPosts'] === 1 && this.trunc) {
this._getFull(this.trunc, true);
}
el.addEventListener('click', this, true);
el.addEventListener('mouseover', this, true);
el.addEventListener('mouseout', this, true);
}
Post.hiddenNums = [];
Post.getWrds = function(text) {
return text.replace(/\s+/g, ' ').replace(/[^a-zа-яё ]/ig, '').substring(0, 800).split(' ');
};
Post.findSameText = function(oNum, oHid, oWords, date, post) {
var j, words = Post.getWrds(post.text),
len = words.length,
i = oWords.length,
olen = i,
_olen = i,
n = 0;
if(len < olen * 0.4 || len > olen * 3) {
return;
}
while(i--) {
if(olen > 6 && oWords[i].length < 3) {
_olen--;
continue;
}
j = len;
while(j--) {
if(words[j] === oWords[i] || oWords[i].match(/>>\d+/) && words[j].match(/>>\d+/)) {
n++;
}
}
}
if(n < _olen * 0.4 || len > _olen * 3) {
return;
}
if(oHid) {
post.note = '';
if(!post.spellHidden) {
post.setVisib(false);
}
if(post.userToggled) {
delete uVis[post.num];
post.userToggled = false;
}
} else {
post.setUserVisib(true, date, true);
post.note = 'similar to >>' + oNum;
}
return false;
};
Post.sizing = {
get wHeight() {
var val = window.innerHeight;
if(!this._enabled) {
window.addEventListener('resize', this, false);
this._enabled = true;
}
Object.defineProperty(this, 'wHeight', { writable: true, value: val });
return val;
},
get wWidth() {
var val = doc.documentElement.clientWidth;
if(!this._enabled) {
window.addEventListener('resize', this, false);
this._enabled = true;
}
Object.defineProperty(this, 'wWidth', { writable: true, value: val });
return val;
},
getOffset: function(el) {
return el.getBoundingClientRect().left + window.pageXOffset;
},
getCachedOffset: function(pCount, el) {
if(pCount === 0) {
return this._opOffset === -1 ? this._opOffset = this.getOffset(el) : this._opOffset;
}
if(pCount > 4) {
return this._pOffset === -1 ? this._pOffset = this.getOffset(el) : this._pOffset;
}
return this.getOffset(el);
},
handleEvent: function() {
this.wHeight = window.innerHeight;
this.wWidth = doc.documentElement.clientWidth;
},
_enabled: false,
_opOffset: -1,
_pOffset: -1
};
Post.prototype = {
banned: false,
deleted: false,
hasRef: false,
hasYTube: false,
hidden: false,
hashHideFun: null,
hashImgsBusy: 0,
imagesExpanded: false,
inited: true,
kid: null,
next: null,
omitted: false,
parent: null,
prev: null,
spellHidden: false,
userToggled: false,
viewed: false,
ytHideFun: null,
ytInfo: null,
ytLinksLoading: 0,
addFuncs: function() {
updRefMap(this, true);
embedMP3Links(this);
if(Cfg['addImgs']) {
embedImagesLinks(this.el);
}
if(isExpImg) {
this.toggleImages(true);
}
},
handleEvent: function(e) {
var temp, el = e.target,
type = e.type;
if(type === 'click') {
if(e.button !== 0) {
return;
}
switch(el.tagName) {
case 'IMG':
if(el.classList.contains('de-video-thumb')) {
if(Cfg['addYouTube'] === 3) {
this.ytLink.classList.add('de-current');
youTube.addPlayer(this.ytObj, this.ytInfo, el.classList.contains('de-ytube'));
$pd(e);
}
} else if(Cfg['expandImgs'] !== 0) {
this._clickImage(el, e);
}
return;
case 'A':
if(el.classList.contains('de-video-link')) {
var m = el.ytInfo;
if(this.ytInfo === m) {
if(Cfg['addYouTube'] === 3) {
if($c('de-video-thumb', this.ytObj)) {
el.classList.add('de-current');
youTube.addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
} else {
el.classList.remove('de-current');
youTube.addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
}
} else {
el.classList.remove('de-current');
this.ytObj.innerHTML = '';
this.ytInfo = null;
}
} else if(Cfg['addYouTube'] > 2) {
this.ytLink.classList.remove('de-current');
this.ytLink = el;
youTube.addThumb(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
} else {
this.ytLink.classList.remove('de-current');
this.ytLink = el;
el.classList.add('de-current');
youTube.addPlayer(this.ytObj, this.ytInfo = m, el.classList.contains('de-ytube'));
}
$pd(e);
} else {
temp = el.parentNode;
if(temp === this.trunc) {
this._getFull(temp, false);
$pd(e);
e.stopPropagation();
} else if(Cfg['insertNum'] && pr.form && temp === this._pref &&
!/Reply|Ответ/.test(el.textContent))
{
if(TNum && Cfg['addPostForm'] > 1 && !pr.isQuick) {
pr.showQuickReply(this, this.num, true);
} else {
if(aib._420 && pr.txta.value === 'Comment') {
pr.txta.value = '';
}
$txtInsert(pr.txta, '>>' + this.num);
}
$pd(e);
e.stopPropagation();
}
}
return;
}
switch(el.className) {
case 'de-btn-expthr':
this.thr.load(1, false, null);
$del(this._menu);
this._menu = null;
return;
case 'de-btn-fav':
case 'de-btn-fav-sel':
toggleFavorites(this, el);
return;
case 'de-btn-hide':
case 'de-btn-hide-user':
if(this._isPview) {
pByNum[this.num].toggleUserVisib();
this.btns.firstChild.className = 'de-btn-hide-user';
if(pByNum[this.num].hidden) {
this.btns.classList.add('de-post-hid');
} else {
this.btns.classList.remove('de-post-hid');
}
} else {
this.toggleUserVisib();
}
$del(this._menu);
this._menu = null;
return;
case 'de-btn-rep':
pr.showQuickReply(this._isPview ? this.getTopParent() : this, this.num, !this._isPview);
return;
case 'de-btn-sage':
addSpell(9, '', false);
return;
}
if(el.classList[0] === 'de-menu-item') {
this._clickMenu(el);
}
return;
}
switch(el.classList[0]) {
case 'de-reflink':
case 'de-preflink':
if(Cfg['linksNavig']) {
if(type === 'mouseover') {
clearTimeout(Pview.delTO);
this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']);
} else {
this._eventRefLinkOut(e);
}
$pd(e);
e.stopPropagation();
}
return;
case 'de-btn-hide':
case 'de-btn-hide-user':
if(type === 'mouseover') {
this._menuDelay = setTimeout(this._addMenu.bind(this, el, 'hide'), Cfg['linksOver']);
} else {
this._closeMenu(e.relatedTarget);
}
return;
case 'de-btn-rep':
if(type === 'mouseover') {
quotetxt = $txtSelect();
}
return;
case 'de-btn-expthr':
if(type === 'mouseover') {
this._menuDelay = setTimeout(this._addMenu.bind(this, el, 'expand'), Cfg['linksOver']);
} else {
this._closeMenu(e.relatedTarget);
}
return;
case 'de-btn-src':
if(type === 'mouseover') {
this._menuDelay = setTimeout(this._addMenu.bind(this, el, 'imgsrc'), Cfg['linksOver']);
} else {
this._closeMenu(e.relatedTarget);
}
break;
case 'de-menu':
case 'de-menu-item':
if(type === 'mouseover') {
clearTimeout(this._menuDelay);
} else {
this._closeMenu(e.relatedTarget);
}
return;
}
if(Cfg['linksNavig'] && el.tagName === 'A' && !el.lchecked) {
if(el.textContent.startsWith('>>')) {
el.className = 'de-preflink ' + el.className;
clearTimeout(Pview.delTO);
this._linkDelay = setTimeout(this._addPview.bind(this, el), Cfg['linksOver']);
$pd(e);
e.stopPropagation();
} else {
el.lchecked = true;
}
return;
}
if(this._isPview) {
if(type === 'mouseout') {
temp = e.relatedTarget;
if(Pview.top && (!temp || (!Pview.getPview(temp) && !temp.classList.contains('de-imgmenu')))) {
Pview.top.markToDel();
}
} else {
temp = Pview.getPview(e.relatedTarget);
if(!temp || temp.post !== this) {
if(this.kid) {
this.kid.markToDel();
} else {
clearTimeout(Pview.delTO);
}
}
}
}
},
hideRefs: function() {
if(!Cfg['hideRefPsts'] || !this.hasRef) {
return;
}
this.ref.forEach(function(num) {
var pst = pByNum[num];
if(pst && !pst.userToggled) {
pst.setVisib(true);
pst.note = 'reference to >>' + this.num;
pst.hideRefs();
}
}, this);
},
getAdjacentVisPost: function(toUp) {
var post = toUp ? this.prev : this.next;
while(post) {
if(post.thr.hidden) {
post = toUp ? post.thr.op.prev : post.thr.last.next;
} else if(post.hidden || post.omitted) {
post = toUp ? post.prev : post.next
} else {
return post;
}
}
return null;
},
get html() {
var val = this.el.innerHTML;
Object.defineProperty(this, 'html', { configurable: true, value: val });
return val;
},
get images() {
var i, len, el, els = getImages(this.el),
imgs = [];
for(i = 0, len = els.length; i < len; i++) {
el = els[i];
el.imgIdx = i;
imgs[i] = new ImageData(this, el, i);
}
Object.defineProperty(this, 'images', { value: imgs });
return imgs;
},
get mp3Obj() {
var val = $new('div', {'class': 'de-mp3'}, null);
$before(this.msg, val);
Object.defineProperty(this, 'mp3Obj', { value: val });
return val;
},
get msg() {
var val = $q(aib.qMsg, this.el);
Object.defineProperty(this, 'msg', { configurable: true, value: val });
return val;
},
get nextInThread() {
var post = this.next;
return !post || post.count === 0 ? null : post;
},
get nextNotDeleted() {
var post = this.nextInThread;
while(post && post.deleted) {
post = post.nextInThread;
}
return post;
},
set note(val) {
if(this.isOp) {
this.noteEl.textContent = val ? '(autohide: ' + val + ')' : '(' + this.title + ')';
} else if(!Cfg['delHiddPost']) {
this.noteEl.textContent = val ? 'autohide: ' + val : '';
}
},
get noteEl() {
var val;
if(this.isOp) {
val = this.thr.el.previousElementSibling.lastChild;
} else {
this.btns.insertAdjacentHTML('beforeend', '<span class="de-post-note"></span>');
val = this.btns.lastChild;
}
Object.defineProperty(this, 'noteEl', { value: val });
return val;
},
get posterName() {
var pName = $q(aib.qName, this.el), val = pName ? pName.textContent : '';
Object.defineProperty(this, 'posterName', { value: val });
return val;
},
get posterTrip() {
var pTrip = $c(aib.cTrip, this.el), val = pTrip ? pTrip.textContent : '';
Object.defineProperty(this, 'posterTrip', { value: val });
return val;
},
get ref() {
var val = [];
Object.defineProperty(this, 'ref', { configurable: true, value: val });
return val;
},
get sage() {
var val = aib.getSage(this.el);
Object.defineProperty(this, 'sage', { value: val });
return val;
},
select: function() {
if(this.isOp) {
if(this.hidden) {
this.thr.el.previousElementSibling.classList.add('de-selected');
}
this.thr.el.classList.add('de-selected');
} else {
this.el.classList.add('de-selected');
}
},
setUserVisib: function(hide, date, sync) {
this.setVisib(hide);
this.btns.firstChild.className = 'de-btn-hide-user';
this.userToggled = true;
if(hide) {
this.note = '';
this.hideRefs();
} else {
this.unhideRefs();
}
uVis[this.num] = [+!hide, date];
if(sync) {
localStorage['__de-post'] = JSON.stringify({
'brd': brd,
'date': date,
'isOp': this.isOp,
'num': this.num,
'hide': hide,
'title': this.isOp ? this.title : ''
});
localStorage.removeItem('__de-post');
}
},
setVisib: function(hide) {
var el, tEl;
if(this.hidden === hide) {
return;
}
if(this.isOp) {
this.hidden = this.thr.hidden = hide;
tEl = this.thr.el;
tEl.style.display = hide ? 'none' : '';
el = $id('de-thr-hid-' + this.num);
if(el) {
el.style.display = hide ? '' : 'none';
} else {
tEl.insertAdjacentHTML('beforebegin', '<div class="' + aib.cReply +
' de-thr-hid" id="de-thr-hid-' + this.num + '">' + Lng.hiddenThrd[lang] +
' <a href="#">№' + this.num + '</a> <span class="de-thread-note"></span></div>');
el = $t('a', tEl.previousSibling);
el.onclick = el.onmouseover = el.onmouseout = function(e) {
switch(e.type) {
case 'click':
this.toggleUserVisib();
$pd(e);
return;
case 'mouseover': this.thr.el.style.display = ''; return;
default: // mouseout
if(this.hidden) {
this.thr.el.style.display = 'none';
}
}
}.bind(this);
}
return;
}
if(Cfg['delHiddPost']) {
if(hide) {
this.wrap.classList.add('de-hidden');
this.wrap.insertAdjacentHTML('beforebegin',
'<span style="counter-increment: de-cnt 1;"></span>');
} else if(this.hidden) {
this.wrap.classList.remove('de-hidden');
$del(this.wrap.previousSibling);
}
} else {
if(!hide) {
this.note = '';
}
this._pref.onmouseover = this._pref.onmouseout = hide && function(e) {
this.toggleContent(e.type === 'mouseout');
}.bind(this);
}
this.hidden = hide;
this.toggleContent(hide);
if(Cfg['strikeHidd']) {
setTimeout(this._strikePostNum.bind(this, hide), 50);
}
},
spellHide: function(note) {
this.spellHidden = true;
if(!this.userToggled) {
if(TNum && !this.deleted) {
sVis[this.count] = 0;
}
if(!this.hidden) {
this.hideRefs();
}
this.setVisib(true);
this.note = note;
}
},
spellUnhide: function() {
this.spellHidden = false;
if(!this.userToggled) {
if(TNum && !this.deleted) {
sVis[this.count] = 1;
}
this.setVisib(false);
this.unhideRefs();
}
},
get subj() {
var subj = $c(aib.cSubj, this.el), val = subj ? subj.textContent : '';
Object.defineProperty(this, 'subj', { value: val });
return val;
},
get text() {
var val = this.msg.innerHTML
.replace(/<\/?(?:br|p|li)[^>]*?>/gi,'\n')
.replace(/<[^>]+?>/g,'')
.replace(/>/g, '>')
.replace(/</g, '<')
.replace(/ /g, '\u00A0')
.trim();
Object.defineProperty(this, 'text', { configurable: true, value: val });
return val;
},
get title() {
var val = this.subj || this.text.substring(0, 70).replace(/\s+/g, ' ')
Object.defineProperty(this, 'title', { value: val });
return val;
},
get tNum() {
return this.thr.num;
},
toggleContent: function(hide) {
if(hide) {
this.el.classList.add('de-post-hid');
} else {
this.el.classList.remove('de-post-hid');
}
},
toggleImages: function(expand) {
var i, dat;
for(var dat, i = 0, imgs = this.images, len = imgs.length; i < len; ++i) {
dat = imgs[i];
if(dat.isImage && (dat.expanded ^ expand)) {
if(expand) {
this._addFullImage(dat.el, dat, true);
} else {
this._removeFullImage(null, dat.el.nextSibling, dat.el, dat);
}
}
}
this.imagesExpanded = expand;
},
toggleUserVisib: function() {
var isOp = this.isOp,
hide = !this.hidden,
date = Date.now();
this.setUserVisib(hide, date, true);
if(isOp) {
if(hide) {
hThr[brd][this.num] = this.title;
} else {
delete hThr[brd][this.num];
}
saveHiddenThreads(false);
}
saveUserPosts();
},
get topCoord() {
var el = this.isOp && this.hidden ? this.thr.el.previousElementSibling : this.el;
return el.getBoundingClientRect().top;
},
get trunc() {
var el = $q(aib.qTrunc, this.el), val = null;
if(el && /long|full comment|gekürzt|слишком|длинн|мног|полная версия/i.test(el.textContent)) {
val = el;
}
Object.defineProperty(this, 'trunc', { configurable: true, value: val });
return val;
},
unhideRefs: function() {
if(!Cfg['hideRefPsts'] || !this.hasRef) {
return;
}
this.ref.forEach(function(num) {
var pst = pByNum[num];
if(pst && pst.hidden && !pst.userToggled && !pst.spellHidden) {
pst.setVisib(false);
pst.unhideRefs();
}
});
},
unselect: function() {
if(this.isOp) {
var el = $id('de-thr-hid-' + this.num);
if(el) {
el.classList.remove('de-selected');
}
this.thr.el.classList.remove('de-selected');
} else {
this.el.classList.remove('de-selected');
}
},
updateMsg: function(newMsg) {
var origMsg = aib.dobr ? this.msg.firstElementChild : this.msg,
ytExt = $c('de-video-ext', origMsg),
ytLinks = $Q(':not(.de-video-ext) > .de-video-link', origMsg);
origMsg.parentNode.replaceChild(newMsg, origMsg);
Object.defineProperties(this, {
'msg': { configurable: true, value: newMsg },
'trunc': { configurable: true, value: null }
});
delete this.html;
delete this.text;
youTube.updatePost(this, ytLinks, $Q('a[href*="youtu"]', newMsg), false);
if(ytExt) {
newMsg.appendChild(ytExt);
}
this.addFuncs();
spells.check(this);
closeAlert($id('de-alert-load-fullmsg'));
},
get wrap() {
var val = aib.getWrap(this.el, this.isOp);
Object.defineProperty(this, 'wrap', { value: val });
return val;
},
get ytData() {
var val = [];
Object.defineProperty(this, 'ytData', { value: val });
return val;
},
get ytObj() {
var msg, prev, val = $new('div', {'class': 'de-video-obj'}, null);
if(aib.krau) {
msg = this.msg.parentNode;
prev = msg.previousElementSibling;
$before(prev.hasAttribute('style') ? prev : msg, val);
} else {
$before(this.msg, val);
}
Object.defineProperty(this, 'ytObj', { value: val });
return val;
},
_isPview: false,
_linkDelay: 0,
_menu: null,
_menuDelay: 0,
_pref: null,
_selRange: null,
_selText: '',
_addFullImage: function(el, data, inPost) {
var elMove, elStop, newW, newH, scrH, img, scrW = Post.sizing.wWidth;
if(inPost) {
(aib.hasPicWrap ? data.wrap : el.parentNode).insertAdjacentHTML('afterend',
'<div class="de-after-fimg"></div>');
scrW -= this._isPview ? Post.sizing.getOffset(el) : Post.sizing.getCachedOffset(this.count, el);
el.style.display = 'none';
} else {
$del($c('de-img-center', doc));
}
newW = !Cfg['resizeImgs'] || data.width < scrW ? data.width : scrW - 5;
newH = newW * data.height / data.width;
if(inPost) {
data.expanded = true;
} else {
scrH = Post.sizing.wHeight;
if(Cfg['resizeImgs'] && newH > scrH) {
newH = scrH - 2;
newW = newH * data.width / data.height;
}
}
img = $add('<img class="de-img-full" src="' + data.fullSrc + '" alt="' + data.fullSrc +
'" width="' + newW + '" height="' + newH + '">');
img.onload = img.onerror = function(e) {
if(this.naturalHeight + this.naturalWidth === 0 && !this.onceLoaded) {
this.src = this.src;
this.onceLoaded = true;
}
};
$after(el, img);
if(!inPost) {
img.classList.add('de-img-center');
img.style.cssText = 'left: ' + ((scrW - newW) / 2 - 1) +
'px; top: ' + ((scrH - newH) / 2 - 1) + 'px;';
img.mover = new ImageMover(img);
if(this._isPview) {
$id('de-img-btns').style.display = 'none';
} else {
$id('de-img-btn-next').onclick = this._navigateImages.bind(this, true);
$id('de-img-btn-prev').onclick = this._navigateImages.bind(this, false);
if ($id('de-img-btns').style.display) {
var btns = $id('de-img-btns');
btns.style.display = '';
btns.style.opacity = 0;
_setFadeOutDelay = function() {
clearTimeout(btns._fadeOutDelay);
btns._fadeOutDelay = setTimeout(function() {
clearInterval(btns._fadeOut);
btns._fadeOut = setInterval(function() {
if(+btns.style.opacity > 0) {
btns.style.opacity = +btns.style.opacity - 0.05;
} else {
clearInterval(btns._fadeOut);
}
}, 25);
}, 2000);
}
window.addEventListener('mousemove', btns._imgBtnsFade = function() {
if(!btns._fadeIn && !btns._isOverBtns) {
clearTimeout(btns._fadeOutDelay);
clearInterval(btns._fadeOut);
btns._fadeIn = setInterval(function() {
if(+btns.style.opacity < 1) {
btns.style.opacity =+ btns.style.opacity + 0.05;
} else {
clearInterval(btns._fadeIn); btns._fadeIn = 0;
_setFadeOutDelay();
}
}, 25);
}
}, false);
btns.addEventListener('mouseover', btns._imgBtnsOverCheck = function() {
if(!btns._overChecker) {
this.style.opacity = 1;
btns._overChecker = setInterval(function() {
if(btns.parentElement.querySelector(':hover') === btns) {
clearTimeout(btns._fadeOutDelay);
btns._isOverBtns = true;
} else {
clearInterval(btns._overChecker); btns._overChecker = 0;
btns._isOverBtns = false;
_setFadeOutDelay();
}
}, 100);
}
}, false)
window.addEventListener('keypress', btns._leftRightNavig = function(e) {
if(e.keyCode == 37) {
$pd(e);
$id('de-img-btn-prev').click();
} else if(e.keyCode == 39) {
$pd(e);
$id('de-img-btn-next').click();
}
}, false)
}
}
}
},
_addMenu: function(el, type) {
var html, cr = el.getBoundingClientRect(),
isLeft = false,
className = 'de-menu ' + aib.cReply,
xOffset = window.pageXOffset;
switch(type) {
case 'hide':
if(!Cfg['menuHiddBtn']) {
return;
}
html = this._addMenuHide();
break;
case 'expand':
html = '<span class="de-menu-item" info="thr-exp">' + Lng.selExpandThrd[lang]
.join('</span><span class="de-menu-item" info="thr-exp">') + '</span>';
break;
case 'imgsrc':
isLeft = true;
className += ' de-imgmenu';
html = this._addMenuImgSrc(el);
break;
}
doc.body.insertAdjacentHTML('beforeend', '<div class="' + className +
'" style="position: absolute; ' + (
isLeft ? 'left: ' + (cr.left + xOffset) :
'right: ' + (doc.documentElement.clientWidth - cr.right - xOffset)
) + 'px; top: ' + (window.pageYOffset + cr.bottom) + 'px;">' + html + '</div>');
if(this._menu) {
clearTimeout(this._menuDelay);
$del(this._menu);
}
this._menu = doc.body.lastChild;
this._menu.addEventListener('click', this, false);
this._menu.addEventListener('mouseover', this, false);
this._menu.addEventListener('mouseout', this, false);
},
_addMenuHide: function() {
var sel, ssel, str = '', addItem = function(name) {
str += '<span info="spell-' + name + '" class="de-menu-item">' +
Lng.selHiderMenu[name][lang] + '</span>';
};
sel = nav.Opera ? doc.getSelection() : window.getSelection();
if(ssel = sel.toString()) {
this._selText = ssel;
this._selRange = sel.getRangeAt(0);
addItem('sel');
}
if(this.posterName) {
addItem('name');
}
if(this.posterTrip) {
addItem('trip');
}
if(this.images.length === 0) {
addItem('noimg');
} else {
addItem('img');
addItem('ihash');
}
if(this.text) {
addItem('text');
} else {
addItem('notext');
}
return str;
},
_addMenuImgSrc: function(el) {
var p = el.nextSibling.href + '" target="_blank">' + Lng.search[lang],
c = doc.body.getAttribute('de-image-search'),
str = '';
if(c) {
c = c.split(';');
c.forEach(function(el) {
var info = el.split(',');
str += '<a class="de-src' + info[0] + (!info[1] ?
'" onclick="de_isearch(event, \'' + info[0] + '\')" de-url="' :
'" href="' + info[1]
) + p + info[0] + '</a>';
});
}
return '<a class="de-menu-item de-imgmenu de-src-iqdb" href="http://iqdb.org/?url=' + p + 'IQDB</a>' +
'<a class="de-menu-item de-imgmenu de-src-tineye" href="http://tineye.com/search/?url=' + p + 'TinEye</a>' +
'<a class="de-menu-item de-imgmenu de-src-google" href="http://google.com/searchbyimage?image_url=' + p + 'Google</a>' +
'<a class="de-menu-item de-imgmenu de-src-saucenao" href="http://saucenao.com/search.php?url=' + p + 'SauceNAO</a>' + str;
},
_addPview: function(link) {
var tNum = (link.pathname.match(/.+?\/[^\d]*(\d+)/) || [,0])[1],
pNum = (link.textContent.trim().match(/\d+$/) || [tNum])[0],
pv = this._isPview ? this.kid : Pview.top;
if(pv && pv.num === pNum) {
Pview.del(pv.kid);
setPviewPosition(link, pv.el, Cfg['animation'] && animPVMove);
if(pv.parent.num !== this.num) {
$each($C('de-pview-link', pv.el), function(el) {
el.classList.remove('de-pview-link');
});
pv._markLink(this.num);
}
this.kid = pv;
pv.parent = this;
} else {
this.kid = new Pview(this, link, tNum, pNum);
}
},
_clickImage: function(el, e) {
var data, iEl, mover, inPost = (Cfg['expandImgs'] === 1) ^ e.ctrlKey;
var clearBtns = function() {
var btns = $id('de-img-btns');
btns.style.display = 'none';
window.removeEventListener('mousemove', btns._imgBtnsFade, false);
btns.removeEventListener('mouseover', btns._imgBtnsOverCheck, false);
window.removeEventListener('keypress', btns._leftRightNavig, false);
clearInterval(btns._fadeIn); btns._fadeIn = 0;
clearInterval(btns._fadeOut);
clearTimeout(btns._fadeOutDelay);
clearInterval(btns._overChecker); btns._overChecker = 0;
}
switch(el.className) {
case 'de-img-full de-img-center':
mover = el.mover;
if(mover.moved) {
mover.moved = false;
break;
}
el.mover = null;
case 'de-img-full':
iEl = el.previousSibling;
this._removeFullImage(e, el, iEl, this.images[iEl.imgIdx] || iEl.data);
clearBtns();
break;
case 'de-img-pre':
if(!(data = el.data)) {
iEl = new Image();
iEl.src = el.src;
data = el.data = {
expanded: false,
isImage: true,
width: iEl.width,
height: iEl.height,
fullSrc: el.src
};
}
break;
case 'thumb':
case 'ca_thumb':
data = this.images[el.imgIdx];
break;
default:
if(!/thumb|\/spoiler|^blob:/i.test(el.src)) {
return;
}
data = this.images[el.imgIdx];
}
if(data && data.isImage) {
if(!inPost && (iEl = $c('de-img-center', el.parentNode))) {
$del(iEl);
clearBtns();
} else {
this._addFullImage(el, data, inPost);
}
}
$pd(e);
e.stopPropagation();
return;
},
_clickMenu: function(el) {
$del(this._menu);
this._menu = null;
switch(el.getAttribute('info')) {
case 'spell-sel':
var start = this._selRange.startContainer,
end = this._selRange.endContainer;
if(start.nodeType === 3) {
start = start.parentNode;
}
if(end.nodeType === 3) {
end = end.parentNode;
}
if((nav.matchesSelector(start, aib.qMsg + ' *') && nav.matchesSelector(end, aib.qMsg + ' *')) ||
(nav.matchesSelector(start, '.' + aib.cSubj) && nav.matchesSelector(end, '.' + aib.cSubj))
) {
if(this._selText.contains('\n')) {
addSpell(1 /* #exp */, '/' +
regQuote(this._selText).replace(/\r?\n/g, '\\n') + '/', false);
} else {
addSpell(0 /* #words */, this._selText.replace(/\)/g, '\\)').toLowerCase(), false);
}
} else {
dummy.innerHTML = '';
dummy.appendChild(this._selRange.cloneContents());
addSpell(2 /* #exph */, '/' +
regQuote(dummy.innerHTML.replace(/^<[^>]+>|<[^>]+>$/g, '')) + '/', false);
}
return;
case 'spell-name': addSpell(6 /* #name */, this.posterName.replace(/\)/g, '\\)'), false); return;
case 'spell-trip': addSpell(7 /* #trip */, this.posterTrip.replace(/\)/g, '\\)'), false); return;
case 'spell-img':
var img = this.images[0],
w = img.weight,
wi = img.width,
h = img.height;
addSpell(8 /* #img */, [0, [w, w], [wi, wi, h, h]], false);
return;
case 'spell-ihash':
this.images[0].getHash(function(hash) {
addSpell(4 /* #ihash */, hash, false);
});
return;
case 'spell-noimg': addSpell(0x108 /* (#all & !#img) */, '', true); return;
case 'spell-text':
var num = this.num,
hidden = this.hidden,
wrds = Post.getWrds(this.text),
time = Date.now();
for(var post = firstThr.op; post; post = post.next) {
Post.findSameText(num, hidden, wrds, time, post);
}
saveUserPosts();
return;
case 'spell-notext': addSpell(0x10B /* (#all & !#tlen) */, '', true); return;
case 'thr-exp': this.thr.load(parseInt(el.textContent, 10), false, null); return;
}
},
_closeMenu: function(rt) {
clearTimeout(this._menuDelay);
if(this._menu && (!rt || rt.className !== 'de-menu-item')) {
this._menuDelay = setTimeout(function() {
$del(this._menu);
this._menu = null;
}.bind(this), 75);
}
},
_eventRefLinkOut: function(e) {
var rt = e.relatedTarget,
pv = Pview.getPview(rt);
clearTimeout(this._linkDelay);
if(!rt || !pv) {
if(Pview.top) {
Pview.top.markToDel();
}
} else if(pv.post === this && this.kid && rt.className !== 'de-reflink') {
this.kid.markToDel();
}
},
_getFull: function(node, isInit) {
if(aib.dobr) {
$del(node.nextSibling);
$del(node.previousSibling);
$del(node);
if(isInit) {
this.msg.replaceChild($q('.alternate > div', this.el), this.msg.firstElementChild);
} else {
this.updateMsg($q('.alternate > div', this.el));
}
return;
}
if(!isInit) {
$alert(Lng.loading[lang], 'load-fullmsg', true);
}
ajaxLoad(aib.getThrdUrl(brd, this.tNum), true, function(node, form, xhr) {
if(this.isOp) {
this.updateMsg(replacePost($q(aib.qMsg, form)));
$del(node);
} else {
for(var i = 0, els = aib.getPosts(form), len = els.length; i < len; i++) {
if(this.num === aib.getPNum(els[i])) {
this.updateMsg(replacePost($q(aib.qMsg, els[i])));
$del(node);
return;
}
}
}
}.bind(this, node), null);
},
_markLink: function(pNum) {
$each($Q('a[href*="' + pNum + '"]', this.el), function(num, el) {
if(el.textContent === '>>' + num) {
el.classList.add('de-pview-link');
}
}.bind(null, pNum));
},
_navigateImages: function(isNext) {
var el = $c('de-img-full', doc),
iEl = el.previousSibling,
data = this.images[iEl.imgIdx];
this._removeFullImage(null, el, iEl, data);
data = data.getAdjacentImage(!isNext);
data.post._addFullImage(data.el, data, false);
},
_removeFullImage: function(e, full, thumb, data) {
var pv, cr, x, y, inPost = data.expanded;
data.expanded = false;
if(nav.Firefox && this._isPview) {
cr = this.el.getBoundingClientRect();
x = e.pageX;
y = e.pageY;
if(!inPost) {
pv = this;
while(x > cr.right || x < cr.left || y > cr.bottom || y < cr.top) {
if(pv = pv.parent) {
cr = pv.el.getBoundingClientRect();
} else {
if(Pview.top) {
Pview.top.markToDel();
}
$del(full);
return;
}
}
if(pv.kid) {
pv.kid.markToDel();
}
} else if(x > cr.right || y > cr.bottom && Pview.top) {
Pview.top.markToDel();
}
}
$del(full);
if(inPost) {
thumb.style.display = '';
$del((aib.hasPicWrap ? data.wrap : thumb.parentNode).nextSibling);
}
},
_strikePostNum: function(isHide) {
var idx, num = this.num;
if(isHide) {
Post.hiddenNums.push(+num);
} else {
idx = Post.hiddenNums.indexOf(+num);
if(idx !== -1) {
Post.hiddenNums.splice(idx, 1);
}
}
$each($Q('a[href*="#' + num + '"]', dForm), isHide ? function(el) {
el.classList.add('de-ref-hid');
} : function(el) {
el.classList.remove('de-ref-hid');
});
}
}
//============================================================================================================
// PREVIEW
//============================================================================================================
function Pview(parent, link, tNum, pNum) {
var b, post = pByNum[pNum];
if(Cfg['noNavigHidd'] && post && post.hidden) {
return;
}
this.parent = parent;
this._link = link;
this.num = pNum;
Object.defineProperty(this, 'tNum', { value: tNum });
if(post && (!post.isOp || !parent._isPview || !parent._loaded)) {
this._showPost(post);
return;
}
b = link.pathname.match(/^\/?(.+\/)/)[1].replace(aib.res, '').replace(/\/$/, '');
if(post = this._cache && this._cache[b + tNum] && this._cache[b + tNum].getPost(pNum)) {
this._loaded = true;
this._showPost(post);
} else {
this._showText('<span class="de-wait">' + Lng.loading[lang] + '</span>');
ajaxLoad(aib.getThrdUrl(b, tNum), true, this._onload.bind(this, b), this._onerror.bind(this));
}
}
Pview.clearCache = function() {
Pview.prototype._cache = {};
};
Pview.del = function(pv) {
var el;
if(!pv) {
return;
}
pv.parent.kid = null;
if(!pv.parent._isPview) {
Pview.top = null;
}
do {
clearTimeout(pv._readDelay);
el = pv.el;
if(Cfg['animation']) {
nav.animEvent(el, $del);
el.classList.add('de-pview-anim');
el.style[nav.animName] = 'de-post-close-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r');
} else {
$del(el);
}
} while(pv = pv.kid);
};
Pview.getPview = function(el) {
while(el && !el.classList.contains('de-pview')) {
el = el.parentElement;
}
return el;
};
Pview.delTO = 0;
Pview.top = null;
Pview.prototype = Object.create(Post.prototype, {
getTopParent: { value: function pvGetBoardParent() {
var post = this.parent;
while(post._isPview) {
post = post.parent;
}
return post;
} },
markToDel: { value: function pvMarkToDel() {
clearTimeout(Pview.delTO);
Pview.delTO = setTimeout(Pview.del, Cfg['linksOut'], this);
} },
_isPview: { value: true },
_loaded: { value: false, writable: true },
_cache: { value: {}, writable: true },
_readDelay: { value: 0, writable: true },
_onerror: { value: function(eCode, eMsg, xhr) {
Pview.del(this);
this._showText(eCode === 404 ? Lng.postNotFound[lang] : getErrorMessage(eCode, eMsg));
} },
_onload: { value: function pvOnload(b, form, xhr) {
var rm, parent = this.parent,
parentNum = parent.num,
cache = this._cache[b + this.tNum] = new PviewsCache(form, b, this.tNum),
post = cache.getPost(this.num);
if(post && (brd !== b || !post.hasRef || post.ref.indexOf(parentNum) === -1)) {
if(post.hasRef) {
rm = $c('de-refmap', post.el)
} else {
post.msg.insertAdjacentHTML('afterend', '<div class="de-refmap"></div>');
rm = post.msg.nextSibling;
}
rm.insertAdjacentHTML('afterbegin', '<a class="de-reflink" href="' +
aib.getThrdUrl(b, parent._isPview ? parent.tNum : parent.tNum) + aib.anchor +
parentNum + '">>>' + (brd === b ? '' : '/' + brd + '/') + parentNum +
'</a><span class="de-refcomma">, </span>');
}
if(parent.kid === this) {
Pview.del(this);
if(post) {
this._loaded = true;
this._showPost(post);
} else {
this._showText(Lng.postNotFound[lang]);
}
}
} },
_showPost: { value: function pvShowPost(post) {
var btns, el = this.el = post.el.cloneNode(true),
pText = '<span class="de-btn-rep"></span>' +
(post.sage ? '<span class="de-btn-sage" title="SAGE"></span>' : '') +
(post.deleted ? '' : '<span style="margin-right: 4px; vertical-align: 1px; color: #4f7942; ' +
'font: bold 11px tahoma; cursor: default;">' + (post.isOp ? 'OP' : post.count + 1) + '</span>');
el.post = this;
el.className = aib.cReply + ' de-pview' + (post.viewed ? ' de-viewed' : '');
el.style.display = '';
if(aib._7ch) {
el.firstElementChild.style.cssText = 'max-width: 100%; margin: 0;';
$del($c('doubledash', el));
}
if(Cfg['linksNavig'] === 2) {
this._markLink(this.parent.num);
}
this._pref = $q(aib.qRef, el);
if(post.inited) {
this.btns = btns = $c('de-ppanel', el);
this.isOp = post.isOp;
btns.classList.remove('de-ppanel-cnt');
if(post.hidden) {
btns.classList.add('de-post-hid');
}
btns.innerHTML = '<span class="de-btn-hide' +
(post.userToggled ? '-user' : '') + '"></span>' + pText;
$each($Q((!TNum && post.isOp ? aib.qOmitted + ', ' : '') +
'.de-img-full, .de-after-fimg', el), $del);
$each(getImages(el), function(el) {
el.style.display = '';
});
if(post.hasYTube) {
if(post.ytInfo !== null) {
Object.defineProperty(this, 'ytObj', { value: $c('de-video-obj', el) });
this.ytInfo = post.ytInfo;
}
youTube.updatePost(this, $C('de-video-link', post.el), $C('de-video-link', el), true);
}
if(Cfg['addImgs']) {
$each($C('de-img-pre', el), function(el) {
el.style.display = '';
});
}
if(Cfg['markViewed']) {
this._readDelay = setTimeout(function(pst) {
if(!pst.viewed) {
pst.el.classList.add('de-viewed');
pst.viewed = true;
}
var arr = (sessionStorage['de-viewed'] || '').split(',');
arr.push(pst.num);
sessionStorage['de-viewed'] = arr;
}, 2e3, post);
}
} else {
this._pref.insertAdjacentHTML('afterend', '<span class="de-ppanel">' + pText + '</span');
embedMP3Links(this);
youTube.parseLinks(this);
if(Cfg['addImgs']) {
embedImagesLinks(el);
}
if(Cfg['imgSrcBtns']) {
addImagesSearch(el);
}
}
el.addEventListener('click', this, true);
this._showPview(el);
} },
_showPview: { value: function pvShowPview(el, id) {
if(this.parent._isPview) {
Pview.del(this.parent.kid);
} else {
Pview.del(Pview.top);
Pview.top = this;
}
this.parent.kid = this;
el.addEventListener('mouseover', this, true);
el.addEventListener('mouseout', this, true);
(aib.arch ? doc.body : dForm).appendChild(el);
setPviewPosition(this._link, el, false);
if(Cfg['animation']) {
nav.animEvent(el, function(node) {
node.classList.remove('de-pview-anim');
node.style[nav.animName] = '';
});
el.classList.add('de-pview-anim');
el.style[nav.animName] = 'de-post-open-' + (el.aTop ? 't' : 'b') + (el.aLeft ? 'l' : 'r');
}
} },
_showText: { value: function pvShowText(txt) {
this._showPview(this.el = $add('<div class="' + aib.cReply + ' de-pview-info de-pview">' +
txt + '</div>'));
} },
});
function PviewsCache(form, b, tNum) {
var i, len, post, pBn = {},
pProto = Post.prototype,
thr = $q(aib.qThread, form) || form,
posts = aib.getPosts(thr);
for(i = 0, len = posts.length; i < len; ++i) {
post = posts[i];
pBn[aib.getPNum(post)] = Object.create(pProto, {
count: { value: i + 1 },
el: { value: post },
inited: { value: false },
pvInited: { value: false, writable: true }
});
}
pBn[tNum] = this._opObj = Object.create(pProto, {
inited: { value: false },
isOp: { value: true },
msg: { value: $q(aib.qMsg, thr), writable: true },
ref: { value: [], writable: true }
});
this._brd = b;
this._thr = thr;
this._tNum = tNum;
this._tUrl = aib.getThrdUrl(b, tNum);
this._posts = pBn;
if(Cfg['linksNavig'] === 2) {
genRefMap(pBn, false, this._tUrl);
}
}
PviewsCache.prototype = {
getPost: function(num) {
if(num === this._tNum) {
return this._op;
}
var pst = this._posts[num];
if(pst && !pst.pvInited) {
pst.el = replacePost(pst.el);
delete pst.msg;
if(pst.hasRef) {
addRefMap(pst, this._tUrl);
}
pst.pvInited = true;
}
return pst;
},
get _op() {
var i, j, len, num, nRef, oRef, rRef, oOp, op = this._opObj;
op.el = replacePost(aib.getOp(this._thr));
op.msg = $q(aib.qMsg, op.el);
if(this._brd === brd && (oOp = pByNum[this._tNum])) {
oRef = op.ref;
rRef = [];
for(i = j = 0, nRef = oOp.ref, len = nRef.length; j < len; ++j) {
num = nRef[j];
if(oRef[i] === num) {
i++;
} else if(oRef.indexOf(num) !== -1) {
continue;
}
rRef.push(num)
}
for(len = oRef.length; i < len; i++) {
rRef.push(oRef[i]);
}
op.ref = rRef;
if(rRef.length !== 0) {
op.hasRef = true;
addRefMap(op, this._tUrl);
}
} else if(op.hasRef) {
addRefMap(op, this._tUrl);
}
Object.defineProperty(this, '_op', { value: op });
return op;
}
};
function PviewMoved() {
if(this.style[nav.animName]) {
this.classList.remove('de-pview-anim');
this.style.cssText = this.newPos;
this.newPos = false;
$each($C('de-css-move', doc.head), $del);
this.removeEventListener(nav.animEnd, PviewMoved, false);
}
}
function animPVMove(pView, lmw, top, oldCSS) {
var uId = 'de-movecss-' + Math.round(Math.random() * 1e3);
$css('@' + nav.cssFix + 'keyframes ' + uId + ' {to { ' + lmw + ' top:' + top + '; }}').className =
'de-css-move';
if(pView.newPos) {
pView.style.cssText = pView.newPos;
pView.removeEventListener(nav.animEnd, PviewMoved, false);
} else {
pView.style.cssText = oldCSS;
}
pView.newPos = lmw + ' top:' + top + ';';
pView.addEventListener(nav.animEnd, PviewMoved, false);
pView.classList.add('de-pview-anim');
pView.style[nav.animName] = uId;
}
function setPviewPosition(link, pView, animFun) {
if(pView.link === link) {
return;
}
pView.link = link;
var isTop, top, oldCSS, cr = link.getBoundingClientRect(),
offX = cr.left + window.pageXOffset + link.offsetWidth / 2,
offY = cr.top + window.pageYOffset,
bWidth = doc.documentElement.clientWidth,
isLeft = offX < bWidth / 2,
tmp = (isLeft ? offX : offX -
Math.min(parseInt(pView.offsetWidth, 10), offX - 10)),
lmw = 'max-width:' + (bWidth - tmp - 10) + 'px; left:' + tmp + 'px;';
if(animFun) {
oldCSS = pView.style.cssText;
pView.style.cssText = 'opacity: 0; ' + lmw;
} else {
pView.style.cssText = lmw;
}
top = pView.offsetHeight;
isTop = top + cr.top + link.offsetHeight < window.innerHeight || cr.top - top < 5;
top = (isTop ? offY + link.offsetHeight : offY - top) + 'px';
pView.aLeft = isLeft;
pView.aTop = isTop;
if(animFun) {
animFun(pView, lmw, top, oldCSS);
} else {
pView.style.top = top;
}
}
function addRefMap(post, tUrl) {
var i, ref, len, bStr = '<a ' + aib.rLinkClick + ' href="' + tUrl + aib.anchor,
str = '<div class="de-refmap">';
for(i = 0, ref = post.ref, len = ref.length; i < len; ++i) {
str += bStr + ref[i] + '" class="de-reflink">>>' + ref[i] +
'</a><span class="de-refcomma">, </span>';
}
post.msg.insertAdjacentHTML('afterend', str + '</div>');
}
function genRefMap(posts, hideRefs, thrURL) {
var tc, lNum, post, ref, i, len, links, url, pNum, opNums = Thread.tNums;
for(pNum in posts) {
for(i = 0, links = $T('a', posts[pNum].msg), len = links.length; i < len; ++i) {
tc = links[i].textContent;
if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in posts)) {
post = posts[lNum];
ref = post.ref;
if(ref.indexOf(pNum) === -1) {
ref.push(pNum);
post.hasRef = true;
if(hideRefs && post.hidden) {
post = posts[pNum];
post.setVisib(true);
post.note = 'reference to >>' + lNum;
post.hideRefs();
}
}
if(opNums.indexOf(lNum) !== -1) {
links[i].classList.add('de-opref');
}
if(thrURL) {
url = links[i].getAttribute('href');
if(url[0] === '#') {
links[i].setAttribute('href', thrURL + url);
}
}
}
}
}
}
function updRefMap(post, add) {
var tc, ref, idx, link, lNum, lPost, i, len, links, pNum = post.num,
strNums = add && Cfg['strikeHidd'] && Post.hiddenNums.length !== 0 ? Post.hiddenNums : null,
opNums = add && Thread.tNums;
for(i = 0, links = $T('a', post.msg), len = links.length; i < len; ++i) {
link = links[i];
tc = link.textContent;
if(tc[0] === '>' && tc[1] === '>' && (lNum = +tc.substr(2)) && (lNum in pByNum)) {
lPost = pByNum[lNum];
if(!TNum) {
link.href = '#' + (aib.fch ? 'p' : '') + lNum;
}
if(add) {
if(strNums && strNums.lastIndexOf(lNum) !== -1) {
link.classList.add('de-ref-hid');
}
if(opNums.indexOf(lNum) !== -1) {
link.classList.add('de-opref');
}
if(lPost.ref.indexOf(pNum) === -1) {
lPost.ref.push(pNum);
post.hasRef = true;
if(Cfg['hideRefPsts'] && lPost.hidden) {
if(!post.hidden) {
post.hideRefs();
}
post.setVisib(true);
post.note = 'reference to >>' + lNum;
}
} else {
continue;
}
} else if(lPost.hasRef) {
ref = lPost.ref;
idx = ref.indexOf(pNum);
if(idx === -1) {
continue;
}
ref.splice(idx, 1);
if(ref.length === 0) {
lPost.hasRef = false;
$del($c('de-refmap', lPost.el));
continue;
}
}
$del($c('de-refmap', lPost.el));
addRefMap(lPost, '');
}
}
}
//============================================================================================================
// THREAD
//============================================================================================================
function Thread(el, prev) {
if(aib._420 || aib.tiny) {
$after(el, el.lastChild);
$del($c('clear', el));
}
var i, pEl, lastPost,
els = aib.getPosts(el),
len = els.length,
num = aib.getTNum(el),
omt = TNum ? 1 : this.omitted = aib.getOmitted($q(aib.qOmitted, el), len);
this.num = num;
Thread.tNums.push(+num);
this.pcount = omt + len;
pByNum[num] = lastPost = this.op = el.post = new Post(aib.getOp(el), this, num, 0, true,
prev ? prev.last : null);
for(i = 0; i < len; i++) {
num = aib.getPNum(pEl = els[i]);
pByNum[num] = lastPost = new Post(pEl, this, num, omt + i, false, lastPost);
}
this.last = lastPost;
el.style.counterReset = 'de-cnt ' + omt;
el.removeAttribute('id');
el.setAttribute('de-thread', null);
visPosts = Math.max(visPosts, len);
this.el = el;
this.prev = prev;
if(prev) {
prev.next = this;
}
}
Thread.parsed = false;
Thread.loadNewPosts = function(e) {
if(e) {
$pd(e);
}
$alert(Lng.loading[lang], 'newposts', true);
firstThr.clearPostsMarks();
updater.forceLoad();
};
Thread.tNums = [];
Thread.prototype = {
hasNew: false,
hidden: false,
loadedOnce: false,
next: null,
get lastNotDeleted() {
var post = this.last;
while(post.deleted) {
post = post.prev;
}
return post;
},
get nextNotHidden() {
for(var thr = this.next; thr && thr.hidden; thr = thr.next) {}
return thr;
},
get prevNotHidden() {
for(var thr = this.prev; thr && thr.hidden; thr = thr.prev) {}
return thr;
},
clearPostsMarks: function() {
if(this.hasNew) {
this.hasNew = false;
$each($Q('.de-new-post', this.el), function(el) {
el.classList.remove('de-new-post');
});
}
},
load: function(last, smartScroll, Fn) {
if(!Fn) {
$alert(Lng.loading[lang], 'load-thr', true);
}
ajaxLoad(aib.getThrdUrl(brd, this.num), true, function threadOnload(last, smartScroll, Fn, form, xhr) {
var nextCoord, els = aib.getPosts(form),
op = this.op,
thrEl = this.el,
expEl = $c('de-expand', thrEl),
nOmt = last === 1 ? 0 : Math.max(els.length - last, 0);
if(smartScroll) {
if(this.next) {
nextCoord = this.next.topCoord;
} else {
smartScroll = false;
}
}
pr.closeQReply();
$del($q(aib.qOmitted + ', .de-omitted', thrEl));
if(!this.loadedOnce) {
if(op.trunc) {
op.updateMsg(replacePost($q(aib.qMsg, form)));
}
delete op.ref;
this.loadedOnce = true;
}
this._checkBans(op, form);
this._parsePosts(els, nOmt, this.omitted - 1);
this.omitted = nOmt;
thrEl.style.counterReset = 'de-cnt ' + (nOmt + 1);
if(nOmt !== 0) {
op.el.insertAdjacentHTML('afterend', '<div class="de-omitted">' + nOmt + '</div>');
}
if(this.pcount - nOmt - 1 <= visPosts) {
$del(expEl);
} else if(!expEl) {
thrEl.insertAdjacentHTML('beforeend', '<span class="de-expand">[<a href="' +
aib.getThrdUrl(brd, this.num) + aib.anchor + this.last.num + '">' +
Lng['collapseThrd'][lang] + '</a>]</span>');
thrEl.lastChild.onclick = function(e) {
$pd(e);
this.load(visPosts, true, null);
}.bind(this);
} else if(expEl !== thrEl.lastChild) {
thrEl.appendChild(expEl);
}
if(smartScroll) {
scrollTo(pageXOffset, pageYOffset - (nextCoord - this.next.topCoord));
}
closeAlert($id('de-alert-load-thr'));
Fn && Fn();
}.bind(this, last, smartScroll, Fn), function(eCode, eMsg, xhr) {
$alert(getErrorMessage(eCode, eMsg), 'load-thr', false);
if(typeof this === 'function') {
this();
}
}.bind(Fn));
},
loadNew: function(Fn, useAPI) {
if(aib.dobr && useAPI) {
return getJsonPosts('/api/thread/' + brd + '/' + TNum +
'/new.json?message_html&new_format&last_post=' + this.last.num,
function parseNewPosts(status, sText, json, xhr) {
if(status !== 200 || json['error']) {
Fn(status, sText || json['message'], 0, xhr);
} else {
var i, pCount, fragm, last, temp, el = (json['result'] || {})['posts'],
len = el ? el.length : 0,
np = len;
if(len > 0) {
fragm = doc.createDocumentFragment();
pCount = this.pcount;
last = this.last;
for(i = 0; i < len; i++) {
temp = getHanaPost(el[i]);
last = this._addPost(fragm, el[i]['display_id'].toString(),
replacePost(temp[1]), temp[0], pCount + i, last);
np -= spells.check(last)
}
spells.end(savePosts);
this.last = last;
this.el.appendChild(fragm);
this.pcount = pCount + len;
}
Fn(200, '', np, xhr);
Fn = null;
}
}.bind(this)
);
}
return ajaxLoad(aib.getThrdUrl(brd, TNum), true, function parseNewPosts(form, xhr) {
this._checkBans(firstThr.op, form);
var info = this._parsePosts(aib.getPosts(form), 0, 0);
Fn(200, '', info[1], xhr);
if(info[0] !== 0) {
$id('de-panel-info').firstChild.textContent = this.pcount + '/' + getImages(dForm).length;
}
Fn = null;
}.bind(this), function(eCode, eMsg, xhr) {
Fn(eCode, eMsg, 0, xhr);
Fn = null;
});
},
get topCoord() {
return this.op.topCoord;
},
updateHidden: function(data) {
var realHid, date = Date.now(),
thr = this;
do {
realHid = thr.num in data;
if(thr.hidden ^ realHid) {
if(realHid) {
thr.op.setUserVisib(true, date, false);
data[thr.num] = thr.op.title;
} else if(thr.hidden) {
thr.op.setUserVisib(false, date, false);
}
}
} while(thr = thr.next);
},
_addPost: function(parent, num, el, wrap, i, prev) {
var post = new Post(el, this, num, i, false, prev);
pByNum[num] = post;
Object.defineProperty(post, 'wrap', { value: wrap });
parent.appendChild(wrap);
if(TNum && Cfg['animation']) {
nav.animEvent(post.el, function(node) {
node.classList.remove('de-post-new');
});
post.el.classList.add('de-post-new');
}
youTube.parseLinks(post);
if(Cfg['imgSrcBtns']) {
addImagesSearch(el);
}
post.addFuncs();
preloadImages(el);
if(TNum && Cfg['markNewPosts']) {
if(updater.focused) {
this.clearPostsMarks();
} else {
this.hasNew = true;
el.classList.add('de-new-post');
}
}
return post;
},
_checkBans: function(op, thrNode) {
var pEl, bEl, post, i, bEls, len;
if(aib.qBan) {
for(i = 0, banEls = $Q(aib.qBan, thrNode), len = banEls.length; i < len; ++i) {
bEl = banEls[i];
pEl = aib.getPostEl(bEl);
post = pEl ? pByNum[aib.getPNum(pEl)] : op;
if(post && !post.banned) {
if(!$q(aib.qBan, post.el)) {
post.msg.appendChild(bEl);
}
post.banned = true;
}
}
}
},
_parsePosts: function(nPosts, from, omt) {
var i, c, len, el, tPost, fragm, newPosts = 0,
newVisPosts = 0,
firstDelPost = null,
rerunSpells = spells.hasNumSpell,
saveSpells = false,
post = this.op.nextNotDeleted;
for(i = 0, len = nPosts.length; i <= len && post; ) {
if(post.count - 1 === i) {
if(i === len || post.num !== aib.getPNum(nPosts[i])) {
if(!firstDelPost) {
firstDelPost = post;
}
c = 0;
do {
if(TNum) {
post.deleted = true;
post.btns.classList.remove('de-ppanel-cnt');
post.btns.classList.add('de-ppanel-del');
($q('input[type="checkbox"]', post.el) || {}).disabled = true;
} else {
$del(post.wrap);
delete pByNum[post.num];
if(post.hidden) {
post.unhideRefs();
}
updRefMap(post, false);
if(post.prev.next = post.next) {
post.next.prev = post.prev;
}
if(this.last === post) {
this.last = post.prev;
}
}
post = post.nextNotDeleted;
c++;
} while(post && (i === len || post.num !== aib.getPNum(nPosts[i])));
if(!rerunSpells) {
sVis.splice(i + 1, c);
}
for(tPost = post; tPost; tPost = tPost.nextInThread) {
tPost.count -= c;
}
} else {
if(i < from) {
if(i >= omt) {
post.wrap.classList.add('de-hidden');
post.omitted = true;
}
} else if(!TNum) {
if(post.trunc) {
post.updateMsg(replacePost($q(aib.qMsg, nPosts[i])));
}
post.wrap.classList.remove('de-hidden');
post.omitted = false;
updRefMap(post, true);
}
i++;
post = post.nextNotDeleted;
}
} else if(!TNum && i >= from) {
fragm = doc.createDocumentFragment();
tPost = this.op;
for(c = post.count - 1; i < c; i++) {
el = nPosts[i];
tPost = this._addPost(fragm, aib.getPNum(el), replacePost(el),
aib.getWrap(el, false), i + 1, tPost);
spells.check(tPost);
}
$after(this.op.el, fragm);
tPost.next = post;
post.prev = tPost;
} else {
if(TNum) {
console.error('Loaded thread has extra post, num:', aib.getPNum(nPosts[i]),
'count:', i, '. Latest in thread post num:', post.num, 'count:', post.count,
'. Posts count in thread:', this.pcount, 'Posts count loaded:', len + 1);
}
i++;
}
}
this.pcount = len + 1;
if(firstDelPost && rerunSpells) {
disableSpells();
for(post = firstDelPost.nextInThread; post; post = post.nextInThread) {
spells.check(post);
}
saveSpells = true;
}
if(i < len) {
newPosts = newVisPosts = len - i;
post = this.last;
fragm = doc.createDocumentFragment();
do {
el = nPosts[i];
post = this._addPost(fragm, aib.getPNum(el), replacePost(el),
aib.getWrap(el, false), i + 1, post);
newVisPosts -= spells.check(post);
} while(++i < len);
this.el.appendChild(fragm);
this.last = post;
saveSpells = true;
}
if(saveSpells) {
spells.end(savePosts);
}
return [newPosts, newVisPosts];
}
};
//============================================================================================================
// IMAGEBOARD
//============================================================================================================
function getImageBoard(checkDomains, checkOther) {
var ibDomains = {
'02ch.in': [{
css: { value: 'span[id$="_display"] { display: none !important; }' },
isBB: { value: true }
}],
'02ch.net': [{
ru: { value: true },
timePattern: { value: 'yyyy+nn+dd++w++hh+ii+ss' }
}],
'0chan.hk': [{
nul: { value: true },
css: { value: '#captcha_status, .content-background > hr, #postform nobr, .postnode + a, .replieslist, label[for="save"], span[style="float: right;"] { display: none !important; }\
.ui-wrapper { position: static !important; margin: 0 !important; overflow: visible !important; }\
.ui-resizable { display: inline !important; }\
form textarea { resize: both !important; }'
},
ru: { value: true },
timePattern: { value: 'w+yyyy+m+dd+hh+ii+ss' }
}, 'script[src*="kusaba"]'],
get '22chan.net'() { return this['ernstchan.com']; },
get '2ch.hk'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.pm'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.re'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.tf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.wf'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2ch.yt'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
get '2-ch.so'() { return [ibEngines['#ABU_css, #ShowLakeSettings']]; },
'2--ch.ru': [{
tire: { value: true },
qPages: { value: 'table[border="1"] tr:first-of-type > td:first-of-type a' },
qTable: { value: 'table:not(.postfiles)' },
_qThread: { value: '.threadz' },
getOmitted: { value: function(el, len) {
var txt;
return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] - len : 1;
} },
docExt: { value: '.html' },
css: { value: 'span[id$="_display"] { display: none !important; }' },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p : 0) + '.memhtml';
} },
hasPicWrap: { value: true },
ru: { value: true },
isBB: { value: true }
}],
get '2-ch.su'() { return this['2--ch.ru']; },
get '2--ch.su'() { return this['2--ch.ru']; },
'2chru.net': [{
_2chru: { value: true }
}],
'410chan.org': [{
_410: { value: true },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['**', '*', '__', '^^', '%%', '`', '', '', 'q'] }
});
} },
getSage: { value: function(post) {
var el = $c('filetitle', post);
return el && el.textContent.contains('\u21E9');
} },
isBB: { value: false },
timePattern: { value: 'dd+nn+yyyy++w++hh+ii+ss' }
}, 'script[src*="kusaba"]'],
'420chan.org': [{
_420: { value: true },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['**', '*', '', '', '%', 'pre', '', '', 'q'] }
});
} },
qBan: { value: '.ban' },
qError: { value: 'pre' },
qPages: { value: '.pagelist > a:last-child' },
qThread: { value: '[id*="thread"]' },
getTNum: { value: function(op) {
return $q('a[id]', op).id.match(/\d+/)[0];
} },
css: { value: '#content > hr, .hidethread, .ignorebtn, .opqrbtn, .qrbtn, noscript { display: none !important; }\
.de-thr-hid { margin: 1em 0; }' },
cssHide: { value: '.de-post-hid > .replyheader ~ *' },
docExt: { value: '.php' },
isBB: { value: true }
}],
'4chan.org': [{
fch: { value: true },
cFileInfo: { value: 'fileText' },
cOPost: { value: 'op' },
cSubj: { value: 'subject' },
cReply: { value: 'post reply' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['**', '*', '__', '^H', 'spoiler', 'code', '', '', 'q'] },
bb: { value: [false, false, false, false, true, true, false, false, false] }
});
} },
qBan: { value: 'strong[style="color: red;"]' },
qDelBut: { value: '.deleteform > input[type="submit"]' },
qError: { value: '#errmsg' },
qName: { value: '.name' },
qOmitted: { value: '.summary.desktop' },
qPages: { value: '.pagelist > .pages:not(.cataloglink) > a:last-of-type' },
qPostForm: { value: 'form[name="post"]' },
qRef: { value: '.postInfo > .postNum' },
qTable: { value: '.replyContainer' },
timePattern: { value: 'nn+dd+yy+w+hh+ii-?s?s?' },
getSage: { value: function(post) {
return !!$q('.id_Heaven, .useremail[href^="mailto:sage"]', post);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
getWrap: { value: function(el, isOp) {
return el.parentNode;
} },
anchor: { value: '#p' },
css: { value: '#mpostform, .navLinks, .postingMode { display: none !important; }' },
cssHide: { value: '.de-post-hid > .postInfo ~ *' },
docExt: { value: '' },
rLinkClick: { value: '' },
rep: { value: true }
}],
'7chan.org': [{
_7ch: { value: true },
cOPost: { value: 'op' },
cFileInfo: { value: 'file_size' },
qMsg: { value: '.message' },
qPages: { value: '#paging > ul > li:nth-last-child(2)' },
qThread: { value: '[id^="thread"]:not(#thread_controls)' },
css: { get: function() {
return '.reply { background-color: ' + $getStyle(doc.body, 'background-color') + '; }'
} },
cssHide: { value: '.de-post-hid > div > .post_header ~ *' },
getImgWrap: { value: function(el) {
return el.parentNode.parentNode;
} },
timePattern: { value: 'yy+dd+nn+w+hh+ii+ss' },
trTag: { value: 'LI' }
}, 'script[src*="kusaba"]'],
'9ch.ru': [{
qRef: { value: '[color="#117743"]' },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : 'index.htm');
} },
getThrdUrl: { value: function(b, tNum) {
return this.prot + '//' + this.host + fixBrd(b) + 'index.php?res=' + tNum;
} }
}, 'form[action*="futaba.php"]'],
'britfa.gs': [{
init: { value: function() { return true; } }
}],
'dfwk.ru': [{
timePattern: { value: 'w+yy+nn+dd+hh+ii' }
}, 'script[src*="kusaba"]'],
'dobrochan.com': [{
dobr: { value: true },
cSubj: { value: 'replytitle' },
cFileInfo: { value: 'fileinfo' },
qDForm: { value: 'form[action*="delete"]' },
qError: { value: '.post-error, h2' },
qOmitted: { value: '.abbrev > span:first-of-type' },
qMsg: { value: '.postbody' },
qPages: { value: '.pages > tbody > tr > td' },
qTrunc: { value: '.abbrev > span:nth-last-child(2)' },
timePattern: { value: 'dd+m+?+?+?+?+?+yyyy++w++hh+ii-?s?s?' },
getImgLink: { value: function(img) {
var el = img.parentNode;
if(el.tagName === 'A') {
return el;
}
return $q('.fileinfo > a', img.previousElementSibling ? el : el.parentNode);
} },
getImgSrc: { value: function(el) {
return this.getImgLink(el).href;
} },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : 'index.xhtml');
} },
getImgWrap: { value: function(el) {
return el.tagName === 'A' ? (el.previousElementSibling ? el : el.parentNode).parentNode :
el.firstElementChild.tagName === 'IMG' ? el.parentNode : el;
} },
getTNum: { value: function(op) {
return $q('a[name]', op).name.match(/\d+/)[0];
} },
css: { value: '.delete > img, .popup, .reply_, .search_google, .search_iqdb { display: none !important; }\
.delete { background: none; }\
.delete_checkbox { position: static !important; }\
.file + .de-video-obj { float: left; margin: 5px 20px 5px 5px; }\
.de-video-obj + div { clear: left; }' },
hasPicWrap: { value: true },
rLinkClick: { value: 'onclick="Highlight(event, this.getAttribute(\'de-num\'))"' },
ru: { value: true },
init: { value: function() {
if(window.location.pathname === '/settings') {
nav = getNavFuncs();
$q('input[type="button"]', doc).addEventListener('click', function() {
readCfg();
saveCfg('__hanarating', $id('rating').value);
}, false);
return true;
}
} }
}],
'ernstchan.com': [{
css: { value: '.content > hr, .de-parea > hr { display: none !important }' },
cOPost: { value: 'thread_OP' },
cReply: { value: 'post' },
cRPost: { value: 'thread_reply' },
qError: { value: '.error' },
qMsg: { value: '.text' }
}, 'link[href$="phutaba.css"]'],
'hiddenchan.i2p': [{
hid: { value: true }
}, 'script[src*="kusaba"]'],
'iichan.hk': [{
iich: { value: true }
}],
'inach.org': [{
css: { value: '#postform > table > tbody > tr:first-child { display: none !important; }' },
isBB: { value: true }
}],
'krautchan.net': [{
krau: { value: true },
cFileInfo: { value: 'fileinfo' },
cReply: { value: 'postreply' },
cRPost: { value: 'postreply' },
cSubj: { value: 'postsubject' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'aa', '', '', 'q'] },
});
} },
qBan: { value: '.ban_mark' },
qDForm: { value: 'form[action*="delete"]' },
qError: { value: '.message_text' },
qImgLink: { value: '.filename > a' },
qOmitted: { value: '.omittedinfo' },
qPages: { value: 'table[border="1"] > tbody > tr > td > a:nth-last-child(2) + a' },
qRef: { value: '.postnumber' },
qThread: { value: '.thread_body' },
qTrunc: { value: 'p[id^="post_truncated"]' },
timePattern: { value: 'yyyy+nn+dd+hh+ii+ss+--?-?-?-?-?' },
getImgWrap: { value: function(el) {
return el.parentNode;
} },
getSage: { value: function(post) {
return !!$c('sage', post);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
css: { value: 'img[id^="translate_button"], img[src$="button-expand.gif"], img[src$="button-close.gif"], body > center > hr, form > div:first-of-type > hr, h2 { display: none !important; }\
div[id^="Wz"] { z-index: 10000 !important; }\
.de-thr-hid { margin-bottom: ' + (!TNum ? '7' : '2') + 'px; float: none !important; }\
.file_reply + .de-video-obj, .file_thread + .de-video-obj { margin: 5px 20px 5px 5px; float: left; }\
.de-video-obj + div { clear: left; }' },
cssHide: { value: '.de-post-hid > div:not(.postheader)' },
hasPicWrap: { value: true },
isBB: { value: true },
rLinkClick: { value: 'onclick="highlightPost(this.textContent.substr(2)))"' },
rep: { value: true },
res: { value: 'thread-' },
init: { value: function() {
doc.body.insertAdjacentHTML('beforeend', '<div style="display: none;">' +
'<div onclick="window.lastUpdateTime = 0;"></div>' +
'<div onclick="window.fileCounter = 1;"></div>' +
'<div onclick="if(boardRequiresCaptcha) { requestCaptcha(true); }"></div>' +
'<div onclick="setupProgressTracking();"></div>' +
'</div>');
var els = doc.body.lastChild.children;
this.btnZeroLUTime = els[0];
this.btnSetFCntToOne = els[1];
this.initCaptcha = els[2];
this.addProgressTrack = els[3];
} }
}],
'lambdadelta.net': [{
css: { value: '.content > hr { display: none !important }' },
cssHide: { value: '.de-post-hid > .de-ppanel ~ *' }
}, 'link[href$="phutaba.css"]'],
'mlpg.co': [{
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', '-', 'spoiler', 'c', '', '', 'q'] },
});
} },
getWrap: { value: function(el, isOp) {
return el.parentNode;
} },
css: { value: '.image-hover, form > div[style="text-align: center;"], form > div[style="text-align: center;"] + hr { display: none !important; }' },
isBB: { value: true }
}, 'form[name*="postcontrols"]'],
'nido.org': [{
qPages: { value: '.pagenavi > tbody > tr > td:nth-child(2) > a:last-of-type' },
getSage: { value: function(post) {
return !!$q('a[href="mailto:cejas"]', post);
} },
init: { value: function() {
for(var src, el, i = 0, els = $Q('span[id^="pv-"]', doc.body), len = els.length; i < len; ++i) {
el = els[i];
src = 'https://www.youtube.com/watch?v=' + el.id.substring(3);
el.parentNode.insertAdjacentHTML('beforeend',
'<p class="de-video-ext"><a href="' + src + '">' + src + '</a></p>');
$del(el);
}
} }
}, 'script[src*="kusaba"]'],
'ponychan.net': [{
pony: { value: true },
cOPost: { value: 'op' },
qPages: { value: 'table[border="0"] > tbody > tr > td:nth-child(2) > a:last-of-type' },
css: { value: '#bodywrap3 > hr { display: none !important; }' }
}, 'script[src*="kusaba"]'],
'syn-ch.ru': [{
css: { value: '.fa-sort, .image_id { display: none !important; }\
time:after { content: none; }' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sub', 'sup', 'q'] },
});
} },
init: { value: function() {
$script('$ = function(){};');
$each($Q('.mentioned', doc), $del);
} },
isBB: { value: true }
}, 'form[name*="postcontrols"]'],
'urupchan.ru': [{
urup: { value: true },
init: { value: function() {
for(var src, el, i = 0, els = $Q('blockquote > span[style="float: left;"]', doc.body), len = els.length; i < len; ++i) {
el = els[i];
src = $t('a', el).href;
el.parentNode.insertAdjacentHTML('beforeend',
'<p class="de-video-ext"><a href="' + src + '">' + src + '</a></p>');
$del(el);
}
} },
css: { value: '#captchaimage, .replybacklinks, .messagehelperC { display: none !important }' }
}, 'script[src*="kusaba"]']
};
var ibEngines = {
'#ABU_css, #ShowLakeSettings': {
abu: { value: true },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', 'sup', 'sub', 'q'] }
});
} },
qBan: { value: 'font[color="#C12267"]' },
qDForm: { value: '#posts_form, #delform' },
qOmitted: { value: '.mess_post, .omittedposts' },
getSage: { writable: true, value: function(post) {
if($c('postertripid', dForm)) {
this.getSage = function(post) {
return !$c('postertripid', post);
};
} else {
this.getSage = Object.getPrototypeOf(this).getSage;
}
return this.getSage(post);
} },
cssEn: { value: '#ABU_alert_wait, .ABU_refmap, #captcha_div + font, #CommentToolbar, .postpanel, #usrFlds + tbody > tr:first-child, body > center { display: none !important; }\
.de-abtn { transition: none; }\
#de-txt-panel { font-size: 16px !important; }\
.reflink:before { content: none !important; }' },
isBB: { value: true },
init: { value: function() {
var cd = $id('captcha_div'),
img = cd && $t('img', cd);
if(img) {
cd.setAttribute('onclick', ['var el, i = 4,',
'isCustom = (typeof event.detail === "object") && event.detail.isCustom;',
"if(!isCustom && event.target.tagName !== 'IMG') {",
'return;',
'}',
'do {', img.getAttribute('onclick'), '} while(--i > 0 && !/<img|не нужно/i.test(this.innerHTML));',
"if(el = this.getElementsByTagName('img')[0]) {",
"el.removeAttribute('onclick');",
"if((!isCustom || event.detail.focus) && (el = this.querySelector('input[type=\\'text\\']'))) {",
'el.focus();',
'}',
'}'
].join(''));
img.removeAttribute('onclick');
}
} }
},
'form[action*="futaba.php"]': {
futa: { value: true },
qDForm: { value: 'form:not([enctype])' },
qImgLink: { value: 'a[href$=".jpg"]:nth-of-type(1), a[href$=".png"]:nth-of-type(1), a[href$=".gif"]:nth-of-type(1)' },
qOmitted: { value: 'font[color="#707070"]' },
qPostForm: { value: 'form:nth-of-type(1)' },
qRef: { value: '.del' },
getPageUrl: { value: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : 'futaba.htm');
} },
getPNum: { value: function(post) {
return $t('input', post).name;
} },
getPostEl: { value: function(el) {
while(el && el.tagName !== 'TD' && !el.hasAttribute('de-thread')) {
el = el.parentElement;
}
return el;
} },
getPosts: { value: function(thr) {
return $Q('td:nth-child(2)', thr);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
cssEn: { value: '.de-cfg-body, .de-content { font-family: arial; }\
.ftbl { width: auto; margin: 0; }\
.reply { background: #f0e0d6; }\
span { font-size: inherit; }' },
docExt: { value: '.htm' }
},
'form[action*="imgboard.php?delete"]': {
tinyIb: { value: true },
ru: { value: true }
},
'form[name*="postcontrols"]': {
tiny: { value: true },
cFileInfo: { value: 'fileinfo' },
cOPost: { value: 'op' },
cReply: { value: 'post reply' },
cSubj: { value: 'subject' },
cTrip: { value: 'trip' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ["'''", "''", '__', '^H', '**', '`', '', '', 'q'] },
});
} },
qDForm: { value: 'form[name="postcontrols"]' },
qMsg: { value: '.body' },
qName: { value: '.name' },
qOmitted: { value: '.omitted' },
qPages: { value: '.pages > a:nth-last-of-type(2)' },
qPostForm: { value: 'form[name="post"]' },
qRef: { value: '.post_no:nth-of-type(2)' },
qTrunc: { value: '.toolong' },
firstPage: { value: 1 },
timePattern: { value: 'nn+dd+yy++w++hh+ii+ss' },
getPageUrl: { value: function(b, p) {
return p > 1 ? fixBrd(b) + p + this.docExt : fixBrd(b);
} },
getTNum: { value: function(op) {
return $q('input[type="checkbox"]', op).name.match(/\d+/)[0];
} },
cssEn: { get: function() {
return '.banner, .mentioned, .post-hover' + (TNum ? '' : ', .de-btn-rep') + ' { display: none !important; }\
form, form table { margin: 0; }';
} },
cssHide: { value: '.de-post-hid > .intro ~ *'}
},
'script[src*="kusaba"]': {
kus: { value: true },
cOPost: { value: 'postnode' },
qError: { value: 'h1, h2, div[style*="1.25em"]' },
cssEn: { value: '.extrabtns, #newposts_get, .replymode, .ui-resizable-handle, blockquote + a { display: none !important; }\
.ui-wrapper { display: inline-block; width: auto !important; height: auto !important; padding: 0 !important; }' },
isBB: { value: true },
rLinkClick: { value: 'onclick="highlight(this.textContent.substr(2), true)"' }
},
'link[href$="phutaba.css"]': {
phut: { value: true },
cSubj: { value: 'subject' },
cTrip: { value: 'tripcode' },
qPages: { value: '.pagelist > li:nth-last-child(2)' },
getImgWrap: { value: function(el) {
return el.parentNode.parentNode;
} },
getSage: { value: function(post) {
return !!$q('.sage', post);
} },
cssHide: { value: '.de-post-hid > .post > .post_body' },
docExt: { value: '' },
formButtons: { get: function() {
return Object.create(this._formButtons, {
tag: { value: ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] },
});
} },
isBB: { value: true },
res: { value: 'thread/' }
}
};
var ibBase = {
cFileInfo: 'filesize',
cOPost: 'oppost',
cReply: 'reply',
cRPost: 'reply',
cSubj: 'filetitle',
cTrip: 'postertrip',
get _formButtons() {
var bb = this.isBB;
return {
id: ['bold', 'italic', 'under', 'strike', 'spoil', 'code', 'sup', 'sub', 'quote'],
val: ['B', 'i', 'U', 'S', '%', 'C', 'v', '^', '>'],
tag: bb ? ['b', 'i', 'u', 's', 'spoiler', 'code', '', '', 'q'] :
['**', '*', '', '^H', '%%', '`', '', '', 'q'],
bb: [bb, bb, bb, bb, bb, bb, bb, bb, bb]
};
},
get formButtons() {
return this._formButtons;
},
qBan: '',
qDelBut: 'input[type="submit"]',
qDForm: '#delform, form[name="delform"]',
qError: 'h1, h2, font[size="5"]',
get qImgLink() {
var val = '.' + this.cFileInfo + ' a[href$=".jpg"]:nth-of-type(1), ' +
'.' + this.cFileInfo + ' a[href$=".png"]:nth-of-type(1), ' +
'.' + this.cFileInfo + ' a[href$=".gif"]:nth-of-type(1)';
Object.defineProperty(this, 'qImgLink', { value: val });
return val;
},
qMsg: 'blockquote',
get qMsgImgLink() {
var val = this.qMsg + ' a[href*=".jpg"], ' +
this.qMsg + ' a[href*=".png"], ' +
this.qMsg + ' a[href*=".gif"], ' +
this.qMsg + ' a[href*=".jpeg"]';
Object.defineProperty(this, 'qMsgImgLink', { value: val });
return val;
},
qName: '.postername, .commentpostername',
qOmitted: '.omittedposts',
qPages: 'table[border="1"] > tbody > tr > td:nth-child(2) > a:last-of-type',
qPostForm: '#postform',
qRef: '.reflink',
qTable: 'form > table, div > table',
timePattern: 'w+dd+m+yyyy+hh+ii+ss',
get qThread() {
var val = $c('thread', doc) ? '.thread' :
$q('div[id*="_info"][style*="float"]', doc) ? 'div[id^="t"]:not([style])' :
'[id^="thread"]';
Object.defineProperty(this, 'qThread', { value: val });
return val;
},
qTrunc: '.abbrev, .abbr, .shortened',
getImgLink: function(img) {
var el = img.parentNode;
return el.tagName === 'SPAN' ? el.parentNode : el;
},
getImgSrc: function(el) {
return el.getAttribute('src');
},
getImgSize: function(info) {
if(info) {
var sz = info.match(/(\d+)\s?[x×]\s?(\d+)/);
return [sz[1], sz[2]];
}
return [-1, -1];
},
getImgWeight: function(info) {
var w = info.match(/(\d+(?:[\.,]\d+)?)\s*([mkк])?i?[bб]/i);
return w[2] === 'M' ? (w[1] * 1e3) | 0 : !w[2] ? Math.round(w[1] / 1e3) : w[1];
},
getImgWrap: function(el) {
var node = (el.tagName === 'SPAN' ? el.parentNode : el).parentNode;
return node.tagName === 'SPAN' ? node.parentNode : node;
},
getOmitted: function(el, len) {
var txt;
return el && (txt = el.textContent) ? +(txt.match(/\d+/) || [0])[0] + 1 : 1;
},
getOp: function(thr) {
var el, op, opEnd;
if(op = $c(this.cOPost, thr)) {
return op;
}
op = thr.ownerDocument.createElement('div'),
opEnd = $q(this.qTable + ', div[id^="repl"]', thr);
while((el = thr.firstChild) !== opEnd) {
op.appendChild(el);
}
if(thr.hasChildNodes()) {
thr.insertBefore(op, thr.firstChild);
} else {
thr.appendChild(op);
}
return op;
},
getPNum: function(post) {
return post.id.match(/\d+/)[0];
},
getPageUrl: function(b, p) {
return fixBrd(b) + (p > 0 ? p + this.docExt : '');
},
getPostEl: function(el) {
while(el && !el.classList.contains(this.cRPost) && !el.hasAttribute('de-thread')) {
el = el.parentElement;
}
return el;
},
getPosts: function(thr) {
return $Q('.' + this.cRPost, thr);
},
getSage: function(post) {
var a = $q('a[href^="mailto:"], a[href="sage"]', post);
return !!a && /sage/i.test(a.href);
},
getThrdUrl: function(b, tNum) {
return this.prot + '//' + this.host + fixBrd(b) + this.res + tNum + this.docExt;
},
getTNum: function(op) {
return $q('input[type="checkbox"]', op).value;
},
getWrap: function(el, isOp) {
if(isOp) {
return el;
}
if(el.tagName === 'TD') {
Object.defineProperty(this, 'getWrap', { value: function(el, isOp) {
return isOp ? el : getAncestor(el, 'TABLE');
}});
} else {
Object.defineProperty(this, 'getWrap', { value: function(el, isOp) {
return el;
}});
}
return this.getWrap(el, isOp);
},
css: '',
cssEn: '',
cssHide: '.de-post-hid > .de-ppanel ~ *',
init: null,
isBB: false,
get lastPage() {
var el = $q(this.qPages, doc),
val = el && +aProto.pop.call(el.textContent.match(/\d+/g) || []) || 0;
if(pageNum === val + 1) {
val++;
}
Object.defineProperty(this, 'pagesCount', { value: val });
return val;
},
get reCrossLinks() {
var val = new RegExp('>https?:\\/\\/[^\\/]*' + this.dm + '\\/([a-z0-9]+)\\/' +
regQuote(this.res) + '(\\d+)(?:[^#<]+)?(?:#i?(\\d+))?<', 'g');
Object.defineProperty(this, 'reCrossLinks', { value: val });
return val;
},
rLinkClick: 'onclick="highlight(this.textContent.substr(2))"',
anchor: '#',
docExt: '.html',
dm: '',
firstPage: 0,
host: window.location.hostname,
hasPicWrap: false,
prot: window.location.protocol,
get rep() {
var val = dTime || spells.haveReps || Cfg['crossLinks'];
Object.defineProperty(this, 'rep', { value: val });
return val;
},
res: 'res/',
ru: false,
trTag: 'TR'
};
var i, ibObj = null, dm = window.location.hostname
.match(/(?:(?:[^.]+\.)(?=org\.|net\.|com\.))?[^.]+\.[^.]+$|^\d+\.\d+\.\d+\.\d+$|localhost/)[0];
if(checkDomains) {
if(dm in ibDomains) {
ibObj = (function createBoard(info) {
return Object.create(
info[2] ? createBoard(ibDomains[info[2]]) :
info[1] ? Object.create(ibBase, ibEngines[info[1]]) :
ibBase, info[0]
);
})(ibDomains[dm]);
checkOther = false;
}
}
if(checkOther) {
for(i in ibEngines) {
if($q(i, doc)) {
ibObj = Object.create(ibBase, ibEngines[i]);
break;
}
}
if(!ibObj) {
ibObj = ibBase;
}
}
if(ibObj) {
ibObj.dm = dm;
}
return ibObj;
};
//============================================================================================================
// BROWSER
//============================================================================================================
function getNavFuncs() {
if(!('contains' in String.prototype)) {
String.prototype.contains = function(s) {
return this.indexOf(s) !== -1;
};
String.prototype.startsWith = function(s) {
return this.indexOf(s) === 0;
};
}
if(!('repeat' in String.prototype)) {
String.prototype.repeat = function(nTimes) {
return new Array(nTimes + 1).join(this.valueOf());
};
}
if('toJSON' in aProto) {
delete aProto.toJSON;
}
if(!('URL' in window)) {
window.URL = window.webkitURL;
}
var ua = window.navigator.userAgent,
opera = window.opera ? +window.opera.version() : 0,
isOldOpera = opera ? opera < 12.1 : false,
webkit = ua.contains('WebKit/'),
chrome = webkit && ua.contains('Chrome/'),
safari = webkit && !chrome,
isGM = typeof GM_setValue === 'function' &&
(!chrome || !GM_setValue.toString().contains('not supported')),
isScriptStorage = !!scriptStorage && !ua.contains('Opera Mobi');
if(!window.GM_xmlhttpRequest) {
window.GM_xmlhttpRequest = $xhr;
}
return {
get ua() {
return navigator.userAgent + (this.Firefox ? ' [' + navigator.buildID + ']' : '');
},
Firefox: ua.contains('Gecko/'),
Opera: !!opera,
oldOpera: isOldOpera,
WebKit: webkit,
Chrome: chrome,
Safari: safari,
isGM: isGM,
isGlobal: isGM || isScriptStorage,
isSStorage: isScriptStorage,
cssFix: webkit ? '-webkit-' : isOldOpera ? '-o-' : '',
Anim: !isOldOpera,
animName: webkit ? 'webkitAnimationName' : isOldOpera ? 'OAnimationName' : 'animationName',
animEnd: webkit ? 'webkitAnimationEnd' : isOldOpera ? 'oAnimationEnd' : 'animationend',
animEvent: function(el, Fn) {
el.addEventListener(this.animEnd, function aEvent() {
this.removeEventListener(nav.animEnd, aEvent, false);
Fn(this);
Fn = null;
}, false);
},
noBlob: isOldOpera,
fixLink: safari ? getAbsLink : function fixLink(url) {
return url;
},
get hasWorker() {
var val = 'Worker' in (this.Firefox ? unsafeWindow : Window);
Object.defineProperty(this, 'hasWorker', { value: val });
return val;
},
get canPlayMP3() {
var val = !!new Audio().canPlayType('audio/mp3; codecs="mp3"');
Object.defineProperty(this, 'canPlayMP3', { value: val });
return val;
},
get matchesSelector() {
var dE = doc.documentElement,
fun = dE.matchesSelector || dE.mozMatchesSelector ||
dE.webkitMatchesSelector || dE.oMatchesSelector,
val = Function.prototype.call.bind(fun);
Object.defineProperty(this, 'matchesSelector', { value: val });
return val;
}
};
}
//============================================================================================================
// INITIALIZATION
//============================================================================================================
function Initialization(checkDomains) {
if(/^(?:about|chrome|opera|res)/i.test(window.location)) {
return false;
}
if(!(window.localStorage && typeof localStorage === 'object' && window.sessionStorage)) {
GM_log('WEBSTORAGE ERROR: please, enable webstorage!');
return false;
}
var intrv, url;
if(!aib) {
aib = getImageBoard(checkDomains, true);
}
if(aib.init && aib.init()) {
return false;
}
switch(window.name) {
case '': break;
case 'de-iframe-pform':
case 'de-iframe-dform':
$script((
'window.top.postMessage("A' + window.name + '$#$' +
getSubmitResponse(doc, true).join('$#$') + '", "*");'
).replace(/\n|\r/g, '\\n'));
return false;
case 'de-iframe-fav':
intrv = setInterval(function() {
$script('window.top.postMessage("B' + (doc.body.offsetHeight + 5) + '", "*");');
}, 1500);
window.addEventListener('load', setTimeout.bind(window, clearInterval, 3e4, intrv), false);
liteMode = true;
pr = {};
}
dForm = $q(aib.qDForm, doc);
if(!dForm || $id('de-panel')) {
return false;
}
nav = getNavFuncs();
window.addEventListener('storage', function(e) {
var data, temp, post, val = e.newValue;
if(!val) {
return;
}
switch(e.key) {
case '__de-post': {
try {
data = JSON.parse(val);
} catch(e) {
return;
}
temp = data['hide'];
if(data['brd'] === brd && (post = pByNum[data['num']]) && (post.hidden ^ temp)) {
post.setUserVisib(temp, data['date'], false);
} else {
if(!(data['brd'] in bUVis)) {
bUVis[data['brd']] = {};
}
bUVis[data['brd']][data['num']] = [+!temp, data['date']];
}
if(data['isOp']) {
if(!(data['brd'] in hThr)) {
if(temp) {
hThr[data['brd']] = {};
} else {
break;
}
}
if(temp) {
hThr[data['brd']][data['num']] = data['title'];
} else {
delete hThr[data['brd']][data['num']];
}
}
break;
}
case '__de-threads': {
try {
hThr = JSON.parse(val);
} catch(e) {
return;
}
if(!(brd in hThr)) {
hThr[brd] = {};
}
firstThr.updateHidden(hThr[brd]);
break;
}
case '__de-spells': {
try {
data = JSON.parse(val);
} catch(e) {
return;
}
Cfg['hideBySpell'] = data['hide'];
if(temp = $q('input[info="hideBySpell"]', doc)) {
temp.checked = data['hide'];
}
doc.body.style.display = 'none';
disableSpells();
if(data['data']) {
spells.setSpells(data['data'], false);
if(temp = $id('de-spell-edit')) {
temp.value = spells.list;
}
} else {
if(data['data'] === '') {
spells.disable();
if(temp = $id('de-spell-edit')) {
temp.value = '';
}
saveCfg('spells', '');
}
spells.enable = false;
}
doc.body.style.display = '';
}
default: return;
}
toggleContent('hid', true);
}, false);
url = (window.location.pathname || '').match(new RegExp(
'^(?:\\/?([^\\.]*?)\\/?)?' + '(' + regQuote(aib.res) + ')?' +
'(\\d+|index|wakaba|futaba)?' + '(\\.(?:[a-z]+))?$'
));
brd = url[1];
TNum = url[2] ? url[3] :
aib.futa ? +(window.location.search.match(/\d+/) || [false])[0] :
false;
pageNum = url[3] && !TNum ? +url[3] || aib.firstPage : aib.firstPage;
if(!aib.hasOwnProperty('docExt') && url[4]) {
aib.docExt = url[4];
}
dummy = doc.createElement('div');
return true;
}
function parseThreadNodes(form, threads) {
var el, i, len, node, fNodes = aProto.slice.call(form.childNodes),
cThr = doc.createElement('div');
for(i = 0, len = fNodes.length - 1; i < len; ++i) {
node = fNodes[i];
if(node.tagName === 'HR') {
form.insertBefore(cThr, node);
form.insertBefore(cThr.lastElementChild, node);
el = cThr.lastElementChild;
if(el.tagName === 'BR') {
form.insertBefore(el, node);
}
threads.push(cThr);
cThr = doc.createElement('div');
} else {
cThr.appendChild(node);
}
}
cThr.appendChild(fNodes[i]);
form.appendChild(cThr);
return threads;
}
function parseDelform(node, thrds) {
var i, lThr, len = thrds.length;
$each($T('script', node), $del);
if(len === 0) {
Thread.parsed = true;
thrds = parseThreadNodes(dForm, []);
len = thrds.length;
}
if(len) {
firstThr = lThr = new Thread(thrds[0], null);
}
for(i = 1; i < len; i++) {
lThr = new Thread(thrds[i], lThr);
}
lastThr = lThr;
node.setAttribute('de-form', '');
node.removeAttribute('id');
if(aib.abu && TNum) {
lThr = firstThr.el;
while((node = lThr.nextSibling) && node.tagName !== 'HR') {
$del(node);
}
}
}
function replaceString(txt) {
if(dTime) {
txt = dTime.fix(txt);
}
if(aib.fch || aib.krau) {
if(aib.fch) {
txt = txt.replace(/<wbr>/g, '');
}
txt = txt.replace(/(^|>|\s|>)(https*:\/\/.*?)(<\/a>)?(?=$|<|\s)/ig, function(x, a, b, c) {
return c ? x : a + '<a href="' + b + '">' + b + '</a>';
});
}
if(spells.haveReps) {
txt = spells.replace(txt);
}
if(Cfg['crossLinks']) {
txt = txt.replace(aib.reCrossLinks, function(str, b, tNum, pNum) {
return '>>>/' + b + '/' + (pNum || tNum) + '<';
});
}
return txt;
}
function replacePost(el) {
if(aib.rep) {
el.innerHTML = replaceString(el.innerHTML);
}
return el;
}
function replaceDelform() {
if(liteMode) {
doc.body.insertAdjacentHTML('afterbegin', dForm.outerHTML);
dForm = doc.body.firstChild;
window.addEventListener('load', function() {
while(dForm.nextSibling) {
$del(dForm.nextSibling);
}
}, false);
} else if(aib.rep) {
dForm.insertAdjacentHTML('beforebegin', replaceString(dForm.outerHTML));
dForm.style.display = 'none';
dForm.id = 'de-dform-old';
dForm = dForm.previousSibling;
window.addEventListener('load', function() {
$del($id('de-dform-old'));
}, false);
}
}
function initDelformAjax() {
var btn;
if(Cfg['ajaxReply'] === 2) {
dForm.onsubmit = $pd;
if(btn = $q(aib.qDelBut, dForm)) {
btn.onclick = function(e) {
$pd(e);
pr.closeQReply();
$alert(Lng.deleting[lang], 'deleting', true);
new html5Submit(dForm, e.target, checkDelete);
};
}
} else if(Cfg['ajaxReply'] === 1) {
dForm.insertAdjacentHTML('beforeend',
'<iframe name="de-iframe-pform" src="about:blank" style="display: none;"></iframe>' +
'<iframe name="de-iframe-dform" src="about:blank" style="display: none;"></iframe>'
);
dForm.target = 'de-iframe-dform';
dForm.onsubmit = function() {
pr.closeQReply();
$alert(Lng.deleting[lang], 'deleting', true);
};
}
}
function initThreadUpdater(title, enableUpdate) {
var delay, checked404, loadTO, audioRep, currentXHR, audioEl, stateButton, hasAudio,
initDelay, favIntrv, favNorm, favHref, enabled = false,
inited = false,
lastECode = 200,
newPosts = 0,
aPlayers = 0,
focused = true;
if(enableUpdate) {
init();
}
if(focused && Cfg['desktNotif'] && ('permission' in Notification)) {
switch(Notification.permission.toLowerCase()) {
case 'default': requestNotifPermission(); break;
case 'denied': saveCfg('desktNotif', 0);
}
}
function init() {
audioEl = null;
stateButton = null;
hasAudio = false;
initDelay = Cfg['updThrDelay'] * 1e3;
favIntrv = 0;
favNorm = notifGranted = inited = true;
favHref = ($q('head link[rel="shortcut icon"]', doc) || {}).href;
if(('hidden' in doc) || ('webkitHidden' in doc)) {
focused = !(doc.hidden || doc.webkitHidden);
doc.addEventListener((nav.WebKit ? 'webkit' : '') + 'visibilitychange', function() {
if(doc.hidden || doc.webkitHidden) {
onBlur();
} else {
onVis();
}
}, false);
} else {
focused = false;
window.addEventListener('focus', onVis, false);
window.addEventListener('blur', onBlur, false);
window.addEventListener('mousemove', function mouseMove() {
window.removeEventListener('mousemove', mouseMove, false);
onVis();
}, false);
}
enable();
}
function enable() {
if(!enabled) {
enabled = true;
checked404 = false;
newPosts = 0;
delay = initDelay;
loadTO = setTimeout(loadPostsFun, delay);
}
}
function disable() {
if(enabled) {
clearTimeout(loadTO);
enabled = hasAudio = false;
setState('off');
var btn = $id('de-btn-audio-on');
if(btn) {
btn.id = 'de-btn-audio-off';
}
}
}
function toggleAudio(aRep) {
if(!audioEl) {
audioEl = $new('audio', {
'preload': 'auto',
'src': 'https://raw.github.com/SthephanShinkufag/Dollchan-Extension-Tools/master/signal.ogg'
}, null);
}
audioRep = aRep;
return hasAudio = !hasAudio;
}
function audioNotif() {
if(focused) {
hasAudio = false;
} else {
audioEl.play()
setTimeout(audioNotif, audioRep);
hasAudio = true;
}
}
function requestNotifPermission() {
notifGranted = false;
Notification.requestPermission(function(state) {
if(state.toLowerCase() === 'denied') {
saveCfg('desktNotif', 0);
} else {
notifGranted = true;
}
});
}
function loadPostsFun() {
currentXHR = firstThr.loadNew(onLoaded, true);
}
function forceLoadPosts() {
if(currentXHR) {
currentXHR.abort();
}
clearTimeout(loadTO);
delay = initDelay;
loadPostsFun();
}
function onLoaded(eCode, eMsg, lPosts, xhr) {
if(currentXHR !== xhr && eCode === 0) { // Loading aborted
return;
}
currentXHR = null;
infoLoadErrors(eCode, eMsg, -1);
if(eCode !== 200) {
lastECode = eCode;
if(!Cfg['noErrInTitle']) {
updateTitle();
}
if(eCode !== 0 && Math.floor(eCode / 500) === 0) {
if(eCode === 404 && !checked404) {
checked404 = true;
} else {
updateTitle();
disable();
return;
}
}
setState('warn');
if(enabled) {
loadTO = setTimeout(loadPostsFun, delay);
}
return;
}
if(lastECode !== 200) {
lastECode = 200;
setState('on');
checked404 = false;
if((focused || lPosts === 0) && !Cfg['noErrInTitle']) {
updateTitle();
}
}
if(!focused) {
if(lPosts !== 0) {
if(Cfg['favIcoBlink'] && favHref && newPosts === 0) {
favIntrv = setInterval(function() {
$del($q('link[rel="shortcut icon"]', doc.head));
doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' +
(!favNorm ? favHref : 'data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAA' +
'AQEAYAAABPYyMiAAAABmJLR0T///////8JWPfcAAAACXBIWXMAAABIAAAASABGyWs+AAAAF0lEQVR' +
'Ix2NgGAWjYBSMglEwCkbBSAcACBAAAeaR9cIAAAAASUVORK5CYII=') + '">');
favNorm = !favNorm;
}, 800);
}
newPosts += lPosts;
updateTitle();
if(Cfg['desktNotif'] && notifGranted) {
var post = firstThr.last,
imgs = post.images,
notif = new Notification(aib.dm + '/' + brd + '/' + TNum + ': ' + newPosts +
Lng.newPost[lang][lang !== 0 ? +(newPosts !== 1) : (newPosts % 10) > 4 ||
(newPosts % 10) === 0 || (((newPosts % 100) / 10) | 0) === 1 ? 2 :
(newPosts % 10) === 1 ? 0 : 1] + Lng.newPost[lang][3],
{
'body': post.text.substring(0, 250).replace(/\s+/g, ' '),
'tag': aib.dm + brd + TNum,
'icon': imgs.length === 0 ? favHref : imgs[0].src
});
notif.onshow = function() {
setTimeout(this.close.bind(this), 12e3);
};
notif.onclick = function() {
window.focus();
};
notif.onerror = function() {
window.focus();
requestNotifPermission();
};
}
if(hasAudio) {
if(audioRep) {
audioNotif();
} else {
audioEl.play()
}
}
delay = initDelay;
} else if(delay !== 12e4) {
delay = Math.min(delay + initDelay, 12e4);
}
}
if(enabled) {
loadTO = setTimeout(loadPostsFun, delay);
}
}
function setState(state) {
var btn = stateButton || (stateButton = $q('a[id^="de-btn-upd"]', doc));
btn.id = 'de-btn-upd-' + state;
btn.title = Lng.panelBtn['upd-' + (state === 'off' ? 'off' : 'on')][lang];
}
function onBlur() {
focused = false;
firstThr.clearPostsMarks();
}
function onVis() {
if(Cfg['favIcoBlink'] && favHref) {
clearInterval(favIntrv);
favNorm = true;
$del($q('link[rel="shortcut icon"]', doc.head));
doc.head.insertAdjacentHTML('afterbegin', '<link rel="shortcut icon" href="' + favHref + '">');
}
focused = true;
newPosts = 0;
setTimeout(function() {
updateTitle();
if(enabled) {
forceLoadPosts();
}
}, 200);
}
function updateTitle() {
doc.title = (aPlayers === 0 ? '' : '♫ ') +
(lastECode === 200 ? '' : '{' + lastECode + '} ') +
(newPosts === 0 ? '' : '[' + newPosts + '] ') + title;
}
function addPlayingTag() {
aPlayers++;
if(aPlayers === 1) {
updateTitle();
}
}
function removePlayingTag() {
aPlayers = Math.max(aPlayers - 1, 0);
if(aPlayers === 0) {
updateTitle();
}
}
return {
get enabled() {
return enabled;
},
get focused() {
return focused;
},
forceLoad: forceLoadPosts,
enable: function() {
if(!inited) {
init();
} else if(!enabled) {
enable();
} else {
return;
}
setState('on');
},
disable: disable,
toggleAudio: toggleAudio,
addPlayingTag: addPlayingTag,
removePlayingTag: removePlayingTag
};
}
function initPage() {
if(Cfg['updScript']) {
checkForUpdates(false, function(html) {
$alert(html, 'updavail', false);
});
}
if(TNum) {
if(Cfg['rePageTitle']) {
if(aib.abu) {
window.addEventListener('load', function() {
doc.title = '/' + brd + ' - ' + pByNum[TNum].title;
}, false);
}
doc.title = '/' + brd + ' - ' + pByNum[TNum].title;
}
firstThr.el.insertAdjacentHTML('afterend',
'<div id="de-updater-div">>> [<a class="de-abtn" id="de-updater-btn" href="#"></a>]</div>');
firstThr.el.nextSibling.addEventListener('click', Thread.loadNewPosts, false);
} else if(needScroll) {
setTimeout(window.scrollTo, 20, 0, 0);
}
updater = initThreadUpdater(doc.title, TNum && Cfg['ajaxUpdThr']);
}
//============================================================================================================
// MAIN
//============================================================================================================
function addDelformStuff(isLog) {
var pNum, post;
preloadImages(null);
isLog && (Cfg['preLoadImgs'] || Cfg['openImgs']) && $log('Preload images');
embedMP3Links(null);
isLog && Cfg['addMP3'] && $log('MP3 links');
youTube.parseLinks(null);
isLog && Cfg['addYouTube'] && $log('YouTube links');
if(Cfg['addImgs']) {
embedImagesLinks(dForm);
isLog && $log('Image links');
}
if(Cfg['imgSrcBtns']) {
addImagesSearch(dForm);
isLog && $log('Sauce buttons');
}
if(Cfg['linksNavig'] === 2) {
genRefMap(pByNum, !!Cfg['hideRefPsts'], '');
for(pNum in pByNum) {
post = pByNum[pNum];
if(post.hasRef) {
addRefMap(post, '');
}
}
isLog && $log('Reflinks map');
}
}
function doScript(checkDomains) {
var initTime = oldTime = Date.now();
if(!Initialization(checkDomains)) {
return;
}
$log('Init');
readCfg();
spells = new Spells(!!Cfg['hideBySpell']);
youTube = initYouTube(Cfg['addYouTube'], Cfg['YTubeType'], Cfg['YTubeWidth'], Cfg['YTubeHeigh'],
Cfg['YTubeHD'], Cfg['YTubeTitles']);
readFavorites();
$log('Read config');
$disp(doc.body);
replaceDelform();
$log('Replace delform');
pr = new PostForm($q(aib.qPostForm, doc), false, !liteMode);
pByNum = Object.create(null);
try {
parseDelform(dForm, $Q(aib.qThread, dForm));
} catch(e) {
GM_log('DELFORM ERROR:\n' + getPrettyErrorMessage(e));
$disp(doc.body);
return;
}
initDelformAjax();
readViewedPosts();
saveFavorites();
$log('Parse delform');
if(Cfg['keybNavig']) {
keyNav = new KeyNavigation();
$log('Init keybinds');
}
if(!liteMode) {
initPage();
$log('Init page');
addPanel();
$log('Add panel');
}
initMessageFunctions();
addDelformStuff(true);
scriptCSS();
$disp(doc.body);
$log('Apply CSS');
readPosts();
readUserPosts();
checkPostsVisib();
saveUserPosts();
$log('Apply spells');
timeLog.push(Lng.total[lang] + (Date.now() - initTime) + 'ms');
}
if(doc.readyState === 'interactive' || doc.readyState === 'complete') {
needScroll = false;
doScript(true);
} else {
aib = getImageBoard(true, false);
needScroll = true;
doc.addEventListener(doc.onmousewheel !== undefined ? "mousewheel" : "DOMMouseScroll", function wheelFunc(e) {
needScroll = false;
doc.removeEventListener(e.type, wheelFunc, false);
}, false);
doc.addEventListener('DOMContentLoaded', doScript.bind(null, false), false);
}
})(window.opera && window.opera.scriptStorage);
| Move image buttons navigation to the main hotkey storage
| Dollchan_Extension_Tools.user.js | Move image buttons navigation to the main hotkey storage | <ide><path>ollchan_Extension_Tools.user.js
<ide>
<ide> keyNavEdit: [
<ide> '%l%i24 – предыдущая страница%/l' +
<del> '%l%i33 – следующая страница%/l' +
<add> '%l%i217 – следующая страница%/l' +
<ide> '%l%i23 – скрыть текущий пост/тред%/l' +
<del> '%l%i34 – раскрыть текущий тред%/l' +
<add> '%l%i33 – раскрыть текущий тред%/l' +
<ide> '%l%i22 – быстрый ответ или создать тред%/l' +
<ide> '%l%i25t – отправить пост%/l' +
<ide> '%l%i21 – тред (на доске)/пост (в треде) ниже%/l' +
<ide> '%l%i215t – спойлер%/l' +
<ide> '%l%i216t – код%/l',
<ide> '%l%i24 – previous page%/l' +
<del> '%l%i33 – next page%/l' +
<add> '%l%i217 – next page%/l' +
<ide> '%l%i23 – hide current post/thread%/l' +
<del> '%l%i34 – expand current thread%/l' +
<add> '%l%i33 – expand current thread%/l' +
<ide> '%l%i22 – quick reply or create thread%/l' +
<ide> '%l%i25t – send post%/l' +
<ide> '%l%i21 – thread (on board) / post (in thread) below%/l' +
<ide> this.tKeys = keys[4];
<ide> doc.addEventListener('keydown', this, true);
<ide> }
<del>KeyNavigation.version = 3;
<add>KeyNavigation.version = 4;
<ide> KeyNavigation.readKeys = function() {
<ide> var tKeys, keys, str = getStored('DESU_keys');
<ide> if(!str) {
<ide> keys[2][14] = tKeys[2][14];
<ide> keys[2][15] = tKeys[2][15];
<ide> keys[2][16] = tKeys[2][16];
<add> case 3:
<add> keys[2][17] = keys[3][3];
<add> keys[3][3] = keys[3].splice(4, 1)[0];
<ide> }
<ide> keys[0] = KeyNavigation.version;
<ide> setStored('DESU_keys', JSON.stringify(keys));
<ide> /* Italic text */ 0xC049 /* = Alt + I */,
<ide> /* Strike text */ 0xC054 /* = Alt + T */,
<ide> /* Spoiler text */ 0xC050 /* = Alt + P */,
<del> /* Code text */ 0xC043 /* = Alt + C */
<add> /* Code text */ 0xC043 /* = Alt + C */,
<add> /* Open next page/picture */ 0x1027 /* = Ctrl + right arrow*/
<ide> ];
<ide> var nonThrKeys = [
<ide> /* One post above */ 0x004D /* = M */,
<ide> /* One post below */ 0x004E /* = N */,
<ide> /* Open thread */ 0x0056 /* = V */,
<del> /* Open next page */ 0x1027 /* = Ctrl + right arrow */,
<ide> /* Expand thread */ 0x0045 /* = E */
<ide> ];
<ide> var thrKeys = [
<ide> }
<ide> loadPages(+Cfg['loadPages']);
<ide> } else if(kc === 0x1B) { // ESC
<add> if($c('de-img-full de-img-center', doc)) {
<add> $c('de-img-full de-img-center', doc).click();
<add> return;
<add> }
<ide> if(this.cPost) {
<ide> this.cPost.unselect();
<ide> this.cPost = null;
<ide> this._scroll(post, false, post.isOp);
<ide> }
<ide> break;
<del> case 4: // Open previous page
<del> if(TNum || pageNum !== aib.firstPage) {
<add> case 4: // Open previous page/picture
<add> if($c('de-img-full de-img-center', doc)) {
<add> $id('de-img-btn-prev').click();
<add> } else if(TNum || pageNum !== aib.firstPage) {
<ide> window.location.pathname = aib.getPageUrl(brd, TNum ? 0 : pageNum - 1);
<ide> }
<ide> break;
<ide> }
<ide> $id('de-btn-code').click();
<ide> break;
<add> case 17: // Open next page/picture
<add> if($c('de-img-full de-img-center', doc)) {
<add> $id('de-img-btn-next').click();
<add> } else if(!TNum && this.lastPage !== aib.lastPage) {
<add> window.location.pathname = aib.getPageUrl(brd, this.lastPage + 1);
<add> }
<add> break;
<ide> case -1:
<ide> if(TNum) {
<ide> idx = this.tKeys.indexOf(kc);
<ide> }
<ide> }
<ide> break;
<del> } else if(idx === 3) { // Open next page
<del> if(this.lastPage !== aib.lastPage) {
<del> window.location.pathname = aib.getPageUrl(brd, this.lastPage + 1);
<del> }
<del> break;
<del> } else if(idx === 4) { // Expand/collapse thread
<add> } else if(idx === 3) { // Expand/collapse thread
<ide> post = this._getFirstVisPost(false, true) || this._getNextVisPost(null, true, false);
<ide> if(post) {
<ide> if(post.thr.loadedOnce && post.thr.omitted === 0) {
<ide> }, 100);
<ide> }
<ide> }, false)
<del> window.addEventListener('keypress', btns._leftRightNavig = function(e) {
<del> if(e.keyCode == 37) {
<del> $pd(e);
<del> $id('de-img-btn-prev').click();
<del> } else if(e.keyCode == 39) {
<del> $pd(e);
<del> $id('de-img-btn-next').click();
<del> }
<del> }, false)
<ide> }
<ide> }
<ide> }
<ide> btns.style.display = 'none';
<ide> window.removeEventListener('mousemove', btns._imgBtnsFade, false);
<ide> btns.removeEventListener('mouseover', btns._imgBtnsOverCheck, false);
<del> window.removeEventListener('keypress', btns._leftRightNavig, false);
<ide> clearInterval(btns._fadeIn); btns._fadeIn = 0;
<ide> clearInterval(btns._fadeOut);
<ide> clearTimeout(btns._fadeOutDelay); |
|
Java | lgpl-2.1 | b21d7502ec26bdfb16835072e36a7e4a0b0c32c8 | 0 | rhusar/wildfly,tomazzupan/wildfly,rhusar/wildfly,rhusar/wildfly,tomazzupan/wildfly,iweiss/wildfly,wildfly/wildfly,iweiss/wildfly,iweiss/wildfly,golovnin/wildfly,xasx/wildfly,jstourac/wildfly,jstourac/wildfly,jstourac/wildfly,99sono/wildfly,tadamski/wildfly,pferraro/wildfly,99sono/wildfly,rhusar/wildfly,xasx/wildfly,golovnin/wildfly,tomazzupan/wildfly,jstourac/wildfly,wildfly/wildfly,pferraro/wildfly,xasx/wildfly,99sono/wildfly,tadamski/wildfly,tadamski/wildfly,wildfly/wildfly,golovnin/wildfly,pferraro/wildfly,wildfly/wildfly,iweiss/wildfly,pferraro/wildfly | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.jboss.as.controller;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceListener;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartException;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import static org.jboss.as.controller.ControllerMessages.MESSAGES;
/**
* Tracks the status of a service installed by an {@link OperationStepHandler}, recording a failure desription
* if the service has a problme starting.
*
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class ServiceVerificationHandler extends AbstractServiceListener<Object> implements ServiceListener<Object>, OperationStepHandler {
private final Set<ServiceController<?>> set = new HashSet<ServiceController<?>>();
private final Set<ServiceController<?>> failed = new HashSet<ServiceController<?>>();
private final Set<ServiceController<?>> problem = new HashSet<ServiceController<?>>();
private int outstanding;
public synchronized void execute(final OperationContext context, final ModelNode operation) {
// Wait for services to reach rest state.
// Additionally...
// Temp workaround to MSC issue of geting STARTING_TO_STARTED notification for parent service before
// getting the PROBLEM_TO_START_REQUESTED notification for dependent services. If there are
// services in PROBLEM state, wait up to 100ms to give them a chance to transition to START_REQUESTED.
long start = 0;
long settleTime = 100;
while (outstanding > 0 || (settleTime > 0 && !problem.isEmpty())) {
try {
long wait = outstanding > 0 ? 0 : settleTime;
wait(wait);
if (outstanding == 0) {
if (start == 0) {
start = System.currentTimeMillis();
} else {
settleTime -= System.currentTimeMillis() - start;
}
} else {
start = 0;
settleTime = 100;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
context.getFailureDescription().set(MESSAGES.operationCancelled());
context.completeStep();
return;
}
}
if (!failed.isEmpty() || !problem.isEmpty()) {
final ModelNode failureDescription = context.getFailureDescription();
ModelNode failedList = null;
for (ServiceController<?> controller : failed) {
if (failedList == null) {
failedList = failureDescription.get(MESSAGES.failedServices());
}
failedList.get(controller.getName().getCanonicalName()).set(getServiceFailureDescription(controller.getStartException()));
}
ModelNode problemList = null;
for (ServiceController<?> controller : problem) {
if (!controller.getImmediateUnavailableDependencies().isEmpty()) {
if (problemList == null) {
problemList = failureDescription.get(MESSAGES.servicesMissingDependencies());
}
final StringBuilder problem = new StringBuilder();
problem.append(controller.getName().getCanonicalName());
for(Iterator<ServiceName> i = controller.getImmediateUnavailableDependencies().iterator(); i.hasNext(); ) {
ServiceName missing = i.next();
problem.append(missing.getCanonicalName());
if(i.hasNext()) {
problem.append(", ");
}
}
problem.append(MESSAGES.servicesMissing(problem));
problemList.add(problem.toString());
}
}
if (context.isRollbackOnRuntimeFailure()) {
context.setRollbackOnly();
}
}
for (ServiceController<?> controller : set) {
controller.removeListener(this);
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
public synchronized void listenerAdded(final ServiceController<?> controller) {
set.add(controller);
if (!controller.getSubstate().isRestState()) {
outstanding++;
}
}
public synchronized void transition(final ServiceController<?> controller, final ServiceController.Transition transition) {
switch (transition) {
case STARTING_to_START_FAILED: {
failed.add(controller);
break;
}
case START_FAILED_to_STARTING: {
failed.remove(controller);
break;
}
case START_REQUESTED_to_PROBLEM: {
problem.add(controller);
break;
}
case PROBLEM_to_START_REQUESTED: {
problem.remove(controller);
break;
}
}
if (transition.leavesRestState()) {
outstanding++;
} else if (transition.entersRestState()) {
if (outstanding-- == 1) {
notifyAll();
}
}
}
private static ModelNode getServiceFailureDescription(final StartException exception) {
final ModelNode result = new ModelNode();
if (exception != null) {
StringBuilder sb = new StringBuilder(exception.toString());
Throwable cause = exception.getCause();
while (cause != null) {
sb.append("\n Caused by: ");
sb.append(cause.toString());
cause = cause.getCause();
}
result.set(sb.toString());
}
return result;
}
}
| controller/src/main/java/org/jboss/as/controller/ServiceVerificationHandler.java | /*
* JBoss, Home of Professional Open Source.
* Copyright 2011, 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.jboss.as.controller;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.AbstractServiceListener;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceListener;
import org.jboss.msc.service.ServiceName;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import static org.jboss.as.controller.ControllerMessages.MESSAGES;
/**
* @author <a href="mailto:[email protected]">David M. Lloyd</a>
*/
public final class ServiceVerificationHandler extends AbstractServiceListener<Object> implements ServiceListener<Object>, OperationStepHandler {
private final Set<ServiceController<?>> set = new HashSet<ServiceController<?>>();
private final Set<ServiceController<?>> failed = new HashSet<ServiceController<?>>();
private final Set<ServiceController<?>> problem = new HashSet<ServiceController<?>>();
private int outstanding;
public synchronized void execute(final OperationContext context, final ModelNode operation) {
// Wait for services to reach rest state.
// Additionally...
// Temp workaround to MSC issue of geting STARTING_TO_STARTED notification for parent service before
// getting the PROBLEM_TO_START_REQUESTED notification for dependent services. If there are
// services in PROBLEM state, wait up to 100ms to give them a chance to transition to START_REQUESTED.
long start = 0;
long settleTime = 100;
while (outstanding > 0 || (settleTime > 0 && !problem.isEmpty())) {
try {
long wait = outstanding > 0 ? 0 : settleTime;
wait(wait);
if (outstanding == 0) {
if (start == 0) {
start = System.currentTimeMillis();
} else {
settleTime -= System.currentTimeMillis() - start;
}
} else {
start = 0;
settleTime = 100;
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
context.getFailureDescription().set(MESSAGES.operationCancelled());
context.completeStep();
return;
}
}
if (!failed.isEmpty() || !problem.isEmpty()) {
final ModelNode failureDescription = context.getFailureDescription();
ModelNode failedList = null;
for (ServiceController<?> controller : failed) {
if (failedList == null) {
failedList = failureDescription.get(MESSAGES.failedServices());
}
failedList.get(controller.getName().getCanonicalName()).set(controller.getStartException().toString());
}
ModelNode problemList = null;
for (ServiceController<?> controller : problem) {
if (!controller.getImmediateUnavailableDependencies().isEmpty()) {
if (problemList == null) {
problemList = failureDescription.get(MESSAGES.servicesMissingDependencies());
}
final StringBuilder problem = new StringBuilder();
problem.append(controller.getName().getCanonicalName());
for(Iterator<ServiceName> i = controller.getImmediateUnavailableDependencies().iterator(); i.hasNext(); ) {
ServiceName missing = i.next();
problem.append(missing.getCanonicalName());
if(i.hasNext()) {
problem.append(", ");
}
}
problem.append(MESSAGES.servicesMissing(problem));
problemList.add(problem.toString());
}
}
if (context.isRollbackOnRuntimeFailure()) {
context.setRollbackOnly();
}
}
for (ServiceController<?> controller : set) {
controller.removeListener(this);
}
context.completeStep(OperationContext.RollbackHandler.NOOP_ROLLBACK_HANDLER);
}
public synchronized void listenerAdded(final ServiceController<?> controller) {
set.add(controller);
if (!controller.getSubstate().isRestState()) {
outstanding++;
}
}
public synchronized void transition(final ServiceController<?> controller, final ServiceController.Transition transition) {
switch (transition) {
case STARTING_to_START_FAILED: {
failed.add(controller);
break;
}
case START_FAILED_to_STARTING: {
failed.remove(controller);
break;
}
case START_REQUESTED_to_PROBLEM: {
problem.add(controller);
break;
}
case PROBLEM_to_START_REQUESTED: {
problem.remove(controller);
break;
}
}
if (transition.leavesRestState()) {
outstanding++;
} else if (transition.entersRestState()) {
if (outstanding-- == 1) {
notifyAll();
}
}
}
}
| Include exception cause details in SVH failure descriptions
| controller/src/main/java/org/jboss/as/controller/ServiceVerificationHandler.java | Include exception cause details in SVH failure descriptions | <ide><path>ontroller/src/main/java/org/jboss/as/controller/ServiceVerificationHandler.java
<ide> import org.jboss.msc.service.ServiceController;
<ide> import org.jboss.msc.service.ServiceListener;
<ide> import org.jboss.msc.service.ServiceName;
<add>import org.jboss.msc.service.StartException;
<ide>
<ide> import java.util.HashSet;
<ide> import java.util.Iterator;
<ide> import static org.jboss.as.controller.ControllerMessages.MESSAGES;
<ide>
<ide> /**
<add> * Tracks the status of a service installed by an {@link OperationStepHandler}, recording a failure desription
<add> * if the service has a problme starting.
<add> *
<ide> * @author <a href="mailto:[email protected]">David M. Lloyd</a>
<ide> */
<ide> public final class ServiceVerificationHandler extends AbstractServiceListener<Object> implements ServiceListener<Object>, OperationStepHandler {
<ide> if (failedList == null) {
<ide> failedList = failureDescription.get(MESSAGES.failedServices());
<ide> }
<del> failedList.get(controller.getName().getCanonicalName()).set(controller.getStartException().toString());
<add> failedList.get(controller.getName().getCanonicalName()).set(getServiceFailureDescription(controller.getStartException()));
<ide> }
<ide> ModelNode problemList = null;
<ide> for (ServiceController<?> controller : problem) {
<ide> }
<ide> }
<ide> }
<add>
<add> private static ModelNode getServiceFailureDescription(final StartException exception) {
<add> final ModelNode result = new ModelNode();
<add> if (exception != null) {
<add> StringBuilder sb = new StringBuilder(exception.toString());
<add> Throwable cause = exception.getCause();
<add> while (cause != null) {
<add> sb.append("\n Caused by: ");
<add> sb.append(cause.toString());
<add> cause = cause.getCause();
<add> }
<add> result.set(sb.toString());
<add> }
<add> return result;
<add> }
<ide> } |
|
JavaScript | mit | eb9947b5102149b64f64e109b90c17f448b3732a | 0 | mccxiv/xivmap,mccxiv/xivmap | var fs = require('fs');
var del = require('del');
var gulp = require('gulp');
var escape = require('escape-html');
var ghPages = require('gh-pages');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var gulpif = require('gulp-if');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var replace = require('gulp-replace');
var runSequence = require('run-sequence');
// ==================================================================
// For publishing to GitHub Pages
// ==================================================================
gulp.task('make-gh-pages', function(cb) {
runSequence('clean-gh-pages', 'prep-files-gh-pages', 'fix-references-gh-pages', cb);
});
gulp.task('publish-gh-pages', function(cb) {
runSequence('make-gh-pages', 'deploy-gh-pages', 'clean-gh-pages', cb);
});
gulp.task('clean-gh-pages', function() {
return del('.gh-pages/');
});
gulp.task('prep-files-gh-pages', function() {
return gulp.src(['demo/**', 'xivmap.css', 'xivmap.js', 'xivmap-docked.css'])
.pipe(gulp.dest('.gh-pages/'));
});
gulp.task('fix-references-gh-pages', function() {
return gulp.src('.gh-pages/index.html')
.pipe(replace('href="../xivmap.css"', 'href="xivmap.css"'))
.pipe(replace('href="../xivmap-docked.css"', 'href="xivmap-docked.css"'))
.pipe(replace('src="../xivmap.js"', 'src="xivmap.js"'))
.pipe(gulp.dest('.gh-pages/'));
});
gulp.task('deploy-gh-pages', function(cb) {
ghPages.publish('.gh-pages/', cb);
});
// ==================================================================
// For publishing a downloadable version including documentation
// ==================================================================
gulp.task('make-dist', function(cb) {
runSequence(
'clean',
['copy-demo', 'copy-xivmap', 'copy-docs', 'copy-ty-note'],
['minify-js', 'minify-css', 'minify-docked-css'],
['fix-references', 'make-standalone-demo'],
cb
);
});
gulp.task('make-standalone-demo', function(cb) {
runSequence(['copy-standalone-demo', 'copy-xivmap-standalone-demo'], 'fix-standalone-demo-references', cb);
});
gulp.task('copy-standalone-demo', function() {
return gulp.src('demo/**')
.pipe(gulp.dest('dist/demo-standalone/'));
});
gulp.task('copy-xivmap-standalone-demo', function() {
gulp.src('dist/packaged/xivmap/**')
.pipe(gulp.dest('dist/demo-standalone/xivmap/'))
});
gulp.task('fix-standalone-demo-references', function() {
return gulp.src('dist/demo-standalone/index.html')
.pipe(replace('href="../xivmap.css"', 'href="xivmap/xivmap.min.css"'))
.pipe(replace('href="../xivmap-docked.css"', 'href="xivmap/xivmap-docked.min.css"'))
.pipe(replace('src="../xivmap.js"', 'src="xivmap/xivmap.min.js"'))
.pipe(gulp.dest('dist/demo-standalone/'));
});
gulp.task('clean', function() {
return del('dist/');
});
gulp.task('copy-demo', function() {
return gulp.src('demo/**')
.pipe(gulp.dest('dist/packaged/demo/'));
});
gulp.task('copy-xivmap', function() {
return gulp.src(['xivmap.js', 'xivmap.css', 'xivmap-docked.css'])
.pipe(gulp.dest('dist/packaged/xivmap/'));
});
gulp.task('copy-docs', function() {
var readme = escape(fs.readFileSync('README.md', {encoding: 'utf8'}));
readme = readme.replace('', '');
readme = readme.split('# License')[0];
var assets = useref.assets({noconcat: true});
return gulp.src('src-docs/MANUAL.html')
.pipe(replace('{{markdown}}', readme))
.pipe(assets)
.pipe(gulpif('*.js', concat('assets/docs.min.js')))
.pipe(gulpif('*.js', uglify({output: {max_line_len: 200}})))
.pipe(gulpif('*.css', concat('assets/docs.min.css')))
.pipe(gulpif('*.css', minifyCss()))
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist/packaged/documentation'));
});
gulp.task('copy-ty-note', function() {
return gulp.src('marketing/thank-you-note/thanks.html')
.pipe(gulp.dest('dist/packaged/'));
});
gulp.task('minify-js', function() {
return gulp.src('dist/packaged/xivmap/xivmap.js')
.pipe(rename('xivmap.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/packaged/xivmap/'));
});
gulp.task('minify-css', function() {
gulp.src('dist/packaged/xivmap/xivmap.css')
.pipe(rename('xivmap.min.css'))
.pipe(minifyCss())
.pipe(gulp.dest('dist/packaged/xivmap/'));
});
gulp.task('minify-docked-css', function() {
return gulp.src('dist/packaged/xivmap/xivmap-docked.css')
.pipe(rename('xivmap-docked.min.css'))
.pipe(minifyCss())
.pipe(gulp.dest('dist/packaged/xivmap/'));
});
gulp.task('fix-references', function() {
return gulp.src('dist/packaged/demo/index.html')
.pipe(replace('href="../xivmap.css"', 'href="../xivmap/xivmap.min.css"'))
.pipe(replace('href="../xivmap-docked.css"', 'href="../xivmap/xivmap-docked.min.css"'))
.pipe(replace('src="../xivmap.js"', 'src="../xivmap/xivmap.min.js"'))
.pipe(gulp.dest('dist/packaged/demo/'));
});
| gulpfile.js | var fs = require('fs');
var del = require('del');
var gulp = require('gulp');
var escape = require('escape-html');
var ghPages = require('gh-pages');
var useref = require('gulp-useref');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var gulpif = require('gulp-if');
var concat = require('gulp-concat');
var minifyCss = require('gulp-minify-css');
var replace = require('gulp-replace');
var runSequence = require('run-sequence');
// ==================================================================
// For publishing to GitHub Pages
// ==================================================================
gulp.task('make-gh-pages', function(cb) {
runSequence('clean-gh-pages', 'prep-files-gh-pages', 'fix-references-gh-pages', cb);
});
gulp.task('publish-gh-pages', function(cb) {
runSequence('make-gh-pages', 'deploy-gh-pages', 'clean-gh-pages', cb);
});
gulp.task('clean-gh-pages', function() {
return del('.gh-pages/');
});
gulp.task('prep-files-gh-pages', function() {
return gulp.src(['demo/**', 'xivmap.css', 'xivmap.js', 'xivmap-docked.css'])
.pipe(gulp.dest('.gh-pages/'));
});
gulp.task('fix-references-gh-pages', function() {
return gulp.src('.gh-pages/index.html')
.pipe(replace('href="../xivmap.css"', 'href="xivmap.css"'))
.pipe(replace('href="../xivmap-docked.css"', 'href="xivmap-docked.css"'))
.pipe(replace('src="../xivmap.js"', 'src="xivmap.js"'))
.pipe(gulp.dest('.gh-pages/'));
});
gulp.task('deploy-gh-pages', function(cb) {
ghPages.publish('.gh-pages/', cb);
});
// ==================================================================
// For publishing a downloadable version including documentation
// ==================================================================
gulp.task('make-dist', function(cb) {
runSequence('clean', ['copy-demo', 'copy-xivmap', 'copy-docs', 'copy-ty-note'], ['minify-js', 'minify-css', 'minify-docked-css'], 'fix-references', cb);
});
gulp.task('clean', function() {
return del('dist/');
});
gulp.task('copy-demo', function() {
return gulp.src('demo/**')
.pipe(gulp.dest('dist/demo/'));
});
gulp.task('copy-xivmap', function() {
return gulp.src(['xivmap.js', 'xivmap.css', 'xivmap-docked.css'])
.pipe(gulp.dest('dist/xivmap/'));
});
gulp.task('copy-docs', function() {
var readme = escape(fs.readFileSync('README.md', {encoding: 'utf8'}));
readme = readme.replace('', '');
readme = readme.split('# License')[0];
var assets = useref.assets({noconcat: true});
return gulp.src('src-docs/MANUAL.html')
.pipe(replace('{{markdown}}', readme))
.pipe(assets)
.pipe(gulpif('*.js', concat('assets/docs.min.js')))
.pipe(gulpif('*.js', uglify({output: {max_line_len: 200}})))
.pipe(gulpif('*.css', concat('assets/docs.min.css')))
.pipe(gulpif('*.css', minifyCss()))
.pipe(assets.restore())
.pipe(useref())
.pipe(gulp.dest('dist/documentation'));
});
gulp.task('copy-ty-note', function() {
return gulp.src('marketing/thank-you-note/thanks.html')
.pipe(gulp.dest('dist/'));
});
gulp.task('minify-js', function() {
return gulp.src('dist/xivmap/xivmap.js')
.pipe(rename('xivmap.min.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/xivmap/'));
});
gulp.task('minify-css', function() {
gulp.src('dist/xivmap/xivmap.css')
.pipe(rename('xivmap.min.css'))
.pipe(minifyCss())
.pipe(gulp.dest('dist/xivmap/'));
});
gulp.task('minify-docked-css', function() {
return gulp.src('dist/xivmap/xivmap-docked.css')
.pipe(rename('xivmap-docked.min.css'))
.pipe(minifyCss())
.pipe(gulp.dest('dist/xivmap/'));
});
gulp.task('fix-references', function() {
return gulp.src('dist/demo/index.html')
.pipe(replace('href="../xivmap.css"', 'href="../xivmap/xivmap.min.css"'))
.pipe(replace('href="../xivmap-docked.css"', 'href="../xivmap/xivmap-docked.min.css"'))
.pipe(replace('src="../xivmap.js"', 'src="../xivmap/xivmap.min.js"'))
.pipe(gulp.dest('dist/demo/'));
});
| Add standalone demo to dist
| gulpfile.js | Add standalone demo to dist | <ide><path>ulpfile.js
<ide> // For publishing a downloadable version including documentation
<ide> // ==================================================================
<ide> gulp.task('make-dist', function(cb) {
<del> runSequence('clean', ['copy-demo', 'copy-xivmap', 'copy-docs', 'copy-ty-note'], ['minify-js', 'minify-css', 'minify-docked-css'], 'fix-references', cb);
<add> runSequence(
<add> 'clean',
<add> ['copy-demo', 'copy-xivmap', 'copy-docs', 'copy-ty-note'],
<add> ['minify-js', 'minify-css', 'minify-docked-css'],
<add> ['fix-references', 'make-standalone-demo'],
<add> cb
<add> );
<add>});
<add>
<add>gulp.task('make-standalone-demo', function(cb) {
<add> runSequence(['copy-standalone-demo', 'copy-xivmap-standalone-demo'], 'fix-standalone-demo-references', cb);
<add>});
<add>
<add>gulp.task('copy-standalone-demo', function() {
<add> return gulp.src('demo/**')
<add> .pipe(gulp.dest('dist/demo-standalone/'));
<add>});
<add>
<add>gulp.task('copy-xivmap-standalone-demo', function() {
<add> gulp.src('dist/packaged/xivmap/**')
<add> .pipe(gulp.dest('dist/demo-standalone/xivmap/'))
<add>});
<add>
<add>gulp.task('fix-standalone-demo-references', function() {
<add> return gulp.src('dist/demo-standalone/index.html')
<add> .pipe(replace('href="../xivmap.css"', 'href="xivmap/xivmap.min.css"'))
<add> .pipe(replace('href="../xivmap-docked.css"', 'href="xivmap/xivmap-docked.min.css"'))
<add> .pipe(replace('src="../xivmap.js"', 'src="xivmap/xivmap.min.js"'))
<add> .pipe(gulp.dest('dist/demo-standalone/'));
<ide> });
<ide>
<ide> gulp.task('clean', function() {
<ide>
<ide> gulp.task('copy-demo', function() {
<ide> return gulp.src('demo/**')
<del> .pipe(gulp.dest('dist/demo/'));
<add> .pipe(gulp.dest('dist/packaged/demo/'));
<ide> });
<ide>
<ide> gulp.task('copy-xivmap', function() {
<ide> return gulp.src(['xivmap.js', 'xivmap.css', 'xivmap-docked.css'])
<del> .pipe(gulp.dest('dist/xivmap/'));
<add> .pipe(gulp.dest('dist/packaged/xivmap/'));
<ide> });
<ide>
<ide> gulp.task('copy-docs', function() {
<ide> .pipe(gulpif('*.css', minifyCss()))
<ide> .pipe(assets.restore())
<ide> .pipe(useref())
<del> .pipe(gulp.dest('dist/documentation'));
<add> .pipe(gulp.dest('dist/packaged/documentation'));
<ide> });
<ide>
<ide> gulp.task('copy-ty-note', function() {
<ide> return gulp.src('marketing/thank-you-note/thanks.html')
<del> .pipe(gulp.dest('dist/'));
<add> .pipe(gulp.dest('dist/packaged/'));
<ide> });
<ide>
<ide> gulp.task('minify-js', function() {
<del> return gulp.src('dist/xivmap/xivmap.js')
<add> return gulp.src('dist/packaged/xivmap/xivmap.js')
<ide> .pipe(rename('xivmap.min.js'))
<ide> .pipe(uglify())
<del> .pipe(gulp.dest('dist/xivmap/'));
<add> .pipe(gulp.dest('dist/packaged/xivmap/'));
<ide> });
<ide>
<ide> gulp.task('minify-css', function() {
<del> gulp.src('dist/xivmap/xivmap.css')
<add> gulp.src('dist/packaged/xivmap/xivmap.css')
<ide> .pipe(rename('xivmap.min.css'))
<ide> .pipe(minifyCss())
<del> .pipe(gulp.dest('dist/xivmap/'));
<add> .pipe(gulp.dest('dist/packaged/xivmap/'));
<ide> });
<ide>
<ide> gulp.task('minify-docked-css', function() {
<del> return gulp.src('dist/xivmap/xivmap-docked.css')
<add> return gulp.src('dist/packaged/xivmap/xivmap-docked.css')
<ide> .pipe(rename('xivmap-docked.min.css'))
<ide> .pipe(minifyCss())
<del> .pipe(gulp.dest('dist/xivmap/'));
<add> .pipe(gulp.dest('dist/packaged/xivmap/'));
<ide> });
<ide>
<ide> gulp.task('fix-references', function() {
<del> return gulp.src('dist/demo/index.html')
<add> return gulp.src('dist/packaged/demo/index.html')
<ide> .pipe(replace('href="../xivmap.css"', 'href="../xivmap/xivmap.min.css"'))
<ide> .pipe(replace('href="../xivmap-docked.css"', 'href="../xivmap/xivmap-docked.min.css"'))
<ide> .pipe(replace('src="../xivmap.js"', 'src="../xivmap/xivmap.min.js"'))
<del> .pipe(gulp.dest('dist/demo/'));
<add> .pipe(gulp.dest('dist/packaged/demo/'));
<ide> }); |
|
Java | apache-2.0 | a773873b3b4bc44d6d13470fe619d72180603bcb | 0 | the-diamond-dogs-group-oss/android-http,SphericalElephant/android-http,SphericalElephant/android-http,the-diamond-dogs-group-oss/android-http | /*
* Copyright (C) 2012 the diamond:dogs|group
*
* 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 at.diamonddogs.example.http.activity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.ListActivity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import at.diamonddogs.data.dataobjects.WebRequest;
import at.diamonddogs.example.http.R;
import at.diamonddogs.example.http.processor.RssProcessor;
import at.diamonddogs.service.net.HttpServiceAssister;
import at.diamonddogs.service.processor.ServiceProcessor;
/**
* A simple caching example
*/
public class CachingExampleActivity extends ListActivity {
private static final Logger LOGGER = LoggerFactory.getLogger(CachingExampleActivity.class.getSimpleName());
private static final Uri RSS = Uri.parse("http://rss.golem.de/rss.php?tp=inet&feed=RSS2.0");
private HttpServiceAssister assister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cachingexampleactivity);
assister = new HttpServiceAssister(this);
assister.runWebRequest(new RssHandler(), createGetRssRequest(), new RssProcessor());
}
/**
* {@inheritDoc}
*/
@Override
protected void onResume() {
super.onResume();
assister.bindService();
}
/**
* {@inheritDoc}
*/
@Override
protected void onPause() {
super.onPause();
assister.unbindService();
}
private WebRequest createGetRssRequest() {
WebRequest wr = new WebRequest();
wr.setUrl(RSS);
wr.setProcessorId(RssProcessor.ID);
// This is the important part, telling HttpService how long a WebRequest
// will be saved. Since RssProcessor extends XMLProcessor, which extends
// DataProcessor, the WebRequest's data will be cached automatically,
// provided that cacheTime is not CACHE_NO.
wr.setCacheTime(5000);
// Enables offline caching. usually, cache data is deleted on retrieval
// if it has expired even if the device is not online. If this flag is
// set to true, cache data will not be removed if it has expired as long
// as the device was offline during the request
wr.setUseOfflineCache(true);
return wr;
}
private final class RssHandler extends Handler {
/**
* {@inheritDoc}
*/
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == RssProcessor.ID) {
if (msg.arg1 == ServiceProcessor.RETURN_MESSAGE_OK) {
String[] items = (String[]) msg.obj;
setListAdapter(new ArrayAdapter<String>(CachingExampleActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, items));
Toast.makeText(CachingExampleActivity.this,
"From cache -> " + msg.getData().getSerializable(ServiceProcessor.BUNDLE_EXTRA_MESSAGE_FROMCACHE),
Toast.LENGTH_SHORT).show();
} else {
LOGGER.error("An error has occured.", msg.getData().getSerializable(ServiceProcessor.BUNDLE_EXTRA_MESSAGE_THROWABLE));
}
}
}
}
}
| example/src/at/diamonddogs/example/http/activity/CachingExampleActivity.java | /*
* Copyright (C) 2012 the diamond:dogs|group
*
* 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 at.diamonddogs.example.http.activity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import android.app.ListActivity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ArrayAdapter;
import android.widget.Toast;
import at.diamonddogs.data.dataobjects.CacheInformation;
import at.diamonddogs.data.dataobjects.WebRequest;
import at.diamonddogs.example.http.R;
import at.diamonddogs.example.http.processor.RssProcessor;
import at.diamonddogs.service.net.HttpServiceAssister;
import at.diamonddogs.service.processor.ServiceProcessor;
/**
* A simple caching example
*/
public class CachingExampleActivity extends ListActivity {
private static final Logger LOGGER = LoggerFactory.getLogger(CachingExampleActivity.class.getSimpleName());
private static final Uri RSS = Uri.parse("http://rss.golem.de/rss.php?tp=inet&feed=RSS2.0");
private HttpServiceAssister assister;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cachingexampleactivity);
assister = new HttpServiceAssister(this);
assister.runWebRequest(new RssHandler(), createGetRssRequest(), new RssProcessor());
}
/**
* {@inheritDoc}
*/
@Override
protected void onResume() {
super.onResume();
assister.bindService();
}
/**
* {@inheritDoc}
*/
@Override
protected void onPause() {
super.onPause();
assister.unbindService();
}
private WebRequest createGetRssRequest() {
WebRequest wr = new WebRequest();
wr.setUrl(RSS);
wr.setProcessorId(RssProcessor.ID);
// this is the important part, telling HttpService how long a WebRequest
// will be saved. Since RssProcessor extends XMLProcessor, which extends
// DataProcessor, the WebRequest's data will be cached automatically,
// provided that cacheTime is not CACHE_NO.
wr.setCacheTime(CacheInformation.CACHE_1H);
return wr;
}
private final class RssHandler extends Handler {
/**
* {@inheritDoc}
*/
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (msg.what == RssProcessor.ID) {
if (msg.arg1 == ServiceProcessor.RETURN_MESSAGE_OK) {
String[] items = (String[]) msg.obj;
setListAdapter(new ArrayAdapter<String>(CachingExampleActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, items));
Toast.makeText(CachingExampleActivity.this,
"From cache -> " + msg.getData().getSerializable(ServiceProcessor.BUNDLE_EXTRA_MESSAGE_FROMCACHE),
Toast.LENGTH_SHORT).show();
} else {
LOGGER.error("An error has occured.", msg.getData().getSerializable(ServiceProcessor.BUNDLE_EXTRA_MESSAGE_THROWABLE));
}
}
}
}
}
| [ADD] useOfflineCache example
| example/src/at/diamonddogs/example/http/activity/CachingExampleActivity.java | [ADD] useOfflineCache example | <ide><path>xample/src/at/diamonddogs/example/http/activity/CachingExampleActivity.java
<ide> import android.os.Message;
<ide> import android.widget.ArrayAdapter;
<ide> import android.widget.Toast;
<del>import at.diamonddogs.data.dataobjects.CacheInformation;
<ide> import at.diamonddogs.data.dataobjects.WebRequest;
<ide> import at.diamonddogs.example.http.R;
<ide> import at.diamonddogs.example.http.processor.RssProcessor;
<ide> wr.setUrl(RSS);
<ide> wr.setProcessorId(RssProcessor.ID);
<ide>
<del> // this is the important part, telling HttpService how long a WebRequest
<add> // This is the important part, telling HttpService how long a WebRequest
<ide> // will be saved. Since RssProcessor extends XMLProcessor, which extends
<ide> // DataProcessor, the WebRequest's data will be cached automatically,
<ide> // provided that cacheTime is not CACHE_NO.
<del> wr.setCacheTime(CacheInformation.CACHE_1H);
<add> wr.setCacheTime(5000);
<add>
<add> // Enables offline caching. usually, cache data is deleted on retrieval
<add> // if it has expired even if the device is not online. If this flag is
<add> // set to true, cache data will not be removed if it has expired as long
<add> // as the device was offline during the request
<add> wr.setUseOfflineCache(true);
<ide> return wr;
<ide> }
<ide> |
|
JavaScript | mit | 835aefff52e94376d6c112212e089319aad6dedc | 0 | darryd/vanslam_live,darryd/vanslam_live,darryd/vanslam_live | var NUM_COLUMNS = 12;
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_new(performance) {
var div = document.createElement("div");
div.className = "performance_div";
div.id = makeid(20);
var name = performance.name;
div.comm = comm_new(div, performance.name); //Create comm object for communictiation with the server.
performance.comm = div.comm;
performance.add_notify_rank(p_div_rank_updated, div);
performance.add_notify_score(p_div_score_updated, div);
var row = document.createElement("div");
row.className = 'row';
var column = document.createElement('div');
column.className = 'small-11 columns';
column.innerHTML = "<h3> <span style='color:purple'>" + name + "</span> </h3>";
row.appendChild(column);
var column = document.createElement("div");
column.className = 'small-2 columns';
var remove_me = make_remove_me_div(div.id);
column.appendChild(remove_me);
row.appendChild(column);
div.appendChild(row);
div.column_length = {Judges: slam.num_judges, Time: 2, Penalty: 1};
div.titles = ["Judges", "Time", "Penalty"];
p_div_build_columns_hash(div);
div.performance = performance;
p_div_build_titles_row(div);
p_div_build_sub_titles(div);
p_div_build_data_row(div);
p_div_build_footers(div);
div.style.backgroundColor = '#F4F4F4';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px';
row = document.createElement("div");
row.className = "row";
/*
column = document.createElement("div");
column.className = "small-12 columns";
column.style.minHeight = "15px"; //http://stackoverflow.com/a/25431669
row.appendChild(column);
div.appendChild(row);
*/
row = document.createElement("div");
row.className = "row";
column = document.createElement("div");
column.className = "small-2 medium-1 columns";
column.style.color = "blue";
column.innerHTML = "<p> Score: </p>";
row.appendChild(column);
div.score_column = document.createElement("div");
div.score_column.className = "small-2 medium-1 columns";
div.score_column.innerHTML = "";
row.appendChild(div.score_column);
if (div.performance.prev != null) {
column = document.createElement("div");
column.className = "small-2 medium-1 columns";
column.style.color = "blue";
column.innerHTML = "<p> Total: </p>";
row.appendChild(column);
div.cumulative_column = document.createElement("div");
div.cumulative_column.className = "small-2 medium-1 columns";
div.cumulative_column.innerHTML = "";
row.appendChild(div.cumulative_column);
}
column = document.createElement("div");
column.className = "small-2 medium-1 columns";
column.style.color = "blue";
column.innerHTML = "<p> Rank: </p>";
row.appendChild(column);
div.rank_column = document.createElement("div");
div.rank_column.className = "small-2 medium-1 columns end";
div.rank_column.innerHTML = "";
row.appendChild(div.rank_column);
div.appendChild(row);
row = document.createElement("div");
row.className = "row";
div.tied_with = document.createElement("div");
div.tied_with.className = "small-12 columns";
row.appendChild(div.tied_with);
div.appendChild(row);
return div;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_columns_hash(div) {
var num_columns = 12;
var columns = div.columns = {};
var titles = div.titles;
var remaining_columns = num_columns;
for (var i=0; i<titles.length; i++) {
columns[titles[i]] = remaining_columns;
remaining_columns -= div.column_length[titles[i]];
if (i > 0) {
for (j=0; j<i; j++) {
columns[titles[j]] = div.column_length[titles[j]];
}
}
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_titles_row(div) {
var row = document.createElement("div");
row.className = "row";
for (var i=0; i<div.titles.length; i++) {
var column = document.createElement("div");
column.className = "small-" + div.columns[div.titles[i]] + " columns";
column.innerHTML = "<span style='color:blue;'>" + div.titles[i] + "</span>";
row.appendChild(column);
}
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_sub_titles(div) {
var num_columns = 12;
var row = document.createElement("div");
row.className = "row";
// Add Judges
var column;
for (var i=0; i<slam.num_judges; i++) {
column = document.createElement("div");
column.className = "small-1 columns";
column.innerHTML = "<span style='color:purple'>" + (i + 1) + "</span>";
row.appendChild(column);
}
// Add Time
column = document.createElement("div");
column.className = "small-1 columns";
column.innerHTML = "<span style='color:brown'>m</span>";
row.appendChild(column);
column = document.createElement("div");
column.className = "small-1 columns end";
column.innerHTML = "<span style='color:brown'>s</span>";
row.appendChild(column);
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_setup_indexes(div) {
div.data_columns = [];
div.indexes = {};
var i = slam.num_judges;
div.indexes.minutes_i = i++;
div.indexes.seconds_i = i++;
div.indexes.penalty_i = i++;
div.indexes.score_i = i++;
div.indexes.subscore_i = i++;
div.indexes.rank = i;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function format_value(value) {
// Return a value that has at most one decimal place.
return Math.round(value * 100) / 100;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_update_data_column(div, index, value) {
div.data_columns[index].innerHTML = format_value(value);
// Why bother displaying subscore when it equals score?
if (div.performance.prev == null)
div.data_columns[div.indexes.subscore_i].innerHTML = '';
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_score_updated(div, performance) {
//p_div_update_data_column(div, div.indexes.score_i, performance.score);
//p_div_update_data_column(div, div.indexes.subscore_i, performance.subscore);
div.score_column.innerHTML = format_value(performance.score);
if (div.performance.prev != null)
div.cumulative_column.innerHTML = format_value(performance.subscore);
var min_i = performance.min_judge;
var max_i = performance.max_judge;
if (slam.do_not_include_min_and_max_scores) {
for (var i=0; i<slam.num_judges; i++) {
div.footers[i].innerHTML = "<p></p>";
div.data_columns[i].style.color = "black";
}
var min_max_color = "darkviolet";
var low_str = "<p class='visible-for-small-only'>L</p><p class='visible-for-medium-up'>LOW</p>";
var high_str = "<p class='visible-for-small-only'>H</p><p class='visible-for-medium-up'>HIGH</p>";
div.data_columns[min_i].style.color = min_max_color;
div.data_columns[max_i].style.color = min_max_color;
div.footers[min_i].innerHTML = low_str;
div.footers[min_i].style.color = min_max_color;
div.footers[max_i].innerHTML = high_str;
div.footers[max_i].style.color = min_max_color;
}
// Time Penalty
var time_penalty = performance.calculate_time_penalty() * -1;
if (time_penalty != 0){
div.footers[slam.num_judges].innerHTML = "P:";
div.footers[slam.num_judges].style.color = "green";
div.footers[slam.num_judges + 1].innerHTML = time_penalty;
div.footers[slam.num_judges + 1].style.color = "green";
}
else {
div.footers[slam.num_judges].innerHTML = "<p></p>";
div.footers[slam.num_judges + 1].innerHTML = "<p></p>";
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_rank_updated (div, performance) {
div.rank_column.innerHTML = performance.rank;
div.tied_with.innerHTML = performance.is_tied ? "<p> <span style='color:blue'> Tied With: </span> " + performance.names_tied_with.join() + "</p>" : "";
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_get_time(div) {
var minutes = parse_int_or_return_zero(div.data_columns[div.indexes.minutes_i].value);
var seconds = parse_int_or_return_zero(div.data_columns[div.indexes.seconds_i].value);
return {minutes: minutes, seconds: seconds};
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function is_score_entered_fully(score) {
if (score == "10")
return false;
if (score == "100")
return true;
if (score.length == 2)
return true;
return false;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_input_onkeyup(inputs, input) {
input.value = input.value.replace('\.', '');
var index = parseInt(input.getAttribute('data-index'));
if (is_score_entered_fully(input.value)) {
if (index < inputs.length - 1) {
input.removeAttribute('onkeyup');
next_input = inputs[index + 1];
next_input.focus();
}
else {
$(input).trigger("change");
input.blur();
}
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_input_entered(input) {
if (!login_info.is_logged_in)
return;
var i = parseInt(input.getAttribute('data-index'));
var div = input.div;
var performance = div.performance;
var value = parse_float_or_return_zero(input.value);
switch (i)
{
case div.indexes.minutes_i:
case div.indexes.seconds_i:
var time = p_div_get_time(div);
performance.set_time(time.minutes, time.seconds);
set_time_request(performance.comm, time.minutes, time.seconds);
break;
case div.indexes.penalty_i:
performance.set_penalty(value);
set_penalty_request(performance.comm, value);
break;
default:
if (i >= 0 && i < div.indexes.minutes_i) {
input.value = input.value.replace('\.', '');
var value = input.value / 10;
input.value = value;
performance.judge(i, value);
judge_request(performance.comm, i, value);
}
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_set_score(p_div, judge_i, value) {
p_div.data_columns[judge_i].value = value;
p_div.data_columns[judge_i].removeAttribute('onkeyup');
p_div.performance.judge(judge_i, value);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_set_time(p_div, minutes, seconds) {
var i = p_div.indexes.minutes_i;
p_div.data_columns[i].value = minutes;
p_div.data_columns[++i].value = seconds;
p_div.performance.set_time(minutes, seconds);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_set_penalty(p_div, value) {
var i = p_div.indexes.penalty_i;
p_div.data_columns[i].value = value;
p_div.performance.set_penalty(value);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_data_row(div) {
p_div_setup_indexes(div);
var row = document.createElement("div");
row.className = "row";
var num_columns = slam.num_judges + 3; // Judges + Minutes + Seconds + Penalty
var i;
div.judge_inputs = [];
for (i=0; i<num_columns; i++) {
var column = document.createElement("div");
column.className = "small-1 columns";
var input = document.createElement("input");
input.inputs = div.judge_inputs;
input.className = "scorekeeper_input";
// This (the if statement to follow) is to faciliate automatic refocusing of the next judge
// after two digit are entered for the score (exception 10 and 100)
// last input will be Minutes so that the last judge
// (the one that comes before Minutes) will have another input to
// focus on after the score has been entered.
if (i <= slam.num_judges)
div.judge_inputs.push(input);
input.div = div;
input.className = "scorekeeper_input";
input.setAttribute('size', 4);
input.setAttribute('onchange', 'p_div_input_entered(this)');
if (i < slam.num_judges)
// Only do this for inputs that are judges
input.setAttribute('onkeyup', 'p_div_input_onkeyup(this.inputs, this)');
input.setAttribute('data-index', i);
input.type = "number";
input.style.width = "60px";
input.setAttribute('data-max-width', '60');
if (!login_info.is_logged_in)
input.setAttribute('readonly', null);
column.appendChild(input);
div.data_columns.push(input);
row.appendChild(column);
}
num_columns = 12;
for (; i< num_columns; i++) {
var column = document.createElement("div");
column.className = "small-1 columns";
row.appendChild(column);
div.data_columns.push(column);
}
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_footers(div) {
div.footers = [];
var num_columns = 12;
var row = document.createElement("div");
row.className = "row";
for (var i=0; i<num_columns; i++) {
var column = document.createElement("div");
column.className = "small-1 columns";
column.innerHTML = "<p></p>";
row.appendChild(column);
div.footers.push(column);
}
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
window.addEventListener("resize", function() {
var performance_divs = document.getElementsByClassName('performance_div');
if (performance_divs.length > 0) {
var p_div = performance_divs[0];
var x1 = p_div.data_columns[0].getBoundingClientRect().left;
var x2 = p_div.data_columns[1].getBoundingClientRect().left;
var distance = x2 - x1;
var max_width = parseInt(p_div.data_columns[0].getAttribute('data-max-width'));
var width = Math.min(distance, max_width);
// Set Width for all inputs
var inputs = document.getElementsByClassName('scorekeeper_input');
for (var i=0; i<inputs.length; i++) {
inputs[i].style.width = width + "px";
}
}
});
| app/assets/javascripts/performance_div.js | var NUM_COLUMNS = 12;
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_new(performance) {
var div = document.createElement("div");
div.id = makeid(20);
var name = performance.name;
div.comm = comm_new(div, performance.name); //Create comm object for communictiation with the server.
performance.comm = div.comm;
performance.add_notify_rank(p_div_rank_updated, div);
performance.add_notify_score(p_div_score_updated, div);
var row = document.createElement("div");
row.className = 'row';
var column = document.createElement('div');
column.className = 'small-11 columns';
column.innerHTML = "<h3> <span style='color:purple'>" + name + "</span> </h3>";
row.appendChild(column);
var column = document.createElement("div");
column.className = 'small-2 columns';
var remove_me = make_remove_me_div(div.id);
column.appendChild(remove_me);
row.appendChild(column);
div.appendChild(row);
div.column_length = {Judges: slam.num_judges, Time: 2, Penalty: 1};
div.titles = ["Judges", "Time", "Penalty"];
p_div_build_columns_hash(div);
div.performance = performance;
p_div_build_titles_row(div);
p_div_build_sub_titles(div);
p_div_build_data_row(div);
p_div_build_footers(div);
div.style.backgroundColor = '#F4F4F4';
div.style.borderStyle = 'solid';
div.style.borderWidth = '1px';
row = document.createElement("div");
row.className = "row";
/*
column = document.createElement("div");
column.className = "small-12 columns";
column.style.minHeight = "15px"; //http://stackoverflow.com/a/25431669
row.appendChild(column);
div.appendChild(row);
*/
row = document.createElement("div");
row.className = "row";
column = document.createElement("div");
column.className = "small-2 medium-1 columns";
column.style.color = "blue";
column.innerHTML = "<p> Score: </p>";
row.appendChild(column);
div.score_column = document.createElement("div");
div.score_column.className = "small-2 medium-1 columns";
div.score_column.innerHTML = "";
row.appendChild(div.score_column);
if (div.performance.prev != null) {
column = document.createElement("div");
column.className = "small-2 medium-1 columns";
column.style.color = "blue";
column.innerHTML = "<p> Total: </p>";
row.appendChild(column);
div.cumulative_column = document.createElement("div");
div.cumulative_column.className = "small-2 medium-1 columns";
div.cumulative_column.innerHTML = "";
row.appendChild(div.cumulative_column);
}
column = document.createElement("div");
column.className = "small-2 medium-1 columns";
column.style.color = "blue";
column.innerHTML = "<p> Rank: </p>";
row.appendChild(column);
div.rank_column = document.createElement("div");
div.rank_column.className = "small-2 medium-1 columns end";
div.rank_column.innerHTML = "";
row.appendChild(div.rank_column);
div.appendChild(row);
row = document.createElement("div");
row.className = "row";
div.tied_with = document.createElement("div");
div.tied_with.className = "small-12 columns";
row.appendChild(div.tied_with);
div.appendChild(row);
return div;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_columns_hash(div) {
var num_columns = 12;
var columns = div.columns = {};
var titles = div.titles;
var remaining_columns = num_columns;
for (var i=0; i<titles.length; i++) {
columns[titles[i]] = remaining_columns;
remaining_columns -= div.column_length[titles[i]];
if (i > 0) {
for (j=0; j<i; j++) {
columns[titles[j]] = div.column_length[titles[j]];
}
}
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_titles_row(div) {
var row = document.createElement("div");
row.className = "row";
for (var i=0; i<div.titles.length; i++) {
var column = document.createElement("div");
column.className = "small-" + div.columns[div.titles[i]] + " columns";
column.innerHTML = "<span style='color:blue;'>" + div.titles[i] + "</span>";
row.appendChild(column);
}
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_sub_titles(div) {
var num_columns = 12;
var row = document.createElement("div");
row.className = "row";
// Add Judges
var column;
for (var i=0; i<slam.num_judges; i++) {
column = document.createElement("div");
column.className = "small-1 columns";
column.innerHTML = "<span style='color:purple'>" + (i + 1) + "</span>";
row.appendChild(column);
}
// Add Time
column = document.createElement("div");
column.className = "small-1 columns";
column.innerHTML = "<span style='color:brown'>m</span>";
row.appendChild(column);
column = document.createElement("div");
column.className = "small-1 columns end";
column.innerHTML = "<span style='color:brown'>s</span>";
row.appendChild(column);
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_setup_indexes(div) {
div.data_columns = [];
div.indexes = {};
var i = slam.num_judges;
div.indexes.minutes_i = i++;
div.indexes.seconds_i = i++;
div.indexes.penalty_i = i++;
div.indexes.score_i = i++;
div.indexes.subscore_i = i++;
div.indexes.rank = i;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function format_value(value) {
// Return a value that has at most one decimal place.
return Math.round(value * 100) / 100;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_update_data_column(div, index, value) {
div.data_columns[index].innerHTML = format_value(value);
// Why bother displaying subscore when it equals score?
if (div.performance.prev == null)
div.data_columns[div.indexes.subscore_i].innerHTML = '';
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_score_updated(div, performance) {
//p_div_update_data_column(div, div.indexes.score_i, performance.score);
//p_div_update_data_column(div, div.indexes.subscore_i, performance.subscore);
div.score_column.innerHTML = format_value(performance.score);
if (div.performance.prev != null)
div.cumulative_column.innerHTML = format_value(performance.subscore);
var min_i = performance.min_judge;
var max_i = performance.max_judge;
if (slam.do_not_include_min_and_max_scores) {
for (var i=0; i<slam.num_judges; i++) {
div.footers[i].innerHTML = "<p></p>";
div.data_columns[i].style.color = "black";
}
var min_max_color = "darkviolet";
var low_str = "<p class='visible-for-small-only'>L</p><p class='visible-for-medium-up'>LOW</p>";
var high_str = "<p class='visible-for-small-only'>H</p><p class='visible-for-medium-up'>HIGH</p>";
div.data_columns[min_i].style.color = min_max_color;
div.data_columns[max_i].style.color = min_max_color;
div.footers[min_i].innerHTML = low_str;
div.footers[min_i].style.color = min_max_color;
div.footers[max_i].innerHTML = high_str;
div.footers[max_i].style.color = min_max_color;
}
// Time Penalty
var time_penalty = performance.calculate_time_penalty() * -1;
if (time_penalty != 0){
div.footers[slam.num_judges].innerHTML = "P:";
div.footers[slam.num_judges].style.color = "green";
div.footers[slam.num_judges + 1].innerHTML = time_penalty;
div.footers[slam.num_judges + 1].style.color = "green";
}
else {
div.footers[slam.num_judges].innerHTML = "<p></p>";
div.footers[slam.num_judges + 1].innerHTML = "<p></p>";
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_rank_updated (div, performance) {
div.rank_column.innerHTML = performance.rank;
div.tied_with.innerHTML = performance.is_tied ? "<p> <span style='color:blue'> Tied With: </span> " + performance.names_tied_with.join() + "</p>" : "";
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_get_time(div) {
var minutes = parse_int_or_return_zero(div.data_columns[div.indexes.minutes_i].value);
var seconds = parse_int_or_return_zero(div.data_columns[div.indexes.seconds_i].value);
return {minutes: minutes, seconds: seconds};
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function is_score_entered_fully(score) {
if (score == "10")
return false;
if (score == "100")
return true;
if (score.length == 2)
return true;
return false;
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_input_onkeyup(inputs, input) {
input.value = input.value.replace('\.', '');
var index = parseInt(input.getAttribute('data-index'));
if (is_score_entered_fully(input.value)) {
if (index < inputs.length - 1) {
input.removeAttribute('onkeyup');
next_input = inputs[index + 1];
next_input.focus();
}
else {
$(input).trigger("change");
input.blur();
}
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_input_entered(input) {
if (!login_info.is_logged_in)
return;
var i = parseInt(input.getAttribute('data-index'));
var div = input.div;
var performance = div.performance;
var value = parse_float_or_return_zero(input.value);
switch (i)
{
case div.indexes.minutes_i:
case div.indexes.seconds_i:
var time = p_div_get_time(div);
performance.set_time(time.minutes, time.seconds);
set_time_request(performance.comm, time.minutes, time.seconds);
break;
case div.indexes.penalty_i:
performance.set_penalty(value);
set_penalty_request(performance.comm, value);
break;
default:
if (i >= 0 && i < div.indexes.minutes_i) {
input.value = input.value.replace('\.', '');
var value = input.value / 10;
input.value = value;
performance.judge(i, value);
judge_request(performance.comm, i, value);
}
}
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_set_score(p_div, judge_i, value) {
p_div.data_columns[judge_i].value = value;
p_div.data_columns[judge_i].removeAttribute('onkeyup');
p_div.performance.judge(judge_i, value);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_set_time(p_div, minutes, seconds) {
var i = p_div.indexes.minutes_i;
p_div.data_columns[i].value = minutes;
p_div.data_columns[++i].value = seconds;
p_div.performance.set_time(minutes, seconds);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_set_penalty(p_div, value) {
var i = p_div.indexes.penalty_i;
p_div.data_columns[i].value = value;
p_div.performance.set_penalty(value);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_data_row(div) {
p_div_setup_indexes(div);
var row = document.createElement("div");
row.className = "row";
var num_columns = slam.num_judges + 3; // Judges + Minutes + Seconds + Penalty
var i;
div.judge_inputs = [];
for (i=0; i<num_columns; i++) {
var column = document.createElement("div");
column.className = "small-1 columns";
var input = document.createElement("input");
input.inputs = div.judge_inputs;
// This (the if statement to follow) is to faciliate automatic refocusing of the next judge
// after two digit are entered for the score (exception 10 and 100)
// The last input will be Minutes so that the last judge
// (the one that comes before Minutes) will have another input to
// focus on after the score has been entered.
if (i <= slam.num_judges)
div.judge_inputs.push(input);
input.div = div;
input.className = "scorekeeper_input";
input.setAttribute('size', 4);
input.setAttribute('onchange', 'p_div_input_entered(this)');
if (i < slam.num_judges)
// Only do this for inputs that are judges
input.setAttribute('onkeyup', 'p_div_input_onkeyup(this.inputs, this)');
input.setAttribute('data-index', i);
input.type = "number";
input.style.width = "60px";
if (!login_info.is_logged_in)
input.setAttribute('readonly', null);
column.appendChild(input);
div.data_columns.push(input);
row.appendChild(column);
}
num_columns = 12;
for (; i< num_columns; i++) {
var column = document.createElement("div");
column.className = "small-1 columns";
row.appendChild(column);
div.data_columns.push(column);
}
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
function p_div_build_footers(div) {
div.footers = [];
var num_columns = 12;
var row = document.createElement("div");
row.className = "row";
for (var i=0; i<num_columns; i++) {
var column = document.createElement("div");
column.className = "small-1 columns";
column.innerHTML = "<p></p>";
row.appendChild(column);
div.footers.push(column);
}
div.appendChild(row);
}
/*----------------------------------------------------------------------------------------------------------------------------------*/
| resizing inputs if necessary
| app/assets/javascripts/performance_div.js | resizing inputs if necessary | <ide><path>pp/assets/javascripts/performance_div.js
<ide> function p_div_new(performance) {
<ide>
<ide> var div = document.createElement("div");
<add> div.className = "performance_div";
<ide> div.id = makeid(20);
<ide> var name = performance.name;
<ide>
<ide>
<ide> var input = document.createElement("input");
<ide> input.inputs = div.judge_inputs;
<add> input.className = "scorekeeper_input";
<ide>
<ide> // This (the if statement to follow) is to faciliate automatic refocusing of the next judge
<ide> // after two digit are entered for the score (exception 10 and 100)
<del> // The last input will be Minutes so that the last judge
<add> // last input will be Minutes so that the last judge
<ide> // (the one that comes before Minutes) will have another input to
<ide> // focus on after the score has been entered.
<ide> if (i <= slam.num_judges)
<ide> input.setAttribute('data-index', i);
<ide> input.type = "number";
<ide> input.style.width = "60px";
<add> input.setAttribute('data-max-width', '60');
<ide>
<ide> if (!login_info.is_logged_in)
<ide> input.setAttribute('readonly', null);
<ide> }
<ide> /*----------------------------------------------------------------------------------------------------------------------------------*/
<ide>
<del>
<add>window.addEventListener("resize", function() {
<add>
<add> var performance_divs = document.getElementsByClassName('performance_div');
<add>
<add> if (performance_divs.length > 0) {
<add>
<add> var p_div = performance_divs[0];
<add> var x1 = p_div.data_columns[0].getBoundingClientRect().left;
<add> var x2 = p_div.data_columns[1].getBoundingClientRect().left;
<add>
<add> var distance = x2 - x1;
<add> var max_width = parseInt(p_div.data_columns[0].getAttribute('data-max-width'));
<add> var width = Math.min(distance, max_width);
<add>
<add> // Set Width for all inputs
<add> var inputs = document.getElementsByClassName('scorekeeper_input');
<add>
<add> for (var i=0; i<inputs.length; i++) {
<add> inputs[i].style.width = width + "px";
<add> }
<add> }
<add>});
<add> |
|
JavaScript | mit | 892776b21692c1b9d850cd2947162bd0582342dc | 0 | rasjani/canjs,rjgotten/canjs,Psykoral/canjs,mindscratch/canjs,juristr/canjs,tracer99/canjs,jebaird/canjs,yusufsafak/canjs,shiftplanning/canjs,azazel75/canjs,cohuman/canjs,schmod/canjs,mindscratch/canjs,whitecolor/canjs,patrick-steele-idem/canjs,bitovi/canjs,sporto/canjs,beno/canjs,gsmeets/canjs,rasjani/canjs,schmod/canjs,rasjani/canjs,thomblake/canjs,SpredfastLegacy/canjs,UXsree/canjs,modulexcite/jquerypp,ackl/canjs,yusufsafak/canjs,rasjani/canjs,azazel75/canjs,schmod/canjs,dispatchrabbi/canjs,airhadoken/canjs,WearyMonkey/canjs,scorphus/canjs,thecountofzero/canjs,asavoy/canjs,juristr/canjs,WearyMonkey/canjs,patrick-steele-idem/canjs,modulexcite/jquerypp,janza/canjs,cohuman/canjs,rjgotten/canjs,shiftplanning/canjs,dimaf/canjs,bitovi/jquerypp,jebaird/canjs,cohuman/canjs,SpredfastLegacy/canjs,airhadoken/canjs,beno/canjs,Psykoral/canjs,scorphus/canjs,beno/canjs,asavoy/canjs,dispatchrabbi/canjs,bitovi/canjs,tracer99/canjs,patrick-steele-idem/canjs,ackl/canjs,thecountofzero/canjs,whitecolor/canjs,Psykoral/canjs,dimaf/canjs,Psykoral/canjs,bitovi/canjs,rjgotten/canjs,jebaird/canjs,whitecolor/canjs,thomblake/canjs,bitovi/canjs,gsmeets/canjs,ackl/canjs,bitovi/jquerypp,janza/canjs,gsmeets/canjs,tracer99/canjs,liukaijv/jquerypp,sporto/canjs,sporto/canjs,UXsree/canjs,rjgotten/canjs,liukaijv/jquerypp,WearyMonkey/canjs | /**
* @add jQuery.fn
*/
steal.plugins("jquery/dom").then(function( $ ) {
var radioCheck = /radio|checkbox/i,
keyBreaker = /[^\[\]]+/g,
numberMatcher = /^[\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?$/;
var isNumber = function( value ) {
if ( typeof value == 'number' ) {
return true;
}
if ( typeof value != 'string' ) {
return false;
}
return value.match(numberMatcher);
};
$.fn.extend({
/**
* @parent dom
* @download jquery/dist/jquery.formparams.js
* @plugin jquery/dom/form_params
* @test jquery/dom/form_params/qunit.html
* <p>Returns an object of name-value pairs that represents values in a form.
* It is able to nest values whose element's name has square brackets. </p>
* Example html:
* @codestart html
* <form>
* <input name="foo[bar]" value='2'/>
* <input name="foo[ced]" value='4'/>
* <form/>
* @codeend
* Example code:
* @codestart
* $('form').formParams() //-> { foo:{bar:2, ced: 4} }
* @codeend
*
* @demo jquery/dom/form_params/form_params.html
*
* @param {Boolean} [convert] True if strings that look like numbers and booleans should be converted. Defaults to true.
* @return {Object} An object of name-value pairs.
*/
formParams: function( convert ) {
if ( this[0].nodeName.toLowerCase() == 'form' && this[0].elements ) {
return jQuery(jQuery.makeArray(this[0].elements)).getParams(convert);
}
return jQuery("input[name], textarea[name], select[name]", this[0]).getParams(convert);
},
getParams: function( convert ) {
var data = {},
current;
convert = convert === undefined ? true : convert;
this.each(function() {
var el = this,
type = el.type && el.type.toLowerCase();
//if we are submit, ignore
if ((type == 'submit') || !el.name ) {
return;
}
var key = el.name,
value = $.fn.val.call([el]) || $.data(el, "value"),
isRadioCheck = radioCheck.test(el.type),
parts = key.match(keyBreaker),
write = !isRadioCheck || !! el.checked,
//make an array of values
lastPart;
if ( convert ) {
if ( isNumber(value) ) {
value = parseFloat(value);
} else if ( value === 'true' || value === 'false' ) {
value = Boolean(value);
}
}
// go through and create nested objects
current = data;
for ( var i = 0; i < parts.length - 1; i++ ) {
if (!current[parts[i]] ) {
current[parts[i]] = {};
}
current = current[parts[i]];
}
lastPart = parts[parts.length - 1];
//now we are on the last part, set the value
if ( lastPart in current && type === "checkbox" ) {
if (!$.isArray(current[lastPart]) ) {
current[lastPart] = current[lastPart] === undefined ? [] : [current[lastPart]];
}
if ( write ) {
current[lastPart].push(value);
}
} else if ( write || !current[lastPart] ) {
current[lastPart] = write ? value : undefined;
}
});
return data;
}
});
}); | dom/form_params/form_params.js | /**
* @add jQuery.fn
*/
steal.plugins("jquery/dom").then(function( $ ) {
var radioCheck = /radio|checkbox/i,
keyBreaker = /[^\[\]]+/g,
numberMatcher = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/
isNumber = function( value ) {
if ( typeof value == 'number' ) return true;
if ( typeof value != 'string' ) return false;
return value.match(numberMatcher);
};
$.fn.extend({
/**
* @parent dom
* @download jquery/dist/jquery.formparams.js
* @plugin jquery/dom/form_params
* @test jquery/dom/form_params/qunit.html
* <p>Returns an object of name-value pairs that represents values in a form.
* It is able to nest values whose element's name has square brackets. </p>
* Example html:
* @codestart html
* <form>
* <input name="foo[bar]" value='2'/>
* <input name="foo[ced]" value='4'/>
* <form/>
* @codeend
* Example code:
* @codestart
* $('form').formParams() //-> { foo:{bar:2, ced: 4} }
* @codeend
*
* @demo jquery/dom/form_params/form_params.html
*
* @param {Boolean} [convert] True if strings that look like numbers and booleans should be converted. Defaults to true.
* @return {Object} An object of name-value pairs.
*/
formParams: function( convert ) {
var data = {};
if ( this[0].nodeName.toLowerCase() == 'form' && this[0].elements ) {
return jQuery(jQuery.makeArray(this[0].elements)).getParams(convert);
}
return jQuery("input[name], textarea[name], select[name]", this[0]).getParams(convert);
},
getParams: function( convert ) {
var data = {},
current, convert = convert === undefined ? true : convert;
this.each(function() {
var el = this,
type = el.type && el.type.toLowerCase();
//if we are submit, ignore
if ((type == 'submit') || !el.name ) {
return;
}
var key = el.name,
value = $.fn.val.call([el]) || $.data(el, "value"),
isRadioCheck = radioCheck.test(el.type),
parts = key.match(keyBreaker),
write = !isRadioCheck || !! el.checked,
//overwrite the value
append = false,
//make an array of values
lastPart;
if ( convert ) {
if ( isNumber(value) ) {
value = parseFloat(value);
} else if ( value === 'true' || value === 'false' ) {
value = Boolean(value);
}
}
// go through and create nested objects
current = data;
for ( var i = 0; i < parts.length - 1; i++ ) {
if (!current[parts[i]] ) {
current[parts[i]] = {}
}
current = current[parts[i]];
}
lastPart = parts[parts.length - 1];
//now we are on the last part, set the value
if ( lastPart in current && type === "checkbox" ) {
if (!$.isArray(current[lastPart]) ) {
current[lastPart] = current[lastPart] === undefined ? [] : [current[lastPart]];
}
if ( write ) {
current[lastPart].push(value);
}
} else if ( write || !current[lastPart] ) {
current[lastPart] = write ? value : undefined;
}
})
return data;
}
});
}); | Cleaned and JSLinted form_params.js
| dom/form_params/form_params.js | Cleaned and JSLinted form_params.js | <ide><path>om/form_params/form_params.js
<ide> steal.plugins("jquery/dom").then(function( $ ) {
<ide> var radioCheck = /radio|checkbox/i,
<ide> keyBreaker = /[^\[\]]+/g,
<del> numberMatcher = /^[-+]?[0-9]*\.?[0-9]+([eE][-+]?[0-9]+)?$/
<add> numberMatcher = /^[\-+]?[0-9]*\.?[0-9]+([eE][\-+]?[0-9]+)?$/;
<ide>
<del> isNumber = function( value ) {
<del> if ( typeof value == 'number' ) return true;
<del> if ( typeof value != 'string' ) return false;
<del> return value.match(numberMatcher);
<del> };
<add> var isNumber = function( value ) {
<add> if ( typeof value == 'number' ) {
<add> return true;
<add> }
<add>
<add> if ( typeof value != 'string' ) {
<add> return false;
<add> }
<add>
<add> return value.match(numberMatcher);
<add> };
<ide>
<ide> $.fn.extend({
<ide> /**
<ide> * @return {Object} An object of name-value pairs.
<ide> */
<ide> formParams: function( convert ) {
<del> var data = {};
<ide> if ( this[0].nodeName.toLowerCase() == 'form' && this[0].elements ) {
<ide>
<ide> return jQuery(jQuery.makeArray(this[0].elements)).getParams(convert);
<ide> },
<ide> getParams: function( convert ) {
<ide> var data = {},
<del> current, convert = convert === undefined ? true : convert;
<add> current;
<add>
<add> convert = convert === undefined ? true : convert;
<ide>
<ide> this.each(function() {
<ide> var el = this,
<ide> isRadioCheck = radioCheck.test(el.type),
<ide> parts = key.match(keyBreaker),
<ide> write = !isRadioCheck || !! el.checked,
<del> //overwrite the value
<del> append = false,
<ide> //make an array of values
<ide> lastPart;
<ide>
<ide> current = data;
<ide> for ( var i = 0; i < parts.length - 1; i++ ) {
<ide> if (!current[parts[i]] ) {
<del> current[parts[i]] = {}
<add> current[parts[i]] = {};
<ide> }
<ide> current = current[parts[i]];
<ide> }
<ide> current[lastPart] = write ? value : undefined;
<ide> }
<ide>
<del> })
<add> });
<ide> return data;
<ide> }
<ide> }); |
|
Java | bsd-3-clause | dda273f6b34e835efbd2d8ebd8f814e2809d1d5f | 0 | jthrun/sdl_android,jthrun/sdl_android,anildahiya/sdl_android,smartdevicelink/sdl_android | package com.smartdevicelink.test.proxy;
import android.test.AndroidTestCase;
import com.smartdevicelink.api.ProxyBridge;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.protocol.enums.SessionType;
import com.smartdevicelink.proxy.RPCRequest;
import com.smartdevicelink.proxy.SystemCapabilityManager;
import com.smartdevicelink.proxy.interfaces.IAudioStreamListener;
import com.smartdevicelink.proxy.interfaces.ISdl;
import com.smartdevicelink.proxy.interfaces.ISdlServiceListener;
import com.smartdevicelink.proxy.interfaces.IVideoStreamListener;
import com.smartdevicelink.proxy.interfaces.OnSystemCapabilityListener;
import com.smartdevicelink.proxy.rpc.AudioPassThruCapabilities;
import com.smartdevicelink.proxy.rpc.ButtonCapabilities;
import com.smartdevicelink.proxy.rpc.DisplayCapabilities;
import com.smartdevicelink.proxy.rpc.GetSystemCapabilityResponse;
import com.smartdevicelink.proxy.rpc.HMICapabilities;
import com.smartdevicelink.proxy.rpc.PresetBankCapabilities;
import com.smartdevicelink.proxy.rpc.RegisterAppInterfaceResponse;
import com.smartdevicelink.proxy.rpc.SdlMsgVersion;
import com.smartdevicelink.proxy.rpc.SoftButtonCapabilities;
import com.smartdevicelink.proxy.rpc.SystemCapability;
import com.smartdevicelink.proxy.rpc.VideoStreamingCapability;
import com.smartdevicelink.proxy.rpc.enums.HmiZoneCapabilities;
import com.smartdevicelink.proxy.rpc.enums.SpeechCapabilities;
import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType;
import com.smartdevicelink.proxy.rpc.listeners.OnMultipleRequestListener;
import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener;
import com.smartdevicelink.streaming.audio.AudioStreamingCodec;
import com.smartdevicelink.streaming.audio.AudioStreamingParams;
import com.smartdevicelink.streaming.video.VideoStreamingParameters;
import com.smartdevicelink.test.Test;
import com.smartdevicelink.test.Validator;
import com.smartdevicelink.util.CorrelationIdGenerator;
import java.util.List;
public class SystemCapabilityManagerTests extends AndroidTestCase {
public static final String TAG = "SystemCapabilityManagerTests";
public static SystemCapabilityManager systemCapabilityManager;
@Override
protected void setUp() throws Exception{
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public SystemCapabilityManager createSampleManager(){
SystemCapabilityManager systemCapabilityManager = new SystemCapabilityManager(new InternalSDLInterface());
RegisterAppInterfaceResponse raiResponse = new RegisterAppInterfaceResponse();
raiResponse.setHmiCapabilities(Test.GENERAL_HMICAPABILITIES);
raiResponse.setDisplayCapabilities(Test.GENERAL_DISPLAYCAPABILITIES);
raiResponse.setAudioPassThruCapabilities(Test.GENERAL_AUDIOPASSTHRUCAPABILITIES_LIST);
raiResponse.setButtonCapabilities(Test.GENERAL_BUTTONCAPABILITIES_LIST);
raiResponse.setHmiZoneCapabilities(Test.GENERAL_HMIZONECAPABILITIES_LIST);
raiResponse.setPresetBankCapabilities(Test.GENERAL_PRESETBANKCAPABILITIES);
raiResponse.setSoftButtonCapabilities(Test.GENERAL_SOFTBUTTONCAPABILITIES_LIST);
raiResponse.setSpeechCapabilities(Test.GENERAL_SPEECHCAPABILITIES_LIST);
raiResponse.setSuccess(true);
systemCapabilityManager.parseRAIResponse(raiResponse);
return systemCapabilityManager;
}
public void testParseRAI() {
systemCapabilityManager = createSampleManager();
assertTrue(Test.TRUE,
Validator.validateHMICapabilities(Test.GENERAL_HMICAPABILITIES, (HMICapabilities) systemCapabilityManager.getCapability(SystemCapabilityType.HMI)));
assertTrue(Test.TRUE,
Validator.validateDisplayCapabilities(Test.GENERAL_DISPLAYCAPABILITIES, (DisplayCapabilities) systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY)));
assertTrue(Test.TRUE,
Validator.validateAudioPassThruCapabilities(Test.GENERAL_AUDIOPASSTHRUCAPABILITIES_LIST, (List<AudioPassThruCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.AUDIO_PASSTHROUGH)));
assertTrue(Test.TRUE,
Validator.validateButtonCapabilities(Test.GENERAL_BUTTONCAPABILITIES_LIST, (List<ButtonCapabilities> )systemCapabilityManager.getCapability(SystemCapabilityType.BUTTON)));
assertTrue(Test.TRUE,
Validator.validateHMIZoneCapabilities(Test.GENERAL_HMIZONECAPABILITIES_LIST, (List<HmiZoneCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.HMI_ZONE)));
assertTrue(Test.TRUE,
Validator.validatePresetBankCapabilities(Test.GENERAL_PRESETBANKCAPABILITIES, (PresetBankCapabilities) systemCapabilityManager.getCapability(SystemCapabilityType.PRESET_BANK)));
assertTrue(Test.TRUE,
Validator.validateSoftButtonCapabilities(Test.GENERAL_SOFTBUTTONCAPABILITIES_LIST, (List<SoftButtonCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.SOFTBUTTON)));
assertTrue(Test.TRUE,
Validator.validateSpeechCapabilities(Test.GENERAL_SPEECHCAPABILITIES_LIST, (List<SpeechCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.SPEECH)));
}
public void testGetVSCapability(){
VideoStreamingCapability vsCapability = new VideoStreamingCapability();
vsCapability.setMaxBitrate(Test.GENERAL_INT);
vsCapability.setPreferredResolution(Test.GENERAL_IMAGERESOLUTION);
vsCapability.setSupportedFormats(Test.GENERAL_VIDEOSTREAMINGFORMAT_LIST);
SystemCapability cap = new SystemCapability();
cap.setSystemCapabilityType(SystemCapabilityType.VIDEO_STREAMING);
cap.setCapabilityForType(SystemCapabilityType.VIDEO_STREAMING, vsCapability);
final SystemCapability referenceCapability = cap;
systemCapabilityManager = new SystemCapabilityManager(new InternalSDLInterface() {
@Override
public void sendRPCRequest(RPCRequest message) {
GetSystemCapabilityResponse response = new GetSystemCapabilityResponse();
response.setSystemCapability(referenceCapability);
response.setSuccess(true);
message.getOnRPCResponseListener().onResponse(CorrelationIdGenerator.generateId(), response);
}
});
systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING, new OnSystemCapabilityListener() {
@Override
public void onCapabilityRetrieved(Object capability) {
assertTrue(Test.TRUE,
Validator.validateVideoStreamingCapability(
(VideoStreamingCapability) referenceCapability.getCapabilityForType(SystemCapabilityType.VIDEO_STREAMING),
(VideoStreamingCapability) capability));
}
@Override
public void onError(String info) {
assertTrue(false);
}
});
}
public void testListConversion(){
SystemCapabilityManager systemCapabilityManager = createSampleManager();
Object capability = systemCapabilityManager.getCapability(SystemCapabilityType.SOFTBUTTON);
assertNotNull(capability);
List<SoftButtonCapabilities> list = SystemCapabilityManager.convertToList(capability, SoftButtonCapabilities.class);
assertNotNull(list);
}
private class InternalSDLInterface implements ISdl{
@Override
public void start(){}
@Override
public void stop() {}
@Override
public boolean isConnected() {return false; }
@Override
public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) {}
@Override
public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) {}
@Override
public void startVideoService(VideoStreamingParameters parameters, boolean encrypted) { }
@Override
public void stopVideoService() {}
@Override
public void stopAudioService() {}
@Override
public void sendRPCRequest(RPCRequest message) {}
@Override
public void sendRequests(List<? extends RPCRequest> rpcs, OnMultipleRequestListener listener) {
}
@Override
public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {}
@Override
public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {return false;}
@Override
public void addOnRPCResponseListener(FunctionID responseId, ProxyBridge.OnRPCListener listener) { }
@Override
public boolean removeOnRPCResponseListener(FunctionID responseId, ProxyBridge.OnRPCListener listener) { return false; }
@Override
public Object getCapability(SystemCapabilityType systemCapabilityType){return null;}
@Override
public void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener) { }
@Override
public SdlMsgVersion getSdlMsgVersion(){
return null;
}
@Override
public boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType){
return false;
}
@Override
public void startAudioService(boolean isEncrypted, AudioStreamingCodec codec,
AudioStreamingParams params) {}
@Override
public IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters){
return null;
}
@Override
public IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec,
AudioStreamingParams params) {
return null;
}
@Override
public void startAudioService(boolean encrypted){}
}
}
| sdl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java | package com.smartdevicelink.test.proxy;
import android.test.AndroidTestCase;
import com.smartdevicelink.protocol.enums.FunctionID;
import com.smartdevicelink.protocol.enums.SessionType;
import com.smartdevicelink.proxy.RPCRequest;
import com.smartdevicelink.proxy.SystemCapabilityManager;
import com.smartdevicelink.proxy.interfaces.IAudioStreamListener;
import com.smartdevicelink.proxy.interfaces.ISdl;
import com.smartdevicelink.proxy.interfaces.ISdlServiceListener;
import com.smartdevicelink.proxy.interfaces.IVideoStreamListener;
import com.smartdevicelink.proxy.interfaces.OnSystemCapabilityListener;
import com.smartdevicelink.proxy.rpc.AudioPassThruCapabilities;
import com.smartdevicelink.proxy.rpc.ButtonCapabilities;
import com.smartdevicelink.proxy.rpc.DisplayCapabilities;
import com.smartdevicelink.proxy.rpc.GetSystemCapabilityResponse;
import com.smartdevicelink.proxy.rpc.HMICapabilities;
import com.smartdevicelink.proxy.rpc.PresetBankCapabilities;
import com.smartdevicelink.proxy.rpc.RegisterAppInterfaceResponse;
import com.smartdevicelink.proxy.rpc.SdlMsgVersion;
import com.smartdevicelink.proxy.rpc.SoftButtonCapabilities;
import com.smartdevicelink.proxy.rpc.SystemCapability;
import com.smartdevicelink.proxy.rpc.VideoStreamingCapability;
import com.smartdevicelink.proxy.rpc.enums.HmiZoneCapabilities;
import com.smartdevicelink.proxy.rpc.enums.SpeechCapabilities;
import com.smartdevicelink.proxy.rpc.enums.SystemCapabilityType;
import com.smartdevicelink.proxy.rpc.listeners.OnMultipleRequestListener;
import com.smartdevicelink.proxy.rpc.listeners.OnRPCNotificationListener;
import com.smartdevicelink.streaming.audio.AudioStreamingCodec;
import com.smartdevicelink.streaming.audio.AudioStreamingParams;
import com.smartdevicelink.streaming.video.VideoStreamingParameters;
import com.smartdevicelink.test.Test;
import com.smartdevicelink.test.Validator;
import com.smartdevicelink.util.CorrelationIdGenerator;
import java.util.List;
public class SystemCapabilityManagerTests extends AndroidTestCase {
public static final String TAG = "SystemCapabilityManagerTests";
public static SystemCapabilityManager systemCapabilityManager;
@Override
protected void setUp() throws Exception{
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public SystemCapabilityManager createSampleManager(){
SystemCapabilityManager systemCapabilityManager = new SystemCapabilityManager(new InternalSDLInterface());
RegisterAppInterfaceResponse raiResponse = new RegisterAppInterfaceResponse();
raiResponse.setHmiCapabilities(Test.GENERAL_HMICAPABILITIES);
raiResponse.setDisplayCapabilities(Test.GENERAL_DISPLAYCAPABILITIES);
raiResponse.setAudioPassThruCapabilities(Test.GENERAL_AUDIOPASSTHRUCAPABILITIES_LIST);
raiResponse.setButtonCapabilities(Test.GENERAL_BUTTONCAPABILITIES_LIST);
raiResponse.setHmiZoneCapabilities(Test.GENERAL_HMIZONECAPABILITIES_LIST);
raiResponse.setPresetBankCapabilities(Test.GENERAL_PRESETBANKCAPABILITIES);
raiResponse.setSoftButtonCapabilities(Test.GENERAL_SOFTBUTTONCAPABILITIES_LIST);
raiResponse.setSpeechCapabilities(Test.GENERAL_SPEECHCAPABILITIES_LIST);
raiResponse.setSuccess(true);
systemCapabilityManager.parseRAIResponse(raiResponse);
return systemCapabilityManager;
}
public void testParseRAI() {
systemCapabilityManager = createSampleManager();
assertTrue(Test.TRUE,
Validator.validateHMICapabilities(Test.GENERAL_HMICAPABILITIES, (HMICapabilities) systemCapabilityManager.getCapability(SystemCapabilityType.HMI)));
assertTrue(Test.TRUE,
Validator.validateDisplayCapabilities(Test.GENERAL_DISPLAYCAPABILITIES, (DisplayCapabilities) systemCapabilityManager.getCapability(SystemCapabilityType.DISPLAY)));
assertTrue(Test.TRUE,
Validator.validateAudioPassThruCapabilities(Test.GENERAL_AUDIOPASSTHRUCAPABILITIES_LIST, (List<AudioPassThruCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.AUDIO_PASSTHROUGH)));
assertTrue(Test.TRUE,
Validator.validateButtonCapabilities(Test.GENERAL_BUTTONCAPABILITIES_LIST, (List<ButtonCapabilities> )systemCapabilityManager.getCapability(SystemCapabilityType.BUTTON)));
assertTrue(Test.TRUE,
Validator.validateHMIZoneCapabilities(Test.GENERAL_HMIZONECAPABILITIES_LIST, (List<HmiZoneCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.HMI_ZONE)));
assertTrue(Test.TRUE,
Validator.validatePresetBankCapabilities(Test.GENERAL_PRESETBANKCAPABILITIES, (PresetBankCapabilities) systemCapabilityManager.getCapability(SystemCapabilityType.PRESET_BANK)));
assertTrue(Test.TRUE,
Validator.validateSoftButtonCapabilities(Test.GENERAL_SOFTBUTTONCAPABILITIES_LIST, (List<SoftButtonCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.SOFTBUTTON)));
assertTrue(Test.TRUE,
Validator.validateSpeechCapabilities(Test.GENERAL_SPEECHCAPABILITIES_LIST, (List<SpeechCapabilities>) systemCapabilityManager.getCapability(SystemCapabilityType.SPEECH)));
}
public void testGetVSCapability(){
VideoStreamingCapability vsCapability = new VideoStreamingCapability();
vsCapability.setMaxBitrate(Test.GENERAL_INT);
vsCapability.setPreferredResolution(Test.GENERAL_IMAGERESOLUTION);
vsCapability.setSupportedFormats(Test.GENERAL_VIDEOSTREAMINGFORMAT_LIST);
SystemCapability cap = new SystemCapability();
cap.setSystemCapabilityType(SystemCapabilityType.VIDEO_STREAMING);
cap.setCapabilityForType(SystemCapabilityType.VIDEO_STREAMING, vsCapability);
final SystemCapability referenceCapability = cap;
systemCapabilityManager = new SystemCapabilityManager(new InternalSDLInterface() {
@Override
public void sendRPCRequest(RPCRequest message) {
GetSystemCapabilityResponse response = new GetSystemCapabilityResponse();
response.setSystemCapability(referenceCapability);
response.setSuccess(true);
message.getOnRPCResponseListener().onResponse(CorrelationIdGenerator.generateId(), response);
}
});
systemCapabilityManager.getCapability(SystemCapabilityType.VIDEO_STREAMING, new OnSystemCapabilityListener() {
@Override
public void onCapabilityRetrieved(Object capability) {
assertTrue(Test.TRUE,
Validator.validateVideoStreamingCapability(
(VideoStreamingCapability) referenceCapability.getCapabilityForType(SystemCapabilityType.VIDEO_STREAMING),
(VideoStreamingCapability) capability));
}
@Override
public void onError(String info) {
assertTrue(false);
}
});
}
public void testListConversion(){
SystemCapabilityManager systemCapabilityManager = createSampleManager();
Object capability = systemCapabilityManager.getCapability(SystemCapabilityType.SOFTBUTTON);
assertNotNull(capability);
List<SoftButtonCapabilities> list = SystemCapabilityManager.convertToList(capability, SoftButtonCapabilities.class);
assertNotNull(list);
}
private class InternalSDLInterface implements ISdl{
@Override
public void start(){}
@Override
public void stop() {}
@Override
public boolean isConnected() {return false; }
@Override
public void addServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) {}
@Override
public void removeServiceListener(SessionType serviceType, ISdlServiceListener sdlServiceListener) {}
@Override
public void startVideoService(VideoStreamingParameters parameters, boolean encrypted) { }
@Override
public void stopVideoService() {}
@Override
public void stopAudioService() {}
@Override
public void sendRPCRequest(RPCRequest message) {}
@Override
public void sendRequests(List<? extends RPCRequest> rpcs, OnMultipleRequestListener listener) {
}
@Override
public void addOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {}
@Override
public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {return false;}
@Override
public Object getCapability(SystemCapabilityType systemCapabilityType){return null;}
@Override
public void getCapability(SystemCapabilityType systemCapabilityType, OnSystemCapabilityListener scListener) { }
@Override
public SdlMsgVersion getSdlMsgVersion(){
return null;
}
@Override
public boolean isCapabilitySupported(SystemCapabilityType systemCapabilityType){
return false;
}
@Override
public void startAudioService(boolean isEncrypted, AudioStreamingCodec codec,
AudioStreamingParams params) {}
@Override
public IVideoStreamListener startVideoStream(boolean isEncrypted, VideoStreamingParameters parameters){
return null;
}
@Override
public IAudioStreamListener startAudioStream(boolean isEncrypted, AudioStreamingCodec codec,
AudioStreamingParams params) {
return null;
}
@Override
public void startAudioService(boolean encrypted){}
}
}
| Update SystemCapabilityManagerTests tests to include Isdl.addOnRPCResponseListener
| sdl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java | Update SystemCapabilityManagerTests tests to include Isdl.addOnRPCResponseListener | <ide><path>dl_android/src/androidTest/java/com/smartdevicelink/test/proxy/SystemCapabilityManagerTests.java
<ide>
<ide> import android.test.AndroidTestCase;
<ide>
<add>import com.smartdevicelink.api.ProxyBridge;
<ide> import com.smartdevicelink.protocol.enums.FunctionID;
<ide> import com.smartdevicelink.protocol.enums.SessionType;
<ide> import com.smartdevicelink.proxy.RPCRequest;
<ide> public boolean removeOnRPCNotificationListener(FunctionID notificationId, OnRPCNotificationListener listener) {return false;}
<ide>
<ide> @Override
<add> public void addOnRPCResponseListener(FunctionID responseId, ProxyBridge.OnRPCListener listener) { }
<add>
<add> @Override
<add> public boolean removeOnRPCResponseListener(FunctionID responseId, ProxyBridge.OnRPCListener listener) { return false; }
<add>
<add> @Override
<ide> public Object getCapability(SystemCapabilityType systemCapabilityType){return null;}
<ide>
<ide> @Override |
|
JavaScript | mit | ef53a13d4adb83771ecf8543b17d51f9ff2eda20 | 0 | Teknologica/js-sdk | import chai from 'chai';
import apiInstance from '../api-instance';
import {createSessionsData} from '../utils.js';
const expect = chai.expect;
describe('when using the sessions resource', () => {
const testIds = {with: null, without: null};
let sharedSessionId;
it('I can create a sessions with ID', async() => {
const {id: id, ...data} = createSessionsData(true);
testIds.with = id;
const session = await apiInstance.sessions.create({id: id, data: data});
expect(session.response.status).to.be.equal(201);
});
it('I can create a sessions without ID', async() => {
const {id: id, ...data} = createSessionsData(false);
const session = await apiInstance.sessions.create({id: id, data: data});
testIds.without = session.fields.id;
expect(session.response.status).to.be.equal(201);
});
it('I can get a list of sessions', async() => {
const sessions = await apiInstance.sessions.getAll();
expect(sessions.response.status).to.be.equal(200);
expect(sessions.total).to.not.be.equal(0);
const [sessionItem] = sessions.items;
expect(sessionItem.fields.id).to.not.be.undefined;
sharedSessionId = sessionItem.fields.id;
});
it('I can get a sessions by its ID', async () => {
const session = await apiInstance.sessions.get({id: sharedSessionId});
expect(session.fields.id).to.be.equal(sharedSessionId);
expect(session.response.status).to.be.equal(200);
});
it('I can update a sessions by its ID', async() => {
const data = createSessionsData(false);
const session = await apiInstance.sessions.update({id: sharedSessionId, data: data});
expect(session.response.status).to.be.equal(200);
});
it('I can delete a sessions by its ID', async() => {
const session1 = await apiInstance.sessions.delete({id: testIds.with});
const session2 = await apiInstance.sessions.delete({id: testIds.without});
expect(session1.response.status).to.be.equal(204);
expect(session2.response.status).to.be.equal(204);
});
});
| test/integration/specs/sessions.spec.js | import chai from 'chai';
import apiInstance from '../api-instance';
import {createSessionsData} from '../utils.js';
const expect = chai.expect;
describe('when using the sessions resource', () => {
let sharedSessionId;
it('I can create a sessions with ID', async() => {
const {id: id, ...data} = createSessionsData(true);
const session = await apiInstance.sessions.create({id: id, data: data});
expect(session.response.status).to.be.equal(201);
});
it('I can create a sessions without ID', async() => {
const {id: id, ...data} = createSessionsData(true);
const session = await apiInstance.sessions.create({id: id, data: data});
expect(session.response.status).to.be.equal(201);
});
it('I can get a list of sessions', async() => {
const sessions = await apiInstance.sessions.getAll();
expect(sessions.response.status).to.be.equal(200);
expect(sessions.total).to.not.be.equal(0);
const [sessionItem] = sessions.items;
expect(sessionItem.fields.id).to.not.be.undefined;
sharedSessionId = sessionItem.fields.id;
});
it('I can get a sessions by its ID', async () => {
const session = await apiInstance.sessions.get({id: sharedSessionId});
expect(session.fields.id).to.be.equal(sharedSessionId);
expect(session.response.status).to.be.equal(200);
});
it('I can update a sessions by its ID', async() => {
const data = createSessionsData(false);
const session = await apiInstance.sessions.update({id: sharedSessionId, data: data});
expect(session.response.status).to.be.equal(200);
});
it('I can delete a sessions by its ID', async() => {
const session = await apiInstance.sessions.delete({id: sharedSessionId});
expect(session.response.status).to.be.equal(204);
});
});
| fix style issue
| test/integration/specs/sessions.spec.js | fix style issue | <ide><path>est/integration/specs/sessions.spec.js
<ide>
<ide> describe('when using the sessions resource', () => {
<ide>
<add> const testIds = {with: null, without: null};
<ide> let sharedSessionId;
<ide>
<ide> it('I can create a sessions with ID', async() => {
<ide> const {id: id, ...data} = createSessionsData(true);
<add> testIds.with = id;
<ide> const session = await apiInstance.sessions.create({id: id, data: data});
<ide> expect(session.response.status).to.be.equal(201);
<ide> });
<ide>
<ide>
<ide> it('I can create a sessions without ID', async() => {
<del> const {id: id, ...data} = createSessionsData(true);
<add> const {id: id, ...data} = createSessionsData(false);
<ide> const session = await apiInstance.sessions.create({id: id, data: data});
<add> testIds.without = session.fields.id;
<ide> expect(session.response.status).to.be.equal(201);
<ide> });
<ide>
<ide>
<ide>
<ide> it('I can delete a sessions by its ID', async() => {
<del> const session = await apiInstance.sessions.delete({id: sharedSessionId});
<del> expect(session.response.status).to.be.equal(204);
<add> const session1 = await apiInstance.sessions.delete({id: testIds.with});
<add> const session2 = await apiInstance.sessions.delete({id: testIds.without});
<add> expect(session1.response.status).to.be.equal(204);
<add> expect(session2.response.status).to.be.equal(204);
<ide> });
<ide>
<ide> }); |
|
Java | bsd-2-clause | error: pathspec 'src/java/grl/src/grl/UDPManager.java' did not match any file(s) known to git
| df7b2afc0a55c9d6479737e480d37b1e6e54a9d2 | 1 | ahundt/robone,ahundt/robone,ahundt/robone | package grl;
import java.nio.ByteBuffer;
import com.kuka.task.ITaskLogger;
import java.io.*;
import java.net.*;
public class UDPManager {
DatagramSocket socket = null;
ITaskLogger logger;
String _Remote_IP;
int _Remote_Port;
InetAddress _address_send = null;
int statesLength = 0;
long message_counter = 0;
long noMessageCounter = 0;
long noMessageCounterLimit = 9999999;
private grl.flatbuffer.KUKAiiwaStates _currentKUKAiiwaStates = null;
private grl.flatbuffer.KUKAiiwaState _currentKUKAiiwaState = null;
private grl.flatbuffer.KUKAiiwaState _previousKUKAiiwaState = null;
ByteBuffer bb = null;
boolean stop;
long startTime;
long elapsedTime;
long lastMessageStartTime;
long lastMessageElapsedTime;
long lastMessageTimeoutMilliseconds = 1000;
int retriesAllowed = 3;
int retriesAttempted = 0;
public UDPManager(String laptopIP, String laptopPort, ITaskLogger errorlogger) {
super();
this.logger = errorlogger;
_Remote_IP = laptopIP;
_Remote_Port = Integer.parseInt(laptopPort);
try {
_address_send = InetAddress.getByName(_Remote_IP);
} catch (UnknownHostException e) {
logger.error("Could not create InetAddress for sending");
}
}
/**
* Blocks until a connection is established or stop() is called.
*
* @return error code: false on success, otherwise failure (or told to stop)
* @throws UnknownHostException
*/
public boolean connect() {
logger.info("Waiting for connection initialization...");
try {
socket = new DatagramSocket();
} catch (SocketException e1) {
logger.info("failed to create socket.");
}
// Dummy message to send to Remote pc (server), in order for the server to know the address of the client (this machine)
String dummyMessage = "Hi";
DatagramPacket packetSend= new DatagramPacket(dummyMessage.getBytes(), dummyMessage.getBytes().length, _address_send, _Remote_Port);
try {
socket.setSoTimeout(100);
} catch (SocketException e1) {
logger.error("failed to set socket timeout");
}
startTime = System.currentTimeMillis();
elapsedTime = 0L;
grl.flatbuffer.KUKAiiwaStates newKUKAiiwaStates = null;
int newStatesLength = 0;
boolean continueSending = true;
while(newStatesLength<1 && newKUKAiiwaStates == null){
byte[] recBuf = new byte[1024];
DatagramPacket packet = new DatagramPacket(recBuf, recBuf.length);
// continues sending dummy messages untill the server receives the address of this machine and sends a message back
while (continueSending){
try {
socket.send(packetSend);
} catch (IOException e1) {
// Could not send
}
try {
socket.receive(packet);
continueSending = false;
} catch (SocketTimeoutException e) {
// TimeOut reached, continue sending until we receive something
} catch (IOException e) {
// Could not receive packet
}
}
if(packet.getLength() > 0){
bb = ByteBuffer.wrap(recBuf);
newKUKAiiwaStates = grl.flatbuffer.KUKAiiwaStates.getRootAsKUKAiiwaStates(bb);
newStatesLength = newKUKAiiwaStates.statesLength();
}
if (stop) {
logger.info("Stopping program.");
return true; // asked to exit
}
}
_currentKUKAiiwaStates = newKUKAiiwaStates;
statesLength = newStatesLength;
logger.info("States initialized...");
startTime = System.currentTimeMillis();
lastMessageStartTime = startTime;
lastMessageElapsedTime = System.currentTimeMillis() - lastMessageStartTime;
elapsedTime = 0L;
return false; // no error
}
/**
* Blocks until a connection is re-established or stop() is called.
*
* @return error code: false on success, otherwise failure (or told to stop)
* @throws IOException
*/
public boolean sendMessage(byte[] msg, int size) throws IOException
{
DatagramPacket packet= new DatagramPacket(msg, size, _address_send , _Remote_Port );
socket.send(packet);
return true;
}
public grl.flatbuffer.KUKAiiwaState waitForNextMessage()
{
boolean haveNextMessage = false;
while(!stop && !haveNextMessage) {
byte[] recBuf = new byte[1024];
DatagramPacket packet = new DatagramPacket(recBuf, recBuf.length);
try {
socket.receive(packet);
} catch (IOException e) {
logger.info("Failed to receive packet");
}
if(packet.getLength() > 0){
message_counter+=1;
bb = ByteBuffer.wrap(recBuf);
_currentKUKAiiwaStates = grl.flatbuffer.KUKAiiwaStates.getRootAsKUKAiiwaStates(bb, _currentKUKAiiwaStates);
if(_currentKUKAiiwaStates.statesLength()>0) {
// initialize the fist state
grl.flatbuffer.KUKAiiwaState tmp = _currentKUKAiiwaStates.states(0);
if (tmp == null || tmp.armControlState() == null) {
noMessageCounter +=1;
if (message_counter % 100 == 0) {
logger.warn("NULL ArmControlState message, main ZMQ message is arriving but doesn't contain any data/commands!");
}
continue;
} else {
_previousKUKAiiwaState = _currentKUKAiiwaState;
_currentKUKAiiwaState = tmp;
}
if (_currentKUKAiiwaState == null) {
noMessageCounter+=1;
logger.error("Missing current state message!");
continue;
}
haveNextMessage=true;
noMessageCounter = 0;
lastMessageStartTime = System.currentTimeMillis();
} else {
logger.error("got a ZMQ message but it isn't a valid message, this is an unexpected state that shouldn't occur. please debug me.");
}
// }
}
}
return _currentKUKAiiwaState;
}
public grl.flatbuffer.KUKAiiwaState getCurrentMessage(){
return _currentKUKAiiwaState;
}
public grl.flatbuffer.KUKAiiwaState getPrevMessage(){
return _previousKUKAiiwaState;
}
public boolean isStop() {
return stop;
}
public void setStop(boolean stop) {
if(stop)
{
// done
socket.close();
logger.error("socket closed");
this.stop = stop;
}
}
public void stop(){
setStop(true);
}
protected void finalize() {
try {
logger.error("Trying to close socket");
socket.close();
logger.error("Socket Closed");
}
catch (Exception e)
{
logger.error("Could not close socket");
}
}
}
| src/java/grl/src/grl/UDPManager.java | Class UDPManager added to Java code for handling communication between java software in robot and the ros interface in pc
| src/java/grl/src/grl/UDPManager.java | Class UDPManager added to Java code for handling communication between java software in robot and the ros interface in pc | <ide><path>rc/java/grl/src/grl/UDPManager.java
<add>package grl;
<add>
<add>import java.nio.ByteBuffer;
<add>
<add>import com.kuka.task.ITaskLogger;
<add>import java.io.*;
<add>import java.net.*;
<add>
<add>public class UDPManager {
<add>
<add> DatagramSocket socket = null;
<add>
<add> ITaskLogger logger;
<add> String _Remote_IP;
<add> int _Remote_Port;
<add>
<add> InetAddress _address_send = null;
<add>
<add> int statesLength = 0;
<add> long message_counter = 0;
<add> long noMessageCounter = 0;
<add> long noMessageCounterLimit = 9999999;
<add> private grl.flatbuffer.KUKAiiwaStates _currentKUKAiiwaStates = null;
<add> private grl.flatbuffer.KUKAiiwaState _currentKUKAiiwaState = null;
<add> private grl.flatbuffer.KUKAiiwaState _previousKUKAiiwaState = null;
<add>
<add> ByteBuffer bb = null;
<add> boolean stop;
<add>
<add> long startTime;
<add> long elapsedTime;
<add> long lastMessageStartTime;
<add> long lastMessageElapsedTime;
<add> long lastMessageTimeoutMilliseconds = 1000;
<add>
<add> int retriesAllowed = 3;
<add> int retriesAttempted = 0;
<add>
<add> public UDPManager(String laptopIP, String laptopPort, ITaskLogger errorlogger) {
<add> super();
<add> this.logger = errorlogger;
<add> _Remote_IP = laptopIP;
<add> _Remote_Port = Integer.parseInt(laptopPort);
<add>
<add> try {
<add> _address_send = InetAddress.getByName(_Remote_IP);
<add> } catch (UnknownHostException e) {
<add> logger.error("Could not create InetAddress for sending");
<add> }
<add>
<add> }
<add>
<add> /**
<add> * Blocks until a connection is established or stop() is called.
<add> *
<add> * @return error code: false on success, otherwise failure (or told to stop)
<add> * @throws UnknownHostException
<add> */
<add> public boolean connect() {
<add>
<add> logger.info("Waiting for connection initialization...");
<add>
<add> try {
<add> socket = new DatagramSocket();
<add> } catch (SocketException e1) {
<add> logger.info("failed to create socket.");
<add> }
<add>
<add> // Dummy message to send to Remote pc (server), in order for the server to know the address of the client (this machine)
<add> String dummyMessage = "Hi";
<add>
<add> DatagramPacket packetSend= new DatagramPacket(dummyMessage.getBytes(), dummyMessage.getBytes().length, _address_send, _Remote_Port);
<add>
<add>
<add> try {
<add> socket.setSoTimeout(100);
<add> } catch (SocketException e1) {
<add> logger.error("failed to set socket timeout");
<add> }
<add>
<add> startTime = System.currentTimeMillis();
<add> elapsedTime = 0L;
<add> grl.flatbuffer.KUKAiiwaStates newKUKAiiwaStates = null;
<add> int newStatesLength = 0;
<add>
<add> boolean continueSending = true;
<add>
<add> while(newStatesLength<1 && newKUKAiiwaStates == null){
<add>
<add> byte[] recBuf = new byte[1024];
<add> DatagramPacket packet = new DatagramPacket(recBuf, recBuf.length);
<add>
<add> // continues sending dummy messages untill the server receives the address of this machine and sends a message back
<add> while (continueSending){
<add> try {
<add> socket.send(packetSend);
<add> } catch (IOException e1) {
<add> // Could not send
<add> }
<add> try {
<add> socket.receive(packet);
<add> continueSending = false;
<add> } catch (SocketTimeoutException e) {
<add> // TimeOut reached, continue sending until we receive something
<add> } catch (IOException e) {
<add> // Could not receive packet
<add> }
<add> }
<add>
<add> if(packet.getLength() > 0){
<add>
<add> bb = ByteBuffer.wrap(recBuf);
<add>
<add> newKUKAiiwaStates = grl.flatbuffer.KUKAiiwaStates.getRootAsKUKAiiwaStates(bb);
<add> newStatesLength = newKUKAiiwaStates.statesLength();
<add>
<add> }
<add>
<add> if (stop) {
<add> logger.info("Stopping program.");
<add> return true; // asked to exit
<add> }
<add> }
<add>
<add> _currentKUKAiiwaStates = newKUKAiiwaStates;
<add> statesLength = newStatesLength;
<add>
<add> logger.info("States initialized...");
<add>
<add> startTime = System.currentTimeMillis();
<add> lastMessageStartTime = startTime;
<add> lastMessageElapsedTime = System.currentTimeMillis() - lastMessageStartTime;
<add> elapsedTime = 0L;
<add>
<add> return false; // no error
<add> }
<add>
<add> /**
<add> * Blocks until a connection is re-established or stop() is called.
<add> *
<add> * @return error code: false on success, otherwise failure (or told to stop)
<add> * @throws IOException
<add> */
<add>
<add>
<add> public boolean sendMessage(byte[] msg, int size) throws IOException
<add> {
<add> DatagramPacket packet= new DatagramPacket(msg, size, _address_send , _Remote_Port );
<add> socket.send(packet);
<add> return true;
<add> }
<add>
<add> public grl.flatbuffer.KUKAiiwaState waitForNextMessage()
<add> {
<add> boolean haveNextMessage = false;
<add> while(!stop && !haveNextMessage) {
<add>
<add> byte[] recBuf = new byte[1024];
<add> DatagramPacket packet = new DatagramPacket(recBuf, recBuf.length);
<add> try {
<add> socket.receive(packet);
<add> } catch (IOException e) {
<add> logger.info("Failed to receive packet");
<add> }
<add>
<add> if(packet.getLength() > 0){
<add>
<add> message_counter+=1;
<add> bb = ByteBuffer.wrap(recBuf);
<add>
<add> _currentKUKAiiwaStates = grl.flatbuffer.KUKAiiwaStates.getRootAsKUKAiiwaStates(bb, _currentKUKAiiwaStates);
<add>
<add> if(_currentKUKAiiwaStates.statesLength()>0) {
<add> // initialize the fist state
<add> grl.flatbuffer.KUKAiiwaState tmp = _currentKUKAiiwaStates.states(0);
<add> if (tmp == null || tmp.armControlState() == null) {
<add> noMessageCounter +=1;
<add> if (message_counter % 100 == 0) {
<add> logger.warn("NULL ArmControlState message, main ZMQ message is arriving but doesn't contain any data/commands!");
<add> }
<add> continue;
<add> } else {
<add> _previousKUKAiiwaState = _currentKUKAiiwaState;
<add> _currentKUKAiiwaState = tmp;
<add> }
<add>
<add> if (_currentKUKAiiwaState == null) {
<add> noMessageCounter+=1;
<add> logger.error("Missing current state message!");
<add> continue;
<add> }
<add>
<add> haveNextMessage=true;
<add> noMessageCounter = 0;
<add> lastMessageStartTime = System.currentTimeMillis();
<add> } else {
<add> logger.error("got a ZMQ message but it isn't a valid message, this is an unexpected state that shouldn't occur. please debug me.");
<add> }
<add> // }
<add> }
<add> }
<add>
<add> return _currentKUKAiiwaState;
<add> }
<add>
<add> public grl.flatbuffer.KUKAiiwaState getCurrentMessage(){
<add> return _currentKUKAiiwaState;
<add> }
<add>
<add> public grl.flatbuffer.KUKAiiwaState getPrevMessage(){
<add> return _previousKUKAiiwaState;
<add> }
<add>
<add>
<add>
<add> public boolean isStop() {
<add> return stop;
<add> }
<add>
<add> public void setStop(boolean stop) {
<add> if(stop)
<add> {
<add> // done
<add> socket.close();
<add> logger.error("socket closed");
<add> this.stop = stop;
<add>
<add> }
<add> }
<add>
<add> public void stop(){
<add> setStop(true);
<add> }
<add>
<add> protected void finalize() {
<add> try {
<add> logger.error("Trying to close socket");
<add> socket.close();
<add> logger.error("Socket Closed");
<add> }
<add> catch (Exception e)
<add> {
<add> logger.error("Could not close socket");
<add> }
<add> }
<add>
<add>
<add>
<add>
<add>
<add>
<add>} |
|
Java | mit | 47801e2da5ca688d4c900fede4d86a4e8f069347 | 0 | rcbyron/java | /* CRITTERS Critter.java
* EE422C Project 4 submission by
* Robert (Connor) Byron
* rcb2746
* 76550
* Joel Guo
* jg55475
* 76550
* Slip days used: 0 (+1 for this project)
* Fall 2015
*/
package project4;
import java.awt.Point;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javafx.scene.paint.Color;
/* see the PDF for descriptions of the methods and fields in this class
* you may add fields, methods or inner classes to Critter ONLY if you make your additions private
* no new public, protected or default-package code or data can be added to Critter
*/
public abstract class Critter {
private static final Point[] dirs = {
new Point(1, 0),
new Point(1, 1),
new Point(0, 1),
new Point(-1, 1),
new Point(-1, 0),
new Point(-1, -1),
new Point(0, -1),
new Point(1, -1)
};
private static Map<Point, ArrayList<Critter>> world = new HashMap<Point, ArrayList<Critter>>();
public static List<Critter> getPopulation() {
return population;
}
public Color getColor() { return Color.BLACK; }
public int getX() { return x_coord; }
public int getY() { return y_coord; }
private static java.util.Random rand = new java.util.Random();
public static int getRandomInt(int max) {
return rand.nextInt(max);
}
public static void setSeed(long new_seed) {
rand = new java.util.Random(new_seed);
}
/* a one-character long string that visually depicts your critter in the ASCII interface */
public String toString() { return "?"; }
private int energy = Params.start_energy;
protected int getEnergy() { return energy; }
private boolean hasMoved;
private int x_coord;
private int y_coord;
private void move(int direction) {
x_coord = (x_coord + dirs[direction].x) % Params.world_width;
y_coord = (y_coord + dirs[direction].y) % Params.world_height;
hasMoved = true;
}
protected String look(int direction) {
int x = (x_coord + dirs[direction].x) % Params.world_width;
int y = (y_coord + dirs[direction].y) % Params.world_height;
Point p = new Point(x, y);
if(world.get(p).size() > 0) {
return world.get(p).get(0).toString();
}
return null;
}
protected String look2(int direction) {
int x = (x_coord + 2 * dirs[direction].x) % Params.world_width;
int y = (y_coord + 2 * dirs[direction].y) % Params.world_height;
Point p = new Point(x, y);
if(world.get(p).size() > 0) {
return world.get(p).get(0).toString();
}
return null;
}
protected final void walk(int direction) {
energy -= Params.walk_energy_cost;
if (energy >= 0)
move(direction);
}
protected final void run(int direction) {
energy -= Params.run_energy_cost;
if (energy >= 0) {
move(direction);
move(direction);
}
}
protected final void reproduce(Critter offspring, int direction) {
if (energy < Params.min_reproduce_energy) { return; }
offspring.energy = energy / 2;
energy = energy % 2 == 0 ? energy / 2 : energy / 2 + 1;
offspring.x_coord = (x_coord + dirs[direction].x) % Params.world_width;
offspring.y_coord = (x_coord + dirs[direction].x) % Params.world_width;
babies.add(offspring);
}
public abstract void doTimeStep();
public abstract boolean fight(String opponent);
/* create and initialize a Critter subclass
* critter_class_name must be the name of a concrete subclass of Critter, if not
* an InvalidCritterException must be thrown
*/
public static void makeCritter(String critter_class_name) throws InvalidCritterException {
Class<?> myCritter = null;
Constructor<?> constructor = null;
Object instanceOfMyCritter = null;
try {
myCritter = Class.forName(critter_class_name);
constructor = myCritter.getConstructor(); // get null parameter constructor
instanceOfMyCritter = constructor.newInstance(); // create instance
Critter me = (Critter) instanceOfMyCritter; // cast to Critter
me.x_coord = getRandomInt(Params.world_width);
me.y_coord = getRandomInt(Params.world_height);
population.add(me);
Point pos = new Point(me.x_coord, me.y_coord);
ArrayList<Critter> bucket = world.get(pos);
if (bucket == null) bucket = new ArrayList<Critter>();
bucket.add(me);
world.put(pos, bucket);
} catch (Exception e) {
if (e instanceof ClassNotFoundException)
throw new InvalidCritterException(critter_class_name);
else
e.printStackTrace();
}
}
public static List<Critter> getInstances(String critter_class_name) throws InvalidCritterException {
List<Critter> result = new java.util.ArrayList<Critter>();
for (ArrayList<Critter> bugs : world.values()) {
for (Critter bug : bugs) {
if (bug.getClass().getTypeName().equals(critter_class_name))
result.add(bug);
}
}
return result;
}
public static void runStats(List<Critter> critters) {
System.out.print("" + critters.size() + " critters as follows -- ");
java.util.Map<String, Integer> critter_count = new java.util.HashMap<String, Integer>();
for (Critter crit : critters) {
String crit_string = crit.toString();
Integer old_count = critter_count.get(crit_string);
if (old_count == null) {
critter_count.put(crit_string, 1);
} else {
critter_count.put(crit_string, old_count.intValue() + 1);
}
}
String prefix = "";
for (String s : critter_count.keySet()) {
System.out.print(prefix + s + ":" + critter_count.get(s));
prefix = ", ";
}
System.out.println();
}
/* the TestCritter class allows some critters to "cheat". If you want to
* create tests of your Critter model, you can create subclasses of this class
* and then use the setter functions contained here.
*
* NOTE: you must make sure that the setter functions work with your implementation
* of Critter. That means, if you're recording the positions of your critters
* using some sort of external grid or some other data structure in addition
* to the x_coord and y_coord functions, then you MUST update these setter functions
* so that they correctly update your grid/data structure.
*/
static abstract class TestCritter extends Critter {
protected void setEnergy(int new_energy_value) {
super.energy = new_energy_value;
}
protected void setXCoord(int new_x_coord) {
super.x_coord = new_x_coord;
}
protected void setYCoord(int new_y_coord) {
super.y_coord = new_y_coord;
}
}
private static List<Critter> population = new java.util.ArrayList<Critter>();
private static List<Critter> babies = new java.util.ArrayList<Critter>();
private static void doEncounters() {
for (ArrayList<Critter> spot : world.values()) {
//if coordinate occupied by more than one critter
while (spot.size() > 1) {
Critter critA = spot.get(0);
Critter critB = spot.get(1);
Point fightPoint = new Point(critA.x_coord, critA.y_coord);
boolean fightA = critA.fight(critB.toString());
boolean fightB = critB.fight(critA.toString());
if (!fightA) { critA.tryToEscape(); }
if (!fightB) { critB.tryToEscape(); }
if (critA.energy <= 0 || critB.energy <= 0) {
if (critB.energy <= 0) { spot.remove(critB); population.remove(critB); }
if (critA.energy <= 0) { spot.remove(critA); population.remove(critA); }
} else if (critA.x_coord == fightPoint.x && critA.y_coord == fightPoint.y
&& critB.x_coord == fightPoint.x && critB.y_coord == fightPoint.y) {
//actually fight
int rollA = getRandomInt(critA.energy);
int rollB = getRandomInt(critB.energy);
if (rollA > rollB) {
critA.energy += .5 * critB.energy;
spot.remove(critB);
population.remove(critB);
} else {
critB.energy += .5 * critA.energy;
spot.remove(critA);
population.remove(critA);
}
} else {
if (!(critB.x_coord == fightPoint.x && critB.y_coord == fightPoint.y)) {
spot.remove(critB);
}
if (!(critA.x_coord == fightPoint.x && critA.y_coord == fightPoint.y)) {
spot.remove(critA);
}
}
}
}
}
/*
* if Critter has already moved or cannot find open space, deduct walking energy
* else walk or run to open spot
*/
private void tryToEscape() {
int escapeDir = openAdjacentPoint(new Point(x_coord, y_coord));
if (hasMoved || escapeDir == -1) { energy -= Params.walk_energy_cost; }
else if (escapeDir < 8) { walk(escapeDir); }
else if(escapeDir < 16) { run(escapeDir - 8); }
}
/*
* return 0-7 for direction of immediate open space
* return 8-15 for direction of open space two spaces away
*/
private static int openAdjacentPoint(Point p){
for (int dir = 0; dir < 8; dir++) {
int temp_x = (p.x + dirs[dir].x) % Params.world_width;
int temp_y = (p.y + dirs[dir].y) % Params.world_height;
Point temp_p = new Point(temp_x, temp_y);
if (!world.containsKey(temp_p) || world.get(temp_p).size() == 0) { return dir; }
}
for (int dir = 0; dir < 8; dir++) {
int temp_x = (p.x + 2 * dirs[dir].x) % Params.world_width;
int temp_y = (p.y + 2 * dirs[dir].y) % Params.world_height;
Point temp_p = new Point(temp_x, temp_y);
if (!world.containsKey(temp_p) || world.get(temp_p).size() == 0) { return dir + 8; }
}
return -1;
}
private static int timestep = 0;
public static void worldTimeStep() {
timestep++;
// System.out.println("step: "+timestep);
// loop through all critters in collection, call doTimeStep for each
// i. walk/run
// ii. energy deduction
// iii. reproduce but babies still in crib
// iv. cheat
for (ArrayList<Critter> spot : world.values()) {
for (Critter bug : spot) {
bug.hasMoved = false;
bug.doTimeStep();
}
}
doEncounters();
// Update rest energy
for (ArrayList<Critter> spot : world.values())
for (Critter bug : spot)
bug.energy -= Params.rest_energy_cost;
// Add algae
try {
for (int i = 0; i < Params.refresh_algae_count; i++)
makeCritter("project4.Algae");
} catch (InvalidCritterException e) {
e.printStackTrace();
}
// Remove dead critters
Iterator<Critter> iter = population.iterator();
while (iter.hasNext()) {
Critter bug = iter.next();
if (bug.energy <= 0) {
iter.remove();
}
}
// Add babies to population
population.addAll(babies);
// Clear and update critter map
for (ArrayList<Critter> spot : world.values())
spot.clear();
for (Critter bug : population) {
Point p = new Point(bug.x_coord, bug.y_coord);
if (!world.containsKey(p)) world.put(p, new ArrayList<Critter>());
world.get(p).add(bug);
}
// displayWorld();
}
public static void displayWorld() {
// for (int i = -1; i <= Params.world_height; i++) {
// for (int j = -1; j <= Params.world_width; j++) {
// if (i == -1 || i == Params.world_height)
// System.out.print((j == -1 || j == Params.world_width) ? '+' : '-');
// else {
// Point currPos = new Point(j, i);
// if (j == -1 || j == Params.world_width)
// System.out.print('|');
// else if (world.containsKey(currPos) && world.get(currPos).size() > 0)
// System.out.print(world.get(currPos).get(0));
// else
// System.out.print(' ');
// }
// }
// System.out.println();
// }
Main.launch(Main.class);
}
}
| critter-world-fx/project4/Critter.java | /* CRITTERS Critter.java
* EE422C Project 4 submission by
* Robert (Connor) Byron
* rcb2746
* 76550
* Joel Guo
* jg55475
* 76550
* Slip days used: 0 (+1 for this project)
* Fall 2015
*/
package project4;
import java.awt.Point;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javafx.scene.paint.Color;
/* see the PDF for descriptions of the methods and fields in this class
* you may add fields, methods or inner classes to Critter ONLY if you make your additions private
* no new public, protected or default-package code or data can be added to Critter
*/
public abstract class Critter {
private static final Point[] dirs = {
new Point(1, 0),
new Point(1, 1),
new Point(0, 1),
new Point(-1, 1),
new Point(-1, 0),
new Point(-1, -1),
new Point(0, -1),
new Point(1, -1)
};
private static Map<Point, ArrayList<Critter>> world = new HashMap<Point, ArrayList<Critter>>();
public static List<Critter> getPopulation() {
return population;
}
public Color getColor() { return Color.BLACK; }
public int getX() { return x_coord; }
public int getY() { return y_coord; }
private static java.util.Random rand = new java.util.Random();
public static int getRandomInt(int max) {
return rand.nextInt(max);
}
public static void setSeed(long new_seed) {
rand = new java.util.Random(new_seed);
}
/* a one-character long string that visually depicts your critter in the ASCII interface */
public String toString() { return "?"; }
private int energy = Params.start_energy;
protected int getEnergy() { return energy; }
private boolean hasMoved;
private int x_coord;
private int y_coord;
private void move(int direction) {
x_coord = (x_coord + dirs[direction].x) % Params.world_width;
y_coord = (y_coord + dirs[direction].y) % Params.world_height;
hasMoved = true;
}
protected final void walk(int direction) {
energy -= Params.walk_energy_cost;
if (energy >= 0)
move(direction);
}
protected final void run(int direction) {
energy -= Params.run_energy_cost;
if (energy >= 0) {
move(direction);
move(direction);
}
}
protected final void reproduce(Critter offspring, int direction) {
if (energy < Params.min_reproduce_energy) { return; }
offspring.energy = energy / 2;
energy = energy % 2 == 0 ? energy / 2 : energy / 2 + 1;
offspring.x_coord = (x_coord + dirs[direction].x) % Params.world_width;
offspring.y_coord = (x_coord + dirs[direction].x) % Params.world_width;
babies.add(offspring);
}
public abstract void doTimeStep();
public abstract boolean fight(String opponent);
/* create and initialize a Critter subclass
* critter_class_name must be the name of a concrete subclass of Critter, if not
* an InvalidCritterException must be thrown
*/
public static void makeCritter(String critter_class_name) throws InvalidCritterException {
Class<?> myCritter = null;
Constructor<?> constructor = null;
Object instanceOfMyCritter = null;
try {
myCritter = Class.forName(critter_class_name);
constructor = myCritter.getConstructor(); // get null parameter constructor
instanceOfMyCritter = constructor.newInstance(); // create instance
Critter me = (Critter) instanceOfMyCritter; // cast to Critter
me.x_coord = getRandomInt(Params.world_width);
me.y_coord = getRandomInt(Params.world_height);
population.add(me);
Point pos = new Point(me.x_coord, me.y_coord);
ArrayList<Critter> bucket = world.get(pos);
if (bucket == null) bucket = new ArrayList<Critter>();
bucket.add(me);
world.put(pos, bucket);
} catch (Exception e) {
if (e instanceof ClassNotFoundException)
throw new InvalidCritterException(critter_class_name);
else
e.printStackTrace();
}
}
public static List<Critter> getInstances(String critter_class_name) throws InvalidCritterException {
List<Critter> result = new java.util.ArrayList<Critter>();
for (ArrayList<Critter> bugs : world.values()) {
for (Critter bug : bugs) {
if (bug.getClass().getTypeName().equals(critter_class_name))
result.add(bug);
}
}
return result;
}
public static void runStats(List<Critter> critters) {
System.out.print("" + critters.size() + " critters as follows -- ");
java.util.Map<String, Integer> critter_count = new java.util.HashMap<String, Integer>();
for (Critter crit : critters) {
String crit_string = crit.toString();
Integer old_count = critter_count.get(crit_string);
if (old_count == null) {
critter_count.put(crit_string, 1);
} else {
critter_count.put(crit_string, old_count.intValue() + 1);
}
}
String prefix = "";
for (String s : critter_count.keySet()) {
System.out.print(prefix + s + ":" + critter_count.get(s));
prefix = ", ";
}
System.out.println();
}
/* the TestCritter class allows some critters to "cheat". If you want to
* create tests of your Critter model, you can create subclasses of this class
* and then use the setter functions contained here.
*
* NOTE: you must make sure that the setter functions work with your implementation
* of Critter. That means, if you're recording the positions of your critters
* using some sort of external grid or some other data structure in addition
* to the x_coord and y_coord functions, then you MUST update these setter functions
* so that they correctly update your grid/data structure.
*/
static abstract class TestCritter extends Critter {
protected void setEnergy(int new_energy_value) {
super.energy = new_energy_value;
}
protected void setXCoord(int new_x_coord) {
super.x_coord = new_x_coord;
}
protected void setYCoord(int new_y_coord) {
super.y_coord = new_y_coord;
}
}
private static List<Critter> population = new java.util.ArrayList<Critter>();
private static List<Critter> babies = new java.util.ArrayList<Critter>();
private static void doEncounters() {
for (ArrayList<Critter> spot : world.values()) {
//if coordinate occupied by more than one critter
while (spot.size() > 1) {
Critter critA = spot.get(0);
Critter critB = spot.get(1);
Point fightPoint = new Point(critA.x_coord, critA.y_coord);
boolean fightA = critA.fight(critB.toString());
boolean fightB = critB.fight(critA.toString());
if (!fightA) { critA.tryToEscape(); }
if (!fightB) { critB.tryToEscape(); }
if (critA.energy <= 0 || critB.energy <= 0) {
if (critB.energy <= 0) { spot.remove(critB); population.remove(critB); }
if (critA.energy <= 0) { spot.remove(critA); population.remove(critA); }
} else if (critA.x_coord == fightPoint.x && critA.y_coord == fightPoint.y
&& critB.x_coord == fightPoint.x && critB.y_coord == fightPoint.y) {
//actually fight
int rollA = getRandomInt(critA.energy);
int rollB = getRandomInt(critB.energy);
if (rollA > rollB) {
critA.energy += .5 * critB.energy;
spot.remove(critB);
population.remove(critB);
} else {
critB.energy += .5 * critA.energy;
spot.remove(critA);
population.remove(critA);
}
} else {
if (!(critB.x_coord == fightPoint.x && critB.y_coord == fightPoint.y)) {
spot.remove(critB);
}
if (!(critA.x_coord == fightPoint.x && critA.y_coord == fightPoint.y)) {
spot.remove(critA);
}
}
}
}
}
/*
* if Critter has already moved or cannot find open space, deduct walking energy
* else walk or run to open spot
*/
private void tryToEscape() {
int escapeDir = openAdjacentPoint(new Point(x_coord, y_coord));
if (hasMoved || escapeDir == -1) { energy -= Params.walk_energy_cost; }
else if (escapeDir < 8) { walk(escapeDir); }
else if(escapeDir < 16) { run(escapeDir - 8); }
}
/*
* return 0-7 for direction of immediate open space
* return 8-15 for direction of open space two spaces away
*/
private static int openAdjacentPoint(Point p){
for (int dir = 0; dir < 8; dir++) {
int temp_x = (p.x + dirs[dir].x) % Params.world_width;
int temp_y = (p.y + dirs[dir].y) % Params.world_height;
Point temp_p = new Point(temp_x, temp_y);
if (!world.containsKey(temp_p) || world.get(temp_p).size() == 0) { return dir; }
}
for (int dir = 0; dir < 8; dir++) {
int temp_x = (p.x + 2 * dirs[dir].x) % Params.world_width;
int temp_y = (p.y + 2 * dirs[dir].y) % Params.world_height;
Point temp_p = new Point(temp_x, temp_y);
if (!world.containsKey(temp_p) || world.get(temp_p).size() == 0) { return dir + 8; }
}
return -1;
}
private static int timestep = 0;
public static void worldTimeStep() {
timestep++;
// System.out.println("step: "+timestep);
// loop through all critters in collection, call doTimeStep for each
// i. walk/run
// ii. energy deduction
// iii. reproduce but babies still in crib
// iv. cheat
for (ArrayList<Critter> spot : world.values()) {
for (Critter bug : spot) {
bug.hasMoved = false;
bug.doTimeStep();
}
}
doEncounters();
// Update rest energy
for (ArrayList<Critter> spot : world.values())
for (Critter bug : spot)
bug.energy -= Params.rest_energy_cost;
// Add algae
try {
for (int i = 0; i < Params.refresh_algae_count; i++)
makeCritter("project4.Algae");
} catch (InvalidCritterException e) {
e.printStackTrace();
}
// Remove dead critters
Iterator<Critter> iter = population.iterator();
while (iter.hasNext()) {
Critter bug = iter.next();
if (bug.energy <= 0) {
iter.remove();
}
}
// Add babies to population
population.addAll(babies);
// Clear and update critter map
for (ArrayList<Critter> spot : world.values())
spot.clear();
for (Critter bug : population) {
Point p = new Point(bug.x_coord, bug.y_coord);
if (!world.containsKey(p)) world.put(p, new ArrayList<Critter>());
world.get(p).add(bug);
}
// displayWorld();
}
public static void displayWorld() {
// for (int i = -1; i <= Params.world_height; i++) {
// for (int j = -1; j <= Params.world_width; j++) {
// if (i == -1 || i == Params.world_height)
// System.out.print((j == -1 || j == Params.world_width) ? '+' : '-');
// else {
// Point currPos = new Point(j, i);
// if (j == -1 || j == Params.world_width)
// System.out.print('|');
// else if (world.containsKey(currPos) && world.get(currPos).size() > 0)
// System.out.print(world.get(currPos).get(0));
// else
// System.out.print(' ');
// }
// }
// System.out.println();
// }
Main.launch(Main.class);
}
}
| Joel sux
| critter-world-fx/project4/Critter.java | Joel sux | <ide><path>ritter-world-fx/project4/Critter.java
<ide> x_coord = (x_coord + dirs[direction].x) % Params.world_width;
<ide> y_coord = (y_coord + dirs[direction].y) % Params.world_height;
<ide> hasMoved = true;
<add> }
<add>
<add> protected String look(int direction) {
<add> int x = (x_coord + dirs[direction].x) % Params.world_width;
<add> int y = (y_coord + dirs[direction].y) % Params.world_height;
<add> Point p = new Point(x, y);
<add> if(world.get(p).size() > 0) {
<add> return world.get(p).get(0).toString();
<add> }
<add> return null;
<add> }
<add>
<add> protected String look2(int direction) {
<add> int x = (x_coord + 2 * dirs[direction].x) % Params.world_width;
<add> int y = (y_coord + 2 * dirs[direction].y) % Params.world_height;
<add> Point p = new Point(x, y);
<add> if(world.get(p).size() > 0) {
<add> return world.get(p).get(0).toString();
<add> }
<add> return null;
<ide> }
<ide>
<ide> protected final void walk(int direction) { |
|
Java | apache-2.0 | 23cc2d5c5420af695b9b0f219bb3f8c8efe982a6 | 0 | polopoly/brap | package no.tornado.brap.auth;
import java.io.Serializable;
/**
* A principal that can hold a username/password combination.
* You are welcome to write your own principal, or just use your
* existing domain object for authentication!
*
* @see no.tornado.brap.auth.AuthenticationProvider
* @see no.tornado.brap.auth.UsernamePasswordPrincipal
*/
public class UsernamePasswordPrincipal implements Serializable {
private String username;
private String password;
public UsernamePasswordPrincipal() {
}
public UsernamePasswordPrincipal(String username, String password) {
this.username = username;
this.password = password;
}
public String toString() {
return "Username: " + username + "\nPassword: " + password;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UsernamePasswordPrincipal that = (UsernamePasswordPrincipal) o;
if (password != null ? !password.equals(that.password) : that.password != null) return false;
if (username != null ? !username.equals(that.username) : that.username != null) return false;
return true;
}
public int hashCode() {
int result = username != null ? username.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return getClass().getCanonicalName();
}
}
| brap-server/src/main/java/no/tornado/brap/auth/UsernamePasswordPrincipal.java | package no.tornado.brap.auth;
import java.io.Serializable;
/**
* A principal that can hold a username/password combination.
* You are welcome to write your own principal, or just use your
* existing domain object for authentication!
*
* @see no.tornado.brap.auth.AuthenticationProvider
* @see no.tornado.brap.auth.UsernamePasswordPrincipal
*/
public class UsernamePasswordPrincipal implements Serializable {
private String username;
private String password;
public UsernamePasswordPrincipal(String username, String password) {
this.username = username;
this.password = password;
}
public String toString() {
return "Username: " + username + "\nPassword: " + password;
}
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UsernamePasswordPrincipal that = (UsernamePasswordPrincipal) o;
if (password != null ? !password.equals(that.password) : that.password != null) return false;
if (username != null ? !username.equals(that.username) : that.username != null) return false;
return true;
}
public int hashCode() {
int result = username != null ? username.hashCode() : 0;
result = 31 * result + (password != null ? password.hashCode() : 0);
return result;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return getClass().getCanonicalName();
}
}
| Added empty constructor to UsernamePasswordPrincipal
git-svn-id: a8e09c428ee126305714c93ec2b5216c2b20765b@88 9f856da2-7ffc-11de-b80a-f3367b01929d
| brap-server/src/main/java/no/tornado/brap/auth/UsernamePasswordPrincipal.java | Added empty constructor to UsernamePasswordPrincipal | <ide><path>rap-server/src/main/java/no/tornado/brap/auth/UsernamePasswordPrincipal.java
<ide> public class UsernamePasswordPrincipal implements Serializable {
<ide> private String username;
<ide> private String password;
<add>
<add> public UsernamePasswordPrincipal() {
<add> }
<ide>
<ide> public UsernamePasswordPrincipal(String username, String password) {
<ide> this.username = username; |
|
Java | apache-2.0 | 8d667d17cef7595a8cc5bce0b8ff01fa9edacfb9 | 0 | bywan/trello-java-wrapper,nilsga/trello-java-wrapper | package com.julienvey.trello.impl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.julienvey.trello.TrelloHttpClient;
import com.julienvey.trello.exception.TrelloHttpException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ApacheHttpClient implements TrelloHttpClient {
private static final Pattern NAMES_PATTERN = Pattern.compile("\\{([^/]+?)\\}");
private DefaultHttpClient httpClient;
private ObjectMapper mapper;
public ApacheHttpClient() {
this.httpClient = new DefaultHttpClient();
this.mapper = new ObjectMapper();
}
@Override
public <T> T get(String url, Class<T> objectClass, String... params) {
HttpGet httpGet = new HttpGet(expandUrl(url, params));
return getEntityAndReleaseConnection(objectClass, httpGet);
}
@Override
public <T> T postForObject(String url, T object, Class<T> objectClass, String... params) {
HttpPost httpPost = new HttpPost(expandUrl(url, params));
try {
HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
return getEntityAndReleaseConnection(objectClass, httpPost);
} catch (JsonProcessingException e) {
// TODO : custom exception
throw new RuntimeException(e);
}
}
@Override
public URI postForLocation(String url, Object object, String... params) {
HttpPost httpPost = new HttpPost(expandUrl(url, params));
try {
HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
HttpResponse httpResponse = this.httpClient.execute(httpPost);
Header location = httpResponse.getFirstHeader("Location");
if (location != null) {
return URI.create(location.getValue());
} else {
// TODO : error
throw new NullPointerException();
}
} catch (JsonProcessingException e) {
// TODO : custom exception
throw new RuntimeException(e);
} catch (IOException e) {
throw new TrelloHttpException(e);
} finally {
httpPost.releaseConnection();
}
}
private <T> T getEntityAndReleaseConnection(Class<T> objectClass, HttpRequestBase httpRequest) {
try {
HttpResponse httpResponse = this.httpClient.execute(httpRequest);
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
return this.mapper.readValue(httpEntity.getContent(), objectClass);
} else {
// TODO : error
throw new NullPointerException();
}
} catch (IOException e) {
throw new TrelloHttpException(e);
} finally {
httpRequest.releaseConnection();
}
}
private String expandUrl(String url, String... params) {
if (url == null) {
return null;
}
if (url.indexOf('{') == -1) {
return url;
}
Matcher matcher = NAMES_PATTERN.matcher(url);
StringBuffer sb = new StringBuffer();
int variable = 0;
while (matcher.find()) {
String variableValue = params[variable];
String replacement = Matcher.quoteReplacement(variableValue);
matcher.appendReplacement(sb, replacement);
variable++;
}
matcher.appendTail(sb);
return sb.toString();
}
}
| src/main/java/com/julienvey/trello/impl/ApacheHttpClient.java | package com.julienvey.trello.impl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.julienvey.trello.TrelloHttpClient;
import com.julienvey.trello.exception.TrelloHttpException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.IOException;
import java.net.URI;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ApacheHttpClient implements TrelloHttpClient {
private static final Pattern NAMES_PATTERN = Pattern.compile("\\{([^/]+?)\\}");
private DefaultHttpClient httpClient;
private ObjectMapper mapper;
public ApacheHttpClient() {
this.httpClient = new DefaultHttpClient();
this.mapper = new ObjectMapper();
}
@Override
public <T> T get(String url, Class<T> objectClass, String... params) {
HttpGet httpGet = new HttpGet(expandUrl(url, params));
try {
HttpResponse httpResponse = this.httpClient.execute(httpGet);
// TODO : check http code
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
return this.mapper.readValue(httpEntity.getContent(), objectClass);
} else {
// TODO : error
throw new NullPointerException();
}
} catch (IOException e) {
throw new TrelloHttpException(e);
} finally {
httpGet.releaseConnection();
}
}
@Override
public <T> T postForObject(String url, T object, Class<T> objectClass, String... params) {
HttpPost httpPost = new HttpPost(expandUrl(url, params));
try {
HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
HttpResponse httpResponse = this.httpClient.execute(httpPost);
// TODO : check http code
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
return this.mapper.readValue(httpEntity.getContent(), objectClass);
} else {
// TODO : error
throw new NullPointerException();
}
} catch (IOException e) {
throw new TrelloHttpException(e);
} finally {
httpPost.releaseConnection();
}
}
@Override
public URI postForLocation(String url, Object object, String... params) {
HttpPost httpPost = new HttpPost(expandUrl(url, params));
try {
HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
HttpResponse httpResponse = this.httpClient.execute(httpPost);
// TODO : check http code
Header location = httpResponse.getFirstHeader("Location");
if (location != null) {
return URI.create(location.getValue());
} else {
throw new NullPointerException();
}
} catch (IOException e) {
throw new TrelloHttpException(e);
} finally {
httpPost.releaseConnection();
}
}
private String expandUrl(String url, String... params) {
if (url == null) {
return null;
}
if (url.indexOf('{') == -1) {
return url;
}
Matcher matcher = NAMES_PATTERN.matcher(url);
StringBuffer sb = new StringBuffer();
int variable = 0;
while (matcher.find()) {
String variableValue = params[variable];
String replacement = Matcher.quoteReplacement(variableValue);
matcher.appendReplacement(sb, replacement);
variable++;
}
matcher.appendTail(sb);
return sb.toString();
}
}
| Add private method getEntityAndReleaseConnection
| src/main/java/com/julienvey/trello/impl/ApacheHttpClient.java | Add private method getEntityAndReleaseConnection | <ide><path>rc/main/java/com/julienvey/trello/impl/ApacheHttpClient.java
<ide> package com.julienvey.trello.impl;
<ide>
<add>import com.fasterxml.jackson.core.JsonProcessingException;
<ide> import com.fasterxml.jackson.databind.ObjectMapper;
<ide> import com.julienvey.trello.TrelloHttpClient;
<ide> import com.julienvey.trello.exception.TrelloHttpException;
<ide> import org.apache.http.HttpResponse;
<ide> import org.apache.http.client.methods.HttpGet;
<ide> import org.apache.http.client.methods.HttpPost;
<add>import org.apache.http.client.methods.HttpRequestBase;
<ide> import org.apache.http.entity.ByteArrayEntity;
<ide> import org.apache.http.entity.ContentType;
<ide> import org.apache.http.impl.client.DefaultHttpClient;
<ide> @Override
<ide> public <T> T get(String url, Class<T> objectClass, String... params) {
<ide> HttpGet httpGet = new HttpGet(expandUrl(url, params));
<del>
<del> try {
<del> HttpResponse httpResponse = this.httpClient.execute(httpGet);
<del> // TODO : check http code
<del> HttpEntity httpEntity = httpResponse.getEntity();
<del> if (httpEntity != null) {
<del> return this.mapper.readValue(httpEntity.getContent(), objectClass);
<del> } else {
<del> // TODO : error
<del> throw new NullPointerException();
<del> }
<del> } catch (IOException e) {
<del> throw new TrelloHttpException(e);
<del> } finally {
<del> httpGet.releaseConnection();
<del> }
<add> return getEntityAndReleaseConnection(objectClass, httpGet);
<ide> }
<ide>
<ide> @Override
<ide> try {
<ide> HttpEntity entity = new ByteArrayEntity(this.mapper.writeValueAsBytes(object), ContentType.APPLICATION_JSON);
<ide> httpPost.setEntity(entity);
<del> HttpResponse httpResponse = this.httpClient.execute(httpPost);
<ide>
<del> // TODO : check http code
<del> HttpEntity httpEntity = httpResponse.getEntity();
<del> if (httpEntity != null) {
<del> return this.mapper.readValue(httpEntity.getContent(), objectClass);
<del> } else {
<del> // TODO : error
<del> throw new NullPointerException();
<del> }
<del> } catch (IOException e) {
<del> throw new TrelloHttpException(e);
<del> } finally {
<del> httpPost.releaseConnection();
<add> return getEntityAndReleaseConnection(objectClass, httpPost);
<add> } catch (JsonProcessingException e) {
<add> // TODO : custom exception
<add> throw new RuntimeException(e);
<ide> }
<ide> }
<ide>
<ide> httpPost.setEntity(entity);
<ide> HttpResponse httpResponse = this.httpClient.execute(httpPost);
<ide>
<del> // TODO : check http code
<ide> Header location = httpResponse.getFirstHeader("Location");
<ide> if (location != null) {
<ide> return URI.create(location.getValue());
<ide> } else {
<add> // TODO : error
<add> throw new NullPointerException();
<add> }
<add> } catch (JsonProcessingException e) {
<add> // TODO : custom exception
<add> throw new RuntimeException(e);
<add> } catch (IOException e) {
<add> throw new TrelloHttpException(e);
<add> } finally {
<add> httpPost.releaseConnection();
<add> }
<add> }
<add>
<add> private <T> T getEntityAndReleaseConnection(Class<T> objectClass, HttpRequestBase httpRequest) {
<add> try {
<add> HttpResponse httpResponse = this.httpClient.execute(httpRequest);
<add>
<add> HttpEntity httpEntity = httpResponse.getEntity();
<add> if (httpEntity != null) {
<add> return this.mapper.readValue(httpEntity.getContent(), objectClass);
<add> } else {
<add> // TODO : error
<ide> throw new NullPointerException();
<ide> }
<ide> } catch (IOException e) {
<ide> throw new TrelloHttpException(e);
<ide> } finally {
<del> httpPost.releaseConnection();
<add> httpRequest.releaseConnection();
<ide> }
<ide> }
<ide> |
|
Java | apache-2.0 | 0fc460695251b91752f7f3ef0a803e83cefc6ab4 | 0 | w2ogroup/incubator-streams,apache/streams,robdouglas/incubator_streams_apache,steveblackmon/incubator-streams,apache/streams,robdouglas/incubator_streams_apache,robdouglas/incubator-streams,jfrazee/incubator-streams,apache/streams | /*
* 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.streams.twitter.serializer.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.streams.exceptions.ActivitySerializerException;
import org.apache.streams.pojo.json.*;
import org.apache.streams.twitter.Url;
import org.apache.streams.twitter.pojo.*;
import org.apache.streams.twitter.serializer.StreamsTwitterMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.streams.data.util.ActivityUtil.ensureExtensions;
/**
* Provides utilities for working with Activity objects within the context of Twitter
*/
public class TwitterActivityUtil {
/**
* Updates the given Activity object with the values from the Tweet
* @param tweet the object to use as the source
* @param activity the target of the updates. Will receive all values from the tweet.
* @throws ActivitySerializerException
*/
public static void updateActivity(Tweet tweet, Activity activity) throws ActivitySerializerException {
ObjectMapper mapper = StreamsTwitterMapper.getInstance();
activity.setActor(buildActor(tweet));
activity.setId(formatId(activity.getVerb(),
Optional.fromNullable(
tweet.getIdStr())
.or(Optional.of(tweet.getId().toString()))
.orNull()));
if(tweet instanceof Retweet) {
updateActivityContent(activity, ((Retweet) tweet).getRetweetedStatus(), "share");
} else {
updateActivityContent(activity, tweet, "post");
}
if(Strings.isNullOrEmpty(activity.getId()))
throw new ActivitySerializerException("Unable to determine activity id");
try {
activity.setPublished(tweet.getCreatedAt());
} catch( Exception e ) {
throw new ActivitySerializerException("Unable to determine publishedDate", e);
}
activity.setTarget(buildTarget(tweet));
activity.setProvider(getProvider());
activity.setUrl(String.format("http://twitter.com/%s/%s/%s", tweet.getUser().getScreenName(),"/status/",tweet.getIdStr()));
activity.setTitle("");
activity.setContent(tweet.getText());
activity.setLinks(getLinks(tweet));
addTwitterExtension(activity, mapper.convertValue(tweet, ObjectNode.class));
addLocationExtension(activity, tweet);
addTwitterExtensions(activity, tweet);
}
/**
* Updates the activity for a delete event
* @param delete the delete event
* @param activity the Activity object to update
* @throws ActivitySerializerException
*/
public static void updateActivity(Delete delete, Activity activity) throws ActivitySerializerException {
activity.setActor(buildActor(delete));
activity.setVerb("delete");
activity.setObject(buildActivityObject(delete));
activity.setId(formatId(activity.getVerb(), delete.getDelete().getStatus().getIdStr()));
if(Strings.isNullOrEmpty(activity.getId()))
throw new ActivitySerializerException("Unable to determine activity id");
activity.setProvider(getProvider());
addTwitterExtension(activity, StreamsTwitterMapper.getInstance().convertValue(delete, ObjectNode.class));
}
/**
* Builds the actor for a delete event
* @param delete the delete event
* @return a valid Actor
*/
public static Actor buildActor(Delete delete) {
Actor actor = new Actor();
actor.setId(formatId(delete.getDelete().getStatus().getUserIdStr()));
return actor;
}
/**
* Builds the ActivityObject for the delete event
* @param delete the delete event
* @return a valid Activity Object
*/
public static ActivityObject buildActivityObject(Delete delete) {
ActivityObject actObj = new ActivityObject();
actObj.setId(formatId(delete.getDelete().getStatus().getIdStr()));
actObj.setObjectType("tweet");
return actObj;
}
/**
* Updates the content, and associated fields, with those from the given tweet
* @param activity the target of the updates. Will receive all values from the tweet.
* @param tweet the object to use as the source
* @param verb the verb for the given activity's type
*/
public static void updateActivityContent(Activity activity, Tweet tweet, String verb) {
activity.setVerb(verb);
activity.setTitle("");
if( tweet != null ) {
activity.setObject(buildActivityObject(tweet));
activity.setLinks(getLinks(tweet));
activity.setContent(tweet.getText());
}
}
/**
* Creates an {@link org.apache.streams.pojo.json.ActivityObject} for the tweet
* @param tweet the object to use as the source
* @return a valid ActivityObject
*/
public static ActivityObject buildActivityObject(Tweet tweet) {
ActivityObject actObj = new ActivityObject();
String id = Optional.fromNullable(
tweet.getIdStr())
.or(Optional.of(tweet.getId().toString()))
.orNull();
if( id != null )
actObj.setId(id);
actObj.setObjectType("tweet");
actObj.setContent(tweet.getText());
return actObj;
}
/**
* Builds the activity {@link org.apache.streams.pojo.json.Actor} object from the tweet
* @param tweet the object to use as the source
* @return a valid Actor populated from the Tweet
*/
public static Actor buildActor(Tweet tweet) {
Actor actor = new Actor();
User user = tweet.getUser();
actor.setId(formatId(
Optional.fromNullable(
user.getIdStr())
.or(Optional.of(user.getId().toString()))
.orNull()
));
actor.setDisplayName(user.getName());
actor.setAdditionalProperty("handle", user.getScreenName());
actor.setSummary(user.getDescription());
if (user.getUrl()!=null){
actor.setUrl(user.getUrl());
}
Map<String, Object> extensions = new HashMap<String, Object>();
extensions.put("location", user.getLocation());
extensions.put("posts", user.getStatusesCount());
extensions.put("favorites", user.getFavouritesCount());
extensions.put("followers", user.getFollowersCount());
Image profileImage = new Image();
profileImage.setUrl(user.getProfileImageUrlHttps());
actor.setImage(profileImage);
extensions.put("screenName", user.getScreenName());
actor.setAdditionalProperty("extensions", extensions);
return actor;
}
/**
* Gets the links from the Twitter event
* @param tweet the object to use as the source
* @return a list of links corresponding to the expanded URL (no t.co)
*/
public static List<String> getLinks(Tweet tweet) {
List<String> links = Lists.newArrayList();
if( tweet.getEntities().getUrls() != null ) {
for (Url url : tweet.getEntities().getUrls()) {
links.add(url.getExpandedUrl());
}
}
else
System.out.println(" 0 links");
return links;
}
/**
* Builds the {@link org.apache.streams.twitter.pojo.TargetObject} from the tweet
* @param tweet the object to use as the source
* @return currently returns null for all activities
*/
public static ActivityObject buildTarget(Tweet tweet) {
return null;
}
/**
* Adds the location extension and populates with teh twitter data
* @param activity the Activity object to update
* @param tweet the object to use as the source
*/
public static void addLocationExtension(Activity activity, Tweet tweet) {
Map<String, Object> extensions = ensureExtensions(activity);
Map<String, Object> location = new HashMap<String, Object>();
location.put("id", formatId(
Optional.fromNullable(
tweet.getIdStr())
.or(Optional.of(tweet.getId().toString()))
.orNull()
));
location.put("coordinates", tweet.getCoordinates());
extensions.put("location", location);
}
/**
* Gets the common twitter {@link org.apache.streams.pojo.json.Provider} object
* @return a provider object representing Twitter
*/
public static Provider getProvider() {
Provider provider = new Provider();
provider.setId("id:providers:twitter");
provider.setDisplayName("Twitter");
return provider;
}
/**
* Adds the given Twitter event to the activity as an extension
* @param activity the Activity object to update
* @param event the Twitter event to add as the extension
*/
public static void addTwitterExtension(Activity activity, ObjectNode event) {
Map<String, Object> extensions = org.apache.streams.data.util.ActivityUtil.ensureExtensions(activity);
extensions.put("twitter", event);
}
/**
* Formats the ID to conform with the Apache Streams activity ID convention
* @param idparts the parts of the ID to join
* @return a valid Activity ID in format "id:twitter:part1:part2:...partN"
*/
public static String formatId(String... idparts) {
return Joiner.on(":").join(Lists.asList("id:twitter", idparts));
}
/**
* Takes various parameters from the twitter object that are currently not part of teh
* activity schema and stores them in a generic extensions attribute
* @param activity
* @param tweet
*/
public static void addTwitterExtensions(Activity activity, Tweet tweet) {
Map<String, Object> extensions = ensureExtensions(activity);
List<String> hashtags = new ArrayList<String>();
for(Hashtag hashtag : tweet.getEntities().getHashtags()) {
hashtags.add(hashtag.getText());
}
extensions.put("hashtags", hashtags);
Map<String, Object> likes = new HashMap<String, Object>();
likes.put("perspectival", tweet.getFavorited());
likes.put("count", tweet.getAdditionalProperties().get("favorite_count"));
extensions.put("likes", likes);
Map<String, Object> rebroadcasts = new HashMap<String, Object>();
rebroadcasts.put("perspectival", tweet.getRetweeted());
rebroadcasts.put("count", tweet.getRetweetCount());
extensions.put("rebroadcasts", rebroadcasts);
List<Map<String, Object>> userMentions = new ArrayList<Map<String, Object>>();
Entities entities = tweet.getEntities();
for(UserMentions user : entities.getUserMentions()) {
//Map the twitter user object into an actor
Map<String, Object> actor = new HashMap<String, Object>();
actor.put("id", "id:twitter:" + user.getIdStr());
actor.put("displayName", user.getName());
actor.put("handle", user.getScreenName());
userMentions.add(actor);
}
extensions.put("user_mentions", userMentions);
extensions.put("keywords", tweet.getText());
}
}
| streams-contrib/streams-provider-twitter/src/main/java/org/apache/streams/twitter/serializer/util/TwitterActivityUtil.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.streams.twitter.serializer.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import org.apache.streams.exceptions.ActivitySerializerException;
import org.apache.streams.pojo.json.Activity;
import org.apache.streams.pojo.json.ActivityObject;
import org.apache.streams.pojo.json.Actor;
import org.apache.streams.pojo.json.Provider;
import org.apache.streams.twitter.Url;
import org.apache.streams.twitter.pojo.*;
import org.apache.streams.twitter.serializer.StreamsTwitterMapper;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.apache.streams.data.util.ActivityUtil.ensureExtensions;
/**
* Provides utilities for working with Activity objects within the context of Twitter
*/
public class TwitterActivityUtil {
/**
* Updates the given Activity object with the values from the Tweet
* @param tweet the object to use as the source
* @param activity the target of the updates. Will receive all values from the tweet.
* @throws ActivitySerializerException
*/
public static void updateActivity(Tweet tweet, Activity activity) throws ActivitySerializerException {
ObjectMapper mapper = StreamsTwitterMapper.getInstance();
activity.setActor(buildActor(tweet));
activity.setId(formatId(activity.getVerb(),
Optional.fromNullable(
tweet.getIdStr())
.or(Optional.of(tweet.getId().toString()))
.orNull()));
if(tweet instanceof Retweet) {
updateActivityContent(activity, ((Retweet) tweet).getRetweetedStatus(), "share");
} else {
updateActivityContent(activity, tweet, "post");
}
if(Strings.isNullOrEmpty(activity.getId()))
throw new ActivitySerializerException("Unable to determine activity id");
try {
activity.setPublished(tweet.getCreatedAt());
} catch( Exception e ) {
throw new ActivitySerializerException("Unable to determine publishedDate", e);
}
activity.setTarget(buildTarget(tweet));
activity.setProvider(getProvider());
activity.setUrl(String.format("http://twitter.com/%s/%s/%s", tweet.getUser().getScreenName(),"/status/",tweet.getIdStr()));
activity.setTitle("");
activity.setContent(tweet.getText());
activity.setLinks(getLinks(tweet));
addTwitterExtension(activity, mapper.convertValue(tweet, ObjectNode.class));
addLocationExtension(activity, tweet);
addTwitterExtensions(activity, tweet);
}
/**
* Updates the activity for a delete event
* @param delete the delete event
* @param activity the Activity object to update
* @throws ActivitySerializerException
*/
public static void updateActivity(Delete delete, Activity activity) throws ActivitySerializerException {
activity.setActor(buildActor(delete));
activity.setVerb("delete");
activity.setObject(buildActivityObject(delete));
activity.setId(formatId(activity.getVerb(), delete.getDelete().getStatus().getIdStr()));
if(Strings.isNullOrEmpty(activity.getId()))
throw new ActivitySerializerException("Unable to determine activity id");
activity.setProvider(getProvider());
addTwitterExtension(activity, StreamsTwitterMapper.getInstance().convertValue(delete, ObjectNode.class));
}
/**
* Builds the actor for a delete event
* @param delete the delete event
* @return a valid Actor
*/
public static Actor buildActor(Delete delete) {
Actor actor = new Actor();
actor.setId(formatId(delete.getDelete().getStatus().getUserIdStr()));
return actor;
}
/**
* Builds the ActivityObject for the delete event
* @param delete the delete event
* @return a valid Activity Object
*/
public static ActivityObject buildActivityObject(Delete delete) {
ActivityObject actObj = new ActivityObject();
actObj.setId(formatId(delete.getDelete().getStatus().getIdStr()));
actObj.setObjectType("tweet");
return actObj;
}
/**
* Updates the content, and associated fields, with those from the given tweet
* @param activity the target of the updates. Will receive all values from the tweet.
* @param tweet the object to use as the source
* @param verb the verb for the given activity's type
*/
public static void updateActivityContent(Activity activity, Tweet tweet, String verb) {
activity.setVerb(verb);
activity.setTitle("");
if( tweet != null ) {
activity.setObject(buildActivityObject(tweet));
activity.setLinks(getLinks(tweet));
activity.setContent(tweet.getText());
}
}
/**
* Creates an {@link org.apache.streams.pojo.json.ActivityObject} for the tweet
* @param tweet the object to use as the source
* @return a valid ActivityObject
*/
public static ActivityObject buildActivityObject(Tweet tweet) {
ActivityObject actObj = new ActivityObject();
String id = Optional.fromNullable(
tweet.getIdStr())
.or(Optional.of(tweet.getId().toString()))
.orNull();
if( id != null )
actObj.setId(id);
actObj.setObjectType("tweet");
actObj.setContent(tweet.getText());
return actObj;
}
/**
* Builds the activity {@link org.apache.streams.pojo.json.Actor} object from the tweet
* @param tweet the object to use as the source
* @return a valid Actor populated from the Tweet
*/
public static Actor buildActor(Tweet tweet) {
Actor actor = new Actor();
User user = tweet.getUser();
actor.setId(formatId(
Optional.fromNullable(
user.getIdStr())
.or(Optional.of(user.getId().toString()))
.orNull()
));
actor.setDisplayName(user.getName());
actor.setAdditionalProperty("handle", user.getScreenName());
actor.setSummary(user.getDescription());
if (user.getUrl()!=null){
actor.setUrl(user.getUrl());
}
Map<String, Object> extensions = new HashMap<String, Object>();
extensions.put("location", user.getLocation());
extensions.put("posts", user.getStatusesCount());
extensions.put("favorites", user.getFavouritesCount());
extensions.put("followers", user.getFollowersCount());
Map<String, Object> image = new HashMap<String, Object>();
image.put("url", user.getProfileImageUrlHttps());
extensions.put("image", image);
extensions.put("screenName", user.getScreenName());
actor.setAdditionalProperty("extensions", extensions);
return actor;
}
/**
* Gets the links from the Twitter event
* @param tweet the object to use as the source
* @return a list of links corresponding to the expanded URL (no t.co)
*/
public static List<String> getLinks(Tweet tweet) {
List<String> links = Lists.newArrayList();
if( tweet.getEntities().getUrls() != null ) {
for (Url url : tweet.getEntities().getUrls()) {
links.add(url.getExpandedUrl());
}
}
else
System.out.println(" 0 links");
return links;
}
/**
* Builds the {@link org.apache.streams.twitter.pojo.TargetObject} from the tweet
* @param tweet the object to use as the source
* @return currently returns null for all activities
*/
public static ActivityObject buildTarget(Tweet tweet) {
return null;
}
/**
* Adds the location extension and populates with teh twitter data
* @param activity the Activity object to update
* @param tweet the object to use as the source
*/
public static void addLocationExtension(Activity activity, Tweet tweet) {
Map<String, Object> extensions = ensureExtensions(activity);
Map<String, Object> location = new HashMap<String, Object>();
location.put("id", formatId(
Optional.fromNullable(
tweet.getIdStr())
.or(Optional.of(tweet.getId().toString()))
.orNull()
));
location.put("coordinates", tweet.getCoordinates());
extensions.put("location", location);
}
/**
* Gets the common twitter {@link org.apache.streams.pojo.json.Provider} object
* @return a provider object representing Twitter
*/
public static Provider getProvider() {
Provider provider = new Provider();
provider.setId("id:providers:twitter");
provider.setDisplayName("Twitter");
return provider;
}
/**
* Adds the given Twitter event to the activity as an extension
* @param activity the Activity object to update
* @param event the Twitter event to add as the extension
*/
public static void addTwitterExtension(Activity activity, ObjectNode event) {
Map<String, Object> extensions = org.apache.streams.data.util.ActivityUtil.ensureExtensions(activity);
extensions.put("twitter", event);
}
/**
* Formats the ID to conform with the Apache Streams activity ID convention
* @param idparts the parts of the ID to join
* @return a valid Activity ID in format "id:twitter:part1:part2:...partN"
*/
public static String formatId(String... idparts) {
return Joiner.on(":").join(Lists.asList("id:twitter", idparts));
}
/**
* Takes various parameters from the twitter object that are currently not part of teh
* activity schema and stores them in a generic extensions attribute
* @param activity
* @param tweet
*/
public static void addTwitterExtensions(Activity activity, Tweet tweet) {
Map<String, Object> extensions = ensureExtensions(activity);
List<String> hashtags = new ArrayList<String>();
for(Hashtag hashtag : tweet.getEntities().getHashtags()) {
hashtags.add(hashtag.getText());
}
extensions.put("hashtags", hashtags);
Map<String, Object> likes = new HashMap<String, Object>();
likes.put("perspectival", tweet.getFavorited());
likes.put("count", tweet.getAdditionalProperties().get("favorite_count"));
extensions.put("likes", likes);
Map<String, Object> rebroadcasts = new HashMap<String, Object>();
rebroadcasts.put("perspectival", tweet.getRetweeted());
rebroadcasts.put("count", tweet.getRetweetCount());
extensions.put("rebroadcasts", rebroadcasts);
List<Map<String, Object>> userMentions = new ArrayList<Map<String, Object>>();
Entities entities = tweet.getEntities();
for(UserMentions user : entities.getUserMentions()) {
//Map the twitter user object into an actor
Map<String, Object> actor = new HashMap<String, Object>();
actor.put("id", "id:twitter:" + user.getIdStr());
actor.put("displayName", user.getName());
actor.put("handle", user.getScreenName());
userMentions.add(actor);
}
extensions.put("user_mentions", userMentions);
extensions.put("keywords", tweet.getText());
}
}
| STREAMS-93 | Properly setting image in actor object
| streams-contrib/streams-provider-twitter/src/main/java/org/apache/streams/twitter/serializer/util/TwitterActivityUtil.java | STREAMS-93 | Properly setting image in actor object | <ide><path>treams-contrib/streams-provider-twitter/src/main/java/org/apache/streams/twitter/serializer/util/TwitterActivityUtil.java
<ide> import com.google.common.base.Strings;
<ide> import com.google.common.collect.Lists;
<ide> import org.apache.streams.exceptions.ActivitySerializerException;
<del>import org.apache.streams.pojo.json.Activity;
<del>import org.apache.streams.pojo.json.ActivityObject;
<del>import org.apache.streams.pojo.json.Actor;
<del>import org.apache.streams.pojo.json.Provider;
<add>import org.apache.streams.pojo.json.*;
<ide> import org.apache.streams.twitter.Url;
<ide> import org.apache.streams.twitter.pojo.*;
<ide> import org.apache.streams.twitter.serializer.StreamsTwitterMapper;
<ide> extensions.put("favorites", user.getFavouritesCount());
<ide> extensions.put("followers", user.getFollowersCount());
<ide>
<del> Map<String, Object> image = new HashMap<String, Object>();
<del> image.put("url", user.getProfileImageUrlHttps());
<del>
<del> extensions.put("image", image);
<add> Image profileImage = new Image();
<add> profileImage.setUrl(user.getProfileImageUrlHttps());
<add> actor.setImage(profileImage);
<add>
<ide> extensions.put("screenName", user.getScreenName());
<ide>
<ide> actor.setAdditionalProperty("extensions", extensions); |
|
Java | apache-2.0 | 7fe43f4e0f2f858e063e261e67d6f021e2227cdd | 0 | google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project,google/data-transfer-project | /*
* Copyright 2018 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.dataportabilityproject.datatransfer.google.photos;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.GphotoEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.dataportabilityproject.datatransfer.google.common.GoogleStaticObjects;
import org.dataportabilityproject.spi.transfer.provider.ExportResult;
import org.dataportabilityproject.spi.transfer.provider.ExportResult.ResultType;
import org.dataportabilityproject.spi.transfer.provider.Exporter;
import org.dataportabilityproject.spi.transfer.types.ContinuationData;
import org.dataportabilityproject.spi.transfer.types.ExportInformation;
import org.dataportabilityproject.spi.transfer.types.IdOnlyContainerResource;
import org.dataportabilityproject.spi.transfer.types.PaginationData;
import org.dataportabilityproject.spi.transfer.types.StringPaginationToken;
import org.dataportabilityproject.types.transfer.auth.TokensAndUrlAuthData;
import org.dataportabilityproject.types.transfer.models.photos.PhotoAlbum;
import org.dataportabilityproject.types.transfer.models.photos.PhotoModel;
import org.dataportabilityproject.types.transfer.models.photos.PhotosContainerResource;
public class GooglePhotosExporter implements Exporter<TokensAndUrlAuthData, PhotosContainerResource> {
static final String ALBUM_TOKEN_PREFIX = "album:";
static final String PHOTO_TOKEN_PREFIX = "photo:";
// TODO(olsona): figure out optimal value here
static final int MAX_RESULTS = 100;
static final String URL_ALBUM_FEED_FORMAT = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&start-index=%d&max-results=%d";
// imgmax=d gets the original image as per https://developers.google.com/picasa-web/docs/3.0/reference
static final String URL_PHOTO_FEED_FORMAT = "https://picasaweb.google.com/data/feed/api/user/default/albumid/%s?imgmax=d&start-index=%s&max-results=%d";
private volatile PicasawebService photosService;
public GooglePhotosExporter() {
this.photosService = null;
}
@VisibleForTesting
GooglePhotosExporter(PicasawebService photosService) {
this.photosService = photosService;
}
@Override
public ExportResult<PhotosContainerResource> export(TokensAndUrlAuthData authData) {
return exportAlbums(authData, Optional.empty());
}
@Override
public ExportResult<PhotosContainerResource> export(TokensAndUrlAuthData authData,
ExportInformation exportInformation) {
StringPaginationToken paginationToken = (StringPaginationToken) exportInformation
.getPaginationData();
if (paginationToken != null && paginationToken.getToken().startsWith(ALBUM_TOKEN_PREFIX)) {
// Next thing to export is more albums
return exportAlbums(authData, Optional.of(paginationToken));
} else {
// Next thing to export is photos
IdOnlyContainerResource idOnlyContainerResource =
(IdOnlyContainerResource) exportInformation.getContainerResource();
Optional<PaginationData> pageData =
paginationToken != null ? Optional.of(paginationToken) : Optional.empty();
return exportPhotos(authData, idOnlyContainerResource.getId(), pageData);
}
}
private ExportResult<PhotosContainerResource> exportAlbums(TokensAndUrlAuthData authData,
Optional<PaginationData> paginationData) {
try {
int startItem = 1;
if (paginationData.isPresent()) {
String token = ((StringPaginationToken) paginationData.get()).getToken();
Preconditions.checkArgument(token.startsWith(ALBUM_TOKEN_PREFIX),
"Invalid pagination token " + token);
startItem = Integer.parseInt(token.substring(ALBUM_TOKEN_PREFIX.length()));
}
URL albumUrl = new URL(String.format(URL_ALBUM_FEED_FORMAT, startItem, MAX_RESULTS));
UserFeed albumFeed = getOrCreatePhotosService(authData).getFeed(albumUrl, UserFeed.class);
PaginationData nextPageData = null;
if (albumFeed.getAlbumEntries().size() == MAX_RESULTS) {
int nextPageStart = startItem + MAX_RESULTS;
nextPageData = new StringPaginationToken(ALBUM_TOKEN_PREFIX + nextPageStart);
}
ContinuationData continuationData = new ContinuationData(nextPageData);
List<PhotoAlbum> albums = new ArrayList<>(albumFeed.getAlbumEntries().size());
for (GphotoEntry googleAlbum : albumFeed.getAlbumEntries()) {
// Add album info to list so album can be recreated later
albums.add(new PhotoAlbum(googleAlbum.getGphotoId(), googleAlbum.getTitle().getPlainText(),
googleAlbum.getDescription().getPlainText()));
// Add album id to continuation data
continuationData
.addContainerResource(new IdOnlyContainerResource(googleAlbum.getGphotoId()));
}
ResultType resultType = ResultType.CONTINUE;
if (nextPageData == null || continuationData.getContainerResources().isEmpty()) {
resultType = ResultType.END;
}
PhotosContainerResource containerResource = new PhotosContainerResource(albums, null);
return new ExportResult<>(resultType, containerResource, continuationData);
} catch (ServiceException | IOException e) {
return new ExportResult<>(ResultType.ERROR, e.getMessage());
}
}
private ExportResult<PhotosContainerResource> exportPhotos(TokensAndUrlAuthData authData, String albumId,
Optional<PaginationData> paginationData) {
try {
int startItem = 1;
if (paginationData.isPresent()) {
String token = ((StringPaginationToken) paginationData.get()).getToken();
Preconditions.checkArgument(token.startsWith(PHOTO_TOKEN_PREFIX),
"Invalid pagination token " + token);
startItem = Integer.parseInt(token.substring(PHOTO_TOKEN_PREFIX.length()));
}
URL photosUrl = new URL(
String.format(URL_PHOTO_FEED_FORMAT, albumId, startItem, MAX_RESULTS));
AlbumFeed photoFeed = getOrCreatePhotosService(authData).getFeed(photosUrl, AlbumFeed.class);
PaginationData nextPageData = null;
if (photoFeed.getEntries().size() == MAX_RESULTS) {
int nextPageStart = startItem + MAX_RESULTS;
nextPageData = new StringPaginationToken(PHOTO_TOKEN_PREFIX + nextPageStart);
}
ContinuationData continuationData = new ContinuationData(nextPageData);
List<PhotoModel> photos = new ArrayList<>(photoFeed.getEntries().size());
for (GphotoEntry photo : photoFeed.getEntries()) {
MediaContent mediaContent = (MediaContent) photo.getContent();
photos.add(new PhotoModel(photo.getTitle().getPlainText(), mediaContent.getUri(), photo
.getDescription().getPlainText(), mediaContent.getMimeType().getMediaType(),
albumId));
}
PhotosContainerResource containerResource = new PhotosContainerResource(null, photos);
ResultType resultType = ResultType.CONTINUE;
if (nextPageData == null) {
resultType = ResultType.END;
}
return new ExportResult<>(resultType, containerResource, continuationData);
} catch (ServiceException | IOException e) {
return new ExportResult<>(ResultType.ERROR, e.getMessage());
}
}
private PicasawebService getOrCreatePhotosService(TokensAndUrlAuthData authData) {
return photosService == null ? makePhotosService(authData) : photosService;
}
private synchronized PicasawebService makePhotosService(TokensAndUrlAuthData authData) {
Credential credential =
new Credential(BearerToken.authorizationHeaderAccessMethod())
.setAccessToken(authData.getAccessToken());
PicasawebService service = new PicasawebService(GoogleStaticObjects.APP_NAME);
service.setOAuth2Credentials(credential);
return service;
}
}
| extensions/data-transfer/portability-data-transfer-google/src/main/java/org/dataportabilityproject/datatransfer/google/photos/GooglePhotosExporter.java | /*
* Copyright 2018 The Data Transfer Project Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://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.dataportabilityproject.datatransfer.google.photos;
import com.google.api.client.auth.oauth2.BearerToken;
import com.google.api.client.auth.oauth2.Credential;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import com.google.gdata.client.photos.PicasawebService;
import com.google.gdata.data.MediaContent;
import com.google.gdata.data.photos.AlbumFeed;
import com.google.gdata.data.photos.GphotoEntry;
import com.google.gdata.data.photos.UserFeed;
import com.google.gdata.util.ServiceException;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.dataportabilityproject.datatransfer.google.common.GoogleStaticObjects;
import org.dataportabilityproject.spi.transfer.provider.ExportResult;
import org.dataportabilityproject.spi.transfer.provider.ExportResult.ResultType;
import org.dataportabilityproject.spi.transfer.provider.Exporter;
import org.dataportabilityproject.spi.transfer.types.ContinuationData;
import org.dataportabilityproject.spi.transfer.types.ExportInformation;
import org.dataportabilityproject.spi.transfer.types.IdOnlyContainerResource;
import org.dataportabilityproject.spi.transfer.types.PaginationData;
import org.dataportabilityproject.spi.transfer.types.StringPaginationToken;
import org.dataportabilityproject.types.transfer.auth.TokensAndUrlAuthData;
import org.dataportabilityproject.types.transfer.models.photos.PhotoAlbum;
import org.dataportabilityproject.types.transfer.models.photos.PhotoModel;
import org.dataportabilityproject.types.transfer.models.photos.PhotosContainerResource;
public class GooglePhotosExporter implements Exporter<TokensAndUrlAuthData, PhotosContainerResource> {
static final String ALBUM_TOKEN_PREFIX = "album:";
static final String PHOTO_TOKEN_PREFIX = "photo:";
// TODO(olsona): figure out optimal value here
static final int MAX_RESULTS = 100;
static final String URL_ALBUM_FEED_FORMAT = "https://picasaweb.google.com/data/feed/api/user/default?kind=album&start-index=%d&max-results=%d";
// imgmax=d gets the original image as per https://developers.google.com/picasa-web/docs/3.0/reference
static final String URL_PHOTO_FEED_FORMAT = "https://picasaweb.google.com/data/feed/api/user/default/albumid/%s?imgmax=d&start-index=%s&max-results=%d";
private volatile PicasawebService photosService;
public GooglePhotosExporter() {
this.photosService = null;
}
@VisibleForTesting
GooglePhotosExporter(PicasawebService photosService) {
this.photosService = photosService;
}
@Override
public ExportResult<PhotosContainerResource> export(TokensAndUrlAuthData authData) {
return exportAlbums(authData, Optional.empty());
}
@Override
public ExportResult<PhotosContainerResource> export(TokensAndUrlAuthData authData,
ExportInformation exportInformation) {
StringPaginationToken paginationToken = (StringPaginationToken) exportInformation
.getPaginationData();
if (paginationToken != null && paginationToken.getToken().startsWith(ALBUM_TOKEN_PREFIX)) {
// Next thing to export is more albums
return exportAlbums(authData, Optional.of(paginationToken));
} else {
// Next thing to export is photos
IdOnlyContainerResource idOnlyContainerResource =
(IdOnlyContainerResource) exportInformation.getContainerResource();
Optional<PaginationData> pageData =
paginationToken != null ? Optional.of(paginationToken) : Optional.empty();
return exportPhotos(authData, idOnlyContainerResource.getId(), pageData);
}
}
private ExportResult<PhotosContainerResource> exportAlbums(TokensAndUrlAuthData authData,
Optional<PaginationData> paginationData) {
try {
int startItem = 1;
if (paginationData.isPresent()) {
String token = ((StringPaginationToken) paginationData.get()).getToken();
Preconditions.checkArgument(token.startsWith(ALBUM_TOKEN_PREFIX),
"Invalid pagination token " + token);
startItem = Integer.parseInt(token.substring(ALBUM_TOKEN_PREFIX.length()));
}
URL albumUrl = new URL(String.format(URL_ALBUM_FEED_FORMAT, startItem, MAX_RESULTS));
UserFeed albumFeed = getOrCreatePhotosService(authData).getFeed(albumUrl, UserFeed.class);
PaginationData nextPageData = null;
if (albumFeed.getAlbumEntries().size() == MAX_RESULTS) {
int nextPageStart = startItem + MAX_RESULTS;
nextPageData = new StringPaginationToken(ALBUM_TOKEN_PREFIX + nextPageStart);
}
ContinuationData continuationData = new ContinuationData(nextPageData);
List<PhotoAlbum> albums = new ArrayList<>(albumFeed.getAlbumEntries().size());
for (GphotoEntry googleAlbum : albumFeed.getAlbumEntries()) {
// Add album info to list so album can be recreated later
albums.add(new PhotoAlbum(googleAlbum.getGphotoId(), googleAlbum.getTitle().getPlainText(),
googleAlbum.getDescription().getPlainText()));
// Add album id to continuation data
continuationData
.addContainerResource(new IdOnlyContainerResource(googleAlbum.getGphotoId()));
}
ResultType resultType = ResultType.CONTINUE;
PhotosContainerResource containerResource = new PhotosContainerResource(albums, null);
return new ExportResult<>(resultType, containerResource, continuationData);
} catch (ServiceException | IOException e) {
return new ExportResult<>(ResultType.ERROR, e.getMessage());
}
}
private ExportResult<PhotosContainerResource> exportPhotos(TokensAndUrlAuthData authData, String albumId,
Optional<PaginationData> paginationData) {
try {
int startItem = 1;
if (paginationData.isPresent()) {
String token = ((StringPaginationToken) paginationData.get()).getToken();
Preconditions.checkArgument(token.startsWith(PHOTO_TOKEN_PREFIX),
"Invalid pagination token " + token);
startItem = Integer.parseInt(token.substring(PHOTO_TOKEN_PREFIX.length()));
}
URL photosUrl = new URL(
String.format(URL_PHOTO_FEED_FORMAT, albumId, startItem, MAX_RESULTS));
AlbumFeed photoFeed = getOrCreatePhotosService(authData).getFeed(photosUrl, AlbumFeed.class);
PaginationData nextPageData = null;
if (photoFeed.getEntries().size() == MAX_RESULTS) {
int nextPageStart = startItem + MAX_RESULTS;
nextPageData = new StringPaginationToken(PHOTO_TOKEN_PREFIX + nextPageStart);
}
ContinuationData continuationData = new ContinuationData(nextPageData);
List<PhotoModel> photos = new ArrayList<>(photoFeed.getEntries().size());
for (GphotoEntry photo : photoFeed.getEntries()) {
MediaContent mediaContent = (MediaContent) photo.getContent();
photos.add(new PhotoModel(photo.getTitle().getPlainText(), mediaContent.getUri(), photo
.getDescription().getPlainText(), mediaContent.getMimeType().getMediaType(),
albumId));
}
PhotosContainerResource containerResource = new PhotosContainerResource(null, photos);
return new ExportResult<>(ResultType.END, containerResource, continuationData);
} catch (ServiceException | IOException e) {
return new ExportResult<>(ResultType.ERROR, e.getMessage());
}
}
private PicasawebService getOrCreatePhotosService(TokensAndUrlAuthData authData) {
return photosService == null ? makePhotosService(authData) : photosService;
}
private synchronized PicasawebService makePhotosService(TokensAndUrlAuthData authData) {
Credential credential =
new Credential(BearerToken.authorizationHeaderAccessMethod())
.setAccessToken(authData.getAccessToken());
PicasawebService service = new PicasawebService(GoogleStaticObjects.APP_NAME);
service.setOAuth2Credentials(credential);
return service;
}
}
| Quick fix on result type in Google Photos Exporter (#291)
| extensions/data-transfer/portability-data-transfer-google/src/main/java/org/dataportabilityproject/datatransfer/google/photos/GooglePhotosExporter.java | Quick fix on result type in Google Photos Exporter (#291) | <ide><path>xtensions/data-transfer/portability-data-transfer-google/src/main/java/org/dataportabilityproject/datatransfer/google/photos/GooglePhotosExporter.java
<ide> }
<ide>
<ide> ResultType resultType = ResultType.CONTINUE;
<add> if (nextPageData == null || continuationData.getContainerResources().isEmpty()) {
<add> resultType = ResultType.END;
<add> }
<ide> PhotosContainerResource containerResource = new PhotosContainerResource(albums, null);
<ide> return new ExportResult<>(resultType, containerResource, continuationData);
<ide> } catch (ServiceException | IOException e) {
<ide> }
<ide>
<ide> PhotosContainerResource containerResource = new PhotosContainerResource(null, photos);
<del> return new ExportResult<>(ResultType.END, containerResource, continuationData);
<add>
<add> ResultType resultType = ResultType.CONTINUE;
<add> if (nextPageData == null) {
<add> resultType = ResultType.END;
<add> }
<add> return new ExportResult<>(resultType, containerResource, continuationData);
<ide> } catch (ServiceException | IOException e) {
<ide> return new ExportResult<>(ResultType.ERROR, e.getMessage());
<ide> } |
|
Java | bsd-3-clause | 6ee916489f02d9e76494e12fd70e4e9a7749429b | 0 | MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2,MjAbuz/carrot2 | /*
* Carrot2 Project
* Copyright (C) 2002-2005, Dawid Weiss
* Portions (C) Contributors listed in carrot2.CONTRIBUTORS file.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the CVS checkout or at:
* http://www.cs.put.poznan.pl/dweiss/carrot2.LICENSE
*/
package com.dawidweiss.carrot.core.local.clustering;
import com.stachoodev.util.common.*;
/**
* An abstract implementation of some of the basic methods of the {@link
* RawDocument} interface.
*
* @author Dawid Weiss
* @author Stanislaw Osinski
* @version $Revision$
*/
public abstract class RawDocumentBase implements RawDocument, PropertyProvider
{
/** Stores this document's properties */
protected PropertyHelper propertyHelper;
/**
* Initializes the internal property storage.
*/
public RawDocumentBase()
{
propertyHelper = new PropertyHelper();
}
/**
* Creates a new raw document.
*
* @param url
* @param title
* @param snippet
*/
public RawDocumentBase( String url, String title, String snippet ) {
this();
setProperty(PROPERTY_URL, url);
setProperty(PROPERTY_TITLE, title);
setProperty(PROPERTY_SNIPPET, snippet);
}
/**
* Cloning constructor.
*/
public RawDocumentBase( RawDocument r ) {
this();
if (r instanceof RawDocumentBase) {
try {
this.propertyHelper = (PropertyHelper) ((RawDocumentBase)r).propertyHelper.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException();
}
} else {
setProperty(PROPERTY_URL, r.getProperty(PROPERTY_URL));
setProperty(PROPERTY_SNIPPET, r.getProperty(PROPERTY_SNIPPET));
setProperty(PROPERTY_TITLE, r.getProperty(PROPERTY_TITLE));
}
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.core.local.clustering.RawDocument#getSnippet()
*/
public String getSnippet()
{
return (String) propertyHelper.getProperty(PROPERTY_SNIPPET);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.core.local.clustering.RawDocument#getUrl()
*/
public String getUrl()
{
return (String) propertyHelper.getProperty(PROPERTY_URL);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.core.local.clustering.RawDocument#getTitle()
*/
public String getTitle()
{
return (String) propertyHelper.getProperty(PROPERTY_TITLE);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#getProperty(java.lang.String)
*/
public Object getProperty(String name)
{
return propertyHelper.getProperty(name);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#setProperty(java.lang.String,
* java.lang.Object)
*/
public Object setProperty(String propertyName, Object value)
{
return propertyHelper.setProperty(propertyName, value);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#getDoubleProperty(java.lang.String)
*/
public double getDoubleProperty(String propertyName, double defaultValue)
{
return propertyHelper.getDoubleProperty(propertyName, defaultValue);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#getIntProperty(java.lang.String)
*/
public int getIntProperty(String propertyName, int defaultValue)
{
return propertyHelper.getIntProperty(propertyName, defaultValue);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#setDoubleProperty(java.lang.String,
* double)
*/
public Object setDoubleProperty(String propertyName, double value)
{
return propertyHelper.setDoubleProperty(propertyName, value);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#setIntProperty(java.lang.String,
* int)
*/
public Object setIntProperty(String propertyName, int value)
{
return propertyHelper.setIntProperty(propertyName, value);
}
/**
* @return Returns 'no score' constant.
*/
public float getScore()
{
return -1;
}
} | carrot2/components/carrot2-local-core/src/com/dawidweiss/carrot/core/local/clustering/RawDocumentBase.java | /*
* Carrot2 Project
* Copyright (C) 2002-2005, Dawid Weiss
* Portions (C) Contributors listed in carrot2.CONTRIBUTORS file.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the CVS checkout or at:
* http://www.cs.put.poznan.pl/dweiss/carrot2.LICENSE
*/
package com.dawidweiss.carrot.core.local.clustering;
import com.stachoodev.util.common.*;
/**
* An abstract implementation of some of the basic methods of the {@link
* RawDocument} interface.
*
* @author Dawid Weiss
* @author Stanislaw Osinski
* @version $Revision$
*/
public abstract class RawDocumentBase implements RawDocument, PropertyProvider
{
/** Stores this document's properties */
protected PropertyHelper propertyHelper;
/**
* Initializes the internal property storage.
*/
public RawDocumentBase()
{
propertyHelper = new PropertyHelper();
}
/**
* Cloning constructor.
*/
public RawDocumentBase( RawDocument r ) {
this();
if (r instanceof RawDocumentBase) {
try {
this.propertyHelper = (PropertyHelper) ((RawDocumentBase)r).propertyHelper.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException();
}
} else {
setProperty(PROPERTY_URL, r.getProperty(PROPERTY_URL));
setProperty(PROPERTY_SNIPPET, r.getProperty(PROPERTY_SNIPPET));
setProperty(PROPERTY_TITLE, r.getProperty(PROPERTY_TITLE));
}
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.core.local.clustering.RawDocument#getSnippet()
*/
public String getSnippet()
{
return (String) propertyHelper.getProperty(PROPERTY_SNIPPET);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.core.local.clustering.RawDocument#getUrl()
*/
public String getUrl()
{
return (String) propertyHelper.getProperty(PROPERTY_URL);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.core.local.clustering.RawDocument#getTitle()
*/
public String getTitle()
{
return (String) propertyHelper.getProperty(PROPERTY_TITLE);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#getProperty(java.lang.String)
*/
public Object getProperty(String name)
{
return propertyHelper.getProperty(name);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#setProperty(java.lang.String,
* java.lang.Object)
*/
public Object setProperty(String propertyName, Object value)
{
return propertyHelper.setProperty(propertyName, value);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#getDoubleProperty(java.lang.String)
*/
public double getDoubleProperty(String propertyName, double defaultValue)
{
return propertyHelper.getDoubleProperty(propertyName, defaultValue);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#getIntProperty(java.lang.String)
*/
public int getIntProperty(String propertyName, int defaultValue)
{
return propertyHelper.getIntProperty(propertyName, defaultValue);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#setDoubleProperty(java.lang.String,
* double)
*/
public Object setDoubleProperty(String propertyName, double value)
{
return propertyHelper.setDoubleProperty(propertyName, value);
}
/*
* (non-Javadoc)
*
* @see com.dawidweiss.carrot.util.common.PropertyProvider#setIntProperty(java.lang.String,
* int)
*/
public Object setIntProperty(String propertyName, int value)
{
return propertyHelper.setIntProperty(propertyName, value);
}
/**
* @return Returns 'no score' constant.
*/
public float getScore()
{
return -1;
}
} | Added an utility constructor that takes snippet, title and url as arguments.
git-svn-id: 659eb10424342cea22344621e2d2cbd98ef34d09@515 7ff1d41c-760d-0410-a7ff-a3a56f310b35
| carrot2/components/carrot2-local-core/src/com/dawidweiss/carrot/core/local/clustering/RawDocumentBase.java | Added an utility constructor that takes snippet, title and url as arguments. | <ide><path>arrot2/components/carrot2-local-core/src/com/dawidweiss/carrot/core/local/clustering/RawDocumentBase.java
<ide> public RawDocumentBase()
<ide> {
<ide> propertyHelper = new PropertyHelper();
<add> }
<add>
<add> /**
<add> * Creates a new raw document.
<add> *
<add> * @param url
<add> * @param title
<add> * @param snippet
<add> */
<add> public RawDocumentBase( String url, String title, String snippet ) {
<add> this();
<add> setProperty(PROPERTY_URL, url);
<add> setProperty(PROPERTY_TITLE, title);
<add> setProperty(PROPERTY_SNIPPET, snippet);
<ide> }
<ide>
<ide> /** |
|
JavaScript | mit | 6cbc52d0caf54d1150e73d2197c3d9813985446e | 0 | amitsch666/nano | const express = require('express')
const path = require('path')
const next = require('next')
const compression = require('compression')
const favicon = require('serve-favicon')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = express()
server.use(compression())
server.use(favicon(path.join(__dirname, 'static', 'img', 'favicon.ico')))
// Custom stylesheet path alias
server.use('/_s.css', express.static(path.join(__dirname, '.build/main.css')))
// server.get('/p/:id', (req, res) => {
// const actualPage = '/post'
// const queryParams = { id: req.params.id }
// app.render(req, res, actualPage, queryParams)
// })
//
server.get('*', (req, res) => {
return handle(req, res)
})
// Normalize a port into a number, string, or false.
function normalizePort(val) {
const port = parseInt(val, 10)
if (isNaN(port)) {
// named pipe
return val
}
if (port >= 0) {
// port number
return port
}
return false
}
// Get port from environment and store in Express.
const port = normalizePort(process.env.PORT || '3000')
server.set('port', port)
server.listen(port, (err) => {
if (err) throw err
console.log(`> Listening on port ${port}...`)
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
| server.js | const express = require('express')
const path = require('path')
const next = require('next')
const compression = require('compression')
const favicon = require('serve-favicon')
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare()
.then(() => {
const server = express()
server.use(compression())
server.use(favicon(path.join(__dirname, 'static', 'img', 'favicon.ico')))
// Custom stylesheet path alias
server.use('/_s.css', express.static(path.join(__dirname, '.build/main.css')))
// server.get('/p/:id', (req, res) => {
// const actualPage = '/post'
// const queryParams = { id: req.params.id }
// app.render(req, res, actualPage, queryParams)
// })
//
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(3000, (err) => {
if (err) throw err
console.log('> Ready on http://localhost:3000')
})
})
.catch((ex) => {
console.error(ex.stack)
process.exit(1)
})
| Minor improvements to Express scaffolding
| server.js | Minor improvements to Express scaffolding | <ide><path>erver.js
<ide> return handle(req, res)
<ide> })
<ide>
<del> server.listen(3000, (err) => {
<add> // Normalize a port into a number, string, or false.
<add> function normalizePort(val) {
<add> const port = parseInt(val, 10)
<add> if (isNaN(port)) {
<add> // named pipe
<add> return val
<add> }
<add> if (port >= 0) {
<add> // port number
<add> return port
<add> }
<add> return false
<add> }
<add>
<add> // Get port from environment and store in Express.
<add> const port = normalizePort(process.env.PORT || '3000')
<add> server.set('port', port)
<add>
<add> server.listen(port, (err) => {
<ide> if (err) throw err
<del> console.log('> Ready on http://localhost:3000')
<add> console.log(`> Listening on port ${port}...`)
<ide> })
<ide> })
<ide> .catch((ex) => { |
|
Java | apache-2.0 | 688907ffbd69149246eed957dd4dd3f9360ae6da | 0 | bhecquet/seleniumRobot,bhecquet/seleniumRobot,bhecquet/seleniumRobot | package com.seleniumtests.ut.browserfactory;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.seleniumtests.MockitoTest;
import com.seleniumtests.browserfactory.SeleniumGridDriverFactory;
import com.seleniumtests.browserfactory.SeleniumRobotCapabilityType;
import com.seleniumtests.connectors.selenium.SeleniumGridConnector;
import com.seleniumtests.core.SeleniumTestsContext;
import com.seleniumtests.core.SeleniumTestsContextManager;
import com.seleniumtests.customexception.ScenarioException;
import com.seleniumtests.customexception.SeleniumGridNodeNotAvailable;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.driver.DriverConfig;
import com.seleniumtests.driver.TestType;
import com.seleniumtests.util.logging.DebugMode;
@PowerMockIgnore("javax.net.ssl.*")
@PrepareForTest({SeleniumGridDriverFactory.class})
public class TestSeleniumGridDriverFactory extends MockitoTest {
@Mock
private DriverConfig config;
@Mock
private Proxy proxyConfig;
@Mock
private SeleniumGridConnector gridConnector1;
@Mock
private SeleniumGridConnector gridConnector2;
@Mock
private SeleniumTestsContext context;
@Mock
private RemoteWebDriver driver;
@Mock
private RemoteWebDriver driver2;
@Mock
private Options options;
@Mock
private Timeouts timeouts;
@BeforeMethod(groups= {"ut"})
public void init() throws Exception {
when(config.getTestContext()).thenReturn(context);
Mockito.when(config.getDebug()).thenReturn(Arrays.asList(DebugMode.NONE));
when(config.getBrowserType()).thenReturn(BrowserType.HTMLUNIT);
when(config.getPlatform()).thenReturn("windows");
// configure driver
Map<String, String> capsMap = new HashMap<>();
capsMap.put(CapabilityType.BROWSER_NAME, "htmlunit");
capsMap.put(CapabilityType.VERSION, "70.0.1.2.3");
Capabilities caps = new MutableCapabilities(capsMap);
when(driver.manage()).thenReturn(options);
when(driver.getCapabilities()).thenReturn(caps);
when(driver2.manage()).thenReturn(options);
when(driver2.getCapabilities()).thenReturn(caps);
when(options.timeouts()).thenReturn(timeouts);
when(gridConnector1.getHubUrl()).thenReturn(new URL("http://localhost:1111/wd/hub"));
when(gridConnector2.getHubUrl()).thenReturn(new URL("http://localhost:2222/wd/hub"));
}
/**
* Check we create a driver from grid
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreation() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
WebDriver newDriver = driverFactory.createWebDriver();
// check that with a single driver creation, retry timeout is 30 mins
Assert.assertEquals(driverFactory.getInstanceRetryTimeout(), SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
// issue #280: also check that BrowserInfo is not null
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver);
Assert.assertNotNull(driverFactory.getSelectedBrowserInfo());
Assert.assertEquals(driverFactory.getSelectedBrowserInfo().getBrowser(), BrowserType.HTMLUNIT);
Assert.assertEquals(driverFactory.getSelectedBrowserInfo().getVersion(), "70.0.1.2.3");
}
/**
* If grid is not active, driver is not created and exception is raised
* @throws Exception
*/
@Test(groups={"ut"}, expectedExceptions=SeleniumGridNodeNotAvailable.class)
public void testDriverNotCreatedIfGridNotActive() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(2);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(false);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
driverFactory.createWebDriver();
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
/**
* If exception is raised during driver creation, exception is raised
* @throws Exception
*/
@Test(groups={"ut"}, expectedExceptions=SeleniumGridNodeNotAvailable.class)
public void testDriverNotCreatedIfError() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(1);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
// connect to grid;
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenThrow(new WebDriverException(""));
new SeleniumGridDriverFactory(config).createWebDriver();
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
/**
* Check we use the first grid connector if it's available
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationWithSeveralGridConnectors() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
// connect to grid. One driver for each connector so that it's easy to distinguish them
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver);
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:2222/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver2);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
Assert.assertNotNull(newDriver);
}
/**
* Check we use the first grid connector if it's available
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationWithSeveralGridConnectorsOneUnavailable() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(false);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
// connect to grid. One driver for each connector so that it's easy to distinguish them
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver);
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:2222/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver2);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver2);
}
/**
* Check we use the connector which is not in error
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationWithSeveralGridConnectorsOneInError() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(1);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
// first driver will create an exception
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenThrow(new WebDriverException(""));
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:2222/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver2);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver2);
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
/**
* Check we can force driver to be created on the same node using capabilities if DriverConfig.getRunOnSameNode() specifies the node name
* For this to work a previous driver must have been created for one of the configured grid connector
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationOnSameNode() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(gridConnector1); // simulate a previously created driver
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
WebDriver newDriver = driverFactory.createWebDriver();
// check that with a multiple drivers creation, retry timeout is 1 min 30 for the second drivers because runOnSameNode is set
Assert.assertEquals(driverFactory.getInstanceRetryTimeout(), 90);
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver);
}
/**
* Check capability is correctly set when requested to run on same node
* @throws Exception
*/
@Test(groups={"ut"})
public void testCapabilitiesCreationOnSameNode() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(gridConnector1); // simulate a previously created driver
DesiredCapabilities caps = new SeleniumGridDriverFactory(config).createSpecificGridCapabilities(config);
Assert.assertEquals(caps.getCapability(SeleniumRobotCapabilityType.ATTACH_SESSION_ON_NODE), "http://localhost:5556/");
}
/**
* Check we can force driver to be created on the same node using capabilities if DriverConfig.getRunOnSameNode() specifies the node name
* For this to work a previous driver must have been created for one of the configured grid connector
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationOnSameNodeMultipleHubs() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(gridConnector2); // simulate a previously created driver
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class)
.withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
WebDriver newDriver = driverFactory.createWebDriver();
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver);
// Check selected grid connector is the requested one
Assert.assertEquals(driverFactory.getActiveGridConnector(), gridConnector2);
}
/**
* Check that it's not possible to create a driver on same node is no previous driver has been created before (gridConnector is null in context)
* @throws Exception
*/
@Test(groups={"ut"}, expectedExceptions=ScenarioException.class)
public void testDriverDoNotCreateDriverOnSameNodeWithoutPreviousOne() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(1);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(null); // simulate the case where no previous driver was created
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
}
| core/src/test/java/com/seleniumtests/ut/browserfactory/TestSeleniumGridDriverFactory.java | package com.seleniumtests.ut.browserfactory;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.when;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.openqa.selenium.Capabilities;
import org.openqa.selenium.MutableCapabilities;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriver.Options;
import org.openqa.selenium.WebDriver.Timeouts;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.seleniumtests.MockitoTest;
import com.seleniumtests.browserfactory.SeleniumGridDriverFactory;
import com.seleniumtests.browserfactory.SeleniumRobotCapabilityType;
import com.seleniumtests.connectors.selenium.SeleniumGridConnector;
import com.seleniumtests.core.SeleniumTestsContext;
import com.seleniumtests.core.SeleniumTestsContextManager;
import com.seleniumtests.customexception.ScenarioException;
import com.seleniumtests.customexception.SeleniumGridException;
import com.seleniumtests.driver.BrowserType;
import com.seleniumtests.driver.DriverConfig;
import com.seleniumtests.driver.TestType;
import com.seleniumtests.util.logging.DebugMode;
@PowerMockIgnore("javax.net.ssl.*")
@PrepareForTest({SeleniumGridDriverFactory.class})
public class TestSeleniumGridDriverFactory extends MockitoTest {
@Mock
private DriverConfig config;
@Mock
private Proxy proxyConfig;
@Mock
private SeleniumGridConnector gridConnector1;
@Mock
private SeleniumGridConnector gridConnector2;
@Mock
private SeleniumTestsContext context;
@Mock
private RemoteWebDriver driver;
@Mock
private RemoteWebDriver driver2;
@Mock
private Options options;
@Mock
private Timeouts timeouts;
@BeforeMethod(groups= {"ut"})
public void init() throws Exception {
when(config.getTestContext()).thenReturn(context);
Mockito.when(config.getDebug()).thenReturn(Arrays.asList(DebugMode.NONE));
when(config.getBrowserType()).thenReturn(BrowserType.HTMLUNIT);
when(config.getPlatform()).thenReturn("windows");
// configure driver
Map<String, String> capsMap = new HashMap<>();
capsMap.put(CapabilityType.BROWSER_NAME, "htmlunit");
capsMap.put(CapabilityType.VERSION, "70.0.1.2.3");
Capabilities caps = new MutableCapabilities(capsMap);
when(driver.manage()).thenReturn(options);
when(driver.getCapabilities()).thenReturn(caps);
when(driver2.manage()).thenReturn(options);
when(driver2.getCapabilities()).thenReturn(caps);
when(options.timeouts()).thenReturn(timeouts);
when(gridConnector1.getHubUrl()).thenReturn(new URL("http://localhost:1111/wd/hub"));
when(gridConnector2.getHubUrl()).thenReturn(new URL("http://localhost:2222/wd/hub"));
}
/**
* Check we create a driver from grid
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreation() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
WebDriver newDriver = driverFactory.createWebDriver();
// check that with a single driver creation, retry timeout is 30 mins
Assert.assertEquals(driverFactory.getInstanceRetryTimeout(), SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
// issue #280: also check that BrowserInfo is not null
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver);
Assert.assertNotNull(driverFactory.getSelectedBrowserInfo());
Assert.assertEquals(driverFactory.getSelectedBrowserInfo().getBrowser(), BrowserType.HTMLUNIT);
Assert.assertEquals(driverFactory.getSelectedBrowserInfo().getVersion(), "70.0.1.2.3");
}
/**
* If grid is not active, driver is not created and exception is raised
* @throws Exception
*/
@Test(groups={"ut"}, expectedExceptions=SeleniumGridException.class)
public void testDriverNotCreatedIfGridNotActive() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(2);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(false);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
driverFactory.createWebDriver();
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
/**
* If exception is raised during driver creation, exception is raised
* @throws Exception
*/
@Test(groups={"ut"}, expectedExceptions=SeleniumGridException.class)
public void testDriverNotCreatedIfError() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(1);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
// connect to grid;
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenThrow(new WebDriverException(""));
new SeleniumGridDriverFactory(config).createWebDriver();
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
/**
* Check we use the first grid connector if it's available
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationWithSeveralGridConnectors() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
// connect to grid. One driver for each connector so that it's easy to distinguish them
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver);
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:2222/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver2);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
Assert.assertNotNull(newDriver);
}
/**
* Check we use the first grid connector if it's available
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationWithSeveralGridConnectorsOneUnavailable() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(false);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
// connect to grid. One driver for each connector so that it's easy to distinguish them
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver);
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:2222/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver2);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver2);
}
/**
* Check we use the connector which is not in error
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationWithSeveralGridConnectorsOneInError() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(1);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
// first driver will create an exception
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:1111/wd/hub")), any(DesiredCapabilities.class)).thenThrow(new WebDriverException(""));
PowerMockito.whenNew(RemoteWebDriver.class).withParameterTypes(URL.class, Capabilities.class).withArguments(eq(new URL("http://localhost:2222/wd/hub")), any(DesiredCapabilities.class)).thenReturn(driver2);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver2);
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
/**
* Check we can force driver to be created on the same node using capabilities if DriverConfig.getRunOnSameNode() specifies the node name
* For this to work a previous driver must have been created for one of the configured grid connector
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationOnSameNode() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(gridConnector1); // simulate a previously created driver
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
WebDriver newDriver = driverFactory.createWebDriver();
// check that with a multiple drivers creation, retry timeout is 1 min 30 for the second drivers because runOnSameNode is set
Assert.assertEquals(driverFactory.getInstanceRetryTimeout(), 90);
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver);
}
/**
* Check capability is correctly set when requested to run on same node
* @throws Exception
*/
@Test(groups={"ut"})
public void testCapabilitiesCreationOnSameNode() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(gridConnector1); // simulate a previously created driver
DesiredCapabilities caps = new SeleniumGridDriverFactory(config).createSpecificGridCapabilities(config);
Assert.assertEquals(caps.getCapability(SeleniumRobotCapabilityType.ATTACH_SESSION_ON_NODE), "http://localhost:5556/");
}
/**
* Check we can force driver to be created on the same node using capabilities if DriverConfig.getRunOnSameNode() specifies the node name
* For this to work a previous driver must have been created for one of the configured grid connector
* @throws Exception
*/
@Test(groups={"ut"})
public void testDriverCreationOnSameNodeMultipleHubs() throws Exception {
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(gridConnector2.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1, gridConnector2));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(gridConnector2); // simulate a previously created driver
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class)
.withAnyArguments().thenReturn(driver);
SeleniumGridDriverFactory driverFactory = new SeleniumGridDriverFactory(config);
WebDriver newDriver = driverFactory.createWebDriver();
Assert.assertNotNull(newDriver);
Assert.assertEquals(newDriver, driver);
// Check selected grid connector is the requested one
Assert.assertEquals(driverFactory.getActiveGridConnector(), gridConnector2);
}
/**
* Check that it's not possible to create a driver on same node is no previous driver has been created before (gridConnector is null in context)
* @throws Exception
*/
@Test(groups={"ut"}, expectedExceptions=ScenarioException.class)
public void testDriverDoNotCreateDriverOnSameNodeWithoutPreviousOne() throws Exception {
try {
SeleniumGridDriverFactory.setRetryTimeout(1);
SeleniumTestsContextManager.setThreadContext(context);
when(context.getTestType()).thenReturn(TestType.WEB);
when(gridConnector1.isGridActive()).thenReturn(true);
when(context.getSeleniumGridConnectors()).thenReturn(Arrays.asList(gridConnector1));
when(config.getRunOnSameNode()).thenReturn("http://localhost:5556/");
when(config.getSeleniumGridConnector()).thenReturn(null); // simulate the case where no previous driver was created
// connect to grid
PowerMockito.whenNew(RemoteWebDriver.class).withAnyArguments().thenReturn(driver);
WebDriver newDriver = new SeleniumGridDriverFactory(config).createWebDriver();
} finally {
SeleniumGridDriverFactory.setRetryTimeout(SeleniumGridDriverFactory.DEFAULT_RETRY_TIMEOUT);
}
}
}
| issue #311: corrected expected exception | core/src/test/java/com/seleniumtests/ut/browserfactory/TestSeleniumGridDriverFactory.java | issue #311: corrected expected exception | <ide><path>ore/src/test/java/com/seleniumtests/ut/browserfactory/TestSeleniumGridDriverFactory.java
<ide> import com.seleniumtests.core.SeleniumTestsContext;
<ide> import com.seleniumtests.core.SeleniumTestsContextManager;
<ide> import com.seleniumtests.customexception.ScenarioException;
<del>import com.seleniumtests.customexception.SeleniumGridException;
<add>import com.seleniumtests.customexception.SeleniumGridNodeNotAvailable;
<ide> import com.seleniumtests.driver.BrowserType;
<ide> import com.seleniumtests.driver.DriverConfig;
<ide> import com.seleniumtests.driver.TestType;
<ide> * If grid is not active, driver is not created and exception is raised
<ide> * @throws Exception
<ide> */
<del> @Test(groups={"ut"}, expectedExceptions=SeleniumGridException.class)
<add> @Test(groups={"ut"}, expectedExceptions=SeleniumGridNodeNotAvailable.class)
<ide> public void testDriverNotCreatedIfGridNotActive() throws Exception {
<ide>
<ide> try {
<ide> * If exception is raised during driver creation, exception is raised
<ide> * @throws Exception
<ide> */
<del> @Test(groups={"ut"}, expectedExceptions=SeleniumGridException.class)
<add> @Test(groups={"ut"}, expectedExceptions=SeleniumGridNodeNotAvailable.class)
<ide> public void testDriverNotCreatedIfError() throws Exception {
<ide>
<ide> try { |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.